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:com.knowgate.dfs.FileSystem.java

private static void copyHTTPToFile(String sSource, String sTarget) throws MalformedURLException, IOException {
    URL oUrl = new URL(sSource);
    FileOutputStream oTrgt = new FileOutputStream(sTarget.substring(7));
    DataHandler oHndlr = new DataHandler(oUrl);
    oHndlr.writeTo(oTrgt);//from   w w w .j  a v  a2  s .  c om
    oTrgt.close();
}

From source file:de.kp.ames.web.function.security.SecurityServiceImpl.java

/**
 * A helper method to update an existing password safe
 * //from   ww  w  . j a va2 s. co  m
 * @param service
 * @param creds
 * @param safe
 * @throws JSONException 
 * @throws JAXRException 
 * @throws UnsupportedCapabilityException 
 * @throws IOException 
 */
private void updateSafe(String service, String creds, ExtrinsicObjectImpl safe)
        throws JSONException, UnsupportedCapabilityException, JAXRException, IOException {

    JaxrTransaction transaction = new JaxrTransaction();
    /* 
     * Create credentials as JSON object
     */
    JSONObject jCredentials = new JSONObject(creds);

    DataHandler handler = safe.getRepositoryItem();
    if (handler == null)
        return;

    byte[] bytes = FileUtil.getByteArrayFromInputStream(handler.getInputStream());
    JSONObject jSafe = new JSONObject(new String(bytes));

    /* 
     * Update password safe
     */
    jSafe.put(service, jCredentials);

    bytes = jSafe.toString().getBytes("UTF-8");
    handler = new DataHandler(FileUtil.createByteArrayDataSource(bytes, "application/json"));

    safe.setRepositoryItem(handler);
    transaction.addObjectToSave(safe);

    JaxrLCM lcm = new JaxrLCM(jaxrHandle);
    lcm.saveObjects(transaction.getObjectsToSave(), false, false);

}

From source file:immf.MyHtmlEmail.java

/**
 * Embeds the specified <code>DataSource</code> in the HTML using the
 * specified Content-ID. Returns the specified Content-ID string.
 *
 * @param dataSource the <code>DataSource</code> to embed
 * @param name the name that will be set in the filename header field
 * @param cid the Content-ID to use for this <code>DataSource</code>
 * @return the supplied Content-ID for this <code>DataSource</code>
 * @throws EmailException if the embedding fails or if <code>name</code> is
 * null or empty/*from w  w w  .j a  v  a 2s.c o m*/
 * @since 1.1
 */
public String embed(DataSource dataSource, String name, String cid) throws EmailException {
    if (StringUtils.isEmpty(name)) {
        throw new EmailException("name cannot be null or empty");
    }

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(dataSource));
        mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.setContentID("<" + cid + ">");

        InlineImage ii = new InlineImage(cid, dataSource, mbp);
        this.inlineEmbeds.put(name, ii);

        return cid;
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}

From source file:org.apache.axis2.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//from w  w w  .  j  av  a2s .  c om
 * @return id of the send mail message
 */
private String sendMail(MailOutTransportInfo outInfo, MessageContext msgContext)
        throws AxisFault, MessagingException, IOException {

    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    // Make sure that non textual attachements are sent with base64 transfer encoding
    // instead of binary.
    format.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS, true);

    MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext);

    if (log.isDebugEnabled()) {
        log.debug(
                "Creating MIME message using message formatter " + messageFormatter.getClass().getSimpleName());
    }

    WSMimeMessage message = null;
    if (outInfo.getFromAddress() != null) {
        message = new WSMimeMessage(session, outInfo.getFromAddress().getAddress());
    } else {
        message = new WSMimeMessage(session, "");
    }

    Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (log.isDebugEnabled() && trpHeaders != null) {
        log.debug("Using transport headers: " + trpHeaders);
    }

    // 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) {
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + outInfo.getFromAddress().getAddress()
                    + " from OutTransportInfo");
        }
        message.setFrom(outInfo.getFromAddress());
        message.setReplyTo((new Address[] { outInfo.getFromAddress() }));
    } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) {
        InternetAddress from = new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM));
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + from.getAddress() + " from transport headers");
        }
        message.setFrom(from);
        message.setReplyTo(new Address[] { from });
    } else {
        if (smtpFromAddress != null) {
            if (log.isDebugEnabled()) {
                log.debug("Setting From header to " + smtpFromAddress.getAddress()
                        + " from transport configuration");
            }
            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)) {
        Address[] to = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO));
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(to) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.TO, to);
    } else if (outInfo.getTargetAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(outInfo.getTargetAddresses())
                    + " from OutTransportInfo");
        }
        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)) {
        Address[] cc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC));
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(cc) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.CC, cc);
    } else if (outInfo.getCcAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(outInfo.getCcAddresses())
                    + " from OutTransportInfo");
        }
        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
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) {
        InternetAddress[] bcc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC));
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(bcc) + " from transport headers");
        }
        message.addRecipients(Message.RecipientType.BCC, bcc);
    }
    if (smtpBccAddresses != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(smtpBccAddresses)
                    + " from transport configuration");
        }
        message.addRecipients(Message.RecipientType.BCC, smtpBccAddresses);
    }

    // set subject
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)
                    + "' from transport headers");
        }
        message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT));
    } else if (outInfo.getSubject() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + outInfo.getSubject() + "' from transport headers");
        }
        message.setSubject(outInfo.getSubject());
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Generating default Subject header from SOAP action");
        }
        message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction());
    }

    //TODO: use a combined message id for smtp so that it generates a unique id while
    // being able to support asynchronous communication.
    // 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
    MessageFormatterEx messageFormatterEx;
    if (messageFormatter instanceof MessageFormatterEx) {
        messageFormatterEx = (MessageFormatterEx) messageFormatter;
    } else {
        messageFormatterEx = new MessageFormatterExAdapter(messageFormatter);
    }

    DataHandler dataHandler = new DataHandler(
            messageFormatterEx.getDataSource(msgContext, format, msgContext.getSoapAction()));

    MimeMultipart mimeMultiPart = null;

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

    if (log.isDebugEnabled()) {
        log.debug("Using mail format '" + mFormat + "'");
    }

    MimePart mainPart;
    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();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);
        mainPart = mimeBodyPart2;
    } else if (MailConstants.TRANSPORT_FORMAT_ATTACHMENT.equals(mFormat)) {
        mimeMultiPart = new MimeMultipart();
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
        MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);

        String fileName = (String) msgContext.getProperty(MailConstants.TRANSPORT_FORMAT_ATTACHMENT_FILE);
        if (fileName != null) {
            mimeBodyPart2.setFileName(fileName);
        } else {
            mimeBodyPart2.setFileName("attachment");
        }

        mainPart = mimeBodyPart2;
    } else {
        mainPart = message;
    }

    try {
        mainPart.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
        mainPart.setDataHandler(dataHandler);

        // AXIOM's idea of what is textual also includes application/xml and
        // application/soap+xml (which JavaMail considers as binary). For these content types
        // always use quoted-printable transfer encoding. Note that JavaMail is a bit smarter
        // here because it can choose between 7bit and quoted-printable automatically, but it
        // needs to scan the entire content to determine this.
        if (msgContext.getOptions().getProperty("Content-Transfer-Encoding") != null) {
            mainPart.setHeader("Content-Transfer-Encoding",
                    (String) msgContext.getOptions().getProperty("Content-Transfer-Encoding"));
        } else {
            String contentType = dataHandler.getContentType().toLowerCase();
            if (!contentType.startsWith("multipart/") && CommonUtils.isTextualPart(contentType)) {
                mainPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
            }
        }

        //setting any custom headers defined by the user
        if (msgContext.getOptions().getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS) != null) {
            Map customTransportHeaders = (Map) msgContext.getOptions()
                    .getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS);
            for (Object header : customTransportHeaders.keySet()) {
                mainPart.setHeader((String) header, (String) customTransportHeaders.get(header));
            }
        }

        log.debug("Sending message");
        Transport.send(message);

        // update metrics
        metrics.incrementMessagesSent(msgContext);
        long bytesSent = message.getBytesSent();
        if (bytesSent != -1) {
            metrics.incrementBytesSent(msgContext, bytesSent);
        }

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

    }
    return message.getMessageID();
}

From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java

public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) {
    // Retrieve SMTP server information
    String host = getSmtpHost();/*from   w  w w  .j ava  2s  . com*/
    boolean isSmtpAuthentication = isSmtpAuthentication();
    int smtpPort = getSmtpPort();
    String smtpUser = getSmtpUser();
    String smtpPwd = getSmtpPwd();
    boolean isSmtpDebug = isSmtpDebug();

    List<String> emailErrors = new ArrayList<String>();

    if (emails.size() > 0) {

        // Corps et sujet du message
        String subject = getString("infoLetter.emailSubject") + ilp.getName();
        // Email du publieur
        String from = getUserDetail().geteMail();
        // create some properties and get the default Session
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication));

        Session session = Session.getInstance(props, null);
        session.setDebug(isSmtpDebug); // print on the console all SMTP messages.

        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "subject = " + subject);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "from = " + from);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "host= " + host);

        try {
            // create a message
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setSubject(subject, CharEncoding.UTF_8);
            ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId());
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg,
                            I18NHelper.defaultLanguage);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            for (SimpleDocument content : contents) {
                AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(),
                        content.getLanguage());
            }
            mbp1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(
                            replaceFileServerWithLocal(
                                    IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server),
                            MimeTypes.HTML_MIME_TYPE)));
            IOUtils.closeQuietly(buffer);
            // Fichiers joints
            WAPrimaryKey publiPK = ilp.getPK();
            publiPK.setComponentName(getComponentId());
            publiPK.setSpace(getSpaceId());

            // create the Multipart and its parts to it
            String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related");
            Multipart mp = new MimeMultipart(mimeMultipart);
            mp.addBodyPart(mbp1);

            // Images jointes
            List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null);
            for (SimpleDocument attachment : fichiers) {
                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                // attach the file to the message
                FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                mbp2.setDataHandler(new DataHandler(fds));
                // For Displaying images in the mail
                mbp2.setFileName(attachment.getFilename());
                mbp2.setHeader("Content-ID", attachment.getFilename());
                SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                        "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                // create the Multipart and its parts to it
                mp.addBodyPart(mbp2);
            }

            // Fichiers joints
            fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null);

            if (!fichiers.isEmpty()) {
                for (SimpleDocument attachment : fichiers) {
                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(attachment.getFilename());
                    // For Displaying images in the mail
                    mbp2.setHeader("Content-ID", attachment.getFilename());
                    SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                    // create the Multipart and its parts to it
                    mp.addBodyPart(mbp2);
                }
            }

            // add the Multipart to the message
            msg.setContent(mp);
            // set the Date: header
            msg.setSentDate(new Date());
            // create a Transport connection (TCP)
            Transport transport = session.getTransport("smtp");

            InternetAddress[] address = new InternetAddress[1];
            for (String email : emails) {
                try {
                    address[0] = new InternetAddress(email);
                    msg.setRecipients(Message.RecipientType.TO, address);
                    // add Transport Listener to the transport connection.
                    if (isSmtpAuthentication) {
                        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                "root.MSG_GEN_PARAM_VALUE",
                                "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser);
                        transport.connect(host, smtpPort, smtpUser, smtpPwd);
                        msg.saveChanges();
                    } else {
                        transport.connect();
                    }
                    transport.sendMessage(msg, address);
                } catch (Exception ex) {
                    SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "Email = " + email,
                            new InfoLetterException(
                                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                                    SilverpeasRuntimeException.ERROR, ex.getMessage(), ex));
                    emailErrors.add(email);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (Exception e) {
                            SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                    "root.EX_IGNORED", "ClosingTransport", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new InfoLetterException(
                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                    SilverpeasRuntimeException.ERROR, e.getMessage(), e);
        }
    }
    return emailErrors.toArray(new String[emailErrors.size()]);
}

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 ww w .  ja  v a2 s.c o m*/

    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.cloud.bridge.io.S3CAStorBucketAdapter.java

@Override
public DataHandler loadObject(String mountedRoot, String bucket, String fileName) {
    try {//  w  w w. ja  v a  2s  . co m
        return new DataHandler(new URL(castorURL(mountedRoot, bucket, fileName)));
    } catch (MalformedURLException e) {
        s_logger.error("Failed to loadObject from CAStor", e);
        throw new FileNotExistException("Unable to load object from CAStor: " + e.getMessage());
    }
}

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   ww w.j a v  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"));
}

From source file:org.kuali.kra.s2s.service.impl.KRAS2SServiceImpl.java

/**
 * This method is used to submit forms to Grants.gov. It generates forms for
 * a given {@link ProposalDevelopmentDocument}, validates and then submits
 * the forms// w w w .  j  ava2 s  .c o m
 * 
 * @param pdDoc
 *            Proposal Development Document.
 * @return true if submitted false otherwise.
 * @throws S2SException
 * @see org.kuali.kra.s2s.service.S2SService#submitApplication(org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument)
 */
public boolean submitApplication(ProposalDevelopmentDocument pdDoc) throws S2SException {
    boolean submissionStatus = false;
    Forms forms = Forms.Factory.newInstance();
    List<AttachmentData> attList = new ArrayList<AttachmentData>();
    if (generateAndValidateForms(forms, attList, pdDoc)) {
        GrantApplicationDocument grantApplicationDocument = getGrantApplicationDocument(pdDoc, forms);

        Map<String, DataHandler> attachments = new HashMap<String, DataHandler>();
        List<S2sAppAttachments> s2sAppAttachmentList = new ArrayList<S2sAppAttachments>();
        DataHandler attachmentFile;
        for (AttachmentData attachmentData : attList) {
            attachmentFile = new DataHandler(
                    new ByteArrayDataSource(attachmentData.getContent(), attachmentData.getContentType()));

            attachments.put(attachmentData.getContentId(), attachmentFile);
            S2sAppAttachments appAttachments = new S2sAppAttachments();
            appAttachments.setContentId(attachmentData.getContentId());
            appAttachments.setProposalNumber(pdDoc.getDevelopmentProposal().getProposalNumber());
            s2sAppAttachmentList.add(appAttachments);
        }
        S2sAppSubmission appSubmission = new S2sAppSubmission();
        appSubmission.setStatus(S2SConstants.GRANTS_GOV_STATUS_MESSAGE);
        appSubmission.setComments(S2SConstants.GRANTS_GOV_COMMENTS_MESSAGE);
        SubmitApplicationResponse response = null;

        String applicationXmlText = grantApplicationDocument
                .xmlText(s2SFormGeneratorService.getXmlOptionsPrefixes());
        String applicationXml = s2SUtilService.removeTimezoneFactor(applicationXmlText);
        response = grantsGovConnectorService.submitApplication(applicationXml, attachments,
                pdDoc.getDevelopmentProposal().getProposalNumber());
        appSubmission.setStatus(S2SConstants.GRANTS_GOV_SUBMISSION_MESSAGE);
        saveSubmissionDetails(pdDoc, appSubmission, response, applicationXml, s2sAppAttachmentList);
        submissionStatus = true;
    }
    return submissionStatus;
}

From source file:immf.MyHtmlEmail.java

public String embed(DataSource dataSource, String name, String nameCharset, String cid) throws EmailException {
    if (StringUtils.isEmpty(name)) {
        throw new EmailException("name cannot be null or empty");
    }/*from   ww  w .  j av a  2s .c  o  m*/

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(dataSource));
        Util.setFileName(mbp, name, nameCharset, null);
        //mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.setContentID("<" + cid + ">");

        InlineImage ii = new InlineImage(cid, dataSource, mbp);
        this.inlineEmbeds.put(name, ii);

        return cid;
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}