Example usage for javax.mail BodyPart getInputStream

List of usage examples for javax.mail BodyPart getInputStream

Introduction

In this page you can find the example usage for javax.mail BodyPart getInputStream.

Prototype

public InputStream getInputStream() throws IOException, MessagingException;

Source Link

Document

Return an input stream for this part's "content".

Usage

From source file:org.mule.service.http.impl.service.server.grizzly.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;//from ww  w.jav  a  2 s.com
    List<HttpPart> parts = Lists.newArrayList();

    try {
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }

            if (partName == null && mimeMultipart.getContentType().contains(MULTIPART_RELATED.toString())) {
                String[] contentIdHeader = part.getHeader(CONTENT_ID);
                if (contentIdHeader != null && contentIdHeader.length > 0) {
                    partName = contentIdHeader[0];
                }
            }

            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

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);/*from   w w  w. j  av a2 s. c o  m*/
        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.zotoh.crypto.CryptoUte.java

/**
 * @param part/* w  w w  .j av  a  2s .c  o  m*/
 * @return
 * @throws IOException
 * @throws MessagingException
 * @throws GeneralSecurityException
 */
public static StreamData decompress(BodyPart part)
        throws IOException, MessagingException, GeneralSecurityException {
    return decompressAsStream(part == null ? null : part.getInputStream());
}

From source file:org.xwiki.administration.test.ui.ResetPasswordIT.java

protected Map<String, String> getMessageContent(MimeMessage message) throws Exception {
    Map<String, String> messageMap = new HashMap<String, String>();

    Address[] addresses = message.getAllRecipients();
    Assert.assertTrue(addresses.length == 1);
    messageMap.put("recipient", addresses[0].toString());

    messageMap.put("subjectLine", message.getSubject());

    Multipart mp = (Multipart) message.getContent();

    BodyPart plain = getPart(mp, "text/plain");
    if (plain != null) {
        messageMap.put("textPart", IOUtils.toString(plain.getInputStream()));
    }//from   w  w w. j a  v  a 2  s  . com
    BodyPart html = getPart(mp, "text/html");
    if (html != null) {
        messageMap.put("htmlPart", IOUtils.toString(html.getInputStream()));
    }

    return messageMap;
}

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

@Override
public void processInputStream(InputStream is) throws Exception {
    try {/*from w  w  w.  j  av  a2  s  .com*/
        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:org.alfresco.cacheserver.CacheServer.java

public List<Patch> getPatches(String host, int port, String nodeId, long nodeVersion)
        throws MessagingException, IOException {
    List<Patch> patches = new LinkedList<>();

    StringBuilder sb = new StringBuilder();
    sb.append("/patch/");
    sb.append(nodeId);/*from   w w  w. j  a v a  2 s . c  o  m*/
    sb.append("/");
    sb.append(nodeVersion);
    String url = sb.toString();

    final ClientConfig config = new DefaultClientConfig();
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    final Client client = Client.create(config);

    final WebResource resource = client.resource(url);
    final MimeMultipart response = resource.get(MimeMultipart.class);

    // This will iterate the individual parts of the multipart response
    for (int i = 0; i < response.getCount(); i++) {
        final BodyPart part = response.getBodyPart(i);
        System.out.printf("Embedded Body Part [Mime Type: %s, Length: %s]\n", part.getContentType(),
                part.getSize());
        InputStream in = part.getInputStream();
        // Patch patch = new Patch();
        // patches.add(patch);
    }

    return patches;
}

From source file:org.apache.oozie.action.email.TestEmailActionExecutor.java

private void assertAttachment(String attachtag, int attachCount, String content1, String content2)
        throws Exception {
    sendAndReceiveEmail(attachtag);//from  w ww. j ava 2  s.  com
    MimeMessage retMeg = server.getReceivedMessages()[0];
    Multipart retParts = (Multipart) (retMeg.getContent());
    int numAttach = 0;
    for (int i = 0; i < retParts.getCount(); i++) {
        BodyPart bp = retParts.getBodyPart(i);
        String disp = bp.getDisposition();
        String retValue = IOUtils.toString(bp.getInputStream());
        if (disp != null && (disp.equals(BodyPart.ATTACHMENT))) {
            assertTrue(retValue.equals(content1) || retValue.equals(content2));
            numAttach++;
        } else {
            assertEquals("This is a test mail", retValue);
        }
    }
    assertEquals(attachCount, numAttach);
}

From source file:org.bonitasoft.connectors.email.test.EmailConnectorTest.java

private List<byte[]> getAttachmentsContent(MimeMultipart multipart) throws MessagingException, IOException {
    List<byte[]> attachments = new ArrayList<byte[]>();
    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        attachments.add(IOUtils.toByteArray(bodyPart.getInputStream()));
    }/*from   w  w w . j av a 2  s.  c  o  m*/
    return attachments;
}

From source file:org.igov.io.mail.Mail.java

public boolean sendWithUniSender() {
    LOG.info("Init...");
    boolean result = true;
    Object oID_Message = null;/*from w ww. j av  a  2  s  .c  om*/
    StringBuilder sbBody = new StringBuilder();
    try {
        sbBody.append("host: ");
        sbBody.append(getHost());
        sbBody.append(":");
        sbBody.append(getPort());
        sbBody.append("\nAuthUser:");
        sbBody.append(getAuthUser());
        sbBody.append("\nfrom:");
        sbBody.append(getFrom());
        sbBody.append("\nto:");
        sbBody.append(getTo());
        sbBody.append("\nhead:");
        sbBody.append(getHead());

        String sKey_Sender = generalConfig.getKey_UniSender_Mail();
        long nID_Sender = generalConfig.getSendListId_UniSender_Mail();
        if (StringUtils.isBlank(sKey_Sender)) {
            throw new IllegalArgumentException("Please check api_key in UniSender property file configuration");
        }

        LOG.info("oUniSender - {}", oUniSender);
        LOG.info("methodCallRunner - {}", methodCallRunner);
        oUniSender.setMethodCallRunner(methodCallRunner);

        if (getTo().contains(",")) {
            String[] asMail = getTo().split("\\,");
            for (String sMail : asMail) {
                sMail = sMailOnly(sMail);
                UniResponse oUniResponse_Subscribe = oUniSender
                        .subscribe(Collections.singletonList(String.valueOf(nID_Sender)), sMail, getToName());
                LOG.info("(sMail={},oUniResponse_Subscribe={})", sMail, oUniResponse_Subscribe);
            }
        } else {
            String sMail = sMailOnly(getTo());
            UniResponse oUniResponse_Subscribe = oUniSender
                    .subscribe(Collections.singletonList(String.valueOf(nID_Sender)), sMail, getToName());
            LOG.info("(oUniResponse_Subscribe={})", oUniResponse_Subscribe);
        }

        String sBody = getBody();
        //sBody = sBody + "" + "<br>? ?   <a href=\"{{UnsubscribeUrl}}\">??</a>";
        sBody = sBody + ""
                + "<br>   ??  ,  ?, ? <a href=\"{{UnsubscribeUrl}}\"</a>/";

        CreateEmailMessageRequest.Builder oBuilder = CreateEmailMessageRequest
                //.getBuilder(sKey_Sender, "en")
                .getBuilder(sKey_Sender, "ua").setSenderName("no reply").setSenderEmail(getFrom())
                .setSubject(getHead()).setBody(sBody).setListId(String.valueOf(nID_Sender));

        try {
            int nAttachments = oMultiparts.getCount();
            for (int i = 0; i < nAttachments; i++) {
                BodyPart oBodyPart = oMultiparts.getBodyPart(i);
                String sFileName = oBodyPart.getFileName();
                InputStream oInputStream = oBodyPart.getInputStream();
                oBuilder.setAttachment(sFileName, oInputStream);
            }
        } catch (IOException e) {
            throw new Exception("Error while getting attachment.", e);
        } catch (MessagingException e) {
            throw new Exception("Error while getting attachment.", e);
        }

        CreateEmailMessageRequest oCreateEmailMessageRequest = oBuilder.build();

        UniResponse oUniResponse_CreateEmailMessage = oUniSender.createEmailMessage(oCreateEmailMessageRequest);
        LOG.info("(oUniResponse_CreateEmailMessage={})", oUniResponse_CreateEmailMessage);

        if (oUniResponse_CreateEmailMessage != null && oUniResponse_CreateEmailMessage.getResult() != null) {
            Map<String, Object> mParam = oUniResponse_CreateEmailMessage.getResult();
            LOG.info("(mParam={})", mParam);
            oID_Message = mParam.get("message_id");
            if (oID_Message != null) {
                LOG.info("(oID_Message={})", oID_Message);
                CreateCampaignRequest oCreateCampaignRequest = CreateCampaignRequest
                        .getBuilder(sKey_Sender, "en").setMessageId(oID_Message.toString()).build();

                UniResponse oUniResponse_CreateCampaign = oUniSender.createCampaign(oCreateCampaignRequest,
                        getTo());
                LOG.info("(oUniResponse_CreateCampaign={})", oUniResponse_CreateCampaign);
            } else {
                result = false;
                LOG.error("error while email creation " + oUniResponse_CreateEmailMessage.getError());
                //throw new EmailException("error while email creation " + oUniResponse_CreateEmailMessage.getError());
            }
        }
    } catch (Exception oException) {
        result = false;
        LOG.error("FAIL: {} (oID_Message()={},getTo()={})", oException.getMessage(), oID_Message, getTo());
        new Log(oException, LOG)._Case("Mail_FailUS")._Status(Log.LogStatus.ERROR)._Head("First try send fail")
                ._Param("getTo", getTo())._Param("sbBody", sbBody)._Param("oID_Message", oID_Message).save();
    }
    LOG.info("SUCCESS: sent!");
    return result;
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageContentFilter.java

private void extractMultiPartMessage(final Multipart parts, final int partIndex) throws MessagingException {
    try {/*  w ww.  jav  a2s.  co m*/
        if (partIndex >= parts.getCount()) {
            throw new StepFailedException("PartIndex too large.", this);
        }
        final BodyPart part = parts.getBodyPart(partIndex);
        final String contentType = part.getContentType();
        if (!StringUtils.isEmpty(getContentType()) && !contentType.equals(getContentType())) {
            throw new MessagingException("Actual contentType of '" + contentType
                    + "' did not match expected contentType of '" + fContentType + "'");
        }
        final String disp = part.getDisposition();
        final String filename = part.getFileName();
        final InputStream inputStream = part.getInputStream();
        if (Part.ATTACHMENT.equals(disp)) {
            fFilename = filename;
        } else {
            fFilename = getClass().getName();
        }
        ContextHelper.defineAsCurrentResponse(getContext(), IOUtils.toString(inputStream), contentType,
                "http://" + fFilename);
    } catch (IOException e) {
        throw new MessagingException("Error extracting part: " + e.getMessage());
    }
}