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(Object obj, String mimeType) 

Source Link

Document

Create a DataHandler instance representing an object of this MIME type.

Usage

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

@Validated
@Test// w  w  w . jav  a  2 s  .c  om
public void testMultipleAttachments() throws Exception {

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage msg = factory.createMessage();

    AttachmentPart a1 = msg.createAttachmentPart(new DataHandler("<some_xml/>", "text/xml"));
    a1.setContentType("text/xml");
    msg.addAttachmentPart(a1);
    AttachmentPart a2 = msg.createAttachmentPart(new DataHandler("<some_xml/>", "text/xml"));
    a2.setContentType("text/xml");
    msg.addAttachmentPart(a2);
    AttachmentPart a3 = msg.createAttachmentPart(new DataHandler("text", "text/plain"));
    a3.setContentType("text/plain");
    msg.addAttachmentPart(a3);

    assertTrue(msg.countAttachments() == 3);

    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-Type", "text/xml");

    int nAttachments = 0;
    Iterator iterator = msg.getAttachments(mimeHeaders);
    while (iterator.hasNext()) {
        nAttachments++;
        AttachmentPart ap = (AttachmentPart) iterator.next();
        assertTrue(ap.equals(a1) || ap.equals(a2));
    }
    assertTrue(nAttachments == 2);
}

From source file:org.apache.axis2.mtom.EchoRawMTOMLoadTest.java

protected OMElement createEnvelope() {

    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://localhost/my", "my");
    OMElement rpcWrapEle = fac.createOMElement("echoOMElement", omNs);
    OMElement data = fac.createOMElement("data", omNs);
    expectedByteArray = new byte[] { 13, 56, 65, 32, 12, 12, 7, -3, -2, -1, 98 };
    for (int i = 0; i < 4; i++) {
        OMElement subData = fac.createOMElement("subData", omNs);
        DataHandler dataHandler = new DataHandler("Thilina", "text/plain");
        //new ByteArrayDataSource(expectedByteArray));
        textData = new OMTextImpl(dataHandler, true, fac);
        subData.addChild(textData);//  ww  w. j  a  v  a2 s .  c  om
        data.addChild(subData);

    }

    rpcWrapEle.addChild(data);
    return rpcWrapEle;
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.Attachment.java

private static DataHandler createDataHandler(Object value, Class cls, String[] mimeTypes, String cid) {
    if (log.isDebugEnabled()) {
        System.out.println("Construct data handler for " + cls + " cid=" + cid);
    }//w w  w .  j  a  va 2  s  . c  om
    DataHandler dh = null;
    if (cls.isAssignableFrom(DataHandler.class)) {
        dh = (DataHandler) value;
        if (dh == null) {
            return dh; //return if DataHandler is null
        }

        try {
            Object content = dh.getContent();
            // If the content is a Source, convert to a String due to 
            // problems with the DataContentHandler
            if (content instanceof Source) {
                if (log.isDebugEnabled()) {
                    System.out
                            .println("Converting DataHandler Source content to " + "DataHandlerString content");
                }
                byte[] bytes = (byte[]) ConvertUtils.convert(content, byte[].class);
                String newContent = new String(bytes);
                return new DataHandler(newContent, mimeTypes[0]);
            }
        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    } else {
        try {
            byte[] bytes = createBytes(value, cls, mimeTypes);
            // Create MIME Body Part
            InternetHeaders ih = new InternetHeaders();
            ih.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, mimeTypes[0]);
            MimeBodyPart mbp = new MimeBodyPart(ih, bytes);

            //Create a data source for the MIME Body Part
            MimePartDataSource ds = new MimePartDataSource(mbp);

            dh = new DataHandler(ds);
            mbp.setHeader(HTTPConstants.HEADER_CONTENT_ID, cid);
        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }
    return dh;
}

From source file:org.apache.cxf.systest.aegis.mtom.MtomTest.java

@Test
public void testAcceptDataHandler() throws Exception {
    setupForTest(true);/*from  w  ww.  j  a  va2 s .co m*/
    DataHandlerBean dhBean = new DataHandlerBean();
    dhBean.setName("some name");
    // some day, we might need this to be higher than some threshold.
    String someData = "This is the cereal shot from guns.";
    DataHandler dataHandler = new DataHandler(someData, "text/plain;charset=utf-8");
    dhBean.setDataHandler(dataHandler);
    client.acceptDataHandler(dhBean);
    DataHandlerBean accepted = impl.getLastDhBean();
    Assert.assertNotNull(accepted);
    Object o = accepted.getDataHandler().getContent();
    String data = null;
    if (o instanceof String) {
        data = (String) o;
    } else if (o instanceof InputStream) {
        data = IOUtils.toString((InputStream) o);
    }
    Assert.assertNotNull(data);
    Assert.assertEquals("This is the cereal shot from guns.", data);
}

From source file:org.openmrs.module.reporting.report.processor.EmailReportProcessor.java

/**
 * Performs some action on the given report
 * @param report the Report to process//from   w  w w .j  a  v a 2 s  .  co m
 */
public void process(Report report, Properties configuration) {

    try {
        Message m = new MimeMessage(getSession());

        m.setFrom(new InternetAddress(configuration.getProperty("from")));
        for (String recipient : configuration.getProperty("to", "").split("\\,")) {
            m.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        // TODO: Make these such that they can contain report information
        m.setSubject(configuration.getProperty("subject"));

        Multipart multipart = new MimeMultipart();

        MimeBodyPart contentBodyPart = new MimeBodyPart();
        String content = configuration.getProperty("content", "");
        if (report.getRenderedOutput() != null
                && "true".equalsIgnoreCase(configuration.getProperty("addOutputToContent"))) {
            content += new String(report.getRenderedOutput());
        }
        contentBodyPart.setContent(content, "text/html");
        multipart.addBodyPart(contentBodyPart);

        if (report.getRenderedOutput() != null
                && "true".equalsIgnoreCase(configuration.getProperty("addOutputAsAttachment"))) {
            MimeBodyPart attachment = new MimeBodyPart();
            Object output = report.getRenderedOutput();
            if (report.getOutputContentType().contains("text")) {
                output = new String(report.getRenderedOutput(), "UTF-8");
            }
            attachment.setDataHandler(new DataHandler(output, report.getOutputContentType()));
            attachment.setFileName(configuration.getProperty("attachmentName"));
            multipart.addBodyPart(attachment);
        }

        m.setContent(multipart);

        Transport.send(m);
    } catch (Exception e) {
        throw new RuntimeException("Error occurred while sending report over email", e);
    }
}

From source file:org.apache.cxf.systest.aegis.mtom.MtomTest.java

@Test
public void testAcceptDataHandlerNoMTOM() throws Exception {
    setupForTest(false);/*  w w w.  j a  va 2  s .  co  m*/
    DataHandlerBean dhBean = new DataHandlerBean();
    dhBean.setName("some name");
    // some day, we might need this to be longer than some threshold.
    String someData = "This is the cereal shot from guns.";
    DataHandler dataHandler = new DataHandler(someData, "text/plain;charset=utf-8");
    dhBean.setDataHandler(dataHandler);
    client.acceptDataHandler(dhBean);
    DataHandlerBean accepted = impl.getLastDhBean();
    Assert.assertNotNull(accepted);
    InputStream data = accepted.getDataHandler().getInputStream();
    Assert.assertNotNull(data);
    String dataString = org.apache.commons.io.IOUtils.toString(data, "utf-8");
    Assert.assertEquals("This is the cereal shot from guns.", dataString);
}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test/*from   ww w . j  a v  a  2  s. c  om*/
public void testWriteToWithAttachment() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    message.getSOAPPart().getEnvelope().getBody().addBodyElement(new QName("urn:ns", "test", "p"));
    AttachmentPart attachment = message.createAttachmentPart();
    attachment.setDataHandler(new DataHandler("This is a test", "text/plain; charset=iso-8859-15"));
    message.addAttachmentPart(attachment);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    System.out.write(baos.toByteArray());
    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), "multipart/related"));
    assertEquals(2, mp.getCount());
    BodyPart part1 = mp.getBodyPart(0);
    // TODO
    //        assertEquals(messageSet.getVersion().getContentType(), part1.getContentType());
    BodyPart part2 = mp.getBodyPart(1);
    // Note: text/plain is the default content type, so we need to include the parameters in the assertion
    assertEquals("text/plain; charset=iso-8859-15", part2.getContentType());
}

From source file:org.sciflex.plugins.synapse.esper.mediators.helpers.EPLStatementHelper.java

/**
 * Changes EPL query./*from w  w w.  ja v  a2s .co  m*/
 *
 * @param query    EPL query.
 * @param registry Registry to use.
 */
public void setEPL(String query, Registry registry) {
    if (registryKey == null) {
        eplStatement = query;
        synchronized (statementLock) {
            statement = provider.getEPAdministrator().createEPL(eplStatement);
            queryActivityMonitor.notify(eplStatement);
        }
        if (listener != null)
            addListener(listener);
    } else if (registry == null) {
        log.error("Cannot lookup Registry");
    } else {
        // You can't fetch while updating. And if you try to do so
        // you may end up getting an incorrect result. Also, changes
        // to registryKey during the process is not allowed.
        synchronized (registryFetchLock) {
            OMNode eplNode = registry.lookup(registryKey);
            OMNode eplNodeNew = null;
            if (eplNode == null) {
                log.error("Registry lookup for EPL statement failed");
            } else if (eplNode instanceof OMElement) {
                ((OMElement) eplNode).getAttribute(new QName("value")).setAttributeValue(eplStatement);
                eplNodeNew = eplNode;
            } else if (eplNode instanceof OMText) {
                DataHandler dh = (DataHandler) (((OMText) eplNode).getDataHandler());
                if (dh == null) {
                    log.error("Error getting EPL statement");
                } else {
                    DataHandler dhNew = null;
                    try {
                        Object content = dh.getContent();
                        if (content instanceof InputStream) {
                            dhNew = new DataHandler(new ByteArrayInputStream(eplStatement.getBytes("UTF-8")),
                                    dh.getContentType());
                        } else if (content instanceof String)
                            dhNew = new DataHandler(eplStatement, dh.getContentType());
                        else {
                            log.error("Content fetched from Registry is not valid");
                        }
                        if (dhNew != null) {
                            OMFactory omFactory = OMAbstractFactory.getOMFactory();
                            eplNodeNew = omFactory.createOMText(dhNew, false);
                        } else {
                            log.error("Failed Creating Data Handler");
                        }
                    } catch (IOException e) {
                        log.error("An error occured while changing EPL statement " + e.getMessage());
                    }
                }
            } else
                log.error("Invalid EPL statement object retrieved");
            if (eplNodeNew == null) {
                log.error("An error occured while changing EPL statement");
            } else {
                updateRegistryResource(registryKey, eplNodeNew, registry);
                synchronized (expiryTimeLock) {
                    expiryTime = 0L;
                }
            }
        }
    }
    log.info("EPL Statement successfully changed");
}

From source file:org.apache.synapse.transport.mail.MailTransportSender.java

/**
 * Populate email with a SOAP formatted message
 * @param outInfo the out transport information holder
 * @param msgContext the message context that holds the message to be written
 * @throws AxisFault on error// w  ww.  ja va2s .  co m
 */
private void sendMail(MailOutTransportInfo outInfo, MessageContext msgContext)
        throws AxisFault, MessagingException, IOException {

    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    MessageFormatter messageFormatter = null;

    try {
        messageFormatter = TransportUtils.getMessageFormatter(msgContext);
    } catch (AxisFault axisFault) {
        throw new BaseTransportException("Unable to get the message formatter to use");
    }

    WSMimeMessage message = new WSMimeMessage(session);
    Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    // set From address - first check if this is a reply, then use from address from the
    // transport out, else if any custom transport headers set on this message, or default
    // to the transport senders default From address        
    if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) {
        message.setFrom(outInfo.getFromAddress());
        message.setReplyTo((new Address[] { outInfo.getFromAddress() }));
    } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) {
        message.setFrom(new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM)));
        message.setReplyTo(InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM)));
    } else {
        if (smtpFromAddress != null) {
            message.setFrom(smtpFromAddress);
            message.setReplyTo(new Address[] { smtpFromAddress });
        } else {
            handleException("From address for outgoing message cannot be determined");
        }
    }

    // set To address/es to any custom transport header set on the message, else use the reply
    // address from the out transport information
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) {
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO)));
    } else if (outInfo.getTargetAddresses() != null) {
        message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses());
    } else {
        handleException("To address for outgoing message cannot be determined");
    }

    // set Cc address/es to any custom transport header set on the message, else use the
    // Cc list from original request message
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) {
        message.setRecipients(Message.RecipientType.CC,
                InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC)));
    } else if (outInfo.getTargetAddresses() != null) {
        message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses());
    }

    // set Bcc address/es to any custom addresses set at the transport sender level + any
    // custom transport header
    InternetAddress[] trpBccArr = null;
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) {
        trpBccArr = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC));
    }

    InternetAddress[] mergedBcc = new InternetAddress[(trpBccArr != null ? trpBccArr.length : 0)
            + (smtpBccAddresses != null ? smtpBccAddresses.length : 0)];
    if (trpBccArr != null) {
        System.arraycopy(trpBccArr, 0, mergedBcc, 0, trpBccArr.length);
    }
    if (smtpBccAddresses != null) {
        System.arraycopy(smtpBccAddresses, 0, mergedBcc, mergedBcc.length, smtpBccAddresses.length);
    }
    if (mergedBcc != null) {
        message.setRecipients(Message.RecipientType.BCC, mergedBcc);
    }

    // set subject
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) {
        message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT));
    } else if (outInfo.getSubject() != null) {
        message.setSubject(outInfo.getSubject());
    } else {
        message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction());
    }

    // if a custom message id is set, use it
    if (msgContext.getMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID());
    }

    // if this is a reply, set reference to original message
    if (outInfo.getRequestMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID());

    } else {
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) {
            message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO));
        }
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) {
            message.setHeader(MailConstants.MAIL_HEADER_REFERENCES,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES));
        }
    }

    // set Date
    message.setSentDate(new Date());

    // set SOAPAction header
    message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());

    // write body
    ByteArrayOutputStream baos = null;
    String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction());
    DataHandler dataHandler = null;
    MimeMultipart mimeMultiPart = null;

    OMElement firstChild = msgContext.getEnvelope().getBody().getFirstElement();
    if (firstChild != null) {

        if (BaseConstants.DEFAULT_BINARY_WRAPPER.equals(firstChild.getQName())) {
            baos = new ByteArrayOutputStream();
            OMNode omNode = firstChild.getFirstOMChild();

            if (omNode != null && omNode instanceof OMText) {
                Object dh = ((OMText) omNode).getDataHandler();
                if (dh != null && dh instanceof DataHandler) {
                    dataHandler = (DataHandler) dh;
                }
            }
        } else if (BaseConstants.DEFAULT_TEXT_WRAPPER.equals(firstChild.getQName())) {
            if (firstChild instanceof OMSourcedElementImpl) {
                baos = new ByteArrayOutputStream();
                try {
                    firstChild.serializeAndConsume(baos);
                } catch (XMLStreamException e) {
                    handleException("Error serializing 'text' payload from OMSourcedElement", e);
                }
                dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()),
                        MailConstants.TEXT_PLAIN);
            } else {
                dataHandler = new DataHandler(firstChild.getText(), MailConstants.TEXT_PLAIN);
            }
        } else {

            baos = new ByteArrayOutputStream();
            messageFormatter.writeTo(msgContext, format, baos, true);

            // create the data handler
            dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()),
                    contentType);

            String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT);
            if (mFormat == null) {
                mFormat = defaultMailFormat;
            }

            if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) {
                mimeMultiPart = new MimeMultipart();
                MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
                mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
                MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
                mimeBodyPart2.setDataHandler(dataHandler);
                mimeBodyPart2.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
                mimeMultiPart.addBodyPart(mimeBodyPart1);
                mimeMultiPart.addBodyPart(mimeBodyPart2);

            } else {
                message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
            }
        }
    }

    try {
        if (mimeMultiPart == null) {
            message.setDataHandler(dataHandler);
        } else {
            message.setContent(mimeMultiPart);
        }
        Transport.send(message);

    } catch (MessagingException e) {
        handleException("Error creating mail message or sending it to the configured server", e);

    } finally {
        try {
            if (baos != null) {
                baos.close();
            }
        } catch (IOException ignore) {
        }
    }
}

From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

protected DataHandler createDataHandler(AttachmentTemplate attachmentTemplate, WorkItem workItem,
        JCRSessionWrapper session) throws Exception {
    // evaluate expression
    String expression = attachmentTemplate.getExpression();
    if (expression != null) {
        Object object = evaluateExpression(workItem, expression, session);
        return new DataHandler(object, attachmentTemplate.getMimeType());
    }//from ww w  .jav a 2  s .  c  o  m

    // resolve local file
    String file = attachmentTemplate.getFile();
    if (file != null) {
        File targetFile = new File(evaluateExpression(workItem, file, session));
        if (!targetFile.isFile()) {
            throw new Exception("could not read attachment content, file not found: " + targetFile);
        }
        // set content from file
        return new DataHandler(new FileDataSource(targetFile));
    }

    // resolve external url
    URL targetUrl;
    String url = attachmentTemplate.getUrl();
    if (url != null) {
        url = evaluateExpression(workItem, url, session);
        targetUrl = new URL(url);
    }
    // resolve classpath resource
    else {
        String resource = evaluateExpression(workItem, attachmentTemplate.getResource(), session);
        targetUrl = Thread.currentThread().getContextClassLoader().getResource(resource);
        if (targetUrl == null) {
            throw new Exception("could not read attachment content, resource not found: " + resource);
        }
    }
    // set content from url
    return new DataHandler(targetUrl);
}