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.wso2.carbon.attachment.mgt.test.AttachmentMgtDAOBasicOperationsTest.java

/**
 * Creates an attachment stub bean which is consumable by the Back-End server interface
 * {@link org.wso2.carbon.attachment.mgt.skeleton.AttachmentMgtServiceSkeletonInterface}
 *
 * @return an attachment stub bean which is consumable by the Back-End server interface
 *//*  www .ja  v a 2  s  . c  o  m*/
private TAttachment createAttachment() {
    dummyAttachment = new TAttachment();
    dummyAttachment.setName("DummyName");
    dummyAttachment.setContentType("DummyContentType");
    dummyAttachment.setCreatedBy("DummyUser");

    DataHandler handler = new DataHandler(new FileDataSource(new File(
            "src" + File.separator + "test" + File.separator + "resources" + File.separator + "dbConfig.xml")));
    dummyAttachment.setContent(handler);

    return dummyAttachment;
}

From source file:org.unitime.commons.Email.java

public void addAttachement(final FormFile file) throws MessagingException {
    BodyPart attachement = new MimeBodyPart();
    attachement.setDataHandler(new DataHandler(new DataSource() {
        @Override//from   ww w . j a  v a2 s .  c  o m
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("No output stream.");
        }

        @Override
        public String getName() {
            return file.getFileName();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return file.getInputStream();
        }

        @Override
        public String getContentType() {
            return file.getContentType();
        }
    }));
    attachement.setFileName(file.getFileName());
    iBody.addBodyPart(attachement);
}

From source file:com.github.thorqin.webapi.mail.MailService.java

private void doSendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    Session session;/*from  www. j  a  v a2s .c o m*/
    props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication()));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", serverConfig.getHost());
    if (serverConfig.getPort() != null) {
        props.put("mail.smtp.port", serverConfig.getPort());
    }
    if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", serverConfig.getPort());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else {
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    }

    // Uncomment to show SMTP protocal
    // session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (serverConfig.getFrom() != null)
            message.setFrom(new InternetAddress(serverConfig.getFrom()));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (serverConfig.enableTrace()) {
            MailInfo info = new MailInfo();
            info.recipients = mail.to;
            info.sender = StringUtil.join(message.getFrom());
            info.smtpServer = serverConfig.getHost();
            info.smtpUser = serverConfig.getUsername();
            info.subject = mail.subject;
            info.startTime = beginTime;
            info.runningTime = System.currentTimeMillis() - beginTime;
            MonitorService.record(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:org.wso2.appserver.integration.common.utils.SpringServiceMaker.java

public void createAndUploadSpringBean(String springContextFilePath, String springBeanFilePath,
        String sessionCookie, String backendURL) throws Exception {
    SpringBeansData data = getSpringBeanNames(springContextFilePath, springBeanFilePath,
            this.getClass().getClassLoader());
    String beanClasses[] = data.getBeans();

    if (springBeanFilePath == null) {
        String msg = "spring.non.existent.file";
        log.warn(msg);//w ww  .j  ava 2s  .c om
        throw new AxisFault(msg);
    }

    int endIndex = springBeanFilePath.lastIndexOf(File.separator);
    String filePath = springBeanFilePath.substring(0, endIndex);
    String archiveFileName = springBeanFilePath.substring(endIndex);
    archiveFileName = archiveFileName.substring(1, archiveFileName.lastIndexOf("."));

    ArchiveManipulator archiveManipulator = new ArchiveManipulator();

    // ----------------- Unzip the file ------------------------------------
    String unzippeDir = filePath + File.separator + "springTemp";
    File unzipped = new File(unzippeDir);
    unzipped.mkdirs();

    try {
        archiveManipulator.extract(springBeanFilePath, unzippeDir);
    } catch (IOException e) {
        String msg = "spring.cannot.extract.archive";
        handleException(msg, e);
    }

    // TODO copy the spring xml
    String springContextRelLocation = "spring/context.xml";
    try {
        File springContextRelDir = new File(unzippeDir + File.separator + "spring");
        springContextRelDir.mkdirs();
        File absFile = new File(springContextRelDir, "context.xml");
        if (!absFile.exists()) {
            absFile.createNewFile();
        }
        File file = new File(springContextFilePath);
        FileInputStream in = new FileInputStream(file);
        FileOutputStream out = new FileOutputStream(absFile);
        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();

    } catch (FileNotFoundException e) {
        throw AxisFault.makeFault(e);
    } catch (IOException e) {
        throw AxisFault.makeFault(e);
    }

    // ---- Generate the services.xml and place it in META-INF -----
    File file = new File(unzippeDir + File.separator + "META-INF" + File.separator + "services.xml");
    file.mkdirs();

    try {
        File absoluteFile = file.getAbsoluteFile();

        if (absoluteFile.exists()) {
            absoluteFile.delete();
        }

        absoluteFile.createNewFile();

        OutputStream os = new FileOutputStream(file);
        OMElement servicesXML = createServicesXMLFromSpringBeans(beanClasses, springContextRelLocation);
        servicesXML.build();
        servicesXML.serialize(os);
    } catch (Exception e) {
        String msg = "spring.cannot.write.services.xml";
        handleException(msg, e);
    }

    // ----------------- Create the AAR ------------------------------------
    // These are the files to include in the ZIP file
    String outAARFilename = filePath + File.separator + archiveFileName + ".aar";

    try {
        archiveManipulator.archiveDir(outAARFilename, unzipped.getPath());
    } catch (IOException e) {
        String msg = "Spring cannot create new aar archive";
        handleException(msg, e);
    }

    File fileToUpload = new File(outAARFilename);

    FileDataSource fileDataSource = new FileDataSource(fileToUpload);
    DataHandler dataHandler = new DataHandler(fileDataSource);

    try {
        SpringServiceUploaderClient uploaderClient = new SpringServiceUploaderClient(backendURL, sessionCookie);
        uploaderClient.uploadSpringServiceFile(archiveFileName + ".aar", dataHandler);
    } catch (Exception e) {
        String msg = "spring.unable.to.upload";
        handleException(msg, e);
    }

}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods,
        String audio) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from w w w .  ja v a2  s .c  om
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(imageds));
    messageBodyPart.setFileName(image);
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(audiods));
    messageBodyPart.setFileName(audio);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);

}

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

private void gereBonLivraisonDansMail(AppockMail appockMail, MimeMessage msg, String contenuFinal)
        throws MessagingException {
    if (appockMail.getBonLivraison() == null) {
        msg.setContent(contenuFinal, "text/html; charset=utf-8");
    } else {//w ww.j av  a2s  .  c  o m
        BonLivraison bonLivraison = appockMail.getBonLivraison();
        Multipart multipart = new MimeMultipart();
        BodyPart attachmentBodyPart = new MimeBodyPart();

        File file = commandeServiceService.getFileBonLivraison(appockMail.getBonLivraison());

        ByteArrayDataSource bds = null;
        try {
            bds = new ByteArrayDataSource(Files.readAllBytes(file.toPath()),
                    bonLivraison.getMimeType().getLibelle());
        } catch (IOException e) {
            e.printStackTrace();
        }

        attachmentBodyPart.setDataHandler(new DataHandler(bds));
        attachmentBodyPart.setFileName(bonLivraison.getNomFichier());
        multipart.addBodyPart(attachmentBodyPart);

        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(contenuFinal, "text/html; charset=utf-8");
        multipart.addBodyPart(htmlBodyPart);
        msg.setContent(multipart);
    }
}

From source file:org.nuxeo.ecm.automation.core.mail.Composer.java

public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType,
        List<Blob> attachments) throws TemplateException, IOException, MessagingException {
    if (textType == null) {
        textType = "plain";
    }/* ww  w  .  j  a v a2  s  .  c  om*/
    Mailer.Message msg = mailer.newMessage();
    MimeMultipart mp = new MimeMultipart();
    MimeBodyPart body = new MimeBodyPart();
    String result = render(templateContent, ctx);
    body.setText(result, "UTF-8", textType);
    mp.addBodyPart(body);
    for (Blob blob : attachments) {
        MimeBodyPart a = new MimeBodyPart();
        a.setDataHandler(new DataHandler(new BlobDataSource(blob)));
        a.setFileName(blob.getFilename());
        mp.addBodyPart(a);
    }
    msg.setContent(mp);
    return msg;
}

From source file:eu.domibus.ebms3.sender.EbMS3MessageBuilder.java

private void attachPayload(PartInfo partInfo, SOAPMessage message)
        throws ParserConfigurationException, SOAPException, IOException, SAXException {
    String mimeType = null;//from w  w w  . java 2 s . c  om
    boolean compressed = false;
    for (Property prop : partInfo.getPartProperties().getProperties()) {
        if (Property.MIME_TYPE.equals(prop.getName())) {
            mimeType = prop.getValue();
        }
        if (CompressionService.COMPRESSION_PROPERTY_KEY.equals(prop.getName())
                && CompressionService.COMPRESSION_PROPERTY_VALUE.equals(prop.getValue())) {
            compressed = true;
        }
    }
    byte[] binaryData = this.attachmentDAO.loadBinaryData(partInfo.getEntityId());
    DataSource dataSource = new ByteArrayDataSource(binaryData,
            compressed ? CompressionService.COMPRESSION_PROPERTY_VALUE : mimeType);
    DataHandler dataHandler = new DataHandler(dataSource);
    if (partInfo.isInBody() && mimeType != null && mimeType.toLowerCase().contains("xml")) { //TODO: respect empty soap body config
        this.documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder builder = this.documentBuilderFactory.newDocumentBuilder();
        message.getSOAPBody().addDocument(builder.parse(dataSource.getInputStream()));
        partInfo.setHref(null);
        return;
    }
    AttachmentPart attachmentPart = message.createAttachmentPart(dataHandler);
    attachmentPart.setContentId(partInfo.getHref());
    message.addAttachmentPart(attachmentPart);
}

From source file:dtw.webmail.util.FormdataMultipart.java

/**
 * Processes a body part of the form-data.
 * Extracts parameters and set values, and
 * leaves over the attachments.//from   w w w.  java  2s. c o  m
 *
 * @param mbp the <tt>MimeBodyPart</tt> to be processed.
 *
 * @throws IOException if i/o operations fail.
 * @throws MessagingException if parsing or part handling with
 *         Mail API classes fails.
 */
private void processBodyPart(MimeBodyPart mbp) throws MessagingException, IOException {

    //String contenttype=new String(mbp.getContentType());
    //JwmaKernel.getReference().debugLog().write("Processing "+contenttype);

    //check if a content-type is given
    String[] cts = mbp.getHeader("Content-Type");
    if (cts == null || cts.length == 0) {
        //this is a parameter, get it out and
        //remove the part.
        String controlname = extractName((mbp.getHeader("Content-Disposition"))[0]);

        //JwmaKernel.getReference().debugLog().write("Processing control:"+controlname);
        //retrieve value observing encoding
        InputStream in = mbp.getInputStream();
        String[] encoding = mbp.getHeader("Content-Transfer-Encoding");
        if (encoding != null && encoding.length > 0) {
            in = MimeUtility.decode(in, encoding[0]);
        }

        String value = extractValue(in);
        if (value != null || !value.trim().equals("")) {
            addParameter(controlname, value);
        }
        //flag removal
        m_Removed = true;
        removeBodyPart(mbp);
    } else {
        String filename = extractFileName((mbp.getHeader("Content-Disposition"))[0]);

        //normally without file the control should be not successful.
        //but neither netscape nor mircosoft iexploder care much.
        //the only feature is an empty filename.
        if (filename.equals("")) {
            //kick it out too
            m_Removed = true;
            removeBodyPart(mbp);
        } else {

            //JwmaKernel.getReference().debugLog().write("Incoming filename="+filename);

            //IExploder sends files with complete path.
            //jwma doesnt want this.
            int lastindex = filename.lastIndexOf("\\");
            if (lastindex != -1) {
                filename = filename.substring(lastindex + 1, filename.length());
            }

            //JwmaKernel.getReference().debugLog().write("Outgoing filename="+filename);

            //Observe a possible encoding
            InputStream in = mbp.getInputStream();
            String[] encoding = mbp.getHeader("Content-Transfer-Encoding");
            if (encoding != null && encoding.length > 0) {
                in = MimeUtility.decode(in, encoding[0]);
            }
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            OutputStream out = (OutputStream) bout;

            int i = 0;
            while ((i = in.read()) != -1) {
                //maybe more efficient in buffers, but well
                out.write(i);
            }
            out.flush();
            out.close();

            //create the datasource
            MimeBodyPartDataSource mbpds = new MimeBodyPartDataSource(
                    //    contenttype,filename,bout.toByteArray()
                    cts[0], filename, bout.toByteArray());

            //Re-set the Content-Disposition header, in case
            //the file name was changed
            mbp.removeHeader("Content-Disposition");
            mbp.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

            //set a base64 transferencoding und the data handler
            mbp.addHeader("Content-Transfer-Encoding", "base64");
            mbp.setDataHandler(new DataHandler(mbpds));
        }
    }
}

From source file:com.vaushell.superpipes.dispatch.ErrorMailer.java

private void sendHTML(final String message) throws MessagingException, IOException {
    if (message == null || message.isEmpty()) {
        throw new IllegalArgumentException("message");
    }//from  w  w w  .  j  a v  a 2s  .c om

    final String host = properties.getConfigString("host");

    final Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", host);

    final String port = properties.getConfigString("port", null);
    if (port != null) {
        props.setProperty("mail.smtp.port", port);
    }

    if ("true".equalsIgnoreCase(properties.getConfigString("ssl", null))) {
        props.setProperty("mail.smtp.ssl.enable", "true");
    }

    final Session session = Session.getInstance(props, null);
    //        session.setDebug( true );

    final javax.mail.Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(properties.getConfigString("from")));

    msg.setRecipients(javax.mail.Message.RecipientType.TO,
            InternetAddress.parse(properties.getConfigString("to"), false));

    msg.setSubject("superpipes error message");

    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, "text/html")));

    msg.setHeader("X-Mailer", "superpipes");

    Transport t = null;
    try {
        t = session.getTransport("smtp");

        final String username = properties.getConfigString("username", null);
        final String password = properties.getConfigString("password", null);
        if (username == null || password == null) {
            t.connect();
        } else {
            if (port == null || port.isEmpty()) {
                t.connect(host, username, password);
            } else {
                t.connect(host, Integer.parseInt(port), username, password);
            }
        }

        t.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }
}