Search in sources :

Example 21 with DataSource

use of javax.activation.DataSource in project webservices-axiom by apache.

the class TestMTOMForwardStreaming method runTest.

@Override
protected void runTest() throws Throwable {
    DataSource ds1 = new TestDataSource('A', Runtime.getRuntime().maxMemory());
    DataSource ds2 = new TestDataSource('B', Runtime.getRuntime().maxMemory());
    // Programmatically create the original message
    SOAPFactory factory = metaFactory.getSOAP12Factory();
    final SOAPEnvelope orgEnvelope = factory.createSOAPEnvelope();
    SOAPBody orgBody = factory.createSOAPBody(orgEnvelope);
    OMElement orgBodyElement = factory.createOMElement("test", factory.createOMNamespace("urn:test", "p"), orgBody);
    OMElement orgData1 = factory.createOMElement("data", null, orgBodyElement);
    orgData1.addChild(factory.createOMText(new DataHandler(ds1), true));
    OMElement orgData2 = factory.createOMElement("data", null, orgBodyElement);
    orgData2.addChild(factory.createOMText(new DataHandler(ds2), true));
    final OMOutputFormat format = new OMOutputFormat();
    format.setDoOptimize(true);
    format.setSOAP11(false);
    final String contentType = format.getContentType();
    final PipedOutputStream pipe1Out = new PipedOutputStream();
    final PipedInputStream pipe1In = new PipedInputStream(pipe1Out);
    // Create the producer thread (simulating the client sending the MTOM message)
    Thread producerThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                try {
                    orgEnvelope.serialize(pipe1Out, format);
                } finally {
                    pipe1Out.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    });
    producerThread.start();
    final PipedOutputStream pipe2Out = new PipedOutputStream();
    PipedInputStream pipe2In = new PipedInputStream(pipe2Out);
    // Create the forwarder thread (simulating the mediation engine that forwards the message)
    Thread forwarderThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                try {
                    MultipartBody mb = MultipartBody.builder().setInputStream(pipe1In).setContentType(contentType).build();
                    SOAPEnvelope envelope = OMXMLBuilderFactory.createSOAPModelBuilder(metaFactory, mb).getSOAPEnvelope();
                    // the element is built. Therefore we need two different test executions.
                    if (buildSOAPPart) {
                        envelope.build();
                    }
                    // Usage of serializeAndConsume should enable streaming
                    envelope.serializeAndConsume(pipe2Out, format);
                } finally {
                    pipe2Out.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    });
    forwarderThread.start();
    try {
        MultipartBody mb = MultipartBody.builder().setInputStream(pipe2In).setContentType(contentType).build();
        SOAPEnvelope envelope = OMXMLBuilderFactory.createSOAPModelBuilder(metaFactory, mb).getSOAPEnvelope();
        OMElement bodyElement = envelope.getBody().getFirstElement();
        Iterator<OMElement> it = bodyElement.getChildElements();
        OMElement data1 = it.next();
        OMElement data2 = it.next();
        IOTestUtils.compareStreams(ds1.getInputStream(), ((PartDataHandler) ((OMText) data1.getFirstOMChild()).getDataHandler()).getPart().getInputStream(false));
        IOTestUtils.compareStreams(ds2.getInputStream(), ((PartDataHandler) ((OMText) data2.getFirstOMChild()).getDataHandler()).getPart().getInputStream(false));
    } finally {
        pipe2In.close();
    }
}
Also used : TestDataSource(org.apache.axiom.testutils.activation.TestDataSource) OMElement(org.apache.axiom.om.OMElement) PipedOutputStream(java.io.PipedOutputStream) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) DataHandler(javax.activation.DataHandler) PartDataHandler(org.apache.axiom.mime.PartDataHandler) PipedInputStream(java.io.PipedInputStream) SOAPFactory(org.apache.axiom.soap.SOAPFactory) DataSource(javax.activation.DataSource) TestDataSource(org.apache.axiom.testutils.activation.TestDataSource) SOAPBody(org.apache.axiom.soap.SOAPBody) PartDataHandler(org.apache.axiom.mime.PartDataHandler) MultipartBody(org.apache.axiom.mime.MultipartBody) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 22 with DataSource

use of javax.activation.DataSource in project rest.li by linkedin.

the class QueryTunnelUtil method doDecode.

private static RestRequest doDecode(final RestRequest request, RequestContext requestContext) throws MessagingException, IOException, URISyntaxException {
    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 TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    h.putAll(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 = IOUtil.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 = IOUtil.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);
            }
        }
    }
    // 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();
}
Also used : ContentType(javax.mail.internet.ContentType) InputStream(java.io.InputStream) ByteString(com.linkedin.data.ByteString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TreeMap(java.util.TreeMap) URI(java.net.URI) DataSource(javax.activation.DataSource) MimeMultipart(javax.mail.internet.MimeMultipart) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 23 with DataSource

use of javax.activation.DataSource in project rest.li by linkedin.

the class QueryTunnelUtil method createMultiPartEntity.

/**
   * Helper function to create multi-part MIME
   *
   * @param entity         the body of a request
   * @param entityContentType content type of the body
   * @param query          a query part of a request
   *
   * @return a ByteString that represents a multi-part encoded entity that contains both
   */
private static MimeMultipart createMultiPartEntity(final ByteString entity, final String entityContentType, String query) throws MessagingException {
    MimeMultipart multi = new MimeMultipart(MIXED);
    // Create current entity with the associated type
    MimeBodyPart dataPart = new MimeBodyPart();
    ContentType contentType = new ContentType(entityContentType);
    if (MULTIPART.equals(contentType.getBaseType())) {
        MimeMultipart nested = new MimeMultipart(new DataSource() {

            @Override
            public InputStream getInputStream() throws IOException {
                return entity.asInputStream();
            }

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

            @Override
            public String getContentType() {
                return entityContentType;
            }

            @Override
            public String getName() {
                return null;
            }
        });
        dataPart.setContent(nested, contentType.getBaseType());
    } else {
        dataPart.setContent(entity.copyBytes(), contentType.getBaseType());
    }
    dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType);
    // Encode query params as form-urlencoded
    MimeBodyPart argPart = new MimeBodyPart();
    argPart.setContent(query, FORM_URL_ENCODED);
    argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);
    multi.addBodyPart(argPart);
    multi.addBodyPart(dataPart);
    return multi;
}
Also used : ContentType(javax.mail.internet.ContentType) MimeMultipart(javax.mail.internet.MimeMultipart) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ByteString(com.linkedin.data.ByteString) MimeBodyPart(javax.mail.internet.MimeBodyPart) DataSource(javax.activation.DataSource)

Example 24 with DataSource

use of javax.activation.DataSource in project jodd by oblac.

the class SendMailTest method assertEmail.

// ---------------------------------------------------------------- util
private void assertEmail(Email email) throws MessagingException, IOException {
    Message message = createMessage(email);
    assertEquals(1, message.getFrom().length);
    assertEquals("from@example.com", message.getFrom()[0].toString());
    assertEquals(1, message.getRecipients(Message.RecipientType.TO).length);
    assertEquals("to@example.com", message.getRecipients(Message.RecipientType.TO)[0].toString());
    assertEquals("sub", message.getSubject());
    // wrapper
    MimeMultipart multipart = (MimeMultipart) message.getContent();
    assertEquals(2, multipart.getCount());
    // inner content #1
    MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(0);
    MimeMultipart mimeMultipart = (MimeMultipart) mimeBodyPart.getContent();
    assertEquals(2, mimeMultipart.getCount());
    MimeBodyPart bodyPart = (MimeBodyPart) mimeMultipart.getBodyPart(0);
    assertEquals("Hello!", bodyPart.getContent());
    // html message
    bodyPart = (MimeBodyPart) mimeMultipart.getBodyPart(1);
    MimeMultipart htmlMessage = (MimeMultipart) bodyPart.getContent();
    assertTrue(htmlMessage.getContentType().contains("multipart/related"));
    assertEquals(2, htmlMessage.getCount());
    // html - text
    MimeBodyPart htmlMimeBodyPart = (MimeBodyPart) htmlMessage.getBodyPart(0);
    assertEquals("<html><body><h1>Hey!</h1><img src='cid:c.png'></body></html>", htmlMimeBodyPart.getContent());
    assertTrue(htmlMimeBodyPart.getDataHandler().getContentType().contains("text/html"));
    // html - embedded
    htmlMimeBodyPart = (MimeBodyPart) htmlMessage.getBodyPart(1);
    DataSource dataSource = htmlMimeBodyPart.getDataHandler().getDataSource();
    assertEquals("image/png", dataSource.getContentType());
    assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7 }, read(dataSource));
    // inner content #2
    mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(1);
    dataSource = mimeBodyPart.getDataHandler().getDataSource();
    assertEquals("application/zip", dataSource.getContentType());
    assertArrayEquals(new byte[] { 11, 12, 13, 14, 15 }, read(dataSource));
}
Also used : Message(javax.mail.Message) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) DataSource(javax.activation.DataSource)

Example 25 with DataSource

use of javax.activation.DataSource in project camel by apache.

the class AttachmentHttpBinding method populateAttachments.

@Override
protected void populateAttachments(HttpServletRequest request, HttpMessage message) {
    Object object = request.getAttribute("org.eclipse.jetty.servlet.MultiPartFile.multiPartInputStream");
    if (object instanceof MultiPartInputStreamParser) {
        MultiPartInputStreamParser parser = (MultiPartInputStreamParser) object;
        Collection<Part> parts;
        try {
            parts = parser.getParts();
            for (Part part : parts) {
                DataSource ds = new PartDataSource(part);
                Attachment attachment = new DefaultAttachment(ds);
                for (String headerName : part.getHeaderNames()) {
                    for (String headerValue : part.getHeaders(headerName)) {
                        attachment.addHeader(headerName, headerValue);
                    }
                }
                message.addAttachmentObject(part.getName(), attachment);
            }
        } catch (Exception e) {
            throw new RuntimeCamelException("Cannot populate attachments", e);
        }
    }
}
Also used : Part(javax.servlet.http.Part) MultiPartInputStreamParser(org.eclipse.jetty.util.MultiPartInputStreamParser) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) Attachment(org.apache.camel.Attachment) RuntimeCamelException(org.apache.camel.RuntimeCamelException) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) RuntimeCamelException(org.apache.camel.RuntimeCamelException) IOException(java.io.IOException) DataSource(javax.activation.DataSource)

Aggregations

DataSource (javax.activation.DataSource)53 DataHandler (javax.activation.DataHandler)31 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)16 InputStream (java.io.InputStream)12 MimeMultipart (javax.mail.internet.MimeMultipart)11 OMFactory (org.apache.axiom.om.OMFactory)11 RandomDataSource (org.apache.axiom.testutils.activation.RandomDataSource)11 MimeBodyPart (javax.mail.internet.MimeBodyPart)10 IOException (java.io.IOException)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 FileDataSource (javax.activation.FileDataSource)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 OMElement (org.apache.axiom.om.OMElement)7 File (java.io.File)6 Reader (java.io.Reader)5 QName (javax.xml.namespace.QName)5 MimeHandlerException (com.zimbra.cs.mime.MimeHandlerException)4 Document (ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document)4 URI (java.net.URI)4 Multipart (javax.mail.Multipart)4