Example usage for javax.activation DataHandler DataHandler

List of usage examples for javax.activation DataHandler DataHandler

Introduction

In this page you can find the example usage for javax.activation DataHandler DataHandler.

Prototype

public DataHandler(URL url) 

Source Link

Document

Create a DataHandler instance referencing a URL.

Usage

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param contentType//from ww w . j  a  v a  2 s  .  c o  m
 * @param msg
 * @return
 * @throws IOException
 * @throws MessagingException
 * @throws GeneralSecurityException
 */
public static MimeBodyPart compressContent(String contentType, StreamData msg)
        throws IOException, MessagingException, GeneralSecurityException {

    tstEStrArg("content-type", contentType);
    tstObjArg("input-content", msg);

    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();
    MimeBodyPart bp = new MimeBodyPart();
    SmDataSource ds;

    if (msg.isDiskFile()) {
        ds = new SmDataSource(msg.getFileRef(), contentType);
    } else {
        ds = new SmDataSource(msg.getBytes(), contentType);
    }

    bp.setDataHandler(new DataHandler(ds));
    try {
        return gen.generate(bp, SMIMECompressedGenerator.ZLIB);
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private MimeMessage prepareMessageWithAttachment(String scriptContent, String subject)
        throws MessagingException, IOException {
    MimeMessage message = prepareMimeMessage(subject);
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(//from  w w w  .java 2s .  co  m
            new DataHandler(new ByteArrayDataSource(scriptContent, "application/sieve; charset=UTF-8")));
    scriptPart.setDisposition(MimeBodyPart.ATTACHMENT);
    // setting a DataHandler with no mailcap definition is not
    // supported by the specs. Javamail activation still work,
    // but Geronimo activation translate it to text/plain.
    // Let's manually force the header.
    scriptPart.setHeader("Content-Type", "application/sieve; charset=UTF-8");
    scriptPart.setFileName(SCRIPT_NAME);
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    return message;
}

From source file:org.paxle.core.doc.impl.BasicDocumentFactoryTest.java

public void testLoadUnmarshalledCommand() throws IOException, ParseException {
    final ZipFile zf = new ZipFile(new File("src/test/resources/command.zip"));

    // process attachments
    final Map<String, DataHandler> attachments = new HashMap<String, DataHandler>();
    for (Enumeration<? extends ZipEntry> entries = zf.entries(); entries.hasMoreElements();) {
        final ZipEntry entry = entries.nextElement();
        final String name = entry.getName();
        if (name.equals("command.xml"))
            continue;

        // create a data-source to load the attachment
        final DataSource source = new DataSource() {
            private ZipFile zip = zf;
            private ZipEntry zipEntry = entry;

            public String getContentType() {
                return "application/x-java-serialized-object";
            }//from w  w w  .  j  a v a 2s  . c o  m

            public InputStream getInputStream() throws IOException {
                return this.zip.getInputStream(this.zipEntry);
            }

            public String getName() {
                return this.zipEntry.getName();
            }

            public OutputStream getOutputStream() throws IOException {
                throw new UnsupportedOperationException();
            }
        };
        final DataHandler handler = new DataHandler(source);
        attachments.put(name, handler);
    }

    // process command
    final ZipEntry commandEntry = zf.getEntry("command.xml");
    final InputStream commandInput = zf.getInputStream(commandEntry);

    // marshal command
    TeeInputStream input = new TeeInputStream(commandInput, System.out);
    final ICommand cmd1 = this.docFactory.unmarshal(input, attachments);
    assertNotNull(cmd1);
    zf.close();

    final ICommand cmd2 = this.createTestCommand();
    assertEquals(cmd2, cmd1);
}

From source file:com.emc.kibana.emailer.KibanaEmailer.java

private static void sendFileEmail(String security) {

    final String username = smtpUsername;
    final String password = smtpPassword;

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);

    if (security.equals(SMTP_SECURITY_TLS)) {
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.port", smtpPort);
    } else if (security.equals(SMTP_SECURITY_SSL)) {
        properties.put("mail.smtp.socketFactory.port", smtpPort);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", smtpPort);
    }//from  w w  w.j  a va  2 s .co m

    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

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

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

        // Set To: header field of the header.
        for (String destinationAddress : destinationAddressList) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress));
        }

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

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        StringBuffer bodyBuffer = new StringBuffer(mailBody);
        if (!kibanaUrls.isEmpty()) {
            bodyBuffer.append("\n\n");
        }

        // Add urls info to e-mail
        for (Map<String, String> kibanaUrl : kibanaUrls) {
            // Add urls to e-mail
            String urlName = kibanaUrl.get(NAME_KEY);
            String reportUrl = kibanaUrl.get(URL_KEY);
            if (urlName != null && reportUrl != null) {
                bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n");
            }
        }

        // Fill the message
        messageBodyPart.setText(bodyBuffer.toString());

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

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

        // Part two is attachments
        for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) {
            messageBodyPart = new MimeBodyPart();
            String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY);
            String filename = kibanaScreenCapture.get(FILE_NAME_KEY);
            DataSource source = new FileDataSource(absoluteFilename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);
        }

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

        // Send message
        Transport.send(message);
        logger.info("Sent mail message successfully");
    } catch (MessagingException mex) {
        throw new RuntimeException(mex);
    }
}

From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java

private void processZipFile(ExtrinsicObjectType zipEO, InputSource inputSource)
        throws JAXRException, JAXBException, IOException, CatalogingException {
    // This method unzips the zip file and places all files in the idToFileMap
    // This method also places all files from a zip file in a Map. This is done so 
    // that a file can be looked up at any time during the processing of any other file
    Collection<File> files = addZipEntriesToMap(zipEO, inputSource);
    //Now iterate and create ExtrinsicObject - Repository Item pair for each unzipped file

    Iterator<File> iter = files.iterator();
    while (iter.hasNext()) {
        File file = iter.next();/*w w  w  .  j a  v  a2  s  . c  o  m*/
        @SuppressWarnings("unused")
        String fileName = file.getName();
        String fileNameAbsolute = file.getAbsolutePath();
        String tmp_dir = TMP_DIR;
        if (!tmp_dir.endsWith(File.separator)) {
            tmp_dir = tmp_dir + File.separator;
        }
        String fileNameRelative = fileNameAbsolute.substring(tmp_dir.length(), fileNameAbsolute.length());
        // TODO: the id below is a temporary id. Create final id using 
        // namespace of the wsdl:service
        // Assign repository item to idToRepositoryItemMap
        idToRepositoryItemMap.put(fileNameRelative,
                new RepositoryItemImpl(fileNameRelative, new DataHandler(new FileDataSource(file))));
        // Get the ExtrinsicObjectType instance for this file using the 
        // relative file name as the key            
        currentRelativeFilename = fileNameRelative;
        ExtrinsicObjectType eo = createExtrinsicObject(fileNameRelative);
        // Create the InputSource
        String urlStr = fileNameAbsolute;
        urlStr = Utility.absolutize(Utility.getFileOrURLName(urlStr));
        inputSource = new InputSource(urlStr);
        if (eo.getObjectType().equals(CanonicalConstants.CANONICAL_OBJECT_TYPE_ID_WSDL)) {
            catalogWSDLExtrinsicObject(eo, inputSource);
        } else if (eo.getObjectType().equals(CanonicalConstants.CANONICAL_OBJECT_TYPE_ID_XMLSchema)) {
            catalogXMLSchemaExtrinsicObject(eo, inputSource);
        }
    }
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

protected Message createMessage(String personalName, String sender, Address[] to, Address[] cc, Address[] bcc,
        String subject, String body, List<MailFile> mailFiles)
        throws MessagingException, UnsupportedEncodingException {

    Message jxMessage = new MimeMessage(_imapConnection.getSession());

    jxMessage.setFrom(new InternetAddress(sender, personalName));
    jxMessage.addRecipients(Message.RecipientType.TO, to);
    jxMessage.addRecipients(Message.RecipientType.CC, cc);
    jxMessage.addRecipients(Message.RecipientType.BCC, bcc);
    jxMessage.setSentDate(new Date());
    jxMessage.setSubject(subject);//  w  w  w.  j  a  v  a2 s  . com

    MimeMultipart multipart = new MimeMultipart();

    BodyPart messageBodyPart = new MimeBodyPart();

    messageBodyPart.setContent(body, ContentTypes.TEXT_HTML_UTF8);

    multipart.addBodyPart(messageBodyPart);

    if (mailFiles != null) {
        for (MailFile mailFile : mailFiles) {
            File file = mailFile.getFile();

            if (!file.exists()) {
                continue;
            }

            DataSource dataSource = new FileDataSource(file);

            BodyPart attachmentBodyPart = new MimeBodyPart();

            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(mailFile.getFileName());

            multipart.addBodyPart(attachmentBodyPart);
        }
    }

    jxMessage.setContent(multipart);

    return jxMessage;
}

From source file:org.apache.servicemix.http.HttpSoapTest.java

public void testAttachments() throws Exception {
    EchoComponent echo = new EchoComponent();
    echo.setService(new QName("urn:test", "echo"));
    echo.setEndpoint("echo");
    container.activateComponent(echo, "echo");

    HttpComponent http = new HttpComponent();

    HttpEndpoint ep0 = new HttpEndpoint();
    ep0.setService(new QName("urn:test", "s0"));
    ep0.setEndpoint("ep0");
    ep0.setLocationURI("http://localhost:8192/ep1/");
    ep0.setRoleAsString("provider");
    ep0.setSoap(true);/*  w ww  .  j  a  va  2s.c o  m*/

    HttpEndpoint ep1 = new HttpEndpoint();
    ep1.setService(new QName("urn:test", "s1"));
    ep1.setEndpoint("ep1");
    ep1.setTargetService(new QName("urn:test", "s2"));
    ep1.setLocationURI("http://localhost:8192/ep1/");
    ep1.setRoleAsString("consumer");
    ep1.setDefaultMep(URI.create("http://www.w3.org/2004/08/wsdl/in-out"));
    ep1.setSoap(true);

    HttpEndpoint ep2 = new HttpEndpoint();
    ep2.setService(new QName("urn:test", "s2"));
    ep2.setEndpoint("ep2");
    ep2.setLocationURI("http://localhost:8192/ep3/");
    ep2.setRoleAsString("provider");
    ep2.setSoap(true);

    HttpEndpoint ep3 = new HttpEndpoint();
    ep3.setService(new QName("urn:test", "s3"));
    ep3.setEndpoint("ep3");
    ep3.setTargetService(new QName("urn:test", "echo"));
    ep3.setLocationURI("http://localhost:8192/ep3/");
    ep3.setRoleAsString("consumer");
    ep3.setDefaultMep(URI.create("http://www.w3.org/2004/08/wsdl/in-out"));
    ep3.setSoap(true);

    http.setEndpoints(new HttpEndpoint[] { ep0, ep1, ep2, ep3 });

    container.activateComponent(http, "http");

    container.start();

    DefaultServiceMixClient client = new DefaultServiceMixClient(container);
    Destination d = client.createDestination("service:urn:test:s0");
    InOut me = d.createInOutExchange();
    me.getInMessage().setContent(new StringSource("<hello>world</hello>"));
    File f = new File(getClass().getResource("servicemix.jpg").getFile());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileUtil.copyInputStream(new FileInputStream(f), baos);
    DataSource ds = new ByteArrayDataSource(baos.toByteArray(), "image/jpeg");
    DataHandler dh = new DataHandler(ds);
    me.getInMessage().addAttachment("image", dh);
    client.sendSync(me);
    assertEquals(ExchangeStatus.ACTIVE, me.getStatus());
    assertEquals(1, me.getOutMessage().getAttachmentNames().size());
    client.done(me);
}

From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java

private void addEncryptedPDF(MimeMessage message, byte[] pdf) throws MessagingException {
    /*//from w  w w  .  ja  v a2 s. c  om
     * Find the existing PDF. The expect that the message is a multipart/mixed. 
     */
    if (!message.isMimeType("multipart/mixed")) {
        throw new MessagingException("Content-type should have been multipart/mixed.");
    }

    Multipart mp;

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

    BodyPart pdfPart = null;

    /*
     * Fallback in case the template does not contain a DjigzoHeader.MARKER
     */
    BodyPart fallbackPart = null;

    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) {
            pdfPart = part;

            break;
        }

        /*
         * Fallback scanning for application/pdf in case the template does not contain a DjigzoHeader.MARKER
         */
        if (part.isMimeType("application/pdf")) {
            fallbackPart = part;
        }
    }

    if (pdfPart == null) {
        if (fallbackPart != null) {
            getLogger().info("Marker not found. Using ocet-stream instead.");

            /*
             * Use the octet-stream part
             */
            pdfPart = fallbackPart;
        } else {
            throw new MessagingException("Unable to find the attachment part in the template.");
        }
    }

    pdfPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pdf, "application/pdf")));
}

From source file:org.jlibrary.core.repository.axis.AxisRepositoryService.java

private void createAttachment(byte[] content) throws IOException {
    // We will add the content as attachment instead         
    MessageContext context = MessageContext.getCurrentContext();
    Message message = context.getResponseMessage();
    DataHandler handler = new DataHandler(new ByteArrayDataSource(content, "application/octet-stream"));
    javax.xml.soap.AttachmentPart attachment = message.createAttachmentPart(handler);
    message.addAttachmentPart(attachment);
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param cType//  www. j  ava 2  s . c o m
 * @param cte
 * @param contentLoc
 * @param cid
 * @param msg
 * @return
 * @throws MessagingException
 * @throws IOException
 * @throws GeneralSecurityException
 */
public static MimeBodyPart compressContent(String cType, String cte, String contentLoc, String cid,
        StreamData msg) throws MessagingException, IOException, GeneralSecurityException {

    tstEStrArg("content-type", cType);
    tstEStrArg("content-id", cid);
    tstObjArg("input-content", msg);

    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();
    MimeBodyPart bp = new MimeBodyPart();
    SmDataSource ds;

    if (msg.isDiskFile()) {
        ds = new SmDataSource(msg.getFileRef(), cType);
    } else {
        ds = new SmDataSource(msg.getBytes(), cType);
    }

    if (!isEmpty(contentLoc)) {
        bp.setHeader("content-location", contentLoc);
    }

    try {
        bp.setHeader("content-id", cid);
        bp.setDataHandler(new DataHandler(ds));
        bp = gen.generate(bp, SMIMECompressedGenerator.ZLIB);
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }

    if (true) {
        int pos = cid.lastIndexOf(">");
        if (pos >= 0) {
            cid = cid.substring(0, pos) + "--z>";
        } else {
            cid = cid + "--z";
        }
    }

    if (!isEmpty(contentLoc)) {
        bp.setHeader("content-location", contentLoc);
    }
    bp.setHeader("content-id", cid);

    // always base64
    cte = "base64";

    if (!isEmpty(cte)) {
        bp.setHeader("content-transfer-encoding", cte);
    }

    return bp;
}