Example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource

List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource

Introduction

In this page you can find the example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource.

Prototype

public ByteArrayDataSource(String data, String type) throws IOException 

Source Link

Document

Create a ByteArrayDataSource with data from the specified String and with the specified MIME type.

Usage

From source file:org.openhim.mediator.normalization.XDSbMimeProcessorActor.java

private void parseMimeMessage(String msg, String contentType)
        throws IOException, MessagingException, SOAPPartNotFound, UnprocessableContentFound {
    mimeMessage = new MimeMultipart(new ByteArrayDataSource(msg, contentType));
    for (int i = 0; i < mimeMessage.getCount(); i++) {
        BodyPart part = mimeMessage.getBodyPart(i);

        if (part.getContentType().contains("application/soap+xml")) {
            _soapPart = getValue(part);/*from ww w .java 2 s. c  o  m*/
        } else {
            _documents.add(getValue(part));
        }
    }

    if (_soapPart == null) {
        throw new SOAPPartNotFound();
    }
}

From source file:org.nuxeo.client.api.marshaller.NuxeoResponseConverterFactory.java

@Override
public T convert(ResponseBody value) throws IOException {
    // Checking custom marshallers with the type of the method clientside.
    if (nuxeoMarshaller != null) {
        String response = value.string();
        logger.debug(response);/*  ww w . j  a  v  a 2 s  .c om*/
        JsonParser jsonParser = objectMapper.getFactory().createParser(response);
        return nuxeoMarshaller.read(jsonParser);
    }
    // Checking if multipart outputs.
    MediaType mediaType = MediaType.parse(value.contentType().toString());
    if (!(mediaType.type().equals(ConstantsV1.APPLICATION) && mediaType.subtype().equals(ConstantsV1.JSON))
            && !(mediaType.type().equals(ConstantsV1.APPLICATION)
                    && mediaType.subtype().equals(ConstantsV1.JSON_NXENTITY))) {
        if (mediaType.type().equals(ConstantsV1.MULTIPART)) {
            Blobs blobs = new Blobs();
            try {
                MimeMultipart mp = new MimeMultipart(
                        new ByteArrayDataSource(value.byteStream(), mediaType.toString()));
                int size = mp.getCount();
                for (int i = 0; i < size; i++) {
                    BodyPart part = mp.getBodyPart(i);
                    blobs.add(part.getFileName(), IOUtils.copyToTempFile(part.getInputStream()));
                }
            } catch (MessagingException reason) {
                throw new IOException(reason);
            }
            return (T) blobs;
        } else {
            return (T) new Blob(IOUtils.copyToTempFile(value.byteStream()));
        }
    }
    String nuxeoEntity = mediaType.nuxeoEntity();
    // Checking the type of the method clientside - aka object for Automation calls.
    if (javaType.getRawClass().equals(Object.class)) {
        if (nuxeoEntity != null) {
            switch (nuxeoEntity) {
            case ConstantsV1.ENTITY_TYPE_DOCUMENT:
                return (T) readJSON(value.charStream(), Document.class);
            case ConstantsV1.ENTITY_TYPE_DOCUMENTS:
                return (T) readJSON(value.charStream(), Documents.class);
            default:
                return (T) value;
            }
        } else {
            // This workaround is only for recordsets. There is not
            // header nuxeo-entity set for now serverside.
            String response = value.string();
            Object objectResponse = readJSON(response, Object.class);
            switch ((String) ((Map<String, Object>) objectResponse).get(ConstantsV1.ENTITY_TYPE)) {
            case ConstantsV1.ENTITY_TYPE_RECORDSET:
                return (T) readJSON(response, RecordSet.class);
            default:
                return (T) value;
            }
        }
    }
    Reader reader = value.charStream();
    try {
        return adapter.readValue(reader);
    } catch (IOException reason) {
        throw new NuxeoClientException(reason);
    } finally {
        closeQuietly(reader);
    }
}

From source file:com.exp.tracker.utils.EmailUtility.java

/**
 * Sends an email./* ww  w .j av  a  2s  . co m*/
 * 
 * @param emailIdStrings
 *            A String array containing a list of email addresses.
 * @param emailSubject
 *            The subject of the email.
 * @param messageContent
 *            The message body.
 * @param emailAttachments
 *            A map containing any attachments. The key should be the file
 *            name. The value os a byte[] containing the binary
 *            representation of the attachment.
 * @throws EmailCommunicationException
 *             If any exception occurs.
 */
public void sendEmail(String[] emailIdStrings, String emailSubject, String messageContent,
        Map<String, byte[]> emailAttachments) throws EmailCommunicationException {
    if (null == emailIdStrings) {
        throw new EmailCommunicationException("Null array passed to this method.");
    }
    if (emailIdStrings.length == 0) {
        throw new EmailCommunicationException("No email addresses were provided. Array was empty.");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("About to send an email.");
    }

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setFrom(fromAccount, fromName);
        InternetAddress[] toListArray = new InternetAddress[emailIdStrings.length];
        for (int i = 0; i < emailIdStrings.length; i++) {
            toListArray[i] = new InternetAddress(emailIdStrings[i]);
        }
        //To
        helper.setTo(toListArray);
        //Subject
        helper.setSubject(emailSubject);
        //Body
        helper.setText(messageContent, true);
        //Attachments
        if (null != emailAttachments) {
            Set<String> attachmentFileNames = emailAttachments.keySet();
            for (String fileName : attachmentFileNames) {
                helper.addAttachment(fileName,
                        new ByteArrayDataSource(emailAttachments.get(fileName), "application/octet-stream"));
            }
        }

        javaMailSender.send(mimeMessage);
        System.out.println("Mail sent successfully.");
    } catch (MessagingException e) {
        throw new EmailCommunicationException("Error sending email.", e);
    } catch (UnsupportedEncodingException e) {
        throw new EmailCommunicationException("Error sending email. Unsupported encoding.", e);
    }
}

From source file:org.apache.axis2.jaxws.message.databinding.impl.DataSourceBlockImpl.java

protected Object _getBOFromReader(XMLStreamReader reader, Object busContext)
        throws XMLStreamException, WebServiceException {
    Reader2Writer r2w = new Reader2Writer(reader);
    try {// ww  w  . j  a v a  2 s  . com
        return new ByteArrayDataSource(r2w.getAsString(), "application/octet-stream");
    } catch (IOException e) {
        throw new XMLStreamException(e);
    }

}

From source file:org.cleverbus.core.common.asynch.notification.EmailServiceCamelSmtpImpl.java

@Override
public void sendEmail(final Email email) {
    Assert.notNull(email, "email can not be null");
    Assert.notEmpty(email.getRecipients(), "email must have at least one recipients");
    Assert.hasText(email.getSubject(), "subject in email can not be empty");
    Assert.hasText(email.getBody(), "body in email can not be empty");

    producerTemplate.send("smtp://" + smtp, new Processor() {
        @Override// w  w w. j a  v  a2 s.  co m
        public void process(final Exchange exchange) throws Exception {
            Message in = exchange.getIn();
            in.setHeader("To", StringUtils.join(email.getRecipients(), ","));
            in.setHeader("From", StringUtils.isBlank(email.getFrom()) ? from : email.getFrom());
            in.setHeader("Subject", email.getSubject());
            in.setHeader("contentType", email.getContentType().getContentType());
            in.setBody(email.getBody());
            if (email.getAllAtachments() != null && !email.getAllAtachments().isEmpty()) {
                for (EmailAttachment attachment : email.getAllAtachments()) {
                    in.addAttachment(attachment.getFileName(),
                            new DataHandler(new ByteArrayDataSource(attachment.getContent(), "*/*")));
                }
            }
        }
    });
}

From source file:com.caris.oscarexchange4j.proxy.PreviewCoverage.java

@Override
public void processInputStream(InputStream is) throws Exception {
    try {//  w  w  w. j  av a 2  s .c  o m
        MimeMultipart multiPart = new MimeMultipart(new ByteArrayDataSource(is, MULTI_PART_MIME_TYPE));
        int count = multiPart.getCount();
        for (int part = 0; part < count; part++) {
            BodyPart body = multiPart.getBodyPart(part);
            if (body.isMimeType(OUTPUT_MIME_TYPE)) {
                this.inputStream = body.getInputStream();
                break;
            }
        }
    } catch (Exception e) {
        this.inputStream = getErrorResponseStream();
    }
}

From source file:com.jwm123.loggly.reporter.ReportMailer.java

public MimeBodyPart addReportAttachment() throws MessagingException {
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    String mimeType = "application/vnd.ms-excel";
    if (fileName.endsWith(".xlsx")) {
        mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    }/* ww w  .  j  a  va  2 s  . c  o  m*/
    mimeBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(reportContent, mimeType)));
    mimeBodyPart.setDisposition("attachment");
    mimeBodyPart.setFileName(fileName);

    return mimeBodyPart;
}

From source file:org.apache.servicemix.camel.nmr.AttachmentTest.java

public void testAttachment() throws Exception {
    TestMtom mtomPort = createPort(MTOM_SERVICE, MTOM_PORT, TestMtom.class, true);
    try {/*w  w  w  . jav  a  2s.c o  m*/

        Holder<DataHandler> param = new Holder<DataHandler>();

        param.value = new DataHandler(new ByteArrayDataSource("foobar".getBytes(), "application/octet-stream"));

        Holder<String> name = new Holder<String>("call detail");
        mtomPort.testXop(name, param);
        assertEquals("call detailfoobar", name.value);
        assertNotNull(param.value);
        InputStream bis = param.value.getDataSource().getInputStream();
        byte b[] = new byte[10];
        bis.read(b, 0, 10);
        String attachContent = new String(b);
        assertEquals(attachContent, "testfoobar");
    } catch (UndeclaredThrowableException ex) {
        throw (Exception) ex.getCause();
    }

}

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {// w ww  .  j  a v  a2  s.co  m
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.carbon.user.mgt.ui.Util.java

public static DataHandler buildDataHandler(byte[] content) {
    DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(content, "application/octet-stream"));
    return dataHandler;
}