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:com.nokia.helium.core.EmailDataSender.java

/**
 * Send xml data//from  ww  w .  jav  a  2  s  .  c  om
 * 
 * @param String purpose of this email
 * @param String file to send
 * @param String mime type
 * @param String subject of email
 * @param String header of mail
 * @param boolean compress data if true
 */
public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header,
        boolean compressData) throws EmailSendException {
    try {
        log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType);
        if (fileToSend != null && fileToSend.exists()) {
            InternetAddress[] toAddresses = getToAddressList();
            Properties props = new Properties();
            if (smtpServerAddress != null) {
                log.debug("sendData:smtp address: " + smtpServerAddress);
                props.setProperty("mail.smtp.host", smtpServerAddress);
            }
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject == null ? "" : subject);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            ByteArrayDataSource dataSrc = null;
            String fileName = fileToSend.getName();
            if (compressData) {
                log.debug("Sending compressed data");
                dataSrc = compressFile(fileToSend);
                dataSrc.setName(fileName + ".gz");
                messageBodyPart.setFileName(fileName + ".gz");
            } else {
                log.debug("Sending uncompressed data:");
                dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType);

                message.setContent(FileUtils.readFileToString(fileToSend), "text/html");
                multipart = null;
            }
            String headerToSend = null;
            if (header == null) {
                headerToSend = "";
            }
            messageBodyPart.setHeader("helium-bld-data", headerToSend);
            messageBodyPart.setDataHandler(new DataHandler(dataSrc));

            if (multipart != null) {
                multipart.addBodyPart(messageBodyPart); // add to the
                // multipart
                message.setContent(multipart);
            }
            try {
                message.setFrom(getFromAddress());
            } catch (AddressException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            } catch (LDAPException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            }
            message.addRecipients(Message.RecipientType.TO, toAddresses);
            log.info("Sending email alert: " + subject);
            Transport.send(message);
        }
    } catch (MessagingException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        throw new EmailSendException(fullErrorMessage, e);
    } catch (IOException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        // We are Ignoring the errors as no need to fail the build.
        throw new EmailSendException(fullErrorMessage, e);
    }
}

From source file:eu.openanalytics.rsb.component.SoapMtomJobHandler.java

private ResultType buildResult(final AbstractFunctionCallResult functionCallResult) throws IOException {
    Validate.notNull(functionCallResult, NULL_RESULT_RECEIVED);

    final String resultContentType = functionCallResult.getMimeType().toString();

    final PayloadType payload = soapOF.createPayloadType();
    payload.setContentType(resultContentType);
    payload.setName(functionCallResult.getResultFileName());
    payload.setData(/*  w w w . ja  v a2s . co  m*/
            new DataHandler(new ByteArrayDataSource(functionCallResult.getPayload(), resultContentType)));

    final ResultType result = createResult(functionCallResult);
    result.getPayload().add(payload);
    return result;
}

From source file:com.flexive.shared.FxMailUtils.java

/**
 * Sends an email/*www .  j  a v  a 2s.  c  o m*/
 *
 * @param SMTPServer      IP Address of the SMTP server
 * @param subject         subject of the email
 * @param textBody        plain text
 * @param htmlBody        html text
 * @param to              recipient
 * @param cc              cc recepient
 * @param bcc             bcc recipient
 * @param from            sender
 * @param replyTo         reply-to address
 * @param mimeAttachments strings containing mime encoded attachments
 * @throws FxApplicationException on errors
 */
public static void sendMail(String SMTPServer, String subject, String textBody, String htmlBody, String to,
        String cc, String bcc, String from, String replyTo, String... mimeAttachments)
        throws FxApplicationException {

    try {
        // Set the mail server
        java.util.Properties properties = System.getProperties();
        if (SMTPServer != null)
            properties.put("mail.smtp.host", SMTPServer);

        // Get a session and create a new message
        javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
        MimeMessage msg = new MimeMessage(session);

        // Set the sender
        if (StringUtils.isBlank(from))
            msg.setFrom(); // Uses local IP Adress and the user under which the server is running
        else {
            msg.setFrom(createAddress(from));
        }

        if (!StringUtils.isBlank(replyTo))
            msg.setReplyTo(encodePersonal(InternetAddress.parse(replyTo, false)));

        // Set the To, Cc and Bcc fields
        if (!StringUtils.isBlank(to))
            msg.setRecipients(MimeMessage.RecipientType.TO, encodePersonal(InternetAddress.parse(to, false)));
        if (!StringUtils.isBlank(cc))
            msg.setRecipients(MimeMessage.RecipientType.CC, encodePersonal(InternetAddress.parse(cc, false)));
        if (!StringUtils.isBlank(bcc))
            msg.setRecipients(MimeMessage.RecipientType.BCC, encodePersonal(InternetAddress.parse(bcc, false)));

        // Set the subject
        msg.setSubject(subject, "UTF-8");

        String sMainType = "Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"";

        StringBuilder body = new StringBuilder(5000);

        if (mimeAttachments.length > 0) {
            sMainType = "Multipart/Mixed;\n\tboundary=\"" + BOUNDARY2 + "\"";
            body.append("This is a multi-part message in MIME format.\n\n");
            body.append("--" + BOUNDARY2 + "\n");
            body.append("Content-Type: Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"\n\n\n");
        }

        if (textBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/plain; charset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            body.append(encodeQuotedPrintable(textBody)).append("\n");
        }
        if (htmlBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/html;\n\tcharset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            if (htmlBody.toLowerCase().indexOf("<html>") < 0) {
                body.append("<HTML><HEAD>\n<TITLE></TITLE>\n");
                body.append(
                        "<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Dutf-8\"></HEAD>\n<BODY>\n");
                body.append(encodeQuotedPrintable(htmlBody)).append("</BODY></HTML>\n");
            } else
                body.append(encodeQuotedPrintable(htmlBody)).append("\n");
        }

        body.append("\n--" + BOUNDARY1 + "--\n");

        if (mimeAttachments.length > 0) {
            for (String mimeAttachment : mimeAttachments) {
                body.append("\n--" + BOUNDARY2 + "\n");
                body.append(mimeAttachment).append("\n");
            }
            body.append("\n--" + BOUNDARY2 + "--\n");
        }

        msg.setDataHandler(
                new javax.activation.DataHandler(new ByteArrayDataSource(body.toString(), sMainType)));

        // Set the header
        msg.setHeader("X-Mailer", "JavaMailer");

        // Set the sent date
        msg.setSentDate(new java.util.Date());

        // Send the message
        javax.mail.Transport.send(msg);
    } catch (AddressException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.address", e.getRef());
    } catch (javax.mail.MessagingException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (IOException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (EncoderException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    }
}

From source file:org.apromore.service.impl.CanoniserServiceImplIntgTest.java

@Test
public void deCanoniseWithoutAnnotationsSuccessEPML() throws Exception {
    String name = "EPML 2.0";
    InputStream cpf = new ByteArrayDataSource(CanonicalNoAnnotationModel.CANONICAL_XML, "text/xml")
            .getInputStream();//from  w ww . jav a 2s . c o  m

    Set<Canoniser> availableCanonisers = cSrv.listByNativeType(name);
    Iterator<Canoniser> iter = availableCanonisers.iterator();
    assertTrue(iter.hasNext());
    Canoniser c = iter.next();
    assertNotNull(c);
    assertEquals(name, c.getNativeType());
    assertEquals(0, c.getMandatoryParameters().size());
    assertEquals(1, c.getOptionalParameters().size());

    DecanonisedProcess dp = cSrv.deCanonise(name, getTypeFromXML(cpf), null, epmlCanoniserRequest);

    MatcherAssert.assertThat(dp.getNativeFormat(), Matchers.notNullValue());
    MatcherAssert.assertThat(dp.getMessages(), Matchers.notNullValue());
}

From source file:org.wso2.carbon.logging.util.LoggingReader.java

public DataHandler downloadLogFiles(String logFile, String tenantDomain, String serviceName)
        throws LogViewerException {
    InputStream is;/*from   w  w w.  j a va2 s . c o  m*/
    int tenantId = getTenantIdForDomain(tenantDomain);
    try {
        is = getInputStream(logFile, tenantId, serviceName);
    } catch (LogViewerException e) {
        throw new LogViewerException("Cannot read InputStream from the file " + logFile, e);
    }
    try {
        ByteArrayDataSource bytArrayDS = new ByteArrayDataSource(is, "application/zip");
        DataHandler dataHandler = new DataHandler(bytArrayDS);
        return dataHandler;
    } catch (IOException e) {
        throw new LogViewerException("Cannot read file size from the " + logFile, e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new LogViewerException("Cannot close the input stream " + logFile, e);
        }
    }
}

From source file:org.apache.stratos.theme.mgt.ui.processors.AddThemeResourceProcessor.java

private static DataHandler scaleImage(DataHandler dataHandler, int height, int width) throws IOException {

    Image image = ImageIO.read(new BufferedInputStream(dataHandler.getInputStream()));
    // Check if the image has transparent pixels
    boolean hasAlpha = ((BufferedImage) image).getColorModel().hasAlpha();

    // Maintain Aspect ratio
    int thumbHeight = height;
    int thumbWidth = width;
    double thumbRatio = (double) width / (double) height;
    double imageRatio = (double) image.getWidth(null) / (double) image.getHeight(null);
    if (thumbRatio < imageRatio) {
        thumbHeight = (int) (thumbWidth / imageRatio);
    } else {/*w w  w . j  a v  a2s .co  m*/
        thumbWidth = (int) (thumbHeight * imageRatio);
    }

    BufferedImage thumb;
    // Check if transparent pixels are available and set the color mode accordingly 
    if (hasAlpha) {
        thumb = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_ARGB);
    } else {
        thumb = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
    }
    Graphics2D graphics2D = thumb.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

    // Save the image as PNG so that transparent images are rendered as intended
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ImageIO.write(thumb, "PNG", output);

    DataSource dataSource = new ByteArrayDataSource(output.toByteArray(), "application/octet-stream");
    return new DataHandler(dataSource);
}

From source file:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java

@DirtiesContext
@Test// ww  w .j  av  a2  s .  c o  m
public void testMarshalJpg() throws Exception {
    Assert.assertNotNull(testShsMessage);
    Assert.assertNotNull(testJpgFile);

    testShsMessage.getDataParts().remove(0);
    DataPart dataPart = new DataPart(
            new DataHandler(new ByteArrayDataSource(testJpgFile.getInputStream(), "image/jpeg")));
    dataPart.setContentType("image/jpeg");
    dataPart.setFileName(testJpgFile.getFilename());
    dataPart.setTransferEncoding("base64");
    dataPart.setDataPartType("jpg");

    testShsMessage.getDataParts().add(dataPart);

    resultEndpoint.expectedMessageCount(1);
    template.sendBody("direct:marshalRoundtrip", testShsMessage);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getReceivedExchanges();
    Exchange exchange = exchanges.get(0);

    ShsMessage shsMessage = exchange.getIn().getMandatoryBody(ShsMessage.class);

    Assert.assertNotSame(shsMessage, testShsMessage);

    ShsLabel label = shsMessage.getLabel();

    Assert.assertNotNull(label, "label should not be null");

    Assert.assertEquals(label.getSubject(), testShsMessage.getLabel().getSubject());
    Assert.assertEquals(label.getDatetime().toString(), testShsMessage.getLabel().getDatetime().toString());

    Assert.assertNotNull(testShsMessage.getDataParts());
    DataPart dataPartResponse = testShsMessage.getDataParts().get(0);

    Assert.assertTrue(isSame(testJpgFile.getInputStream(), dataPartResponse.getDataHandler().getInputStream()),
            "Response data stream is not same as source data stream");
}

From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapter.java

private void replaceSMIMEAttachment(MimeMessage containerMessage, MimeMessage sourceMessage)
        throws MessagingException, IOException, PartException {
    Part smimePart = findAttachment(containerMessage);

    if (sourceMessage.getSize() > directSizeLimit) {
        /*//from  ww w  .  j  a va  2 s. com
         * The message is too large to be sent to the BB directly so we should 
         * sent it as an attachment that can be downloaded and handled using
         * a content handler on the BB
         */
        String filename = downloadAttachmentName + DOWNLOAD_ATTACHMENT_EXTENSION;

        smimePart.setFileName(filename);
    }

    smimePart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(sourceMessage.getInputStream(), "application/octet-stream")));
}

From source file:pt.ist.fenix.api.SupportFormResource.java

private void sendEmail(String from, String subject, String body, SupportBean bean) {
    Properties props = new Properties();
    props.put("mail.smtp.host", Objects
            .firstNonNull(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), "localhost"));
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    try {//  w  ww  .ja  v  a 2  s.  com
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress()));
        message.setSubject(subject);
        message.setText(body);

        Multipart multipart = new MimeMultipart();
        {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multipart.addBodyPart(messageBodyPart);
        }

        if (!Strings.isNullOrEmpty(bean.attachment)) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(
                    new ByteArrayDataSource(Base64.getDecoder().decode(bean.attachment), bean.mimeType)));
            messageBodyPart.setFileName(bean.fileName);
            multipart.addBodyPart(messageBodyPart);
        }

        message.setContent(multipart);

        Transport.send(message);
    } catch (Exception e) {
        logger.error("Could not send support email! Original message was: " + body, e);
    }
}

From source file:sendhtml.java

public void collect(BufferedReader in, Message msg) throws MessagingException, IOException {
    String line;//from   w  w w . j  av  a  2  s  .c o  m
    String subject = msg.getSubject();
    StringBuffer sb = new StringBuffer();
    sb.append("<HTML>\n");
    sb.append("<HEAD>\n");
    sb.append("<TITLE>\n");
    sb.append(subject + "\n");
    sb.append("</TITLE>\n");
    sb.append("</HEAD>\n");

    sb.append("<BODY>\n");
    sb.append("<H1>" + subject + "</H1>" + "\n");

    while ((line = in.readLine()) != null) {
        sb.append(line);
        sb.append("\n");
    }

    sb.append("</BODY>\n");
    sb.append("</HTML>\n");

    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(sb.toString(), "text/html")));
}