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:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogServiceIT.java

@Test(groups = "largeTests")
public void receivedErrorShouldQuarantineMessages() {

    // ------------------------------------------------------------
    // Inject two SHS messages with same corrId & contentId
    ShsLabel label1 = make(a(ShsLabel));
    ShsMessage message1 = make(a(ShsMessage, with(ShsMessage.label, label1)));
    messageLogService.saveMessage(message1);

    ShsLabel label2 = make(a(ShsLabel, with(corrId, label1.getCorrId()),
            with(content, make(a(Content, with(Content.contentId, label1.getContent().getContentId()))))));
    ShsMessage message2 = make(a(ShsMessage, with(ShsMessage.label, label2)));
    messageLogService.saveMessage(message2);

    // Assert//from   w ww  .jav  a2s.  co  m
    Query queryQuarantinedMessages = new Query(
            Criteria.where("label.corrId").is(label1.getCorrId()).and("label.content.contentId")
                    .is(label1.getContent().getContentId()).and("state").is(MessageState.QUARANTINED));
    List<ShsMessageEntry> list = mongoTemplate.find(queryQuarantinedMessages, ShsMessageEntry.class);
    assertEquals(list.size(), 0, "no messages should have been quarantined");

    // ------------------------------------------------------------
    // Build an error message correlating to the previous two messages
    ShsManagement shsManagement = new ShsManagement();
    shsManagement.setCorrId(label1.getCorrId());
    shsManagement.setContentId(label1.getContent().getContentId());
    Error error = shsManagementFactory.createError();
    error.setErrorcode("ERROR_CODE");
    error.setErrorinfo("ERROR_INFO");
    shsManagement.getConfirmationOrError().add(error);

    DataPart dp = new DataPart();
    dp.setDataPartType("error");
    dp.setContentType("text/xml");
    dp.setFileName("error.xml");
    ShsManagementMarshaller marshaller = new ShsManagementMarshaller();
    dp.setDataHandler(new DataHandler(marshaller.marshal(shsManagement), "text/xml"));

    ShsMessage errorMessage = make(a(ShsMessage, with(ShsMessage.label, make(a(ShsLabel)))));
    errorMessage.getDataParts().clear();
    errorMessage.getDataParts().add(dp);

    // Inject error message
    messageLogService.quarantineCorrelatedMessages(errorMessage);

    // Assert
    list = mongoTemplate.find(queryQuarantinedMessages, ShsMessageEntry.class);
    assertEquals(list.size(), 2, "both messages should have been quarantined");
}

From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogServiceIT.java

@Test(groups = "largeTests")
public void receivedConfirmShouldAcknowledgeMessages() {

    // ------------------------------------------------------------
    // Inject two SHS messages with same corrId & contentId
    ShsLabel label1 = make(a(ShsLabel));
    ShsMessage message1 = make(a(ShsMessage, with(ShsMessage.label, label1)));
    messageLogService.saveMessage(message1);

    ShsLabel label2 = make(a(ShsLabel, with(corrId, label1.getCorrId()),
            with(content, make(a(Content, with(Content.contentId, label1.getContent().getContentId()))))));
    ShsMessage message2 = make(a(ShsMessage, with(ShsMessage.label, label2)));
    messageLogService.saveMessage(message2);

    // Assert/*from ww w .j a  va  2 s.c  om*/
    Query queryAcknowledged = new Query(
            Criteria.where("label.corrId").is(label1.getCorrId()).and("label.content.contentId")
                    .is(label1.getContent().getContentId()).and("acknowledged").is(true));
    List<ShsMessageEntry> list = mongoTemplate.find(queryAcknowledged, ShsMessageEntry.class);
    assertEquals(list.size(), 0, "no message should have been acknowledged");

    // ------------------------------------------------------------
    // Build confirm message correlating to the previous two messages
    ShsManagement shsManagement = new ShsManagement();
    shsManagement.setCorrId(label1.getCorrId());
    shsManagement.setContentId(label1.getContent().getContentId());
    Confirmation confirmation = shsManagementFactory.createConfirmation();
    shsManagement.getConfirmationOrError().add(confirmation);

    DataPart dp = new DataPart();
    dp.setDataPartType("confirm");
    dp.setContentType("text/xml");
    dp.setFileName("confirm.xml");
    ShsManagementMarshaller marshaller = new ShsManagementMarshaller();
    dp.setDataHandler(new DataHandler(marshaller.marshal(shsManagement), "text/xml"));

    ShsMessage confirmMessage = make(a(ShsMessage, with(ShsMessage.label, make(a(ShsLabel)))));
    confirmMessage.getDataParts().clear();
    confirmMessage.getDataParts().add(dp);

    // Inject confirm message
    messageLogService.acknowledgeCorrelatedMessages(confirmMessage);

    // Assert
    list = mongoTemplate.find(queryAcknowledged, ShsMessageEntry.class);
    assertEquals(list.size(), 2, "both messages should have been acknowledged");
}

From source file:org.mule.DefaultMuleMessage.java

@Override
public void addOutboundAttachment(String name, Object object, String contentType) throws Exception {
    assertAccess(WRITE);/*from w w  w  .  ja  va  2s.c om*/
    DataHandler dh;
    if (object instanceof File) {
        if (contentType != null) {
            dh = new DataHandler(new FileInputStream((File) object), contentType);

        } else {
            dh = new DataHandler(new FileDataSource((File) object));
        }
    } else if (object instanceof URL) {
        if (contentType != null) {
            dh = new DataHandler(((URL) object).openStream(), contentType);
        } else {
            dh = new DataHandler((URL) object);
        }
    } else {
        dh = new DataHandler(object, contentType);
    }
    outboundAttachments.put(name, dh);
}

From source file:com.sonicle.webtop.mail.Service.java

public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave)
        throws Exception {
    MimeMessage msg = null;/*  w  w w .ja  v  a  2  s  .co m*/
    boolean success = true;

    String[] to = SimpleMessage.breakAddr(smsg.getTo());
    String[] cc = SimpleMessage.breakAddr(smsg.getCc());
    String[] bcc = SimpleMessage.breakAddr(smsg.getBcc());
    String replyTo = smsg.getReplyTo();

    msg = new MimeMessage(mainAccount.getMailSession());
    msg.setFrom(getInternetAddress(from));
    InternetAddress ia = null;

    //set the TO recipient
    for (int q = 0; q < to.length; q++) {
        //        Service.logger.debug("to["+q+"]="+to[q]);
        to[q] = to[q].replace(',', ' ');
        try {
            ia = getInternetAddress(to[q]);
        } catch (AddressException exc) {
            throw new AddressException(to[q]);
        }
        msg.addRecipient(Message.RecipientType.TO, ia);
    }

    //set the CC recipient
    for (int q = 0; q < cc.length; q++) {
        cc[q] = cc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(cc[q]);
        } catch (AddressException exc) {
            throw new AddressException(cc[q]);
        }
        msg.addRecipient(Message.RecipientType.CC, ia);
    }

    //set BCC recipients
    for (int q = 0; q < bcc.length; q++) {
        bcc[q] = bcc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(bcc[q]);
        } catch (AddressException exc) {
            throw new AddressException(bcc[q]);
        }
        msg.addRecipient(Message.RecipientType.BCC, ia);
    }

    //set reply to addr
    if (replyTo != null && replyTo.length() > 0) {
        Address[] replyaddr = new Address[1];
        replyaddr[0] = getInternetAddress(replyTo);
        msg.setReplyTo(replyaddr);
    }

    //add any header
    String headerLines[] = smsg.getHeaderLines();
    for (int i = 0; i < headerLines.length; ++i) {
        if (!headerLines[i].startsWith("Sonicle-reply-folder")) {
            msg.addHeaderLine(headerLines[i]);
        }
    }

    //add reply/references
    String inreplyto = smsg.getInReplyTo();
    String references[] = smsg.getReferences();
    String replyfolder = smsg.getReplyFolder();
    if (inreplyto != null) {
        msg.setHeader("In-Reply-To", inreplyto);
    }
    if (references != null && references[0] != null) {
        msg.setHeader("References", references[0]);
    }
    if (tosave) {
        if (replyfolder != null) {
            msg.setHeader("Sonicle-reply-folder", replyfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }

    //add forward data
    String forwardedfrom = smsg.getForwardedFrom();
    String forwardedfolder = smsg.getForwardedFolder();
    if (forwardedfrom != null) {
        msg.setHeader("Forwarded-From", forwardedfrom);
    }
    if (tosave) {
        if (forwardedfolder != null) {
            msg.setHeader("Sonicle-forwarded-folder", forwardedfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }
    //set the subject
    String subject = smsg.getSubject();
    try {
        //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null);
        subject = MimeUtility.encodeText(smsg.getSubject());
    } catch (Exception exc) {
    }
    msg.setSubject(subject);

    //set priority
    int priority = smsg.getPriority();
    if (priority != 3) {
        msg.setHeader("X-Priority", "" + priority);

        //set receipt
    }
    String receiptTo = from;
    try {
        receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null);
    } catch (Exception exc) {
    }
    if (smsg.getReceipt()) {
        msg.setHeader("Disposition-Notification-To", from);

        //see if there are any new attachments for the message
    }
    int noAttach;
    int newAttach;

    if (attachments == null) {
        newAttach = 0;
    } else {
        newAttach = attachments.size();
    }

    //get the array of the old attachments
    Part[] oldParts = smsg.getAttachments();

    //check if there are old attachments
    if (oldParts == null) {
        noAttach = 0;
    } else { //old attachments exist
        noAttach = oldParts.length;
    }

    if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) {
        // create the main Multipart
        MimeMultipart mp = new MimeMultipart("mixed");
        MimeMultipart unrelated = null;

        String textcontent = smsg.getTextContent();
        //if is text, or no alternative text is available, add the content as one single body part
        //else create a multipart/alternative with both rich and text mime content
        if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) {
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            mp.addBodyPart(mbp1);
        } else {
            MimeMultipart alternative = new MimeMultipart("alternative");
            //the rich part
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            //the text part
            MimeBodyPart mbp1 = new MimeBodyPart();

            /*          ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length());
             com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos);
             for(int i=0;i<textcontent.length();++i) {
             try {
             qpe.write(textcontent.charAt(i));
             } catch(IOException exc) {
             Service.logger.error("Exception",exc);
             }
             }
             textcontent=new String(bos.toByteArray());*/
            mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8"));
            //          mbp1.setHeader("Content-transfer-encoding","quoted-printable");

            alternative.addBodyPart(mbp1);
            alternative.addBodyPart(mbp2);

            MimeBodyPart altbody = new MimeBodyPart();
            altbody.setContent(alternative);

            mp.addBodyPart(altbody);
        }

        if (noAttach > 0) { //if there are old attachments
            // create the parts with the attachments
            //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach];
            //Part[] mbps2 = new Part[noAttach];

            //for(int e = 0;e < noAttach;e++) {
            //  mbps2[e] = (Part)oldParts[e];
            //}//end for e
            //add the old attachment parts
            for (int r = 0; r < noAttach; r++) {
                Object content = null;
                String contentType = null;
                String contentFileName = null;
                if (oldParts[r] instanceof Message) {
                    //                Service.logger.debug("Attachment is a message");
                    Message msgpart = (Message) oldParts[r];
                    MimeMessage mm = new MimeMessage(mainAccount.getMailSession());
                    mm.addFrom(msgpart.getFrom());
                    mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO));
                    mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC));
                    mm.setRecipients(Message.RecipientType.BCC,
                            msgpart.getRecipients(Message.RecipientType.BCC));
                    mm.setReplyTo(msgpart.getReplyTo());
                    mm.setSentDate(msgpart.getSentDate());
                    mm.setSubject(msgpart.getSubject());
                    mm.setContent(msgpart.getContent(), msgpart.getContentType());
                    content = mm;
                    contentType = "message/rfc822";
                } else {
                    //                Service.logger.debug("Attachment is not a message");
                    content = oldParts[r].getContent();
                    if (!(content instanceof MimeMultipart)) {
                        contentType = oldParts[r].getContentType();
                        contentFileName = oldParts[r].getFileName();
                    }
                }
                MimeBodyPart mbp = new MimeBodyPart();
                if (contentFileName != null) {
                    mbp.setFileName(contentFileName);
                    //              Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName);
                    contentType += "; name=\"" + contentFileName + "\"";
                }
                if (content instanceof MimeMultipart)
                    mbp.setContent((MimeMultipart) content);
                else
                    mbp.setDataHandler(new DataHandler(content, contentType));
                mp.addBodyPart(mbp);
            }

        } //end if, adding old attachments

        if (newAttach > 0) { //if there are new attachments
            // create the parts with the attachments
            MimeBodyPart[] mbps = new MimeBodyPart[newAttach];

            for (int e = 0; e < newAttach; e++) {
                mbps[e] = new MimeBodyPart();

                // attach the file to the message
                JsAttachment attach = (JsAttachment) attachments.get(e);
                UploadedFile upfile = getUploadedFile(attach.uploadId);
                FileDataSource fds = new FileDataSource(upfile.getFile());
                mbps[e].setDataHandler(new DataHandler(fds));
                // filename starts has format:
                // "_" + userid + sessionId + "_" + filename
                //
                if (attach.inline) {
                    mbps[e].setDisposition(Part.INLINE);
                }
                String contentFileName = attach.fileName.trim();
                mbps[e].setFileName(contentFileName);
                String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\"";
                mbps[e].setHeader("Content-type", contentType);
                if (attach.cid != null && attach.cid.trim().length() > 0) {
                    mbps[e].setHeader("Content-ID", "<" + attach.cid + ">");
                    mbps[e].setHeader("X-Attachment-Id", attach.cid);
                    mbps[e].setDisposition(Part.INLINE);
                    if (unrelated == null)
                        unrelated = new MimeMultipart("mixed");
                }
            } //end for e

            //add the new attachment parts
            if (unrelated == null) {
                for (int r = 0; r < newAttach; r++)
                    mp.addBodyPart(mbps[r]);
            } else {
                //mp becomes the related part with text parts and cids
                MimeMultipart related = mp;
                related.setSubType("related");
                //nest the related part into the mixed part
                mp = unrelated;
                MimeBodyPart mbd = new MimeBodyPart();
                mbd.setContent(related);
                mp.addBodyPart(mbd);
                for (int r = 0; r < newAttach; r++) {
                    if (mbps[r].getHeader("Content-ID") != null) {
                        related.addBodyPart(mbps[r]);
                    } else {
                        mp.addBodyPart(mbps[r]);
                    }
                }
            }

        } //end if, adding new attachments

        //
        //          msg.addHeaderLine("This is a multi-part message in MIME format.");
        // add the Multipart to the message
        msg.setContent(mp);

    } else { //end if newattach
        msg.setText(smsg.getContent());
    } //singlepart message

    msg.setSentDate(new java.util.Date());

    return msg;

}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRdbmsClientImpl.java

/**
 * Custom artifacts deployment. deploy capp related to RDBMS on DAS
 *
 * @param url  url of the DAS//w w  w.  j av  a 2 s .com
 * @param user user name
 * @param pass password
 * @throws Exception general exception throws, because different exception can occur
 */
@Override
public void deployArtifacts(String url, String user, String pass) throws Exception {

    //name of the capp to deploy
    String cAppName = "API_Manager_Analytics_RDBMS.car";
    String cAppPath = System.getProperty("carbon.home") + File.separator + "statistics";
    cAppPath = cAppPath + File.separator + cAppName;
    File file = new File(cAppPath);

    //get the byte array of file
    byte[] byteArray = FileUtils.readFileToByteArray(file);
    DataHandler dataHandler = new DataHandler(byteArray,
            APIUsageStatisticsClientConstants.APPLICATION_OCTET_STREAM);

    //create the stub to deploy artifacts
    CarbonAppUploaderStub stub = new CarbonAppUploaderStub(url + "/services/CarbonAppUploader");
    ServiceClient client = stub._getServiceClient();
    Options options = client.getOptions();
    //set the security
    HttpTransportProperties.Authenticator authenticator = new HttpTransportProperties.Authenticator();
    authenticator.setUsername(user);
    authenticator.setPassword(pass);
    authenticator.setPreemptiveAuthentication(true);
    options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, authenticator);
    client.setOptions(options);
    log.info("Deploying DAS cApp '" + cAppName + "'...");
    //create UploadedFileItem array and 1st element contain the deploy artifact
    UploadedFileItem[] fileItem = new UploadedFileItem[1];
    fileItem[0] = new UploadedFileItem();
    fileItem[0].setDataHandler(dataHandler);
    fileItem[0].setFileName(cAppName);
    fileItem[0].setFileType("jar");
    //upload the artifacts
    stub.uploadApp(fileItem);
}

From source file:de.innovationgate.wgpublisher.WGACore.java

public void send(WGAMailNotification notification) {
    WGAMailConfiguration config = getMailConfig();

    if (config != null && config.isEnableAdminNotifications()) {
        try {/*  www . ja v  a  2  s .  c om*/
            Message msg = new MimeMessage(config.createMailSession());

            // set recipient and from address
            String toAddress = config.getToAddress();
            if (toAddress == null) {
                getLog().error(
                        "Unable to send wga admin notification because no recipient address is configured");
                return;
            }

            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            InternetAddress[] fromAddr = new InternetAddress[1];
            fromAddr[0] = new InternetAddress(config.getFromAddress());
            msg.addFrom(fromAddr);

            msg.setSentDate(new Date());

            InetAddress localMachine = InetAddress.getLocalHost();
            String hostname = localMachine.getHostName();
            String serverName = getWgaConfiguration().getServerName();
            if (serverName == null) {
                serverName = hostname;
            }

            msg.setSubject(notification.getSubject());

            msg.setHeader(WGAMailNotification.HEADERFIELD_TYPE, notification.getType());

            MimeMultipart content = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();

            StringBuffer strBody = new StringBuffer();
            strBody.append("<html><head></head><body style=\"color:#808080\">");
            strBody.append(notification.getMessage());
            String rootURL = getWgaConfiguration().getRootURL();
            if (rootURL != null) {
                //strBody.append("<br><br>");
                strBody.append("<p><a href=\"" + rootURL + "/plugin-admin\">" + WGABrand.getName()
                        + " admin client ...</a></p>");
            }
            // append footer
            strBody.append("<br><br><b>System information:</b><br><br>");
            strBody.append("<b>Server:</b> " + serverName + " / " + WGACore.getReleaseString() + "<br>");
            strBody.append("<b>Host:</b> " + hostname + "<br>");
            strBody.append("<b>Operation System:</b> " + System.getProperty("os.name") + " Version "
                    + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")<br>");
            strBody.append("<b>Java virtual machine:</b> " + System.getProperty("java.vm.name") + " Version "
                    + System.getProperty("java.vm.version") + " (" + System.getProperty("java.vm.vendor")
                    + ")");

            strBody.append("</body></html>");
            body.setText(strBody.toString());
            body.setHeader("MIME-Version", "1.0");
            body.setHeader("Content-Type", "text/html");

            content.addBodyPart(body);
            AppLog appLog = WGA.get(this).service(AppLog.class);

            if (notification.isAttachLogfile()) {
                MimeBodyPart attachmentBody = new MimeBodyPart();

                StringWriter applog = new StringWriter();
                int applogSize = appLog.getLinesCount();
                int offset = applogSize - notification.getLogfileLines();
                if (offset < 0) {
                    offset = 1;
                }
                appLog.writePage(offset, notification.getLogfileLines(), applog, LogLevel.LEVEL_INFO, false);

                attachmentBody.setDataHandler(new DataHandler(applog.toString(), "text/plain"));
                attachmentBody.setFileName("wga.log");
                content.addBodyPart(attachmentBody);
            }
            msg.setContent(content);

            // Send mail
            Thread mailThread = new Thread(new AsyncMailSender(msg), "WGAMailSender");
            mailThread.start();
        } catch (Exception e) {
            getLog().error("Unable to send wga admin notification.", e);
        }
    }
}