Example usage for javax.activation DataHandler DataHandler

List of usage examples for javax.activation DataHandler DataHandler

Introduction

In this page you can find the example usage for javax.activation DataHandler DataHandler.

Prototype

public DataHandler(URL url) 

Source Link

Document

Create a DataHandler instance referencing a URL.

Usage

From source file:org.forumj.email.FJEMail.java

public static void sendMail(String to, String from, String host, String subject, String text)
        throws ConfigurationException, AddressException, MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    String mailDebug = FJConfiguration.getConfig().getString("mail.debug");
    props.put("mail.debug", mailDebug == null ? "false" : mailDebug);
    Session session = Session.getInstance(props);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = { new InternetAddress(to) };
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.addHeader("charset", "UTF-8");
    msg.setSubject(subject);//from  w w  w  .j a v a  2s.c  o  m
    msg.setSentDate(new Date());
    msg.setDataHandler(new DataHandler(new HTMLDataSource(text)));
    Transport.send(msg);
}

From source file:mitm.application.djigzo.ws.impl.MailRepositoryWSImpl.java

@Override
@StartTransaction//from   w w w.j  a v  a  2  s . c  o m
public BinaryDTO getMimeMessage(String id) throws WebServiceCheckedException {
    try {
        MimeMessage message = getItemInternal(id).getMimeMessage();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        MailUtils.writeMessage(message, bos);

        DataSource source = new ByteArrayDataSource(bos.toByteArray(), MimeTypes.OCTET_STREAM);
        DataHandler dataHandler = new DataHandler(source);

        return new BinaryDTO(dataHandler);
    } catch (MessagingException e) {
        throw new WebServiceCheckedException("Error while getting MimeMessage", e);
    } catch (IOException e) {
        throw new WebServiceCheckedException("Error while getting MimeMessage", e);
    }
}

From source file:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java

public void addAttachement(final NodeRef nodeRef, MimeMultipart content, final Boolean convert)
        throws MessagingException {

    MappedByteBuffer buf;/*from  w  w  w  .j a  v  a 2 s. c  o m*/
    byte[] array = new byte[0];
    ContentReader reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
    String fileName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
    String type = reader.getMimetype().split("/")[0];
    if (!type.equalsIgnoreCase("image") && !reader.getMimetype().equalsIgnoreCase(MimetypeMap.MIMETYPE_PDF)
            && convert) {
        ContentWriter writer = contentService.getTempWriter();
        writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
        String srcMimeType = reader.getMimetype();
        //String srcMimeType = ((ContentData) nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT)).getMimetype();
        //String srcMimeType = this.getMimeTypeForFileName(fileName);
        ContentTransformer transformer = contentService.getTransformer(srcMimeType, MimetypeMap.MIMETYPE_PDF);
        if (transformer != null) {
            try {
                transformer.transform(reader, writer);
                reader = writer.getReader();
                fileName = fileName.substring(0, fileName.lastIndexOf('.'));
                fileName += ".pdf";
            } catch (ContentIOException ex) {
                logger.warn("could not transform content");
                logger.warn(ex);
                //need to refresh reader as the transformer failing closes the reader
                reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
            }
        }
    }
    try {
        buf = reader.getFileChannel().map(FileChannel.MapMode.READ_ONLY, 0, reader.getSize());
        if (reader.getSize() <= Integer.MAX_VALUE) {
            array = new byte[(int) reader.getSize()];
            buf.get(array);
        }
    } catch (IOException ex) {
        logger.error("There was an error reading file into memory.");
        logger.error(ex);
        array = new byte[0];
    }

    ByteArrayDataSource ds = new ByteArrayDataSource(array, reader.getMimetype());
    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setFileName(fileName);
    attachment.setDataHandler(new DataHandler(ds));
    content.addBodyPart(attachment);
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected String populateContentOnBodyPart(BodyPart part, MailConfiguration configuration, Exchange exchange)
        throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Using Content-Type " + contentType + " for BodyPart: " + part);
    }/*from  w w  w.  j  a  v a  2 s. c  o  m*/

    // always store content in a byte array data store to avoid various content type and charset issues
    DataSource ds = new ByteArrayDataSource(exchange.getIn().getBody(String.class), contentType);
    part.setDataHandler(new DataHandler(ds));

    // set the content type header afterwards
    part.setHeader("Content-Type", contentType);

    return contentType;
}

From source file:org.pentaho.reporting.engine.classic.extensions.modules.mailer.MailProcessor.java

public static MimeMessage createReport(final MailDefinition mailDefinition, final Session session,
        final DataRow parameters) throws ReportProcessingException, ContentIOException, MessagingException {
    final MasterReport bodyReport = mailDefinition.getBodyReport();
    final String[] paramNames = parameters.getColumnNames();
    final ReportParameterValues parameterValues = bodyReport.getParameterValues();
    for (int i = 0; i < paramNames.length; i++) {
        final String paramName = paramNames[i];
        if (isParameterDefined(bodyReport, paramName)) {
            parameterValues.put(paramName, parameters.get(paramName));
        }/*from w w w  .j  ava2  s  .  c o m*/
    }

    final ReportProcessTaskRegistry registry = ReportProcessTaskRegistry.getInstance();
    final String bodyType = mailDefinition.getBodyType();
    final ReportProcessTask processTask = registry.createProcessTask(bodyType);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ReportProcessTaskUtil.configureBodyStream(processTask, bout, "report", null);
    processTask.setReport(bodyReport);
    if (processTask instanceof MultiStreamReportProcessTask) {
        final MultiStreamReportProcessTask mtask = (MultiStreamReportProcessTask) processTask;
        mtask.setBulkLocation(mtask.getBodyContentLocation());
        mtask.setBulkNameGenerator(new DefaultNameGenerator(mtask.getBodyContentLocation(), "data"));
        mtask.setUrlRewriter(new MailURLRewriter());
    }
    processTask.run();
    if (processTask.isTaskSuccessful() == false) {
        if (processTask.isTaskAborted()) {
            logger.info("EMail Task received interrupt.");
            return null;
        } else {
            logger.info("EMail Task failed:", processTask.getError());
            throw new ReportProcessingException("EMail Task failed", processTask.getError());
        }
    }

    final EmailRepository repository = new EmailRepository(session);
    final MimeBodyPart messageBodyPart = repository.getBodypart();
    final ByteArrayDataSource dataSource = new ByteArrayDataSource(bout.toByteArray(),
            processTask.getReportMimeType());
    messageBodyPart.setDataHandler(new DataHandler(dataSource));

    final int attachmentsSize = mailDefinition.getAttachmentCount();
    for (int i = 0; i < attachmentsSize; i++) {
        final MasterReport report = mailDefinition.getAttachmentReport(i);
        final String type = mailDefinition.getAttachmentType(i);
        final ContentLocation location = repository.getRoot();
        final ContentLocation bulkLocation = location.createLocation("attachment-" + i);

        final ReportProcessTask attachmentProcessTask = registry.createProcessTask(type);
        attachmentProcessTask.setBodyContentLocation(bulkLocation);
        attachmentProcessTask.setBodyNameGenerator(new DefaultNameGenerator(bulkLocation, "report"));
        attachmentProcessTask.setReport(report);
        if (attachmentProcessTask instanceof MultiStreamReportProcessTask) {
            final MultiStreamReportProcessTask mtask = (MultiStreamReportProcessTask) attachmentProcessTask;
            mtask.setBulkLocation(bulkLocation);
            mtask.setBulkNameGenerator(new DefaultNameGenerator(bulkLocation, "data"));
            mtask.setUrlRewriter(new MailURLRewriter());
        }
        attachmentProcessTask.run();

        if (attachmentProcessTask.isTaskSuccessful() == false) {
            if (attachmentProcessTask.isTaskAborted()) {
                logger.info("EMail Task received interrupt.");
            } else {
                logger.info("EMail Task failed:", attachmentProcessTask.getError());
                throw new ReportProcessingException("EMail Task failed", attachmentProcessTask.getError());
            }
        }
    }

    return repository.getEmail();
}

From source file:javamailclient.GmailAPI.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email./* ww w .j  a  va 2  s  .  c o m*/
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:org.pentaho.platform.scheduler2.email.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {/*from   w  w w.j a  v  a  2  s  .co  m*/
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        if (attachment == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }

        ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

        if (body != null) {
            MimeBodyPart bodyMessagePart = new MimeBodyPart();
            bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
            multipart.addBodyPart(bodyMessagePart);
        }

        // attach the file to the message
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
        multipart.addBodyPart(attachmentBodyPart);

        // add the Multipart to the message
        msg.setContent(multipart);

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Validated
@Test/*from  ww  w  .j ava  2 s  .c o  m*/
public void testSetBase64Content() {
    try {
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage msg = factory.createMessage();
        AttachmentPart ap = msg.createAttachmentPart();

        String urlString = "http://ws.apache.org/images/project-logo.jpg";
        if (isNetworkedResourceAvailable(urlString)) {
            URL url = new URL(urlString);
            DataHandler dh = new DataHandler(url);
            //Create InputStream from DataHandler's InputStream
            InputStream is = dh.getInputStream();

            byte buf[] = IOUtils.getStreamAsByteArray(is);
            //Setting Content via InputStream for image/jpeg mime type
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Base64.encode(buf, 0, buf.length, bos);
            buf = bos.toByteArray();
            InputStream stream = new ByteArrayInputStream(buf);
            ap.setBase64Content(stream, "image/jpeg");

            //Getting Content.. should return InputStream object
            InputStream r = ap.getBase64Content();
            if (r != null) {
                if (r instanceof InputStream) {
                    //InputStream object was returned (ok)
                } else {
                    fail("Unexpected object was returned");
                }
            }
        }
    } catch (Exception e) {
        fail("Exception: " + e);
    }
}

From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java

/**
 * Prepares message prior to be sent via execute()-method, i.e. sets
 * properties such as protocol, authentication, etc.
 *
 * @return Message-object to be sent to execute()-method
 * @throws MessagingException/* w  w  w  .j a va2 s .  c o  m*/
 *             when problems constructing or sending the mail occur
 * @throws IOException
 *             when the mail content can not be read or truststore problems
 *             are detected
 */
public Message prepareMessage() throws MessagingException, IOException {

    Properties props = new Properties();

    String protocol = getProtocol();

    // set properties using JAF
    props.setProperty("mail." + protocol + ".host", smtpServer);
    props.setProperty("mail." + protocol + ".port", getPort());
    props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication));

    // set timeout
    props.setProperty("mail." + protocol + ".timeout", getTimeout());
    props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout());

    if (useStartTLS || useSSL) {
        try {
            String allProtocols = StringUtils
                    .join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " ");
            logger.info("Use ssl/tls protocols for mail: " + allProtocols);
            props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols);
        } catch (Exception e) {
            logger.error("Problem setting ssl/tls protocols for mail", e);
        }
    }

    if (enableDebug) {
        props.setProperty("mail.debug", "true");
    }

    if (useStartTLS) {
        props.setProperty("mail.smtp.starttls.enable", "true");
        if (enforceStartTLS) {
            // Requires JavaMail 1.4.2+
            props.setProperty("mail.smtp.starttls.require", "true");
        }
    }

    if (trustAllCerts) {
        if (useSSL) {
            props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    } else if (useLocalTrustStore) {
        File truststore = new File(trustStoreToUse);
        logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
        if (!truststore.exists()) {
            logger.info(
                    "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
            truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse);
            logger.info("load local truststore -Attempting to read truststore from:  "
                    + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                logger.info(
                        "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()
                                + ". Local truststore not available, aborting execution.");
                throw new IOException("Local truststore file not found. Also not available under : "
                        + truststore.getAbsolutePath());
            }
        }
        if (useSSL) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    }

    session = Session.getInstance(props, null);

    Message message;

    if (sendEmlMessage) {
        message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
    } else {
        message = new MimeMessage(session);
        // handle body and attachments
        Multipart multipart = new MimeMultipart();
        final int attachmentCount = attachments.size();
        if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
            if (attachmentCount == 1) { // i.e. mailBody is empty
                File first = attachments.get(0);
                InputStream is = null;
                try {
                    is = new BufferedInputStream(new FileInputStream(first));
                    message.setText(IOUtils.toString(is));
                } finally {
                    IOUtils.closeQuietly(is);
                }
            } else {
                message.setText(mailBody);
            }
        } else {
            BodyPart body = new MimeBodyPart();
            body.setText(mailBody);
            multipart.addBodyPart(body);
            for (File f : attachments) {
                BodyPart attach = new MimeBodyPart();
                attach.setFileName(f.getName());
                attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
                multipart.addBodyPart(attach);
            }
            message.setContent(multipart);
        }
    }

    // set from field and subject
    if (null != sender) {
        message.setFrom(new InternetAddress(sender));
    }

    if (null != replyTo) {
        InternetAddress[] to = new InternetAddress[replyTo.size()];
        message.setReplyTo(replyTo.toArray(to));
    }

    if (null != subject) {
        message.setSubject(subject);
    }

    if (receiverTo != null) {
        InternetAddress[] to = new InternetAddress[receiverTo.size()];
        receiverTo.toArray(to);
        message.setRecipients(Message.RecipientType.TO, to);
    }

    if (receiverCC != null) {
        InternetAddress[] cc = new InternetAddress[receiverCC.size()];
        receiverCC.toArray(cc);
        message.setRecipients(Message.RecipientType.CC, cc);
    }

    if (receiverBCC != null) {
        InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
        receiverBCC.toArray(bcc);
        message.setRecipients(Message.RecipientType.BCC, bcc);
    }

    for (int i = 0; i < headerFields.size(); i++) {
        Argument argument = (Argument) ((TestElementProperty) headerFields.get(i)).getObjectValue();
        message.setHeader(argument.getName(), argument.getValue());
    }

    message.saveChanges();
    return message;
}

From source file:com.jaspersoft.jasperserver.ws.axis2.ManagementServiceImpl.java

private static String marshalResponse(OperationResult or, Map datasources, boolean isEncapsulationDime) {

    String result = "";

    // First of all attach the attachments...
    if (datasources != null) {
        MessageContext msgContext = MessageContext.getCurrentContext();
        Message responseMessage = msgContext.getResponseMessage();

        log.debug("Encapsulation DIME? : " + isEncapsulationDime);

        if (isEncapsulationDime) {
            responseMessage.getAttachmentsImpl()
                    .setSendType(org.apache.axis.attachments.Attachments.SEND_TYPE_DIME);
        }//from w w w  . ja v  a 2  s.  c o m

        for (Iterator it = datasources.entrySet().iterator(); it.hasNext();) {
            try {
                Map.Entry entry = (Map.Entry) it.next();
                String name = (String) entry.getKey();
                DataSource datasource = (DataSource) entry.getValue();

                log.debug("Adding attachment: " + name + ", type: " + datasource.getContentType());

                DataHandler expectedDH = new DataHandler(datasource);

                javax.xml.soap.AttachmentPart attachPart = null;
                attachPart = responseMessage.createAttachmentPart(expectedDH);

                //javax.xml.soap.AttachmentPart ap2 = responseMessage.createAttachmentPart();
                //ap2.setContent( datasource.getInputStream(),  datasource.getContentType());
                attachPart.setContentId(name);
                responseMessage.addAttachmentPart(attachPart);

            } catch (Exception ex) {
                log.error("caught exception marshalling an OperationResult: " + ex.getMessage(), ex);
                // What to do?
                or.setReturnCode(1);
                or.setMessage("Error attaching a resource to the SOAP message: " + ex.getMessage());
            }
        }

    }

    try {
        StringWriter xmlStringWriter = new StringWriter();
        Marshaller.marshal(or, xmlStringWriter);
        if (log.isDebugEnabled()) {
            log.debug("Has descriptors: "
                    + ((or.getResourceDescriptors() == null || or.getResourceDescriptors().size() == 0) ? 0
                            : or.getResourceDescriptors().size()));
            log.debug("marshalled response");
            log.debug(xmlStringWriter.toString());
        }
        result = xmlStringWriter.toString();

    } catch (Exception ex) {
        log.error("caught exception marshalling an OperationResult: " + ex.getMessage(), ex);
        // What to do?
    }

    return result;
}