Example usage for javax.mail.internet MimeMultipart getBodyPart

List of usage examples for javax.mail.internet MimeMultipart getBodyPart

Introduction

In this page you can find the example usage for javax.mail.internet MimeMultipart getBodyPart.

Prototype

public synchronized BodyPart getBodyPart(String CID) throws MessagingException 

Source Link

Document

Get the MimeBodyPart referred to by the given ContentID (CID).

Usage

From source file:gov.nist.healthcare.ttt.parsing.Parsing.java

public static SOAPWithAttachment parseMtom(String mtom) throws MessagingException, IOException {

    //        Parsing.fixMissingEndBoundry(mtom);
    MimeMultipart mp;
    // String contentType = Parsing.findContentType(mtom);

    //     mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), ""), new ContentType(contentType));
    mp = new MimeMultipart(new ByteArrayDataSource(mtom.getBytes(), "multipart/related"));
    SOAPWithAttachment swa = new SOAPWithAttachment();
    int count = mp.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bp = mp.getBodyPart(i);
        String contentType = bp.getContentType();
        if (contentType.startsWith("application/xop+xml")) {
            // SOAP
            ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent();
            swa.setSoap(IOUtils.toString(content));

        } else {//from  ww w  .  j av  a  2 s .c o m
            Object contentRaw = bp.getContent();
            if (contentRaw instanceof String) {
                String content = (String) bp.getContent();
                swa.getAttachment().add(content.getBytes());
            } else if (contentRaw instanceof SharedByteArrayInputStream) {
                SharedByteArrayInputStream content = (SharedByteArrayInputStream) bp.getContent();
                swa.getAttachment().add(read(content));
            } else {
                System.out.println("UNKNOWN ATTACHMENT TYPE = " + contentRaw.getClass().getName());
                swa.getAttachment().add(new String().getBytes());
            }
        }

        // System.out.println("contentype=" + bp.getContentType());
        //ByteArrayInputStream content = (ByteArrayInputStream) bp.getContent();
        //String contentString = IOUtils.toString(content);
        //String contentString = (String) bp.getContent();
        /*
        try {
        Envelope env = (Envelope) JAXB.unmarshal(new StringReader(contentString), Envelope.class);
        if (env.getHeader() == null && env.getBody() == null) {
            swa.getAttachment().add(Parsing.read(content));
            //swa.getAttachment().add(contentString.getBytes());
        } else {
            swa.setSoap(contentString);
        }
        } catch (Exception saxe) {
        // Not SOAP so must be attachment.
         swa.getAttachment().add(Parsing.read(content));
        //swa.getAttachment().add(contentString.getBytes());
        }
         */
    }

    if (swa.getAttachment() == null || swa.getAttachment().size() == 0) {
        byte[] document = Parsing.getDocumentFromSoap(swa.getSoap()).getBytes();
        Collection<byte[]> attachments = new ArrayList<byte[]>();
        attachments.add(document);
        swa.setAttachment(attachments);
    }

    return swa;
}

From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java

/**
 * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and
 * creates a new request that represents the intended original request
 *
 * @param request the request to be decoded
 *
 * @return a decoded RestRequest/* w ww  .  ja v  a  2s  .  co m*/
 */
public static RestRequest decode(final RestRequest request)
        throws MessagingException, IOException, URISyntaxException {
    if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) {
        // Not a tunnelled request, just pass thru
        return request;
    }

    String query = null;
    byte[] entity = new byte[0];

    // All encoded requests must have a content type. If the header is missing, ContentType throws an exception
    ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE));

    RestRequestBuilder requestBuilder = request.builder();

    // Get copy of headers and remove the override
    Map<String, String> h = new HashMap<String, String>(request.getHeaders());
    h.remove(HEADER_METHOD_OVERRIDE);

    // Simple case, just extract query params from entity, append to query, and clear entity
    if (contentType.getBaseType().equals(FORM_URL_ENCODED)) {
        query = request.getEntity().asString(Data.UTF_8_CHARSET);
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);
    } else if (contentType.getBaseType().equals(MULTIPART)) {
        // Clear these in case there is no body part
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);

        MimeMultipart multi = new MimeMultipart(new DataSource() {
            @Override
            public InputStream getInputStream() throws IOException {
                return request.getEntity().asInputStream();
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getContentType() {
                return request.getHeader(HEADER_CONTENT_TYPE);
            }

            @Override
            public String getName() {
                return null;
            }
        });

        for (int i = 0; i < multi.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i);

            if (part.isMimeType(FORM_URL_ENCODED) && query == null) {
                // Assume the first segment we come to that is urlencoded is the tunneled query params
                query = IOUtils.toString((InputStream) part.getContent(), UTF8);
            } else if (entity.length <= 0) {
                // Assume the first non-urlencoded content we come to is the intended entity.
                entity = IOUtils.toByteArray((InputStream) part.getContent());
                h.put(CONTENT_LENGTH, Integer.toString(entity.length));
                h.put(HEADER_CONTENT_TYPE, part.getContentType());
            } else {
                // If it's not form-urlencoded and we've already found another section,
                // this has to be be an extra body section, which we have no way to handle.
                // Proceed with the request as if the 1st part we found was the expected body,
                // but log a warning in case some client is constructing a request that doesn't
                // follow the rules.
                String unexpectedContentType = part.getContentType();
                LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type="
                        + unexpectedContentType);
            }
        }
    }

    // Based on what we've found, construct the modified request. It's possible that someone has
    // modified the request URI, adding extra query params for debugging, tracking, etc, so
    // we have to check and append the original query correctly.
    if (query != null && query.length() > 0) {
        String separator = "&";
        String existingQuery = request.getURI().getRawQuery();

        if (existingQuery == null) {
            separator = "?";
        } else if (existingQuery.isEmpty()) {
            // This would mean someone has appended a "?" with no args to the url underneath us
            separator = "";
        }

        requestBuilder.setURI(new URI(request.getURI().toString() + separator + query));
    }
    requestBuilder.setEntity(entity);
    requestBuilder.setHeaders(h);
    requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE));

    return requestBuilder.build();
}

From source file:org.broadleafcommerce.common.email.service.LoggingMailSender.java

@Override
public void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException {
    for (MimeMessagePreparator preparator : mimeMessagePreparators) {
        try {//  w w  w .ja v  a2  s  .co  m
            MimeMessage mimeMessage = createMimeMessage();
            preparator.prepare(mimeMessage);
            LOG.info("\"Sending\" email: ");
            if (mimeMessage.getContent() instanceof MimeMultipart) {
                MimeMultipart msg = (MimeMultipart) mimeMessage.getContent();
                DataHandler dh = msg.getBodyPart(0).getDataHandler();
                ByteArrayOutputStream baos = null;
                try {
                    baos = new ByteArrayOutputStream();
                    dh.writeTo(baos);
                } catch (Exception e) {
                    // Do nothing
                } finally {
                    try {
                        baos.close();
                    } catch (Exception e) {
                        LOG.error("Couldn't close byte array output stream");
                    }
                }
            } else {
                LOG.info(mimeMessage.getContent());
            }
        } catch (Exception e) {
            LOG.error("Could not create message", e);
        }
    }
}

From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java

/**
 * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and
 * creates a new request that represents the intended original request
 *
 * @param request the request to be decoded
 * @param requestContext a RequestContext object associated with the request
 *
 * @return a decoded RestRequest//from   w ww.  j av a 2s . c o  m
 */
public static RestRequest decode(final RestRequest request, RequestContext requestContext)
        throws MessagingException, IOException, URISyntaxException {
    if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) {
        // Not a tunnelled request, just pass thru
        return request;
    }

    String query = null;
    byte[] entity = new byte[0];

    // All encoded requests must have a content type. If the header is missing, ContentType throws an exception
    ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE));

    RestRequestBuilder requestBuilder = request.builder();

    // Get copy of headers and remove the override
    Map<String, String> h = new HashMap<String, String>(request.getHeaders());
    h.remove(HEADER_METHOD_OVERRIDE);

    // Simple case, just extract query params from entity, append to query, and clear entity
    if (contentType.getBaseType().equals(FORM_URL_ENCODED)) {
        query = request.getEntity().asString(Data.UTF_8_CHARSET);
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);
    } else if (contentType.getBaseType().equals(MULTIPART)) {
        // Clear these in case there is no body part
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);

        MimeMultipart multi = new MimeMultipart(new DataSource() {
            @Override
            public InputStream getInputStream() throws IOException {
                return request.getEntity().asInputStream();
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getContentType() {
                return request.getHeader(HEADER_CONTENT_TYPE);
            }

            @Override
            public String getName() {
                return null;
            }
        });

        for (int i = 0; i < multi.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i);

            if (part.isMimeType(FORM_URL_ENCODED) && query == null) {
                // Assume the first segment we come to that is urlencoded is the tunneled query params
                query = IOUtils.toString((InputStream) part.getContent(), UTF8);
            } else if (entity.length <= 0) {
                // Assume the first non-urlencoded content we come to is the intended entity.
                Object content = part.getContent();
                if (content instanceof MimeMultipart) {
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    ((MimeMultipart) content).writeTo(os);
                    entity = os.toByteArray();
                } else {
                    entity = IOUtils.toByteArray((InputStream) content);
                }
                h.put(CONTENT_LENGTH, Integer.toString(entity.length));
                h.put(HEADER_CONTENT_TYPE, part.getContentType());
            } else {
                // If it's not form-urlencoded and we've already found another section,
                // this has to be be an extra body section, which we have no way to handle.
                // Proceed with the request as if the 1st part we found was the expected body,
                // but log a warning in case some client is constructing a request that doesn't
                // follow the rules.
                String unexpectedContentType = part.getContentType();
                LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type="
                        + unexpectedContentType);
            }
        }
    }

    // Based on what we've found, construct the modified request. It's possible that someone has
    // modified the request URI, adding extra query params for debugging, tracking, etc, so
    // we have to check and append the original query correctly.
    if (query != null && query.length() > 0) {
        String separator = "&";
        String existingQuery = request.getURI().getRawQuery();

        if (existingQuery == null) {
            separator = "?";
        } else if (existingQuery.isEmpty()) {
            // This would mean someone has appended a "?" with no args to the url underneath us
            separator = "";
        }

        requestBuilder.setURI(new URI(request.getURI().toString() + separator + query));
    }
    requestBuilder.setEntity(entity);
    requestBuilder.setHeaders(h);
    requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE));

    requestContext.putLocalAttr(R2Constants.IS_QUERY_TUNNELED, true);

    return requestBuilder.build();
}

From source file:org.eclipse.ecr.automation.server.jaxrs.io.MultiPartRequestReader.java

public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;/*from  w w  w.  j ava  2 s  . com*/
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        in = new FileInputStream(tmp); // get the input from the saved
                                       // file
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            req = JsonRequestReader.readRequest(pin, headers);
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw ExceptionHandler.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            tmp.delete();
        }
    } catch (Throwable e) {
        throw ExceptionHandler.newException("Failed to parse multipart request", e);
    }
    return req;
}

From source file:org.nuxeo.ecm.automation.server.jaxrs.io.MultiPartRequestReader.java

@Override
public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;// w w  w  .  j av  a  2 s.  com
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        in = new SharedFileInputStream(tmp); // get the input from the saved
        // file
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            req = JsonRequestReader.readRequest(pin, headers, getCoreSession());
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw ExceptionHandler.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            tmp.delete();
        }
    } catch (Throwable e) {
        throw ExceptionHandler.newException("Failed to parse multipart request", e);
    }
    return req;
}

From source file:org.eclipse.ecr.automation.server.jaxrs.io.MultiPartFormRequestReader.java

public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;//  w w w. j av a2  s  .  c  o m
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        // get the input from the saved file
        in = new SharedFileInputStream(tmp);
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            req = JsonRequestReader.readRequest(pin, headers);
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw ExceptionHandler.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // do nothing
            }
            tmp.delete();
        }
    } catch (Throwable e) {
        throw ExceptionHandler.newException("Failed to parse multipart request", e);
    }
    return req;
}

From source file:org.codice.alliance.core.email.impl.EmailSenderImplTest.java

@Test
public void testBody() throws IOException, MessagingException {

    emailSender.sendEmail(FROM_ADDR, TO_ADDR, SUBJECT_LINE, BODY, Collections.emptyList());

    MimeMultipart mimeMultipart = (MimeMultipart) capturedMessage.value.getContent();

    Object content = mimeMultipart.getBodyPart(0).getContent();

    assertThat(content, is(BODY));/*from ww w . jav a  2 s. c o m*/
}

From source file:org.nuxeo.ecm.automation.server.jaxrs.io.MultiPartFormRequestReader.java

@Override
public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;//from   ww w  . j a  v  a2s.c  o  m
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        // get the input from the saved file
        in = new SharedFileInputStream(tmp);
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            req = JsonRequestReader.readRequest(pin, headers, getCoreSession());
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw ExceptionHandler.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // do nothing
            }
            tmp.delete();
        }
    } catch (Throwable e) {
        throw ExceptionHandler.newException("Failed to parse multipart request", e);
    }
    return req;
}

From source file:org.nuxeo.ecm.automation.jaxrs.io.operations.MultiPartRequestReader.java

@Override
public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;//from   ww w  . ja v  a 2 s  .  c  o m
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = Framework.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        in = new SharedFileInputStream(tmp); // get the input from the saved
        // file
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            JsonParser jp = factory.createJsonParser(pin);
            req = JsonRequestReader.readRequest(jp, headers, getCoreSession());
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw WebException.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            tmp.delete();
        }
    } catch (MessagingException | IOException e) {
        throw WebException.newException("Failed to parse multipart request", e);
    }
    return req;
}