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:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send a calendar message./* www.  ja  v a2s  . c o  m*/
 * @param strRecipientsTo The list of the main recipients email. Every
 *            recipient must be separated by the mail separator defined in
 *            config.properties
 * @param strRecipientsCc The recipients list of the carbon copies .
 * @param strRecipientsBcc The recipients list of the blind carbon copies .
 * @param strSenderName The sender name.
 * @param strSenderEmail The sender email address.
 * @param strSubject The message subject.
 * @param strMessage The HTML message.
 * @param strCalendarMessage The calendar message.
 * @param bCreateEvent True to create the event, false to remove it
 * @param transport the smtp transport object
 * @param session the smtp session object
 * @throws AddressException If invalid address
 * @throws SendFailedException If an error occurred during sending
 * @throws MessagingException If a messaging error occurred
 */
protected static void sendMessageCalendar(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, String strCalendarMessage, boolean bCreateEvent, Transport transport,
        Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    MimeMultipart multipart = new MimeMultipart();
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));

    multipart.addBodyPart(msgBodyPart);

    BodyPart calendarBodyPart = new MimeBodyPart();
    //        calendarBodyPart.addHeader( "Content-Class", "urn:content-classes:calendarmessage" );
    calendarBodyPart.setContent(strCalendarMessage,
            AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_CALENDAR)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET)
                    + AppPropertiesService.getProperty(PROPERTY_CALENDAR_SEPARATOR)
                    + AppPropertiesService.getProperty(
                            bCreateEvent ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL));
    calendarBodyPart.addHeader(HEADER_NAME, CONSTANT_BASE64);
    multipart.addBodyPart(calendarBodyPart);

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

From source file:org.apromore.service.impl.ProcessServiceImpl.java

/**
 * @see org.apromore.service.ProcessService#exportProcess(String, Integer, String, Version, String, String, boolean, java.util.Set)
 * {@inheritDoc}/*w  w  w  .  j  a va  2  s  .  c o m*/
 */
@Override
public ExportFormatResultType exportProcess(final String name, final Integer processId, final String branch,
        final Version version, final String format, final String annName, final boolean withAnn,
        Set<RequestParameterType<?>> canoniserProperties) throws ExportFormatException {
    try {
        // Debug tracing of the authenticated principal
        org.springframework.security.core.Authentication auth = org.springframework.security.core.context.SecurityContextHolder
                .getContext().getAuthentication();
        if (auth != null) {
            LOGGER.info("Authentication principal=" + auth.getPrincipal() + " details=" + auth.getDetails()
                    + " thread=" + Thread.currentThread());
        } else {
            LOGGER.info("Authentication is null");
        }

        ExportFormatResultType exportResult = new ExportFormatResultType();

        // Work out if we are looking at the original format or native format for this model.
        if (isRequestForNativeFormat(processId, branch, version, format)) {
            exportResult.setNative(new DataHandler(new ByteArrayDataSource(
                    nativeRepo.getNative(processId, branch, version.toString(), format).getContent(),
                    "text/xml")));
        } else if (isRequestForAnnotationsOnly(format)) {
            exportResult
                    .setNative(
                            new DataHandler(new ByteArrayDataSource(
                                    annotationRepo.getAnnotation(processId, branch, version.toString(),
                                            AnnotationHelper.getAnnotationName(annName)).getContent(),
                                    "text/xml")));
        } else {
            CanonicalProcessType cpt = getProcessModelVersion(processId, name, branch, version, false);
            Process process;
            if (format.equals(Constants.CANONICAL)) {
                exportResult.setNative(new DataHandler(
                        new ByteArrayDataSource(canoniserSrv.CPFtoString(cpt), Constants.XML_MIMETYPE)));
            } else {
                DecanonisedProcess dp;
                AnnotationsType anf = null;
                process = processRepo.findOne(processId);
                if (withAnn) {
                    Annotation ann = annotationRepo.getAnnotation(processId, branch, version.toString(),
                            annName);
                    if (ann != null) {
                        String annotation = ann.getContent();
                        if (annotation != null && !annotation.equals("")) {
                            ByteArrayDataSource dataSource = new ByteArrayDataSource(annotation,
                                    Constants.XML_MIMETYPE);
                            anf = ANFSchema.unmarshalAnnotationFormat(dataSource.getInputStream(), false)
                                    .getValue();
                        }
                    }

                    if (ann != null && !process.getNativeType().getNatType()
                            .equalsIgnoreCase(ann.getNatve().getNativeType().getNatType())) {
                        anf = annotationSrv.preProcess(ann.getNatve().getNativeType().getNatType(), format, cpt,
                                anf);
                    } else {
                        anf = annotationSrv.preProcess(process.getNativeType().getNatType(), format, cpt, anf);
                    }
                } else if (annName == null) {
                    anf = annotationSrv.preProcess(null, format, cpt, null);
                }

                dp = canoniserSrv.deCanonise(format, cpt, anf, canoniserProperties);

                exportResult.setMessage(PluginHelper.convertFromPluginMessages(dp.getMessages()));
                exportResult.setNative(
                        new DataHandler(new ByteArrayDataSource(dp.getNativeFormat(), Constants.XML_MIMETYPE)));
            }
        }

        return exportResult;
    } catch (Exception e) {
        LOGGER.error("Failed to export process model {} to format {}", name, format);
        LOGGER.error("Original exception was: ", e);
        throw new ExportFormatException(e);
    }
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java

public static MimeBodyPart zipAttachment(String zipFileName, Map mailOptions, File tempFolder) {
    logger.debug("IN");
    MimeBodyPart messageBodyPart = null;
    try {/*from   ww  w .j  ava  2 s . co m*/

        String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : "";

        byte[] buffer = new byte[4096]; // Create a buffer for copying
        int bytesRead;

        // the zip
        String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipOutputStream out = new ZipOutputStream(bout);

        logger.debug("File zip to write: " + tempFolderPath + File.separator + "zippedFile.zip");

        //files to zip
        String[] entries = tempFolder.list();

        for (int i = 0; i < entries.length; i++) {
            //File f = new File(tempFolder, entries[i]);
            File f = new File(tempFolder + File.separator + entries[i]);
            if (f.isDirectory())
                continue;//Ignore directory
            logger.debug("insert file: " + f.getName());
            FileInputStream in = new FileInputStream(f); // Stream to read file
            ZipEntry entry = new ZipEntry(f.getName()); // Make a ZipEntry
            out.putNextEntry(entry); // Store entry
            while ((bytesRead = in.read(buffer)) != -1)
                out.write(buffer, 0, bytesRead);
            in.close();
        }
        out.close();

        messageBodyPart = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(zipFileName + nameSuffix + ".zip");

    } catch (Exception e) {
        logger.error("Error while creating the zip", e);
        return null;
    }

    logger.debug("OUT");

    return messageBodyPart;
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

protected void initRootPart(HttpRequestInterface<?> wsdlRequest, String requestContent, MimeMultipart mp)
        throws MessagingException {
    MimeBodyPart rootPart = new PreencodedMimeBodyPart("8bit");
    // rootPart.setContentID( AttachmentUtils.ROOTPART_SOAPUI_ORG );
    mp.addBodyPart(rootPart, 0);//from  w ww  .j a  v  a 2  s.  c  om

    DataHandler dataHandler = new DataHandler(new RestRequestDataSource(wsdlRequest, requestContent));
    rootPart.setDataHandler(dataHandler);
}

From source file:checkwebsite.Mainframe.java

/**
 *
 * @param email//from w  w w  . j a  v  a  2 s . co  m
 * @param msg
 */
protected void notify(String email, String msg) {
    // Recipient's email ID needs to be mentioned.
    String to = email;//change accordingly

    // go to link below and turn on Access for less secure apps
    //https://www.google.com/settings/security/lesssecureapps
    // Sender's email ID needs to be mentioned
    String from = "";//Enter your email id here
    final String username = "";//Enter your email id here
    final String password = "";//Enter your password here

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

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

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Report of your website : " + wurl);

        //            // Now set the actual message
        //            message.setText("Hello, " + msg + " this is sample for to check send "
        //                    + "email using JavaMailAPI ");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setText("Please! find your website report in attachment");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

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

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "WebsiteReport.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

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

        // Send message
        Transport.send(message);
        lblWarning.setText("report sent...");
        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.axis.attachments.MultiPartRelatedInputStream.java

/**
 * This will read streams in till the one that is needed is found.
 *
 * @param id id is the stream being sought.
 *
 * @return the part for the id//  w  ww  . jav a2  s .  co  m
 *
 * @throws org.apache.axis.AxisFault
 */
protected Part readTillFound(final String[] id) throws org.apache.axis.AxisFault {

    if (boundaryDelimitedStream == null) {
        return null; // The whole stream has been consumed already
    }

    Part ret = null;

    try {
        if (soapStreamBDS == boundaryDelimitedStream) { // Still on the SOAP stream.
            if (!eos) { // The SOAP packet has not been fully read yet. Need to store it away.
                java.io.ByteArrayOutputStream soapdata = new java.io.ByteArrayOutputStream(1024 * 8);
                byte[] buf = new byte[1024 * 16];
                int byteread = 0;

                do {
                    byteread = soapStream.read(buf);

                    if (byteread > 0) {
                        soapdata.write(buf, 0, byteread);
                    }
                } while (byteread > -1);

                soapdata.close();

                soapStream = new java.io.ByteArrayInputStream(soapdata.toByteArray());
            }

            boundaryDelimitedStream = boundaryDelimitedStream.getNextStream();
        }

        // Now start searching for the data.
        if (null != boundaryDelimitedStream) {
            do {
                String contentType = null;
                String contentId = null;
                String contentTransferEncoding = null;
                String contentLocation = null;

                // Read this attachments headers from the stream.
                javax.mail.internet.InternetHeaders headers = new javax.mail.internet.InternetHeaders(
                        boundaryDelimitedStream);

                contentId = headers.getHeader("Content-Id", null);

                if (contentId != null) {
                    contentId = contentId.trim();

                    if (contentId.startsWith("<")) {
                        contentId = contentId.substring(1);
                    }

                    if (contentId.endsWith(">")) {
                        contentId = contentId.substring(0, contentId.length() - 1);
                    }

                    //   if (!contentId.startsWith("cid:")) {
                    //       contentId = "cid:" + contentId;
                    //   }

                    contentId = contentId.trim();
                }

                contentType = headers.getHeader(HTTPConstants.HEADER_CONTENT_TYPE, null);

                if (contentType != null) {
                    contentType = contentType.trim();
                }

                contentLocation = headers.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION, null);

                if (contentLocation != null) {
                    contentLocation = contentLocation.trim();
                }

                contentTransferEncoding = headers.getHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING,
                        null);

                if (contentTransferEncoding != null) {
                    contentTransferEncoding = contentTransferEncoding.trim();
                }

                java.io.InputStream decodedStream = boundaryDelimitedStream;

                if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) {
                    decodedStream = MimeUtility.decode(decodedStream, contentTransferEncoding);
                }

                ManagedMemoryDataSource source = new ManagedMemoryDataSource(decodedStream,
                        ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true);
                DataHandler dh = new DataHandler(source);
                AttachmentPart ap = new AttachmentPart(dh);

                if (contentId != null) {
                    ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId);
                }

                if (contentLocation != null) {
                    ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation);
                }

                for (java.util.Enumeration en = headers.getNonMatchingHeaders(
                        new String[] { HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_LOCATION,
                                HTTPConstants.HEADER_CONTENT_TYPE }); en.hasMoreElements();) {
                    javax.mail.Header header = (javax.mail.Header) en.nextElement();
                    String name = header.getName();
                    String value = header.getValue();

                    if ((name != null) && (value != null)) {
                        name = name.trim();

                        if (name.length() != 0) {
                            ap.addMimeHeader(name, value);
                        }
                    }
                }

                addPart(contentId, contentLocation, ap);

                for (int i = id.length - 1; (ret == null) && (i > -1); --i) {
                    if ((contentId != null) && id[i].equals(contentId)) { // This is the part being sought
                        ret = ap;
                    } else if ((contentLocation != null) && id[i].equals(contentLocation)) {
                        ret = ap;
                    }
                }

                boundaryDelimitedStream = boundaryDelimitedStream.getNextStream();
            } while ((null == ret) && (null != boundaryDelimitedStream));
        }
    } catch (Exception e) {
        throw org.apache.axis.AxisFault.makeFault(e);
    }

    return ret;
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "")
@APIParam(params = { "url", "function(data)" })
public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings)
        throws AddressException, MessagingException {

    if (emailSettings == null) {
        return;/*w  w  w .  ja va  2 s  .  co  m*/
    }

    // final String host = "smtp.gmail.com";
    // final String address = "@gmail.com";
    // final String pass = "";

    Multipart multiPart;
    String finalString = "";

    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", emailSettings.ttl);
    props.put("mail.smtp.host", emailSettings.host);
    props.put("mail.smtp.user", emailSettings.user);
    props.put("mail.smtp.password", emailSettings.password);
    props.put("mail.smtp.port", emailSettings.port);
    props.put("mail.smtp.auth", emailSettings.auth);

    Log.i("Check", "done pops");
    final Session session = Session.getDefaultInstance(props, null);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
    final MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setDataHandler(handler);
    Log.i("Check", "done sessions");

    multiPart = new MimeMultipart();

    InternetAddress toAddress;
    toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Log.i("Check", "added recipient");
    message.setSubject(subject);
    message.setContent(multiPart);
    message.setText(text);

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                MLog.i("check", "transport");
                Transport transport = session.getTransport("smtp");
                MLog.i("check", "connecting");
                transport.connect(emailSettings.host, emailSettings.user, emailSettings.password);
                MLog.i("check", "wana send");
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

                MLog.i("check", "sent");

            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }
    });
    t.start();

}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail from a Mail object/*from ww w  .  ja  va 2s.  c om*/
 */
public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException,
        AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({})", mail);
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (mail.getFrom() != null) {
        InternetAddress from = new InternetAddress(mail.getFrom());
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[mail.getTo().length];
    int i = 0;

    for (String strTo : mail.getTo()) {
        to[i++] = new InternetAddress(strTo);
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    MimeMultipart content = new MimeMultipart();

    if (Mail.MIME_TEXT.equals(mail.getMimeType())) {
        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    } else if (Mail.MIME_HTML.equals(mail.getMimeType())) {
        // HTML Part
        MimeBodyPart htmlPart = new MimeBodyPart();
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
        htmlContent.append("<html>\n<head>\n");
        htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
        htmlContent.append("</head>\n<body>\n");
        htmlContent.append(mail.getContent());
        htmlContent.append("\n</body>\n</html>");
        htmlPart.setContent(htmlContent.toString(), "text/html");
        htmlPart.setHeader("Content-Type", "text/html");
        htmlPart.setDisposition(Part.INLINE);
        content.addBodyPart(htmlPart);
    } else {
        log.warn("Email does not specify content MIME type");

        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    }

    for (Document doc : mail.getAttachments()) {
        InputStream is = null;
        FileOutputStream fos = null;
        String docName = PathUtils.getName(doc.getPath());

        try {
            is = OKMDocument.getInstance().getContent(token, doc.getPath(), false);
            File tmp = File.createTempFile("okm", ".tmp");
            fos = new FileOutputStream(tmp);
            IOUtils.copy(is, fos);
            fos.flush();

            // Document attachment part
            MimeBodyPart docPart = new MimeBodyPart();
            DataSource source = new FileDataSource(tmp.getPath());
            docPart.setDataHandler(new DataHandler(source));
            docPart.setFileName(docName);
            docPart.setDisposition(Part.ATTACHMENT);
            content.addBodyPart(docPart);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(mail.getSubject(), "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:se.vgregion.usdservice.USDServiceImpl.java

private DataHandler createDataHandler(Attachment attachment) {
    DataSource source;/*from w  w  w . j  a  va2s  . co  m*/
    try {
        source = new ByteArrayDataSource(attachment.getData(), "application/octet-stream");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return new DataHandler(source);
}

From source file:org.wso2.appserver.integration.tests.qualityofservice.throtllingservice.ThrottlingTestCase.java

private void messageContextJarUpload() throws Exception { // upload and verify jar file
    JARServiceUploaderClient jarServiceUploaderClient = new JARServiceUploaderClient(backendURL, sessionCookie);
    List<DataHandler> jarList = new ArrayList<DataHandler>();
    URL url = new URL("file://" + FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator
            + "AS" + File.separator + "jar" + File.separator + "artifact4" + File.separator
            + "MessageContext.jar");
    DataHandler dh = new DataHandler(url);
    jarList.add(dh);/*from www  .  java2  s  .  c  o m*/

    jarServiceUploaderClient.uploadJARServiceFile("", jarList, dh);
    boolean deployedStatus = isServiceDeployed("MessageContextService");
    assertTrue(deployedStatus, "MessageContext.jar upload failed");
    log.info("MessageContext.jar uploaded and deployed successfully");
}