Example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource

List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource

Introduction

In this page you can find the example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource.

Prototype

public ByteArrayDataSource(String data, String type) throws IOException 

Source Link

Document

Create a ByteArrayDataSource with data from the specified String and with the specified MIME type.

Usage

From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java

private void processSpecificAttachment(final MimeMultipart mixedMultipart, final IContentItem attachmentContent)
        throws IOException, MessagingException {

    // Add this attachment

    if (attachmentContent != null) {

        final ByteArrayDataSource dataSource = new ByteArrayDataSource(attachmentContent.getInputStream(),
                attachmentContent.getMimeType());
        final MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(getAttachmentName());
        mixedMultipart.addBodyPart(attachmentBodyPart);

    }/*  w  w w.j a v  a  2s .  c o  m*/

}

From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxPublicationClientTest.java

@Test
public void testPublishViaSOAPAttachment() throws Exception {
    // STS//from  ww w .  j  a  v  a 2  s. com
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);

    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox publication
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("application/octet-stream");
    publicationDocument.setDownloadFileName("test.dat");
    byte[] message = "hello world".getBytes();
    DataSource dataSource = new ByteArrayDataSource(message, "application/octet-stream");
    DataHandler dataHandler = new DataHandler(dataSource);
    publicationDocument.setEncryptableBinaryContent(dataHandler);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(message);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Builds up a new message from the passed message parts
 * @param messageType one of the message types definfed in the class AS2Message
 *///  w  w w  . j  a  v  a 2 s .  c om
public AS2Message createMessage(Partner sender, Partner receiver, AS2Payload[] payloads, int messageType,
        String messageId) throws Exception {
    if (messageId == null) {
        messageId = UniqueId.createMessageId(sender.getAS2Identification(), receiver.getAS2Identification());
    }
    BCCryptoHelper cryptoHelper = new BCCryptoHelper();
    AS2MessageInfo info = new AS2MessageInfo();
    info.setMessageType(messageType);
    info.setSenderId(sender.getAS2Identification());
    info.setReceiverId(receiver.getAS2Identification());
    info.setSenderEMail(sender.getEmail());
    info.setMessageId(messageId);
    info.setDirection(AS2MessageInfo.DIRECTION_OUT);
    info.setSignType(receiver.getSignType());
    info.setEncryptionType(receiver.getEncryptionType());
    info.setRequestsSyncMDN(receiver.isSyncMDN());
    if (!receiver.isSyncMDN()) {
        info.setAsyncMDNURL(sender.getMdnURL());
    }
    info.setSubject(receiver.getSubject());
    try {
        info.setSenderHost(InetAddress.getLocalHost().getCanonicalHostName());
    } catch (UnknownHostException e) {
        //nop
    }
    //create message object to return
    AS2Message message = new AS2Message(info);
    //stores all the available body parts that have been prepared
    List<MimeBodyPart> contentPartList = new ArrayList<MimeBodyPart>();
    for (AS2Payload as2Payload : payloads) {
        //add payload
        message.addPayload(as2Payload);
        if (this.runtimeConnection != null) {
            MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            messageAccess.initializeOrUpdateMessage(info);
        }
        //no MIME message: single payload, unsigned, no CEM
        if (info.getSignType() == AS2Message.SIGNATURE_NONE && payloads.length == 1
                && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) {
            return (this.createMessageNoMIME(message, receiver));
        }
        //MIME message
        MimeBodyPart bodyPart = new MimeBodyPart();
        String contentType = null;
        if (as2Payload.getContentType() == null) {
            contentType = receiver.getContentType();
        } else {
            contentType = as2Payload.getContentType();
        }
        bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(as2Payload.getData(), contentType)));
        bodyPart.addHeader("Content-Type", contentType);
        if (as2Payload.getContentId() != null) {
            bodyPart.addHeader("Content-ID", as2Payload.getContentId());
        }
        if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
            bodyPart.addHeader("Content-Transfer-Encoding", "base64");
        } else {
            bodyPart.addHeader("Content-Transfer-Encoding", "binary");
        }
        //prepare filename to not violate the MIME header rules
        if (as2Payload.getOriginalFilename() == null) {
            as2Payload.setOriginalFilename(new File(as2Payload.getPayloadFilename()).getName());
        }
        String newFilename = as2Payload.getOriginalFilename().replace(' ', '_');
        newFilename = newFilename.replace('@', '_');
        newFilename = newFilename.replace(':', '_');
        newFilename = newFilename.replace(';', '_');
        newFilename = newFilename.replace('(', '_');
        newFilename = newFilename.replace(')', '_');
        bodyPart.addHeader("Content-Disposition", "attachment; filename=" + newFilename);
        contentPartList.add(bodyPart);
    }
    Part contentPart = null;
    //sigle attachment? No CEM? Every CEM is in a multipart/related container
    if (contentPartList.size() == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) {
        contentPart = contentPartList.get(0);
    } else {
        //build up a new MimeMultipart container for the multiple attachments, content-type
        //is "multipart/related"
        MimeMultipart multipart = null;
        //CEM messages are always in a multipart container (even the response which contains only a single
        //payload) with the subtype "application/ediint-cert-exchange+xml".
        if (info.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
            multipart = new MimeMultipart("related; type=\"application/ediint-cert-exchange+xml\"");
        } else {
            multipart = new MimeMultipart("related");
        }
        for (MimeBodyPart bodyPart : contentPartList) {
            multipart.addBodyPart(bodyPart);
        }
        contentPart = new MimeMessage(Session.getInstance(System.getProperties(), null));
        contentPart.setContent(multipart, multipart.getContentType());
        ((MimeMessage) contentPart).saveChanges();
    }
    //should the content be compressed and enwrapped or just enwrapped?
    if (receiver.getCompressionType() == AS2Message.COMPRESSION_ZLIB) {
        info.setCompressionType(AS2Message.COMPRESSION_ZLIB);
        int uncompressedSize = contentPart.getSize();
        contentPart = this.compressPayload(receiver, contentPart);
        int compressedSize = contentPart.getSize();
        //sometimes size() is unable to determine the size of the compressed body part and will return -1. Dont log the
        //compression ratio in this case.
        if (uncompressedSize == -1 || compressedSize == -1) {
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed.unknownratio",
                        new Object[] { info.getMessageId() }), info);
            }
        } else {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.compressed",
                                new Object[] { info.getMessageId(),
                                        AS2Tools.getDataSizeDisplay(uncompressedSize),
                                        AS2Tools.getDataSizeDisplay(compressedSize) }),
                        info);
            }
        }
    }
    //compute content mic. Try to use sign digest as hash alg. For unsigned messages take sha-1
    String digestOID = null;
    if (info.getSignType() == AS2Message.SIGNATURE_MD5) {
        digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_MD5);
    } else {
        digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1);
    }
    String mic = cryptoHelper.calculateMIC(contentPart, digestOID);
    if (info.getSignType() == AS2Message.SIGNATURE_MD5) {
        info.setReceivedContentMIC(mic + ", md5");
    } else {
        info.setReceivedContentMIC(mic + ", sha1");
    }
    this.enwrappInMessageAndSign(message, contentPart, sender, receiver);
    //encryption requested for the receiver?
    if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
        String cryptAlias = this.encryptionCertManager
                .getAliasByFingerprint(receiver.getCryptFingerprintSHA1());
        this.encryptDataToMessage(message, cryptAlias, info.getEncryptionType(), receiver);
    } else {
        message.setRawData(message.getDecryptedRawData());
        if (this.logger != null) {
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.notencrypted", new Object[] { info.getMessageId() }),
                    info);
        }
    }
    return (message);
}

From source file:gov.nist.healthcare.ttt.parsing.Parsing.java

public static SOAPWithAttachment parseMtom(String mtom) throws MessagingException, IOException {

    //        Parsing.fixMissingEndBoundry(mtom);
    MimeMultipart mp;/* w  w  w  . j  a  va  2  s  .  c om*/
    // String contentType = Parsing.findContentType(mtom);

    //     mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), ""), new ContentType(contentType));
    mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), "multipart/related"));
    SOAPWithAttachment swa = new SOAPWithAttachment();
    int count = mp.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bp = mp.getBodyPart(i);
        String contentType = bp.getContentType();
        if (contentType.startsWith("application/xop+xml")) {
            // SOAP
            ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent();
            swa.setSoap(IOUtils.toString(content));

        } else {
            Object contentRaw = bp.getContent();
            if (contentRaw instanceof String) {
                String content = (String) bp.getContent();
                swa.getAttachment().add(content.getBytes());
            } else if (contentRaw instanceof SharedByteArrayInputStream) {
                SharedByteArrayInputStream content = (SharedByteArrayInputStream) bp.getContent();
                swa.getAttachment().add(read(content));
            } else {
                System.out.println("UNKNOWN ATTACHMENT TYPE = " + contentRaw.getClass().getName());
                swa.getAttachment().add(new String().getBytes());
            }
        }

        // System.out.println("contentype=" + bp.getContentType());
        //ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent();
        //String contentString = IOUtils.toString(content);
        //String contentString = (String) bp.getContent();
        /*
        try {
        Envelope env = (Envelope) JAXB.unmarshal(new StringReader(contentString), Envelope.class);
        if (env.getHeader() == null && env.getBody() == null) {
            swa.getAttachment().add(Parsing.read(content));
            //swa.getAttachment().add(contentString.getBytes());
        } else {
            swa.setSoap(contentString);
        }
        } catch (Exception saxe) {
        // Not SOAP so must be attachment.
         swa.getAttachment().add(Parsing.read(content));
        //swa.getAttachment().add(contentString.getBytes());
        }
         */
    }

    if (swa.getAttachment() == null || swa.getAttachment().size() == 0) {
        byte[] document = Parsing.getDocumentFromSoap(swa.getSoap()).getBytes();
        Collection<byte[]> attachments = new ArrayList<byte[]>();
        attachments.add(document);
        swa.setAttachment(attachments);
    }

    return swa;
}

From source file:test.unit.be.e_contract.dssp.client.DigitalSignatureServiceTestPort.java

private String addAttachment(String mimetype, String contentId, byte[] data) {
    LOG.debug("adding attachment: " + contentId);
    DataSource dataSource = new ByteArrayDataSource(data, mimetype);
    DataHandler dataHandler = new DataHandler(dataSource);
    MessageContext messageContext = this.webServiceContext.getMessageContext();

    Map<String, DataHandler> outputMessageAttachments = (Map<String, DataHandler>) messageContext
            .get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
    outputMessageAttachments.put(contentId, dataHandler);
    messageContext.put(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS, outputMessageAttachments);

    return contentId;
}

From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java

private List<DataSource> getAttachments(long messageId) throws DAOException {
    try {//  w w  w  . ja  va2 s .c o m
        return simpleJdbcTemplate.query(
                "select name, content_type, content" + " from ebms_attachment" + " where ebms_message_id = ?",
                new ParameterizedRowMapper<DataSource>() {
                    @Override
                    public DataSource mapRow(ResultSet rs, int rowNum) throws SQLException {
                        ByteArrayDataSource result = new ByteArrayDataSource(rs.getBytes("content"),
                                rs.getString("content_type"));
                        result.setName(rs.getString("name"));
                        return result;
                    }
                }, messageId);
    } catch (DataAccessException e) {
        throw new DAOException(e);
    }
}

From source file:org.apache.nifi.processors.email.ConsumeEWS.java

public MimeMessage parseMessage(EmailMessage item) throws Exception {
    EmailMessage ewsMessage = item;/*from  www.  j av a 2 s  .c o  m*/
    final String bodyText = ewsMessage.getBody().toString();

    MultiPartEmail mm;

    if (ewsMessage.getBody().getBodyType() == BodyType.HTML) {
        mm = new HtmlEmail().setHtmlMsg(bodyText);
    } else {
        mm = new MultiPartEmail();
        mm.setMsg(bodyText);
    }
    mm.setHostName("NiFi-EWS");
    //from
    mm.setFrom(ewsMessage.getFrom().getAddress());
    //to recipients
    ewsMessage.getToRecipients().forEach(x -> {
        try {
            mm.addTo(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add TO recipient.", e);
        }
    });
    //cc recipients
    ewsMessage.getCcRecipients().forEach(x -> {
        try {
            mm.addCc(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add CC recipient.", e);
        }
    });
    //subject
    mm.setSubject(ewsMessage.getSubject());
    //sent date
    mm.setSentDate(ewsMessage.getDateTimeSent());
    //add message headers
    ewsMessage.getInternetMessageHeaders().forEach(x -> mm.addHeader(x.getName(), x.getValue()));

    //Any attachments
    if (ewsMessage.getHasAttachments()) {
        ewsMessage.getAttachments().forEach(x -> {
            try {
                FileAttachment file = (FileAttachment) x;
                file.load();

                ByteArrayDataSource bds = new ByteArrayDataSource(file.getContent(), file.getContentType());

                mm.attach(bds, file.getName(), "", EmailAttachment.ATTACHMENT);
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    mm.buildMimeMessage();
    return mm.getMimeMessage();
}

From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java

private MimeBodyPart constructEmail(int index, ApplicationGroup appGroup, StringBuilder body)
        throws IOException, MessagingException {

    if (index == 0 && !StringUtils.isEmpty(headerNote))
        body.append(headerNote);/*from  w  ww. j  a  v a  2 s .  com*/

    numberFormatter.setMaximumFractionDigits(1);
    numberFormatter.setMinimumFractionDigits(1);

    File file = createImage(appGroup);

    if (file == null)
        return null;

    DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
    String link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks),
            end);
    body.append(String.format("<b><h4><a href='%s'>%s</a> Weekly Costs:</h4></b>", link,
            appGroup.getDisplayName()));

    body.append("<table style=\"border: 1px solid #DDD; border-collapse: collapse\">");
    body.append(
            "<tr style=\"background-color: whiteSmoke;text-align:center\" ><td style=\"border-left: 1px solid #DDD;\"></td>");
    for (int i = 0; i <= accounts.size(); i++) {
        int cols = i == accounts.size() ? 1 : regions.size();
        String accName = i == accounts.size() ? "total" : accounts.get(i).name;
        body.append(String.format(
                "<td style=\"border-left: 1px solid #DDD;font-weight: bold;padding: 4px\" colspan='%d'>", cols))
                .append(accName).append("</td>");
    }
    body.append("</tr>");
    body.append("<tr style=\"background-color: whiteSmoke;text-align:center\" ><td></td>");
    for (int i = 0; i < accounts.size(); i++) {
        boolean first = true;
        for (Region region : regions) {
            body.append("<td style=\"font-weight: bold;padding: 4px;"
                    + (first ? "border-left: 1px solid #DDD;" : "") + "\">").append(region.name)
                    .append("</td>");
            first = false;
        }
    }
    body.append("<td style=\"border-left: 1px solid #DDD;\"></td></tr>");

    Map<String, Double> costs = Maps.newHashMap();

    Interval interval = new Interval(end.minusWeeks(numWeeks), end);
    double[] total = new double[numWeeks];
    for (Product product : products) {
        List<ResourceGroup> resourceGroups = getResourceGroups(appGroup, product);
        if (resourceGroups.size() == 0) {
            continue;
        }
        DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly);
        if (dataManager == null) {
            continue;
        }
        for (int i = 0; i < accounts.size(); i++) {
            List<Account> accountList = Lists.newArrayList(accounts.get(i));
            TagLists tagLists = new TagLists(accountList, regions, null, Lists.newArrayList(product), null,
                    null, resourceGroups);
            Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Region,
                    AggregateType.none, false);
            for (Tag tag : data.keySet()) {
                for (int week = 0; week < numWeeks; week++) {
                    String key = accounts.get(i) + "|" + tag + "|" + week;
                    if (costs.containsKey(key))
                        costs.put(key, data.get(tag)[week] + costs.get(key));
                    else
                        costs.put(key, data.get(tag)[week]);
                    total[week] += data.get(tag)[week];
                }
            }
        }
    }

    boolean firstLine = true;
    DateTime currentWeekEnd = end;
    for (int week = numWeeks - 1; week >= 0; week--) {
        String weekStr;
        if (week == numWeeks - 1)
            weekStr = "Last week";
        else
            weekStr = (numWeeks - week - 1) + " weeks ago";
        String background = week % 2 == 1 ? "background: whiteSmoke;" : "";
        body.append(String.format(
                "<tr style=\"%s\"><td nowrap style=\"border-left: 1px solid #DDD;padding: 4px\">%s (%s - %s)</td>",
                background, weekStr, formatter.print(currentWeekEnd.minusWeeks(1)).substring(5),
                formatter.print(currentWeekEnd).substring(5)));
        for (int i = 0; i < accounts.size(); i++) {
            Account account = accounts.get(i);
            for (int j = 0; j < regions.size(); j++) {
                Region region = regions.get(j);
                String key = account + "|" + region + "|" + week;
                double cost = costs.get(key) == null ? 0 : costs.get(key);
                Double lastCost = week == 0 ? null : costs.get(account + "|" + region + "|" + (week - 1));
                link = getLink("column", ConsolidateType.daily, appGroup, Lists.newArrayList(account),
                        Lists.newArrayList(region), currentWeekEnd.minusWeeks(1), currentWeekEnd);
                body.append(getValueCell(cost, lastCost, link, firstLine));
            }
        }
        link = getLink("column", ConsolidateType.daily, appGroup, accounts, regions,
                currentWeekEnd.minusWeeks(1), currentWeekEnd);
        body.append(getValueCell(total[week], week == 0 ? null : total[week - 1], link, firstLine));
        body.append("</tr>");
        firstLine = false;
        currentWeekEnd = currentWeekEnd.minusWeeks(1);
    }
    body.append("</table>");

    numberFormatter.setMaximumFractionDigits(0);
    numberFormatter.setMinimumFractionDigits(0);

    if (!StringUtils.isEmpty(throughputMetrics))
        body.append(throughputMetrics);

    body.append("<br><img src=\"cid:image_cid_" + index + "\"><br>");
    for (Map.Entry<String, List<String>> entry : appGroup.data.entrySet()) {
        String product = entry.getKey();
        List<String> selected = entry.getValue();
        if (selected == null || selected.size() == 0)
            continue;
        link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks),
                end);
        body.append(String.format("<b><h4>%s in <a href='%s'>%s</a>:</h4></b>",
                getResourceGroupsDisplayName(product), link, appGroup.getDisplayName()));
        for (String name : selected)
            body.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;").append(name).append("<br>");
    }
    body.append("<hr><br>");

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setFileName(file.getName());
    DataSource ds = new ByteArrayDataSource(new FileInputStream(file), "image/png");
    mimeBodyPart.setDataHandler(new DataHandler(ds));
    mimeBodyPart.setHeader("Content-ID", "<image_cid_" + index + ">");
    mimeBodyPart.setHeader("Content-Disposition", "inline");
    mimeBodyPart.setDisposition(MimeBodyPart.INLINE);

    file.delete();

    return mimeBodyPart;
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties;
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING));

    String responseData = null;/*from ww  w . j a  v a2s . c  om*/
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    CloseableHttpClient client = null;
    HttpRequestBase httpMethod = null;
    CloseableHttpResponse httpResponse = null;
    File tempFile = null;
    int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000);

    try {
        configuration.configureDispatcher(this, httpDispatcherProperties);

        long dispatcherId = getDispatcherId();
        client = clients.get(dispatcherId);
        if (client == null) {
            BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                    socketFactoryRegistry.build());
            httpClientConnectionManager
                    .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
            HttpClientBuilder clientBuilder = HttpClients.custom()
                    .setConnectionManager(httpClientConnectionManager);
            HttpUtil.configureClientBuilder(clientBuilder);

            if (httpDispatcherProperties.isUseProxyServer()) {
                clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner());
            }

            client = clientBuilder.build();
            clients.put(dispatcherId, client);
        }

        URI hostURI = new URI(httpDispatcherProperties.getHost());
        String host = hostURI.getHost();
        String scheme = hostURI.getScheme();
        int port = hostURI.getPort();
        if (port == -1) {
            if (scheme.equalsIgnoreCase("https")) {
                port = 443;
            } else {
                port = 80;
            }
        }

        // Parse the content type field first, and then add the charset if needed
        ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType());
        Charset charset = null;
        if (contentType.getCharset() == null) {
            charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset()));
        } else {
            charset = contentType.getCharset();
        }

        if (httpDispatcherProperties.isMultipart()) {
            tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
        }

        HttpHost target = new HttpHost(host, port, scheme);

        httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile,
                contentType, charset);

        HttpClientContext context = HttpClientContext.create();

        // authentication
        if (httpDispatcherProperties.isUseAuthentication()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(),
                    httpDispatcherProperties.getPassword());
            credsProvider.setCredentials(authScope, credentials);
            AuthCache authCache = new BasicAuthCache();
            RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create();

            if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) {
                logger.debug("using Digest authentication");
                registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    processDigestChallenge(authCache, target, credentials, httpMethod, context);
                }
            } else {
                logger.debug("using Basic authentication");
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    authCache.put(target, new BasicScheme());
                }
            }

            context.setCredentialsProvider(credsProvider);
            context.setAuthSchemeRegistry(registryBuilder.build());
            context.setAuthCache(authCache);

            logger.debug("using authentication with credentials: " + credentials);
        }

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        // Set proxy information
        if (httpDispatcherProperties.isUseProxyServer()) {
            context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(),
                    Integer.parseInt(httpDispatcherProperties.getProxyPort())));
        }

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString());
        httpResponse = client.execute(target, httpMethod, context);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        logger.debug("received status code: " + statusCode);

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        for (Header header : httpResponse.getAllHeaders()) {
            List<String> list = headers.get(header.getName());

            if (list == null) {
                list = new ArrayList<String>();
                headers.put(header.getName(), list);
            }

            list.add(header.getValue());
        }

        connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString());
        connectorMessage.getConnectorMap().put("responseHeaders",
                new MessageHeaders(new CaseInsensitiveMap(headers)));

        ContentType responseContentType = ContentType.get(httpResponse.getEntity());
        if (responseContentType == null) {
            responseContentType = ContentType.TEXT_PLAIN;
        }

        Charset responseCharset = charset;
        if (responseContentType.getCharset() != null) {
            responseCharset = responseContentType.getCharset();
        }

        final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes();
        BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() {
            @Override
            public boolean isBinaryContentType(ContentType contentType) {
                return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType);
            }
        };

        /*
         * First parse out the body of the HTTP response. Depending on the connector settings,
         * this could end up being a string encoded with the response charset, a byte array
         * representing the raw response payload, or a MimeMultipart object.
         */
        Object responseBody = "";

        // The entity could be null in certain cases such as 204 responses
        if (httpResponse.getEntity() != null) {
            // Only parse multipart if XML Body is selected and Parse Multipart is enabled
            if (httpDispatcherProperties.isResponseXmlBody()
                    && httpDispatcherProperties.isResponseParseMultipart()
                    && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
                responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(),
                        responseContentType.toString()));
            } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) {
                responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent());
            } else {
                responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset);
            }
        }

        /*
         * Now that we have the response body, we need to create the actual Response message
         * data. Depending on the connector settings this could be our custom serialized XML, a
         * Base64 string encoded from the raw response payload, or a string encoded from the
         * payload with the request charset.
         */
        if (httpDispatcherProperties.isResponseXmlBody()) {
            responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody,
                    responseContentType, httpDispatcherProperties.isResponseParseMultipart(),
                    httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver);
        } else if (responseBody instanceof byte[]) {
            responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII");
        } else {
            responseData = (String) responseBody;
        }

        validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse();

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            responseStatus = Status.SENT;
        } else {
            eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                    connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                    connectorProperties.getName(), "Received error response from HTTP server.", null));
            responseStatusMessage = ErrorMessageBuilder
                    .buildErrorResponse("Received error response from HTTP server.", null);
            responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData,
                    null);
        }
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error connecting to HTTP server.", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error connecting to HTTP server", e);
    } finally {
        try {
            HttpClientUtils.closeQuietly(httpResponse);

            // Delete temp files if we created them
            if (tempFile != null) {
                tempFile.delete();
                tempFile = null;
            }
        } finally {
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.IDLE));
        }
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSMultipartTest.java

@Test
public void testXopWebClient() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/xop";
    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setAddress(address);//from   w  w  w  .  j av  a  2 s .c o  m
    bean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED, (Object) "true"));
    WebClient client = bean.createWebClient();
    WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
    WebClient.getConfig(client).getOutInterceptors().add(new LoggingOutInterceptor());
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart", "true");
    client.type("multipart/related").accept("multipart/related");

    XopType xop = new XopType();
    xop.setName("xopName");
    InputStream is = getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd");
    byte[] data = IOUtils.readBytesFromStream(is);
    xop.setAttachinfo(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
    xop.setAttachInfoRef(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));

    String bookXsd = IOUtils.readStringFromStream(
            getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
    xop.setAttachinfo2(bookXsd.getBytes());

    xop.setImage(getImage("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));

    XopType xop2 = client.post(xop, XopType.class);

    String bookXsdOriginal = IOUtils.readStringFromStream(
            getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
    String bookXsd2 = IOUtils.readStringFromStream(xop2.getAttachinfo().getInputStream());
    assertEquals(bookXsdOriginal, bookXsd2);
    String bookXsdRef = IOUtils.readStringFromStream(xop2.getAttachInfoRef().getInputStream());
    assertEquals(bookXsdOriginal, bookXsdRef);

    String ctString = client.getResponse().getMetadata().getFirst("Content-Type").toString();
    MediaType mt = MediaType.valueOf(ctString);
    Map<String, String> params = mt.getParameters();
    assertEquals(4, params.size());
    assertNotNull(params.get("boundary"));
    assertNotNull(params.get("type"));
    assertNotNull(params.get("start"));
    assertNotNull(params.get("start-info"));
}