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:de.kp.ames.web.function.security.SecurityServiceImpl.java

/**
 * A helper method to create a new password safe
 * //from w ww.ja v  a  2  s.  c  om
 * @param service
 * @param creds
 * @param user
 * @throws JAXRException
 * @throws JSONException
 * @throws UnsupportedEncodingException
 */
private void createSafe(String service, String creds, UserImpl user)
        throws JAXRException, JSONException, UnsupportedEncodingException {

    JaxrTransaction transaction = new JaxrTransaction();

    /* 
     * Create credentials as JSON object
     */
    JSONObject jCredentials = new JSONObject(creds);

    String rimName = null;
    String rimDesc = null;
    String rimHome = null;

    JSONObject jSafe = new JSONObject();
    jSafe.put(service, jCredentials);

    byte[] bytes = jSafe.toString().getBytes("UTF-8");
    DataHandler handler = new DataHandler(FileUtil.createByteArrayDataSource(bytes, "application/json"));

    /*
     * Create extrinsic object 
     */
    JaxrLCM lcm = new JaxrLCM(jaxrHandle);
    ExtrinsicObjectImpl eo = lcm.createExtrinsicObject();

    /* 
     * Identifier
     */
    String eoid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.SECURITY_PRE);

    eo.setLid(eoid);
    eo.getKey().setId(eoid);

    /* 
     * Name & description
     */
    rimName = "Password Safe";
    eo.setName(lcm.createInternationalString(rimName));

    rimDesc = "This is an auto-generated password safe";
    eo.setDescription(lcm.createInternationalString(rimDesc));

    /* 
     * Home url
     */
    rimHome = jaxrHandle.getEndpoint().replace("/saml", "");
    eo.setHome(rimHome);

    /* 
     * Mimetype & repository item
     */
    eo.setMimeType("application/json");
    eo.setRepositoryItem(handler);

    /*
     * Make sure that the registry object is processed
     * right before any references to this object are 
     * made (e.g. classifications, external links)
     */
    transaction.addObjectToSave(eo);

    /*
     * Create classification
     */
    ClassificationImpl c = lcm.createClassification(ClassificationConstants.FNC_SECURITY_ID_Safe);
    c.setName(lcm.createInternationalString("Security Classification"));

    /* 
     * Associate classification and password safe
     */
    eo.addClassification(c);
    transaction.addObjectToSave(c);

    /*
     * Associate user and safe instance
     */
    AssociationImpl a = lcm.createAssociation_RelatedTo(eo);
    user.addAssociation(a);

    /* 
     * Identifier
     */
    String aid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.SECURITY_PRE);

    a.setLid(aid);
    a.getKey().setId(aid);

    /* 
     * Name & description
     */
    rimName = "User - relatedTo - Safe";
    a.setName(lcm.createInternationalString(rimName));

    rimDesc = "This is a relation between a registry user and his assigned password safe";
    a.setDescription(lcm.createInternationalString(rimDesc));

    /* 
     * Home url
     */
    a.setHome(rimHome);

    /*
     * User must be updated as an association
     * has been added
     */
    transaction.addObjectToSave(user);

    /* 
     * Confirm association
     */
    lcm.confirmAssociation(a);
    lcm.saveObjects(transaction.getObjectsToSave(), false, false);

}

From source file:com.zimbra.cs.service.mail.CreateContact.java

private static Attachment parseAttachment(Element elt, String name, ZimbraSoapContext zsc,
        OperationContext octxt, Contact existing) throws ServiceException {
    // check for uploaded attachment
    String attachId = elt.getAttribute(MailConstants.A_ATTACHMENT_ID, null);
    if (attachId != null) {
        if (Contact.isSMIMECertField(name)) {
            elt.setText(parseCertificate(elt, name, zsc, octxt, existing));
            return null;
        } else {/*from  w w  w . jav  a 2  s  .  c o  m*/
            Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), attachId,
                    zsc.getAuthToken());
            UploadDataSource uds = new UploadDataSource(up);
            return new Attachment(new DataHandler(uds), name, (int) up.getSize());
        }
    }

    int itemId = (int) elt.getAttributeLong(MailConstants.A_ID, -1);
    String part = elt.getAttribute(MailConstants.A_PART, null);
    if (itemId != -1 || (part != null && existing != null)) {
        MailItem item = itemId == -1 ? existing
                : getRequestedMailbox(zsc).getItemById(octxt, itemId, MailItem.Type.UNKNOWN);

        try {
            if (item instanceof Contact) {
                Contact contact = (Contact) item;
                if (part != null && !part.equals("")) {
                    try {
                        int partNum = Integer.parseInt(part) - 1;
                        if (partNum >= 0 && partNum < contact.getAttachments().size()) {
                            Attachment att = contact.getAttachments().get(partNum);
                            return new Attachment(att.getDataHandler(), name, att.getSize());
                        }
                    } catch (NumberFormatException nfe) {
                    }
                    throw ServiceException.INVALID_REQUEST("invalid contact part number: " + part, null);
                } else {
                    VCard vcf = VCard.formatContact(contact);
                    return new Attachment(vcf.getFormatted().getBytes("utf-8"), "text/x-vcard; charset=utf-8",
                            name, vcf.fn + ".vcf");
                }
            } else if (item instanceof Message) {
                Message msg = (Message) item;
                if (part != null && !part.equals("")) {
                    try {
                        MimePart mp = Mime.getMimePart(msg.getMimeMessage(), part);
                        if (mp == null) {
                            throw MailServiceException.NO_SUCH_PART(part);
                        }
                        DataSource ds = new MimePartDataSource(mp);
                        return new Attachment(new DataHandler(ds), name);
                    } catch (MessagingException me) {
                        throw ServiceException.FAILURE("error parsing blob", me);
                    }
                } else {
                    DataSource ds = new MessageDataSource(msg);
                    return new Attachment(new DataHandler(ds), name, (int) msg.getSize());
                }
            } else if (item instanceof Document) {
                Document doc = (Document) item;
                if (part != null && !part.equals("")) {
                    throw MailServiceException.NO_SUCH_PART(part);
                }
                DataSource ds = new DocumentDataSource(doc);
                return new Attachment(new DataHandler(ds), name, (int) doc.getSize());
            }
        } catch (IOException ioe) {
            throw ServiceException.FAILURE("error attaching existing item data", ioe);
        } catch (MessagingException e) {
            throw ServiceException.FAILURE("error attaching existing item data", e);
        }
    }

    return null;
}

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

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param file     The file.//from   w w  w .  j a v  a2 s  .co m
 * @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 createMimeBodyPartFromBinaryFile(final File file, final String contentType,
        String fileName) throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        FileDataSource fileDataSource1 = new FileDataSource(file) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(fileDataSource1));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra binrfil", e);
    }
}

From source file:com.gtwm.jasperexecute.RunJasperReports.java

public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients,
        String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException {
    Properties props = new Properties();
    //props.setProperty("mail.debug", "true");
    props.setProperty("mail.smtp.host", emailHost);
    if (emailUser != null) {
        props.setProperty("mail.smtp.auth", "true");
    }/*from w w  w  .ja  va2s  .  c  o  m*/
    Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass);
    Session mailSession = Session.getDefaultInstance(props, emailAuthenticator);
    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");
    // transport.connect(emailHost, emailUser, emailPass);
    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

private void handlePart(PipelineContext pipelineContext, String dataInputSystemId, Part parentPart,
        Element partOrBodyElement) throws Exception {
    final String name = partOrBodyElement.attributeValue("name");
    String contentTypeAttribute = partOrBodyElement.attributeValue("content-type");
    final String contentType = NetUtils.getContentTypeMediaType(contentTypeAttribute);
    final String charset;
    {/*from   ww w .j a v  a  2s.c  o  m*/
        final String c = NetUtils.getContentTypeCharset(contentTypeAttribute);
        charset = (c != null) ? c : DEFAULT_CHARACTER_ENCODING;
    }
    final String contentTypeWithCharset = contentType + "; charset=" + charset;
    final String src = partOrBodyElement.attributeValue("src");

    // Either a String or a FileItem
    final Object content;
    if (src != null) {
        // Content of the part is not inline

        // Generate a FileItem from the source
        final SAXSource source = getSAXSource(EmailProcessor.this, pipelineContext, src, dataInputSystemId,
                contentType);
        content = handleStreamedPartContent(pipelineContext, source);
    } else {
        // Content of the part is inline

        // In the cases of text/html and XML, there must be exactly one root element
        final boolean needsRootElement = "text/html".equals(contentType);// || ProcessorUtils.isXMLContentType(contentType);
        if (needsRootElement && partOrBodyElement.elements().size() != 1)
            throw new ValidationException(
                    "The <body> or <part> element must contain exactly one element for text/html",
                    (LocationData) partOrBodyElement.getData());

        // Create Document and convert it into a String
        final Element rootElement = (Element) (needsRootElement ? partOrBodyElement.elements().get(0)
                : partOrBodyElement);
        final Document partDocument = new NonLazyUserDataDocument();
        partDocument.setRootElement((Element) rootElement.clone());
        content = handleInlinePartContent(partDocument, contentType);
    }

    if (!XMLUtils.isTextOrJSONContentType(contentType)) {
        // This is binary content (including application/xml)
        if (content instanceof FileItem) {
            final FileItem fileItem = (FileItem) content;
            parentPart.setDataHandler(new DataHandler(new DataSource() {
                public String getContentType() {
                    return contentType;
                }

                public InputStream getInputStream() throws IOException {
                    return fileItem.getInputStream();
                }

                public String getName() {
                    return name;
                }

                public OutputStream getOutputStream() throws IOException {
                    throw new IOException("Write operation not supported");
                }
            }));
        } else {
            byte[] data = NetUtils.base64StringToByteArray((String) content);
            parentPart.setDataHandler(new DataHandler(new SimpleBinaryDataSource(name, contentType, data)));
        }
    } else {
        // This is text content (including text/xml)
        if (content instanceof FileItem) {
            // The text content was encoded when written to the FileItem
            final FileItem fileItem = (FileItem) content;
            parentPart.setDataHandler(new DataHandler(new DataSource() {
                public String getContentType() {
                    // This always contains a charset
                    return contentTypeWithCharset;
                }

                public InputStream getInputStream() throws IOException {
                    // This is encoded with the appropriate charset (user-defined, or the default)
                    return fileItem.getInputStream();
                }

                public String getName() {
                    return name;
                }

                public OutputStream getOutputStream() throws IOException {
                    throw new IOException("Write operation not supported");
                }
            }));
        } else {
            parentPart.setDataHandler(
                    new DataHandler(new SimpleTextDataSource(name, contentTypeWithCharset, (String) content)));
        }
    }

    // Set content-disposition header
    String contentDisposition = partOrBodyElement.attributeValue("content-disposition");
    if (contentDisposition != null)
        parentPart.setDisposition(contentDisposition);

    // Set content-id header
    String contentId = partOrBodyElement.attributeValue("content-id");
    if (contentId != null)
        parentPart.setHeader("content-id", "<" + contentId + ">");
    //part.setContentID(contentId);
}

From source file:mitm.common.pdf.MessagePDFBuilder.java

private Part convertRFC822(Part attachment) {
    try {/*w ww .j  a  v  a2  s . c o  m*/
        Object o = attachment.getContent();

        if (o instanceof MimeMessage) {
            MimeMessage message = (MimeMessage) o;

            MessagePDFBuilder pdfBuilder = this.clone();

            ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

            pdfBuilder.buildPDF(message, null, pdfStream);

            MimePart pdfPart = new MimeBodyPart();

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

            String filename = getFilename(attachment, "message.pdf");

            if (!filename.toLowerCase().endsWith(".pdf")) {
                filename = filename + ".pdf";
            }

            pdfPart.setFileName(filename);

            return pdfPart;
        }
    } catch (IOException e) {
        logger.error("Error trying to converting to RFC822.");
    } catch (MessagingException e) {
        logger.error("Error trying to converting to RFC822.");
    } catch (DocumentException e) {
        logger.error("Error trying to converting to RFC822.");
    }

    return attachment;
}

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

/**
 *
 *//*from  w w  w  .  j ava2 s  . c o m*/
private Message createMessage(String from, String to, String bcc, String subject, String content,
        String contentType, String encoding) throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);
        String contentTypeWithEncoding = contentType + ";charset=" + encoding;

        //message.setContent(content, contentType);
        message.setFrom(createInternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, createInternetAddress(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        //message.setSubject(subject);

        ((MimeMessage) message).setSubject(subject, encoding);
        //message.setText(content);
        message.setDataHandler(
                new DataHandler(new StringDataSource(content, contentTypeWithEncoding, encoding)));
        //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);
    }
}

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

/**
 * Create a mail./*from  www .j  av  a2s .c o m*/
 * 
 * @param fromAddress Origin address.
 * @param toAddress Destination addresses.
 * @param subject The mail subject.
 * @param text The mail body.
 * @throws MessagingException If there is any error.
 */
private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text,
        Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException,
        PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath });
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

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

    InternetAddress[] to = new InternetAddress[toAddress.size()];
    int idx = 0;

    for (Iterator<String> it = toAddress.iterator(); it.hasNext();) {
        to[idx++] = new InternetAddress(it.next());
    }

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

    // 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(text);
    htmlContent.append("\n</body>\n</html>");
    htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8");
    htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8");
    htmlPart.setDisposition(Part.INLINE);
    content.addBodyPart(htmlPart);
    idx = 0;

    if (docsPath != null) {
        for (String docPath : docsPath) {
            InputStream is = null;
            FileOutputStream fos = null;
            String docName = PathUtils.getName(docPath);

            try {
                final Document doc = OKMDocument.getInstance().getProperties(null, docPath);
                is = OKMDocument.getInstance().getContent(null, docPath, false);
                final File tmpAttch = tmpAttachments.get(idx++);
                fos = new FileOutputStream(tmpAttch);
                IOUtils.copy(is, fos);
                fos.flush();

                // Document attachment part
                MimeBodyPart docPart = new MimeBodyPart();
                DataSource source = new FileDataSource(tmpAttch.getPath()) {
                    public String getContentType() {
                        return doc.getMimeType();
                    }
                };

                docPart.setDataHandler(new DataHandler(source));
                docPart.setFileName(MimeUtility.encodeText(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(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

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

From source file:org.apache.axis2.rpc.complex.ComplexDataTypesDocLitBareTest.java

/**
 * Auto generated test method/*from w w  w . j  av a2 s . c o  m*/
 */
public void testretByteArray() throws java.lang.Exception {

    byte[] input = new byte[] { (byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF };
    ComplexDataTypesDocLitBareStub.RetByteArray req = new ComplexDataTypesDocLitBareStub.RetByteArray();
    req.setInByteArray(new DataHandler(new ByteArrayDataSource(input)));
    DataHandler ret = stub.retByteArray(req).get_return();
    byte[] bytes = IOUtils.toByteArray(ret.getInputStream());
    assertTrue(Arrays.equals(bytes, input));
}

From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java

private void processSpecificAttachment(final MimeMultipart mixedMultipart, final IContentItem attachmentContent)
        throws IOException, MessagingException {

    // Add this attachment

    if (attachmentContent != null) {

        final ByteArrayDataSource dataSource = new ByteArrayDataSource(attachmentContent.getInputStream(),
                attachmentContent.getMimeType());
        final MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(getAttachmentName());
        mixedMultipart.addBodyPart(attachmentBodyPart);

    }/*from   www.j a  v a2s  . co  m*/

}