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.pentaho.di.trans.steps.mail.Mail.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (MailMeta) smi;//from  www  . j  a v a  2  s.  co m
    data = (MailData) sdi;

    Object[] r = getRow(); // get row, set busy!
    if (r == null) { // no more input to be expected...

        setOutputDone();
        return false;
    }

    if (first) {
        first = false;

        // get the RowMeta
        data.previousRowMeta = getInputRowMeta().clone();

        // Check is filename field is provided
        if (Const.isEmpty(meta.getDestination())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.DestinationFieldEmpty"));
        }

        // Check is replyname field is provided
        if (Const.isEmpty(meta.getReplyAddress())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.ReplyFieldEmpty"));
        }

        // Check is SMTP server is provided
        if (Const.isEmpty(meta.getServer())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.ServerFieldEmpty"));
        }

        // Check Attached filenames when dynamic
        if (meta.isDynamicFilename() && Const.isEmpty(meta.getDynamicFieldname())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.DynamicFilenameFielddEmpty"));
        }

        // Check Attached zipfilename when dynamic
        if (meta.isZipFilenameDynamic() && Const.isEmpty(meta.getDynamicZipFilenameField())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.DynamicZipFilenameFieldEmpty"));
        }

        if (meta.isZipFiles() && Const.isEmpty(meta.getZipFilename())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.ZipFilenameEmpty"));
        }

        // check authentication
        if (meta.isUsingAuthentication()) {
            // check authentication user
            if (Const.isEmpty(meta.getAuthenticationUser())) {
                throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.AuthenticationUserFieldEmpty"));
            }

            // check authentication pass
            if (Const.isEmpty(meta.getAuthenticationPassword())) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "Mail.Log.AuthenticationPasswordFieldEmpty"));
            }
        }

        // cache the position of the destination field
        if (data.indexOfDestination < 0) {
            String realDestinationFieldname = meta.getDestination();
            data.indexOfDestination = data.previousRowMeta.indexOfValue(realDestinationFieldname);
            if (data.indexOfDestination < 0) {
                throw new KettleException(BaseMessages.getString(PKG,
                        "Mail.Exception.CouldnotFindDestinationField", realDestinationFieldname));
            }
        }

        // Cc
        if (!Const.isEmpty(meta.getDestinationCc())) {
            // cache the position of the Cc field
            if (data.indexOfDestinationCc < 0) {
                String realDestinationCcFieldname = meta.getDestinationCc();
                data.indexOfDestinationCc = data.previousRowMeta.indexOfValue(realDestinationCcFieldname);
                if (data.indexOfDestinationCc < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindDestinationCcField", realDestinationCcFieldname));
                }
            }
        }
        // BCc
        if (!Const.isEmpty(meta.getDestinationBCc())) {
            // cache the position of the BCc field
            if (data.indexOfDestinationBCc < 0) {
                String realDestinationBCcFieldname = meta.getDestinationBCc();
                data.indexOfDestinationBCc = data.previousRowMeta.indexOfValue(realDestinationBCcFieldname);
                if (data.indexOfDestinationBCc < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindDestinationBCcField", realDestinationBCcFieldname));
                }
            }
        }
        // Sender Name
        if (!Const.isEmpty(meta.getReplyName())) {
            // cache the position of the sender field
            if (data.indexOfSenderName < 0) {
                String realSenderName = meta.getReplyName();
                data.indexOfSenderName = data.previousRowMeta.indexOfValue(realSenderName);
                if (data.indexOfSenderName < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindReplyNameField", realSenderName));
                }
            }
        }
        // Sender address
        // cache the position of the sender field
        if (data.indexOfSenderAddress < 0) {
            String realSenderAddress = meta.getReplyAddress();
            data.indexOfSenderAddress = data.previousRowMeta.indexOfValue(realSenderAddress);
            if (data.indexOfSenderAddress < 0) {
                throw new KettleException(BaseMessages.getString(PKG,
                        "Mail.Exception.CouldnotFindReplyAddressField", realSenderAddress));
            }
        }

        // Reply to
        if (!Const.isEmpty(meta.getReplyToAddresses())) {
            // cache the position of the reply to field
            if (data.indexOfReplyToAddresses < 0) {
                String realReplyToAddresses = meta.getReplyToAddresses();
                data.indexOfReplyToAddresses = data.previousRowMeta.indexOfValue(realReplyToAddresses);
                if (data.indexOfReplyToAddresses < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindReplyToAddressesField", realReplyToAddresses));
                }
            }
        }

        // Contact Person
        if (!Const.isEmpty(meta.getContactPerson())) {
            // cache the position of the destination field
            if (data.indexOfContactPerson < 0) {
                String realContactPerson = meta.getContactPerson();
                data.indexOfContactPerson = data.previousRowMeta.indexOfValue(realContactPerson);
                if (data.indexOfContactPerson < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindContactPersonField", realContactPerson));
                }
            }
        }
        // Contact Phone
        if (!Const.isEmpty(meta.getContactPhone())) {
            // cache the position of the destination field
            if (data.indexOfContactPhone < 0) {
                String realContactPhone = meta.getContactPhone();
                data.indexOfContactPhone = data.previousRowMeta.indexOfValue(realContactPhone);
                if (data.indexOfContactPhone < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindContactPhoneField", realContactPhone));
                }
            }
        }
        // cache the position of the Server field
        if (data.indexOfServer < 0) {
            String realServer = meta.getServer();
            data.indexOfServer = data.previousRowMeta.indexOfValue(realServer);
            if (data.indexOfServer < 0) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindServerField", realServer));
            }
        }
        // Port
        if (!Const.isEmpty(meta.getPort())) {
            // cache the position of the port field
            if (data.indexOfPort < 0) {
                String realPort = meta.getPort();
                data.indexOfPort = data.previousRowMeta.indexOfValue(realPort);
                if (data.indexOfPort < 0) {
                    throw new KettleException(
                            BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindPortField", realPort));
                }
            }
        }
        // Authentication
        if (meta.isUsingAuthentication()) {
            // cache the position of the Authentication user field
            if (data.indexOfAuthenticationUser < 0) {
                String realAuthenticationUser = meta.getAuthenticationUser();
                data.indexOfAuthenticationUser = data.previousRowMeta.indexOfValue(realAuthenticationUser);
                if (data.indexOfAuthenticationUser < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindAuthenticationUserField", realAuthenticationUser));
                }
            }

            // cache the position of the Authentication password field
            if (data.indexOfAuthenticationPass < 0) {
                String realAuthenticationPassword = meta.getAuthenticationPassword();
                data.indexOfAuthenticationPass = data.previousRowMeta.indexOfValue(realAuthenticationPassword);
                if (data.indexOfAuthenticationPass < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindAuthenticationPassField", realAuthenticationPassword));
                }
            }
        }
        // Mail Subject
        if (!Const.isEmpty(meta.getSubject())) {
            // cache the position of the subject field
            if (data.indexOfSubject < 0) {
                String realSubject = meta.getSubject();
                data.indexOfSubject = data.previousRowMeta.indexOfValue(realSubject);
                if (data.indexOfSubject < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindSubjectField", realSubject));
                }
            }
        }
        // Mail Comment
        if (!Const.isEmpty(meta.getComment())) {
            // cache the position of the comment field
            if (data.indexOfComment < 0) {
                String realComment = meta.getComment();
                data.indexOfComment = data.previousRowMeta.indexOfValue(realComment);
                if (data.indexOfComment < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindCommentField", realComment));
                }
            }
        }

        if (meta.isAttachContentFromField()) {
            // We are dealing with file content directly loaded from file
            // and not physical file
            String attachedContentField = meta.getAttachContentField();
            if (Const.isEmpty(attachedContentField)) {
                // Empty Field
                throw new KettleException(
                        BaseMessages.getString(PKG, "Mail.Exception.AttachedContentFieldEmpty"));
            }
            data.indexOfAttachedContent = data.previousRowMeta.indexOfValue(attachedContentField);
            if (data.indexOfComment < 0) {
                throw new KettleException(BaseMessages.getString(PKG,
                        "Mail.Exception.CouldnotFindAttachedContentField", attachedContentField));
            }
            // Attached content filename
            String attachedContentFileNameField = meta.getAttachContentFileNameField();
            if (Const.isEmpty(attachedContentFileNameField)) {
                // Empty Field
                throw new KettleException(
                        BaseMessages.getString(PKG, "Mail.Exception.AttachedContentFileNameFieldEmpty"));
            }
            data.IndexOfAttachedFilename = data.previousRowMeta.indexOfValue(attachedContentFileNameField);
            if (data.indexOfComment < 0) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindAttachedContentFileNameField",
                                attachedContentFileNameField));
            }

        } else {

            // Dynamic Zipfilename
            if (meta.isZipFilenameDynamic()) {
                // cache the position of the attached source filename field
                if (data.indexOfDynamicZipFilename < 0) {
                    String realZipFilename = meta.getDynamicZipFilenameField();
                    data.indexOfDynamicZipFilename = data.previousRowMeta.indexOfValue(realZipFilename);
                    if (data.indexOfDynamicZipFilename < 0) {
                        throw new KettleException(BaseMessages.getString(PKG,
                                "Mail.Exception.CouldnotSourceAttachedZipFilenameField", realZipFilename));
                    }
                }
            }
            data.zipFileLimit = Const.toLong(environmentSubstitute(meta.getZipLimitSize()), 0);
            if (data.zipFileLimit > 0) {
                data.zipFileLimit = data.zipFileLimit * 1048576; // Mo
            }

            if (!meta.isZipFilenameDynamic()) {
                data.ZipFilename = environmentSubstitute(meta.getZipFilename());
            }

            // Attached files
            if (meta.isDynamicFilename()) {
                // cache the position of the attached source filename field
                if (data.indexOfSourceFilename < 0) {
                    String realSourceattachedFilename = meta.getDynamicFieldname();
                    data.indexOfSourceFilename = data.previousRowMeta.indexOfValue(realSourceattachedFilename);
                    if (data.indexOfSourceFilename < 0) {
                        throw new KettleException(BaseMessages.getString(PKG,
                                "Mail.Exception.CouldnotSourceAttachedFilenameField",
                                realSourceattachedFilename));
                    }
                }

                // cache the position of the attached wildcard field
                if (!Const.isEmpty(meta.getSourceWildcard())) {
                    if (data.indexOfSourceWildcard < 0) {
                        String realSourceattachedWildcard = meta.getDynamicWildcard();
                        data.indexOfSourceWildcard = data.previousRowMeta
                                .indexOfValue(realSourceattachedWildcard);
                        if (data.indexOfSourceWildcard < 0) {
                            throw new KettleException(
                                    BaseMessages.getString(PKG, "Mail.Exception.CouldnotSourceAttachedWildcard",
                                            realSourceattachedWildcard));
                        }
                    }
                }
            } else {
                // static attached filenames
                data.realSourceFileFoldername = environmentSubstitute(meta.getSourceFileFoldername());
                data.realSourceWildcard = environmentSubstitute(meta.getSourceWildcard());
            }
        }

        // check embedded images
        if (meta.getEmbeddedImages() != null && meta.getEmbeddedImages().length > 0) {
            FileObject image = null;
            data.embeddedMimePart = new HashSet<MimeBodyPart>();
            try {
                for (int i = 0; i < meta.getEmbeddedImages().length; i++) {
                    String imageFile = environmentSubstitute(meta.getEmbeddedImages()[i]);
                    String contentID = environmentSubstitute(meta.getContentIds()[i]);
                    image = KettleVFS.getFileObject(imageFile);

                    if (image.exists() && image.getType() == FileType.FILE) {
                        // Create part for the image
                        MimeBodyPart imagePart = new MimeBodyPart();
                        // Load the image
                        URLDataSource fds = new URLDataSource(image.getURL());
                        imagePart.setDataHandler(new DataHandler(fds));
                        // Setting the header
                        imagePart.setHeader("Content-ID", "<" + contentID + ">");
                        // keep this part for further user
                        data.embeddedMimePart.add(imagePart);
                        logBasic(BaseMessages.getString(PKG, "Mail.Log.ImageAdded", imageFile));

                    } else {
                        logError(BaseMessages.getString(PKG, "Mail.Log.WrongImage", imageFile));
                    }
                }
            } catch (Exception e) {
                logError(BaseMessages.getString(PKG, "Mail.Error.AddingImage", e.getMessage()));
            } finally {
                if (image != null) {
                    try {
                        image.close();
                    } catch (Exception e) { /* Ignore */
                    }
                }
            }
        }

    } // end if first

    boolean sendToErrorRow = false;
    String errorMessage = null;

    try {
        // get values
        String maildestination = data.previousRowMeta.getString(r, data.indexOfDestination);
        if (Const.isEmpty(maildestination)) {
            throw new KettleException("Mail.Error.MailDestinationEmpty");
        }
        String maildestinationCc = null;
        if (data.indexOfDestinationCc > -1) {
            maildestinationCc = data.previousRowMeta.getString(r, data.indexOfDestinationCc);
        }
        String maildestinationBCc = null;
        if (data.indexOfDestinationBCc > -1) {
            maildestinationBCc = data.previousRowMeta.getString(r, data.indexOfDestinationBCc);
        }

        String mailsendername = null;
        if (data.indexOfSenderName > -1) {
            mailsendername = data.previousRowMeta.getString(r, data.indexOfSenderName);
        }
        String mailsenderaddress = data.previousRowMeta.getString(r, data.indexOfSenderAddress);

        // reply addresses
        String mailreplyToAddresses = null;
        if (data.indexOfReplyToAddresses > -1) {
            mailreplyToAddresses = data.previousRowMeta.getString(r, data.indexOfReplyToAddresses);
        }

        String contactperson = null;
        if (data.indexOfContactPerson > -1) {
            contactperson = data.previousRowMeta.getString(r, data.indexOfContactPerson);
        }
        String contactphone = null;
        if (data.indexOfContactPhone > -1) {
            contactphone = data.previousRowMeta.getString(r, data.indexOfContactPhone);
        }

        String servername = data.previousRowMeta.getString(r, data.indexOfServer);
        if (Const.isEmpty(servername)) {
            throw new KettleException("Mail.Error.MailServerEmpty");
        }
        int port = -1;
        if (data.indexOfPort > -1) {
            port = Const.toInt("" + data.previousRowMeta.getInteger(r, data.indexOfPort), -1);
        }

        String authuser = null;
        if (data.indexOfAuthenticationUser > -1) {
            authuser = data.previousRowMeta.getString(r, data.indexOfAuthenticationUser);
        }
        String authpass = null;
        if (data.indexOfAuthenticationPass > -1) {
            authpass = data.previousRowMeta.getString(r, data.indexOfAuthenticationPass);
        }

        String subject = null;
        if (data.indexOfSubject > -1) {
            subject = data.previousRowMeta.getString(r, data.indexOfSubject);
        }

        String comment = null;
        if (data.indexOfComment > -1) {
            comment = data.previousRowMeta.getString(r, data.indexOfComment);
        }

        // send email...
        sendMail(r, servername, port, mailsenderaddress, mailsendername, maildestination, maildestinationCc,
                maildestinationBCc, contactperson, contactphone, authuser, authpass, subject, comment,
                mailreplyToAddresses);

        putRow(getInputRowMeta(), r); // copy row to possible alternate rowset(s).); // copy row to output rowset(s);

        if (log.isRowLevel()) {
            logRowlevel(BaseMessages.getString(PKG, "Mail.Log.LineNumber",
                    getLinesRead() + " : " + getInputRowMeta().getString(r)));
        }

    } catch (Exception e) {
        if (getStepMeta().isDoingErrorHandling()) {
            sendToErrorRow = true;
            errorMessage = e.toString();
        } else {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Error.General"), e);
        }
        if (sendToErrorRow) {
            // Simply add this row to the error row
            putError(getInputRowMeta(), r, 1, errorMessage, null, "MAIL001");
        }
    }

    return true;
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server// w w  w  . j  a  va  2 s . c  om
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());

    final Session session = Session.getInstance(props, null);
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:nl.nn.adapterframework.senders.MailSender.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection recipients, Collection attachments)
        throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }//from   ww  w.  j  a  v a 2s  . c  o  m
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url ["
                        + attachmentUrl + "]contents [" + attachmentText + "]");

                messageBodyPart = new MimeBodyPart();

                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }

                messageBodyPart.setFileName(attachmentName);

                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server/*from w  w w  . j  a  v a  2  s.  co m*/
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:com.aipo.social.opensocial.spi.AipoStorageService.java

@Override
public String getContentType(String filePath, SecurityToken paramSecurityToken)
        throws ProtocolException, FileNotFoundException {
    String contenType = null;//from   w  ww. ja  va 2  s.  c o m
    File file = new File(filePath);
    DataHandler hData = new DataHandler(new FileDataSource(file));

    if (hData != null) {
        contenType = hData.getContentType();
    }
    return contenType;
}

From source file:com.clustercontrol.ws.agent.AgentEndpoint.java

/**
 * [Update] ?//from w  w w .  j av  a2  s .  co m
 *
 * HinemosAgentAccess???
 *
 * @throws HinemosUnknown
 * @throws InvalidRole
 * @throws InvalidUserPass
 */
@XmlMimeType("application/octet-stream")
public DataHandler downloadModule(String filename) throws InvalidUserPass, InvalidRole, HinemosUnknown {
    ArrayList<SystemPrivilegeInfo> systemPrivilegeList = new ArrayList<SystemPrivilegeInfo>();
    systemPrivilegeList
            .add(new SystemPrivilegeInfo(FunctionConstant.HINEMOS_AGENT, SystemPrivilegeMode.MODIFY));
    HttpAuthenticator.authCheck(wsctx, systemPrivilegeList);

    String homeDir = System.getProperty("hinemos.manager.home.dir");
    String filepath = homeDir + "/lib/agent/" + filename;
    File file = new File(filepath);
    if (!file.exists()) {
        m_log.info("file not found : " + filepath);
        return null;
    }
    FileDataSource source = new FileDataSource(file);
    DataHandler dataHandler = new DataHandler(source);
    return dataHandler;
}

From source file:lucee.runtime.net.smtp.SMTPClient.java

public MimeBodyPart toMimeBodyPart(Multipart mp, lucee.runtime.config.Config config, Attachment att)
        throws MessagingException {

    MimeBodyPart mbp = new MimeBodyPart();

    // set Data Source
    String strRes = att.getAbsolutePath();
    if (!StringUtil.isEmpty(strRes)) {

        mbp.setDataHandler(new DataHandler(new ResourceDataSource(config.getResource(strRes))));
    } else//  ww  w .  jav  a 2  s . com
        mbp.setDataHandler(new DataHandler(new URLDataSource2(att.getURL())));

    mbp.setFileName(att.getFileName());
    if (!StringUtil.isEmpty(att.getType()))
        mbp.setHeader("Content-Type", att.getType());
    if (!StringUtil.isEmpty(att.getDisposition())) {
        mbp.setDisposition(att.getDisposition());
        /*if(mp instanceof MimeMultipart) {
           ((MimeMultipart)mp).setSubType("related");
        }*/

    }
    if (!StringUtil.isEmpty(att.getContentID()))
        mbp.setContentID(att.getContentID());

    return mbp;
}

From source file:org.wso2.carbon.application.mgt.ApplicationAdmin.java

/**
 * Used to download a carbon application archive. 
 * @param fileName the name of the application archive (.car) to be downloaded
 * @return datahandler corresponding to the .car file to be downloaded
 * @throws Exception for invalid scenarios 
 *//*from   w  w  w  .ja  va  2 s  . c o  m*/
public DataHandler downloadCappArchive(String fileName) throws Exception {
    CarbonApplication currentApp = null;

    // Iterate all applications for this tenant and find the application to delete
    String tenantId = AppDeployerUtils.getTenantIdString(getAxisConfig());
    ArrayList<CarbonApplication> appList = AppManagementServiceComponent.getAppManager()
            .getCarbonApps(tenantId);
    for (CarbonApplication carbonApp : appList) {
        if (fileName.equals(carbonApp.getAppNameWithVersion())) {
            currentApp = carbonApp;
        }
    }

    FileDataSource datasource = new FileDataSource(new File(currentApp.getAppFilePath()));
    DataHandler handler = new DataHandler(datasource);

    return handler;
}

From source file:nl.nn.adapterframework.senders.MailSender.java

private DataHandler decodeBase64(String str) {
    byte[] bytesDecoded = Base64.decode(str);
    String encodingType = "application/octet-stream";
    DataSource ads = new ByteArrayDataSource(bytesDecoded, encodingType);
    return new DataHandler(ads);
}

From source file:com.cloud.bridge.io.S3CAStorBucketAdapter.java

@Override
public DataHandler loadObjectRange(String mountedRoot, String bucket, String fileName, long startPos,
        long endPos) {
    HttpClient httpClient = new HttpClient(s_httpClientManager);
    // Create a method instance.
    GetMethod method = new GetMethod(castorURL(mountedRoot, bucket, fileName));
    method.addRequestHeader("Range", "bytes=" + startPos + "-" + endPos);
    int statusCode;
    try {/*from   w w  w.  j  a  v a2 s.c  o m*/
        statusCode = httpClient.executeMethod(method);
    } catch (HttpException e) {
        s_logger.error("CAStor loadObjectRange failure", e);
        throw new FileNotExistException("CAStor loadObjectRange failure: " + e);
    } catch (IOException e) {
        s_logger.error("CAStor loadObjectRange failure", e);
        throw new FileNotExistException("CAStor loadObjectRange failure: " + e);
    }
    if (statusCode < HTTP_OK || statusCode >= HTTP_UNSUCCESSFUL) {
        s_logger.error("CAStor loadObjectRange response: " + statusCode);
        throw new FileNotExistException("CAStor loadObjectRange response: " + statusCode);
    }
    DataHandler ret = new DataHandler(new ScspDataSource(method));
    method.releaseConnection();
    return ret;
}