Search in sources :

Example 36 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project zm-mailbox by Zimbra.

the class TestContacts method testServerAttachment.

/**
     * Tests the server-side {@link Attachment} class.
     */
@Test
public void testServerAttachment() throws Exception {
    // Specify the attachment size.
    byte[] data = "test".getBytes();
    ByteArrayDataSource ds = new ByteArrayDataSource(data, "text/plain");
    ds.setName("attachment.txt");
    DataHandler dh = new DataHandler(ds);
    Attachment attach = new Attachment(dh, "attachment", data.length);
    // Don't specify the attachment size.
    attach = new Attachment(dh, "attachment");
    checkServerAttachment(data, attach);
    // Create attachment from byte[].
    attach = new Attachment(data, "text/plain", "attachment", "attachment.txt");
    checkServerAttachment(data, attach);
}
Also used : Attachment(com.zimbra.cs.mailbox.Contact.Attachment) DataHandler(javax.activation.DataHandler) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Test(org.junit.Test)

Example 37 with ByteArrayDataSource

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

the class AttachmentTest method testAttachmentViaWsInterface.

//END SNIPPET: setup    
/**
     * Create a webservice client using wsdl url
     *
     * @throws Exception
     */
//START SNIPPET: webservice
public void testAttachmentViaWsInterface() throws Exception {
    Service service = Service.create(new URL("http://localhost:" + port + "/webservice-attachments/AttachmentImpl?wsdl"), new QName("http://superbiz.org/wsdl", "AttachmentWsService"));
    assertNotNull(service);
    AttachmentWs ws = service.getPort(AttachmentWs.class);
    // retrieve the SOAPBinding
    SOAPBinding binding = (SOAPBinding) ((BindingProvider) ws).getBinding();
    binding.setMTOMEnabled(true);
    String request = "tsztelak@gmail.com";
    // Byte array
    String response = ws.stringFromBytes(request.getBytes());
    assertEquals(request, response);
    // Data Source
    DataSource source = new ByteArrayDataSource(request.getBytes(), "text/plain; charset=UTF-8");
    // not yet supported !
    //        response = ws.stringFromDataSource(source);
    //        assertEquals(request, response);
    // Data Handler
    response = ws.stringFromDataHandler(new DataHandler(source));
    assertEquals(request, response);
}
Also used : QName(javax.xml.namespace.QName) Service(javax.xml.ws.Service) SOAPBinding(javax.xml.ws.soap.SOAPBinding) DataHandler(javax.activation.DataHandler) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) URL(java.net.URL) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource)

Example 38 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 39 with ByteArrayDataSource

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

the class AttachmentsTest method testReadBase64EncodedAttachment.

private void testReadBase64EncodedAttachment(boolean useFile) throws Exception {
    // Note: We are only interested in the MimeMultipart, but we need to create a
    //       MimeMessage to be able to calculate the correct content type
    MimeMessage message = new MimeMessage((Session) null);
    MimeMultipart mp = new MimeMultipart("related");
    // Prepare the "SOAP" part
    MimeBodyPart bp1 = new MimeBodyPart();
    // Obviously this is not SOAP, but this is irrelevant for this test
    bp1.setText("<root/>", "utf-8", "xml");
    bp1.addHeader("Content-Transfer-Encoding", "binary");
    bp1.addHeader("Content-ID", "part1@apache.org");
    mp.addBodyPart(bp1);
    // Prepare the attachment
    MimeBodyPart bp2 = new MimeBodyPart();
    byte[] content = new byte[8192];
    new Random().nextBytes(content);
    bp2.setDataHandler(new DataHandler(new ByteArrayDataSource(content, "application/octet-stream")));
    bp2.addHeader("Content-Transfer-Encoding", "base64");
    bp2.addHeader("Content-ID", "part2@apache.org");
    mp.addBodyPart(bp2);
    message.setContent(mp);
    // Compute the correct content type
    message.saveChanges();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mp.writeTo(baos);
    String contentType = message.getContentType();
    InputStream in = new ByteArrayInputStream(baos.toByteArray());
    Attachments attachments;
    if (useFile) {
        attachments = new Attachments(in, contentType, true, getAttachmentsDir(), "1024");
    } else {
        attachments = new Attachments(in, contentType);
    }
    DataHandler dh = attachments.getDataHandler("part2@apache.org");
    byte[] content2 = IOUtils.toByteArray(dh.getInputStream());
    assertTrue(Arrays.equals(content, content2));
}
Also used : Random(java.util.Random) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PipedInputStream(java.io.PipedInputStream) ExceptionInputStream(org.apache.axiom.testutils.io.ExceptionInputStream) InputStream(java.io.InputStream) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 40 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)

Aggregations

ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)40 DataHandler (javax.activation.DataHandler)27 MimeMultipart (javax.mail.internet.MimeMultipart)18 IOException (java.io.IOException)16 DataSource (javax.activation.DataSource)15 MessagingException (javax.mail.MessagingException)14 MimeBodyPart (javax.mail.internet.MimeBodyPart)13 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 ByteArrayInputStream (java.io.ByteArrayInputStream)9 InputStream (java.io.InputStream)9 ArrayList (java.util.ArrayList)9 MimeMessage (javax.mail.internet.MimeMessage)7 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)5 List (java.util.List)5 Test (org.junit.Test)5 ContentDisposition (com.zimbra.common.mime.ContentDisposition)4 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)4 Document (ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document)4 Exchange (org.apache.camel.Exchange)3 ByteString (com.linkedin.data.ByteString)2