Search in sources :

Example 61 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project webservices-axiom by apache.

the class TestSetOptimize method runTest.

@Override
protected void runTest() throws Throwable {
    InputStream in = XOP_SPEC_SAMPLE.getInputStream();
    try {
        OMDocument document = OMXMLBuilderFactory.createOMBuilder(metaFactory.getOMFactory(), StAXParserConfiguration.DEFAULT, MultipartBody.builder().setInputStream(in).setContentType(XOP_SPEC_SAMPLE.getContentType()).build()).getDocument();
        for (Iterator<OMSerializable> it = document.getDescendants(false); it.hasNext(); ) {
            OMSerializable node = it.next();
            if (node instanceof OMText) {
                OMText text = (OMText) node;
                if (text.isBinary()) {
                    text.setOptimize(optimize);
                }
            }
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OMOutputFormat format = new OMOutputFormat();
        format.setDoOptimize(true);
        document.serialize(out, format);
        Multipart mp = new MimeMultipart(new ByteArrayDataSource(out.toByteArray(), format.getContentType()));
        assertThat(mp.getCount()).isEqualTo(optimize ? 3 : 1);
    } finally {
        in.close();
    }
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) InputStream(java.io.InputStream) OMText(org.apache.axiom.om.OMText) OMSerializable(org.apache.axiom.om.OMSerializable) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) OMDocument(org.apache.axiom.om.OMDocument)

Example 62 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project stanbol by apache.

the class MessageBodyReaderUtils method fromMultipart.

/**
     * Returns content parsed from {@link MediaType#MULTIPART_FORM_DATA}.
     * It iterates over all {@link BodyPart}s and tries to create {@link RequestData}
     * instances. In case the {@link BodyPart#getContentType()} is not present or
     * can not be parsed, the {@link RequestData#getMediaType()} is set to 
     * <code>null</code>. If {@link BodyPart#getInputStream()} is not defined an
     * {@link IllegalArgumentException} is thrown. The {@link BodyPart#getFileName()}
     * is used for {@link RequestData#getName()}. The ordering of the returned
     * Content instances is the same as within the {@link MimeMultipart} instance
     * parsed from the input stream. <p>
     * This Method does NOT load the data into memory, but returns directly the
     * {@link InputStream}s as returned by the {@link BodyPart}s. Therefore
     * it is saved to be used with big attachments.<p>
     * This Method is necessary because within {@link MessageBodyReader} one
     * can not use the usual annotations as used within Resources. so this method
     * allows to access the data directly from the parameters available from the
     * {@link MessageBodyReader#readFrom(Class, Type, java.lang.annotation.Annotation[], MediaType, javax.ws.rs.core.MultivaluedMap, InputStream)}
     * method<p>
     * To test this Method with curl use:
     * <code><pre>
     * curl -v -X POST -F "content=@{dataFile};type={mimeType}" 
     *      {serviceURL}
     * </pre></code>
     * Note that between {contentParam} and the datafile MUST NOT be a '='!
     * @param mimeData the mime encoded data
     * @param mediaType the mediaType (parsed to the {@link ByteArrayDataSource}
     * constructor)
     * @return the contents parsed from the {@link BodyPart}s
     * @throws IOException an any Exception while reading the stream or 
     * {@link MessagingException} exceptions other than {@link ParseException}s
     * @throws IllegalArgumentException If a {@link InputStream} is not available
     * for any {@link BodyPart} or on {@link ParseException}s while reading the
     * MimeData from the stream.
     */
public static List<RequestData> fromMultipart(InputStream mimeData, MediaType mediaType) throws IOException, IllegalArgumentException {
    ByteArrayDataSource ds = new ByteArrayDataSource(mimeData, mediaType.toString());
    List<RequestData> contents = new ArrayList<RequestData>();
    try {
        MimeMultipart data = new MimeMultipart(ds);
        //For now search the first bodypart that fits and only debug the others
        for (int i = 0; i < data.getCount(); i++) {
            BodyPart bp = data.getBodyPart(i);
            String fileName = bp.getFileName();
            MediaType mt;
            try {
                mt = bp.getContentType() != null ? MediaType.valueOf(bp.getContentType()) : null;
            } catch (IllegalArgumentException e) {
                log.warn(String.format("Unable to parse MediaType form Mime Bodypart %s: " + " fileName %s | Disposition %s | Description %s", i + 1, fileName, bp.getDisposition(), bp.getDescription()), e);
                mt = null;
            }
            InputStream stream = bp.getInputStream();
            if (stream == null) {
                throw new IllegalArgumentException(String.format("Unable to get InputStream for Mime Bodypart %s: " + "mediaType %s fileName %s | Disposition %s | Description %s", i + 1, fileName, bp.getDisposition(), bp.getDescription()));
            } else {
                contents.add(new RequestData(mt, bp.getFileName(), stream));
            }
        }
    } catch (ParseException e) {
        throw new IllegalStateException(String.format("Unable to parse data from %s request", MediaType.MULTIPART_FORM_DATA_TYPE), e);
    } catch (MessagingException e) {
        throw new IOException("Exception while reading " + MediaType.MULTIPART_FORM_DATA_TYPE + " request", e);
    }
    return contents;
}
Also used : BodyPart(javax.mail.BodyPart) MessagingException(javax.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) MimeMultipart(javax.mail.internet.MimeMultipart) MediaType(javax.ws.rs.core.MediaType) ParseException(javax.mail.internet.ParseException) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 63 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project cxf by apache.

the class ClientMtomXopTest method testMtomXopProvider.

@Test
public void testMtomXopProvider() throws Exception {
    TestMtom mtomPort = createPort(MTOM_SERVICE, MTOM_PORT_PROVIDER, TestMtom.class, true, true);
    try {
        Holder<DataHandler> param = new Holder<DataHandler>();
        Holder<String> name;
        byte[] bytes;
        InputStream in;
        InputStream pre = this.getClass().getResourceAsStream("/wsdl/mtom_xop.wsdl");
        int fileSize = 0;
        for (int i = pre.read(); i != -1; i = pre.read()) {
            fileSize++;
        }
        int count = 50;
        byte[] data = new byte[fileSize * count];
        for (int x = 0; x < count; x++) {
            this.getClass().getResourceAsStream("/wsdl/mtom_xop.wsdl").read(data, fileSize * x, fileSize);
        }
        Object[] validationTypes = new Object[] { Boolean.TRUE, SchemaValidationType.IN, SchemaValidationType.BOTH };
        for (Object validationType : validationTypes) {
            ((BindingProvider) mtomPort).getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED, validationType);
            param.value = new DataHandler(new ByteArrayDataSource(data, "application/octet-stream"));
            name = new Holder<String>("call detail");
            mtomPort.testXop(name, param);
            assertEquals("name unchanged", "return detail + call detail", name.value);
            assertNotNull(param.value);
            in = param.value.getInputStream();
            bytes = IOUtils.readBytesFromStream(in);
            assertEquals(data.length, bytes.length);
            in.close();
            param.value = new DataHandler(new ByteArrayDataSource(data, "application/octet-stream"));
            name = new Holder<String>("call detail");
            mtomPort.testXop(name, param);
            assertEquals("name unchanged", "return detail + call detail", name.value);
            assertNotNull(param.value);
            in = param.value.getInputStream();
            bytes = IOUtils.readBytesFromStream(in);
            assertEquals(data.length, bytes.length);
            in.close();
        }
        validationTypes = new Object[] { Boolean.FALSE, SchemaValidationType.OUT, SchemaValidationType.NONE };
        for (Object validationType : validationTypes) {
            ((BindingProvider) mtomPort).getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED, validationType);
            SAAJOutInterceptor saajOut = new SAAJOutInterceptor();
            SAAJInInterceptor saajIn = new SAAJInInterceptor();
            param.value = new DataHandler(new ByteArrayDataSource(data, "application/octet-stream"));
            name = new Holder<String>("call detail");
            mtomPort.testXop(name, param);
            assertEquals("name unchanged", "return detail + call detail", name.value);
            assertNotNull(param.value);
            in = param.value.getInputStream();
            bytes = IOUtils.readBytesFromStream(in);
            assertEquals(data.length, bytes.length);
            in.close();
            ClientProxy.getClient(mtomPort).getInInterceptors().add(saajIn);
            ClientProxy.getClient(mtomPort).getInInterceptors().add(saajOut);
            param.value = new DataHandler(new ByteArrayDataSource(data, "application/octet-stream"));
            name = new Holder<String>("call detail");
            mtomPort.testXop(name, param);
            assertEquals("name unchanged", "return detail + call detail", name.value);
            assertNotNull(param.value);
            in = param.value.getInputStream();
            bytes = IOUtils.readBytesFromStream(in);
            assertEquals(data.length, bytes.length);
            in.close();
            ClientProxy.getClient(mtomPort).getInInterceptors().remove(saajIn);
            ClientProxy.getClient(mtomPort).getInInterceptors().remove(saajOut);
        }
    } catch (UndeclaredThrowableException ex) {
        throw (Exception) ex.getCause();
    } catch (Exception ex) {
        if (ex.getMessage().contains("Connection reset") && System.getProperty("java.specification.version", "1.5").contains("1.6")) {
            // we'll ignore for now
            return;
        }
        System.out.println(System.getProperties());
        throw ex;
    }
}
Also used : SAAJOutInterceptor(org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor) InputStream(java.io.InputStream) Holder(javax.xml.ws.Holder) TestMtom(org.apache.cxf.mime.TestMtom) DataHandler(javax.activation.DataHandler) Endpoint(org.apache.cxf.endpoint.Endpoint) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) SAAJInInterceptor(org.apache.cxf.binding.soap.saaj.SAAJInInterceptor) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Test(org.junit.Test)

Example 64 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project cxf by apache.

the class ClientMtomXopWithJMSTest method testMtomXop.

@Test
public void testMtomXop() throws Exception {
    TestMtom mtomPort = createPort(MTOM_SERVICE, MTOM_PORT, TestMtom.class, true);
    InputStream pre = this.getClass().getResourceAsStream("/wsdl/mtom_xop.wsdl");
    int fileSize = 0;
    for (int i = pre.read(); i != -1; i = pre.read()) {
        fileSize++;
    }
    Holder<DataHandler> param = new Holder<DataHandler>();
    int count = 50;
    byte[] data = new byte[fileSize * count];
    for (int x = 0; x < count; x++) {
        this.getClass().getResourceAsStream("/wsdl/mtom_xop.wsdl").read(data, fileSize * x, fileSize);
    }
    param.value = new DataHandler(new ByteArrayDataSource(data, "application/octet-stream"));
    Holder<String> name = new Holder<String>("call detail");
    mtomPort.testXop(name, param);
    // TODO Why should it fail here?
    // Assert.fail("Expect the exception here !");
    Assert.assertEquals("name unchanged", "return detail + call detail", name.value);
    Assert.assertNotNull(param.value);
    param.value.getInputStream().close();
}
Also used : InputStream(java.io.InputStream) Holder(javax.xml.ws.Holder) TestMtom(org.apache.cxf.mime.TestMtom) DataHandler(javax.activation.DataHandler) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Endpoint(javax.xml.ws.Endpoint) Test(org.junit.Test)

Example 65 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project cxf by apache.

the class AttachmentSerializerTest method doTestMessageWrite.

private void doTestMessageWrite(boolean xop, String soapContentType) throws Exception {
    MessageImpl msg = new MessageImpl();
    Collection<Attachment> atts = new ArrayList<>();
    AttachmentImpl a = new AttachmentImpl("test.xml");
    InputStream is = getClass().getResourceAsStream("my.wav");
    ByteArrayDataSource ds = new ByteArrayDataSource(is, "application/octet-stream");
    a.setDataHandler(new DataHandler(ds));
    atts.add(a);
    msg.setAttachments(atts);
    // Set the SOAP content type
    msg.put(Message.CONTENT_TYPE, soapContentType);
    String soapCtType = null;
    String soapCtParams = null;
    String soapCtParamsEscaped = null;
    int p = soapContentType.indexOf(';');
    if (p != -1) {
        soapCtParams = soapContentType.substring(p);
        soapCtParamsEscaped = escapeQuotes(soapCtParams);
        soapCtType = soapContentType.substring(0, p);
    } else {
        soapCtParams = "";
        soapCtParamsEscaped = "";
        soapCtType = soapContentType;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.setContent(OutputStream.class, out);
    AttachmentSerializer serializer = new AttachmentSerializer(msg);
    if (!xop) {
        // default is "on"
        serializer.setXop(xop);
    }
    serializer.writeProlog();
    // we expect the following rules at the package header level
    // - the package header must have media type multipart/related.
    // - the start-info property must be present for mtom but otherwise optional. its
    // value must contain the content type associated with the root content's xml serialization,
    // including its parameters as appropriate.
    // - the action property should not appear directly in the package header level
    // - the type property must contain the media type type/subtype of the root content part.
    // namely application/xop+xml for mtom but otherwise text/xml or application/soap+xml
    // depending on the soap version 1.1 or 1.2, respectively.
    String ct = (String) msg.get(Message.CONTENT_TYPE);
    assertTrue(ct.indexOf("multipart/related;") == 0);
    assertTrue(ct.indexOf("start=\"<root.message@cxf.apache.org>\"") > -1);
    assertTrue(ct.indexOf("start-info=\"" + soapCtType + soapCtParamsEscaped + "\"") > -1);
    assertTrue(ct.indexOf("action=\"") == -1);
    if (xop) {
        assertTrue(ct.indexOf("type=\"application/xop+xml\"") > -1);
    } else {
        assertTrue(ct.indexOf("type=\"" + soapCtType + "\"") > -1);
    }
    out.write("<soap:Body/>".getBytes());
    serializer.writeAttachments();
    out.flush();
    DataSource source = new ByteArrayDataSource(new ByteArrayInputStream(out.toByteArray()), ct);
    MimeMultipart mpart = new MimeMultipart(source);
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage inMsg = new MimeMessage(session);
    inMsg.setContent(mpart);
    inMsg.addHeaderLine("Content-Type: " + ct);
    MimeMultipart multipart = (MimeMultipart) inMsg.getContent();
    MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(0);
    // - the action must appear if it was present in the original message (i.e., for soap 1.2)
    if (xop) {
        assertEquals("application/xop+xml; charset=UTF-8; type=\"" + soapCtType + soapCtParamsEscaped + "\"", part.getHeader("Content-Type")[0]);
    } else {
        assertEquals(soapCtType + "; charset=UTF-8" + soapCtParams, part.getHeader("Content-Type")[0]);
    }
    assertEquals("binary", part.getHeader("Content-Transfer-Encoding")[0]);
    assertEquals("<root.message@cxf.apache.org>", part.getHeader("Content-ID")[0]);
    InputStream in = part.getDataHandler().getInputStream();
    ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
    IOUtils.copy(in, bodyOut);
    out.close();
    in.close();
    assertEquals("<soap:Body/>", bodyOut.toString());
    MimeBodyPart part2 = (MimeBodyPart) multipart.getBodyPart(1);
    assertEquals("application/octet-stream", part2.getHeader("Content-Type")[0]);
    assertEquals("binary", part2.getHeader("Content-Transfer-Encoding")[0]);
    assertEquals("<test.xml>", part2.getHeader("Content-ID")[0]);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.message.Attachment) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Properties(java.util.Properties) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeMultipart(javax.mail.internet.MimeMultipart) MimeMessage(javax.mail.internet.MimeMessage) MimeBodyPart(javax.mail.internet.MimeBodyPart) MessageImpl(org.apache.cxf.message.MessageImpl) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Session(javax.mail.Session)

Aggregations

ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)76 DataHandler (javax.activation.DataHandler)58 InputStream (java.io.InputStream)33 IOException (java.io.IOException)25 MimeMultipart (javax.mail.internet.MimeMultipart)23 Test (org.junit.Test)19 DataSource (javax.activation.DataSource)18 ByteArrayOutputStream (java.io.ByteArrayOutputStream)17 MimeBodyPart (javax.mail.internet.MimeBodyPart)16 ByteArrayInputStream (java.io.ByteArrayInputStream)14 ArrayList (java.util.ArrayList)14 MessagingException (javax.mail.MessagingException)14 MimeMessage (javax.mail.internet.MimeMessage)12 Holder (javax.xml.ws.Holder)7 List (java.util.List)6 AttachmentImpl (org.apache.cxf.attachment.AttachmentImpl)6 Attachment (org.apache.cxf.message.Attachment)6 Date (java.util.Date)5 HashMap (java.util.HashMap)5 ContentDisposition (com.zimbra.common.mime.ContentDisposition)4