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.etudes.component.app.jforum.JForumEmailServiceImpl.java

/**
 * Sends email with attachments/* ww w .  j a  va  2 s. c om*/
 * 
 * @param from
 *        The address this message is to be listed as coming from.
 * @param to
 *        The address(es) this message should be sent to.
 * @param subject
 *        The subject of this message.
 * @param content
 *        The body of the message.
 * @param headerToStr
 *        If specified, this is placed into the message header, but "to" is used for the recipients.
 * @param replyTo
 *        If specified, this is the reply to header address(es).
 * @param additionalHeaders
 *        Additional email headers to send (List of String). For example, content type or forwarded headers (may be null)        
 * @param messageAttachments
 *         Message attachments
 */
protected void sendMailWithAttachments(InternetAddress from, InternetAddress[] to, String subject,
        String content, InternetAddress[] headerTo, InternetAddress[] replyTo, List<String> additionalHeaders,
        List<EmailAttachment> emailAttachments) {
    if (testMode) {
        testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders, emailAttachments);
        return;
    }

    if (smtp == null || smtp.trim().length() == 0) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMailWithAttachments: smtp not set");
        }
        return;
    }

    if (from == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: from is needed to send email");
        }
        return;
    }

    if (to == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: to is needed to send email");
        }
        return;
    }

    if (content == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: content is needed to send email");
        }
        return;
    }

    if (emailAttachments == null || emailAttachments.size() == 0) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: emailAttachments are needed to send email with attachments");
        }
        return;
    }

    try {
        if (session == null) {
            if (logger.isWarnEnabled()) {
                logger.warn("mail session is null");
            }
            return;

        }
        MimeMessage message = new MimeMessage(session);

        // default charset
        String charset = "UTF-8";

        message.setSentDate(new Date());
        message.setFrom(from);
        message.setSubject(subject, charset);

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        // Content-Type: text/plain; text/html;
        String contentType = null, contentTypeValue = null;

        if (additionalHeaders != null) {
            for (String header : additionalHeaders) {
                if (header.toLowerCase().startsWith("content-type:")) {
                    contentType = header;

                    contentTypeValue = contentType.substring(
                            contentType.indexOf("content-type:") + "content-type:".length(),
                            contentType.length());
                    break;
                }
            }
        }

        // message
        String messagetype = "";
        if ((contentTypeValue != null) && (contentTypeValue.trim().equalsIgnoreCase("text/html"))) {
            messagetype = "text/html; charset=" + charset;
            messageBodyPart.setContent(content, messagetype);
        } else {

            messagetype = "text/plain; charset=" + charset;
            messageBodyPart.setContent(content, messagetype);
        }

        //messageBodyPart.setContent(content, "text/html; charset="+ charset);

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        String jforumAttachmentStoreDir = serverConfigurationService()
                .getString(JForumAttachmentService.ATTACHMENTS_STORE_DIR);
        if (jforumAttachmentStoreDir == null || jforumAttachmentStoreDir.trim().length() == 0) {
            if (logger.isWarnEnabled()) {
                logger.warn("JForum attachments directory (" + JForumAttachmentService.ATTACHMENTS_STORE_DIR
                        + ") property is not set in sakai.properties ");
            }
        } else {
            // attachments
            for (EmailAttachment emailAttachment : emailAttachments) {

                String filePath = jforumAttachmentStoreDir + "/" + emailAttachment.getPhysicalFileName();

                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(filePath);
                try {
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(emailAttachment.getRealFileName());

                    multipart.addBodyPart(messageBodyPart);
                } catch (MessagingException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Error while attaching attachments: " + e, e);
                    }
                }
            }
        }

        message.setContent(multipart);

        Transport.send(message, to);

    } catch (MessagingException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: Error in sending email: " + e, e);
        }
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param data Data//from   w  ww. j  a va 2  s . c  om
 * @param contentType The Mime content type of the file.
 * @param fileName   The name of the file - as it will appear for the mail recipient.
 * @return The resulting MimeBodyPart.
 * @throws SystemException if the MimeBodyPart can't be created.
 */
public static MimeBodyPart createMimeBodyPartFromData(byte[] data, final String contentType, String fileName)
        throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        ByteArrayDataSource dataSource = new ByteArrayDataSource(data, contentType) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(dataSource));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra data[]", e);
    }
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeBodyPart????Content-Disposition: inline
 *
 * @param file//w ww. java 2s  . c om
 *            ?
 * @return MimeBodyPartContent-Disposition: inline?
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private MimeBodyPart createImagePart(InlineImageFile file)
        throws MessagingException, UnsupportedEncodingException {
    MimeBodyPart imagePart = new MimeBodyPart();
    imagePart.setContentID(file.getContentId());
    imagePart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null));
    imagePart.setDataHandler(new DataHandler(file.getDataSource()));
    imagePart.setDisposition(MimeBodyPart.INLINE);
    return imagePart;
}

From source file:org.wso2.appserver.integration.tests.usermgt.UserManagementWithAdminUserTestCase.java

@Test(groups = "wso2.as", description = "Upload users in bulk")
public void testBulkUserUpload() throws Exception {
    Path filePath = Paths.get(FrameworkPathUtil.getSystemResourceLocation(), "artifacts", "AS", "usermgt",
            USER_CSV_FILE_NAME);// w  w w . ja v  a 2 s  .  co m
    DataHandler handler = new DataHandler(filePath.toUri().toURL());
    userManagementClient.bulkImportUsers(filePath.toString(), handler, "abc123");
    ArrayList<String> users = (ArrayList<String>) FileUtils.readLines(filePath.toFile());
    users.remove(0); // Remove the username
    HashSet<String> userList = userManagementClient.getUserList();
    for (String user : users) {
        assertTrue(userList.contains(user), "Username " + user + " doesn't exist");
        //assertNotNull(loginLogoutClient.login(user, "abc123", asServer.getInstance().getHosts().get("default")));
        userManagementClient.deleteUser(user);
    }
}

From source file:org.kalypso.services.observation.server.ObservationServiceDelegate.java

@Override
public final DataBean readData(final String href) throws SensorException {
    init();//from   w w  w.  j  a v  a2 s. c  o  m

    final String hereHref = ObservationServiceUtils.removeServerSideId(href);
    final String obsId = org.kalypso.ogc.sensor.zml.ZmlURL.getIdentifierPart(hereHref);
    final ObservationBean obean = new ObservationBean(obsId);

    // request part specified?
    IRequest request = null;
    Request requestType = null;
    try {
        requestType = RequestFactory.parseRequest(hereHref);
        if (requestType != null) {
            request = ObservationRequest.createWith(requestType);

            m_logger.info("Reading data for observation: " + obean.getId() + " Request: " + request); //$NON-NLS-1$ //$NON-NLS-2$
        } else
            m_logger.info("Reading data for observation: " + obean.getId()); //$NON-NLS-1$
    } catch (final SensorException e) {
        m_logger.warning("Invalid Href: " + href); //$NON-NLS-1$
        m_logger.throwing(getClass().getName(), "readData", e); //$NON-NLS-1$

        // this is a fatal error (software programming error on the client-side)
        // so break processing now!
        throw e;
    }

    // fetch observation from repository
    IObservation obs = null;
    try {
        final IRepositoryItem item = itemFromBean(obean);

        obs = (IObservation) item.getAdapter(IObservation.class);
    } catch (final Exception e) {
        m_logger.info("Could not find an observation for " + obean.getId() + ". Reason is:\n" //$NON-NLS-1$//$NON-NLS-2$
                + e.getLocalizedMessage());

        // this is not a fatal error, repository might be temporarely unavailable
    }

    if (obs == null) {
        // obs could not be created, use the request now
        m_logger.info("Creating request-based observation for " + obean.getId()); //$NON-NLS-1$
        obs = RequestFactory.createDefaultObservation(requestType);
    }

    try {
        // tricky: maybe make a filtered observation out of this one
        obs = FilterFactory.createFilterFrom(hereHref, obs, null);

        // name of the temp file must be valid against OS-rules for naming files
        // so remove any special characters
        final String tempFileName = FileUtilities.validateName("___" + obs.getName(), "-"); //$NON-NLS-1$ //$NON-NLS-2$

        // create temp file
        m_tmpDir.mkdirs(); // additionally create the parent dir if not already exists
        final File f = File.createTempFile(tempFileName, ".zml", m_tmpDir); //$NON-NLS-1$

        // we say delete on exit even if we allow the client to delete the file
        // explicitely in the clearTempData() service call. This allows us to
        // clear temp files on shutdown in the case the client forgets it.
        f.deleteOnExit();

        ZmlFactory.writeToFile(obs, f, request);

        final DataBean data = new DataBean(f.toString(), new DataHandler(new FileDataSource(f)));
        m_mapDataId2File.put(data.getId(), f);

        return data;
    } catch (final IOException e) // generic exception used for simplicity
    {
        m_logger.throwing(getClass().getName(), "readData", e); //$NON-NLS-1$
        throw new SensorException(e.getLocalizedMessage(), e);
    }
}

From source file:org.etudes.jforum.util.mail.Spammer.java

/**
 * prepare attachment message//ww w  . j a v a  2 s. com
 * @param addresses Addresses
 * @param params Message params
 * @param subject Message subject
 * @param messageFile Message file
 * @param attachments Attachments
 * @throws EmailException
 */
protected final void prepareAttachmentMessage(List addresses, SimpleHash params, String subject,
        String messageFile, List attachments) throws EmailException {
    if (logger.isDebugEnabled())
        logger.debug("prepareAttachmentMessage with attachments entering.....");

    this.message = new MimeMessage(session);

    try {
        InternetAddress[] recipients = new InternetAddress[addresses.size()];

        String charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET);

        this.message.setSentDate(new Date());
        // this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER)));
        String from = "\"" + ServerConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@"
                + ServerConfigurationService.getServerName() + ">";
        this.message.setFrom(new InternetAddress(from));
        this.message.setSubject(subject, charset);

        this.messageText = this.getMessageText(params, messageFile);

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        String messagetype = "";

        // message
        if (messageFormat == MESSAGE_HTML) {
            messagetype = "text/html; charset=" + charset;
            messageBodyPart.setContent(this.messageText, messagetype);
        } else {

            messagetype = "text/plain; charset=" + charset;
            messageBodyPart.setContent(this.messageText, messagetype);
        }

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        // attachments
        Attachment attachment = null;
        Iterator iterAttach = attachments.iterator();
        while (iterAttach.hasNext()) {
            attachment = (Attachment) iterAttach.next();
            // String filePath = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename();
            String filePath = SakaiSystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/"
                    + attachment.getInfo().getPhysicalFilename();

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filePath);
            try {
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(attachment.getInfo().getRealFilename());

                multipart.addBodyPart(messageBodyPart);
            } catch (MessagingException e) {
                if (logger.isWarnEnabled())
                    logger.warn("Error while attaching attachments in prepareAttachmentMessage(...) : " + e);
            }
        }

        message.setContent(multipart);

        int i = 0;
        for (Iterator iter = addresses.iterator(); iter.hasNext(); i++) {
            recipients[i] = new InternetAddress((String) iter.next());
        }

        this.message.setRecipients(Message.RecipientType.TO, recipients);
    } catch (Exception e) {
        logger.warn(e);
        throw new EmailException(e);
    }
    if (logger.isDebugEnabled())
        logger.debug("prepareAttachmentMessage with attachments exiting.....");
}

From source file:com.iana.boesc.utility.BOESCUtil.java

public static boolean sendEmailWithAttachments(final String emailFrom, final String subject,
        final InternetAddress[] addressesTo, final String body, final File attachment) {
    try {/* ww  w  .  j  a  va2s  .  co m*/
        Session session = Session.getInstance(GlobalVariables.EMAIL_PROPS, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("", "");
            }
        });

        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        InternetAddress addressFrom = new InternetAddress(emailFrom);
        message.setFrom(addressFrom);

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, addressesTo);

        // Set Subject: header field
        message.setSubject(subject);

        // Create the message part
        BodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(body);
        messageBodyPart.setContent(body, "text/html");

        // Create a multi part message
        Multipart multipart = new javax.mail.internet.MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new javax.mail.internet.MimeBodyPart();

        DataSource source = new FileDataSource(attachment);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(attachment.getName());
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);

        return true;
    } catch (Exception ex) {
        ex.getMessage();
        return false;
    }
}

From source file:com.docdoku.client.actions.MainController.java

public void saveFile(Component pParent, DocumentMasterTemplate pTemplate, File pLocalFile) throws Exception {
    if (!NamingConvention.correct(pLocalFile.getName())) {
        throw new NotAllowedException(Locale.getDefault(), "NotAllowedException9");
    }/*from ww w.  j  a v a 2 s  .co  m*/
    MainModel model = MainModel.getInstance();
    String message = I18N.BUNDLE.getString("UploadMsg_part1") + " " + pLocalFile.getName() + " ("
            + (int) (pLocalFile.length() / 1024) + I18N.BUNDLE.getString("UploadMsg_part2");
    DataHandler data = new DataHandler(new ProgressMonitorFileDataSource(pParent, pLocalFile, message));
    try {
        Map<String, Object> ctxt = ((BindingProvider) mFileService).getRequestContext();
        try {
            if (ctxt.containsKey(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE)) {
                mFileService.uploadToTemplate(model.getWorkspace().getId(), pTemplate.getId(),
                        pLocalFile.getName(), data);
            } else {
                //workaround mode
                uploadFileWithServlet(pParent, pLocalFile, getServletURL(pTemplate, pLocalFile));
            }
        } catch (Exception ex) {
            if (ex.getCause() instanceof InterruptedIOException) {
                throw ex;
            }
            //error encountered, try again, workaround mode

            if (ctxt.containsKey(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE)) {
                System.out.println("Disabling chunked mode");
                ctxt.remove(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE);
                uploadFileWithServlet(pParent, pLocalFile, getServletURL(pTemplate, pLocalFile));
            } else {
                //we were already not using the chunked mode
                //there's not much to do...
                throw ex;
            }
        }
    } catch (WebServiceException pWSEx) {
        Throwable t = pWSEx.getCause();
        if (t instanceof Exception) {
            throw (Exception) t;
        } else {
            throw pWSEx;
        }
    }
}

From source file:org.kuali.coeus.propdev.impl.s2s.S2sSubmissionServiceImpl.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/*from  w ww.jav a 2s  . c om*/
 *
 * @param pdDoc
 *            Proposal Development Document.
 * @return true if submitted false otherwise.
 * @throws S2sCommunicationException
 */
public FormGenerationResult submitApplication(ProposalDevelopmentDocument pdDoc)
        throws S2sCommunicationException {

    final FormGenerationResult result = s2SService.generateAndValidateForms(pdDoc);
    if (result.isValid()) {

        Map<String, DataHandler> attachments = new HashMap<String, DataHandler>();
        List<S2sAppAttachments> s2sAppAttachmentList = new ArrayList<S2sAppAttachments>();
        DataHandler attachmentFile;
        for (AttachmentData attachmentData : result.getAttachments()) {
            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(S2sAppSubmissionConstants.GRANTS_GOV_STATUS_MESSAGE);
        appSubmission.setComments(S2sAppSubmissionConstants.GRANTS_GOV_COMMENTS_MESSAGE);
        SubmitApplicationResponse response = null;

        S2sOpportunity s2sOpportunity = pdDoc.getDevelopmentProposal().getS2sOpportunity();
        S2SConnectorService connectorService = getS2sConnectorService(s2sOpportunity);

        response = connectorService.submitApplication(result.getApplicationXml(), attachments,
                pdDoc.getDevelopmentProposal().getProposalNumber());
        appSubmission.setStatus(S2sAppSubmissionConstants.GRANTS_GOV_SUBMISSION_MESSAGE);
        saveSubmissionDetails(pdDoc, appSubmission, response, result.getApplicationXml(), s2sAppAttachmentList);
        result.setValid(true);
    }
    return result;
}

From source file:org.infoglue.cms.util.mail.MailService.java

/**
 *
 *///from w w w .j  a  va2  s .  co  m
private Message createMessage(String from, String to, String bcc, String subject, String content)
        throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);

        message.setContent(content, "text/html");
        message.setFrom(createInternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, createInternetAddress(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        message.setSubject(subject);
        message.setText(content);
        message.setDataHandler(new DataHandler(new StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new Bug("Unable to create the message.", e);
    }
}