Example usage for javax.mail.internet ContentType getBaseType

List of usage examples for javax.mail.internet ContentType getBaseType

Introduction

In this page you can find the example usage for javax.mail.internet ContentType getBaseType.

Prototype

public String getBaseType() 

Source Link

Document

Return the MIME type string, without the parameters.

Usage

From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

public Attach getAttach(Part part, String baseStorePath) throws MessagingException, IOException {
    MimeBodyPart mimePart = (MimeBodyPart) part;
    Attach attach = new Attach();
    if (StringUtils.isEmpty(mimePart.getFileName())) {
        attach.setFileName("UNKNOWN");
    } else {//  w  w w.j a  va  2 s. c  om
        String fileName = mimePart.getFileName();
        String encoded = System.getProperty("mail.mime.encodefilename");
        if (Boolean.parseBoolean(encoded)) {
            fileName = MimeUtility.decodeText(fileName);
        }
        attach.setFileName(fileName);
    }
    ContentType type = new ContentType(mimePart.getContentType());
    attach.setMimeType(type.getBaseType());
    InputStream inputStream = mimePart.getDataHandler().getInputStream();
    attach.buildMd5Checksum(inputStream);
    attach.buildPath(mimePart, baseStorePath);
    return attach;
}

From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java

protected void getAttachmentParts(Part part, String defaultFilename, MimetypeRegistry mimeService,
        ExecutionContext context) throws MessagingException, IOException {
    String filename = getFilename(part, defaultFilename);
    List<Blob> blobs = (List<Blob>) context.get(ATTACHMENTS_KEY);

    if (part.isMimeType("multipart/alternative")) {
        bodyContent += getText(part);/*from  w ww  .  j  ava 2s.c om*/
    } else {
        if (!part.isMimeType("multipart/*")) {
            String disp = part.getDisposition();
            // no disposition => mail body, which can be also blob (image for
            // instance)
            if (disp == null && // convert only text
                    part.getContentType().toLowerCase().startsWith("text/")) {
                bodyContent += decodeMailBody(part);
            } else {
                Blob blob;
                try (InputStream in = part.getInputStream()) {
                    blob = Blobs.createBlob(in);
                }
                String mime = DEFAULT_BINARY_MIMETYPE;
                try {
                    if (mimeService != null) {
                        ContentType contentType = new ContentType(part.getContentType());
                        mime = mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob,
                                contentType.getBaseType());
                    }
                } catch (MessagingException | MimetypeDetectionException e) {
                    log.error(e);
                }
                blob.setMimeType(mime);

                blob.setFilename(filename);

                blobs.add(blob);
            }
        }

        if (part.isMimeType("multipart/*")) {
            // This is a Multipart
            Multipart mp = (Multipart) part.getContent();

            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                getAttachmentParts(mp.getBodyPart(i), defaultFilename, mimeService, context);
            }
        } else if (part.isMimeType(MESSAGE_RFC822_MIMETYPE)) {
            // This is a Nested Message
            getAttachmentParts((Part) part.getContent(), defaultFilename, mimeService, context);
        }
    }

}

From source file:org.esxx.Parsers.java

public Object parse(ContentType ct, InputStream is, final URI is_uri, Collection<URI> external_uris,
        PrintWriter err, Context cx, Scriptable scope) throws Exception {
    // Read-only accesses; no syncronization required
    Parser parser = parserMap.get(ct.getBaseType());

    if (parser == null) {
        if (ct.getBaseType().endsWith("+xml")) {
            parser = parserMap.get("application/xml");
        } else if (ct.match("image/*")) {
            parser = parserMap.get("image/*");
        } else if (ct.match("text/*")) {
            parser = parserMap.get("text/plain");
        } else {/*from  ww  w .  j  a  va 2  s .c  om*/
            parser = parserMap.get("application/octet-stream");
        }
    }

    Object result = null;

    try {
        result = parser.parse(ct, is, is_uri, external_uris, err, cx, scope);
    } finally {
        if (result != is) {
            is.close();
        }
    }

    return result;
}

From source file:org.alfresco.module.org_alfresco_module_rm.action.impl.SplitEmailAction.java

/**
 * Create attachment from Mime Message Part
 * @param messageNodeRef - the node ref of the mime message
 * @param parentNodeRef - the node ref of the parent folder
 * @param part/*from  w  ww  .j  a  v a 2s .c  o  m*/
 * @throws MessagingException
 * @throws IOException
 */
private void createAttachment(NodeRef messageNodeRef, NodeRef parentNodeRef, Part part)
        throws MessagingException, IOException {
    String fileName = part.getFileName();
    try {
        fileName = MimeUtility.decodeText(fileName);
    } catch (UnsupportedEncodingException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("Cannot decode file name '" + fileName + "'", e);
        }
    }

    Map<QName, Serializable> messageProperties = getNodeService().getProperties(messageNodeRef);
    String messageTitle = (String) messageProperties.get(ContentModel.PROP_NAME);
    if (messageTitle == null) {
        messageTitle = fileName;
    } else {
        messageTitle = messageTitle + " - " + fileName;
    }

    ContentType contentType = new ContentType(part.getContentType());

    Map<QName, Serializable> docProps = new HashMap<QName, Serializable>(1);
    docProps.put(ContentModel.PROP_NAME, messageTitle + " - " + fileName);
    docProps.put(ContentModel.PROP_TITLE, fileName);

    /**
     * Create an attachment node in the same folder as the message
     */
    ChildAssociationRef attachmentRef = getNodeService().createNode(parentNodeRef, ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, fileName), ContentModel.TYPE_CONTENT,
            docProps);

    /**
     * Write the content into the new attachment node
     */
    ContentWriter writer = getContentService().getWriter(attachmentRef.getChildRef(), ContentModel.PROP_CONTENT,
            true);
    writer.setMimetype(contentType.getBaseType());
    OutputStream os = writer.getContentOutputStream();
    FileCopyUtils.copy(part.getInputStream(), os);

    /**
     * Create a link from the message to the attachment
     */
    createRMReference(messageNodeRef, attachmentRef.getChildRef());

}

From source file:org.sakaiproject.james.SakaiMailet.java

/**
 * Breaks email messages into parts which can be saved as files (saves as attachments) or viewed as plain text (added to body of message).
 * /*from ww  w .ja  v  a2s . c om*/
 * @param siteId
 *        Site associated with attachments, if any
 * @param p
 *        The message-part embedded in a message..
 * @param id
 *        The string containing the message's id.
 * @param bodyBuf
 *        The string-buffers in which the plain/text and/or html/text message body is being built.
 * @param bodyContentType
 *        The value of the Content-Type header for the mesage body.
 * @param attachments
 *        The ReferenceVector in which references to attachments are collected.
 * @param embedCount
 *        An Integer that counts embedded messages (outer message is zero).
 * @return Value of embedCount (updated if this call processed any embedded messages).
 */
protected Integer parseParts(String siteId, Part p, String id, StringBuilder bodyBuf[],
        StringBuilder bodyContentType, List attachments, Integer embedCount)
        throws MessagingException, IOException {
    // increment embedded message counter
    if (p instanceof Message) {
        embedCount = Integer.valueOf(embedCount.intValue() + 1);
    }

    String type = p.getContentType();

    // discard if content-type is unknown
    if (type == null || "".equals(type)) {
        M_log.warn(this + " message with unknown content-type discarded");
    }

    // add plain text to bodyBuf[0]
    else if (p.isMimeType("text/plain") && p.getFileName() == null) {
        Object o = null;
        // let them convert to text if possible
        // but if bad encaps get the stream and do it ourselves
        try {
            o = p.getContent();
        } catch (java.io.UnsupportedEncodingException ignore) {
            o = p.getInputStream();
        }

        String txt = null;
        String innerContentType = p.getContentType();

        if (o instanceof String) {
            txt = (String) p.getContent();
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        else if (o instanceof InputStream) {
            InputStream in = (InputStream) o;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[in.available()];
            for (int len = in.read(buf); len != -1; len = in.read(buf))
                out.write(buf, 0, len);
            String charset = (new ContentType(innerContentType)).getParameter("charset");
            // RFC 2045 says if no char set specified use US-ASCII.
            // If specified but illegal that's less clear. The common case is X-UNKNOWN.
            // my sense is that UTF-8 is most likely these days but the sample we got
            // was actually ISO 8859-1. Could also justify using US-ASCII. Duh...
            if (charset == null)
                charset = "us-ascii";
            try {
                txt = out.toString(MimeUtility.javaCharset(charset));
            } catch (java.io.UnsupportedEncodingException ignore) {
                txt = out.toString("UTF-8");
            }
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        // remove extra line breaks added by mac Mail, perhaps others
        // characterized by a space followed by a line break
        if (txt != null) {
            txt = txt.replaceAll(" \n", " ");
        }

        // make sure previous message parts ended with newline
        if (bodyBuf[0].length() > 0 && bodyBuf[0].charAt(bodyBuf[0].length() - 1) != '\n')
            bodyBuf[0].append("\n");

        bodyBuf[0].append(txt);
    }

    // add html text to bodyBuf[1]
    else if (p.isMimeType("text/html") && p.getFileName() == null) {
        Object o = null;
        // let them convert to text if possible
        // but if bad encaps get the stream and do it ourselves
        try {
            o = p.getContent();
        } catch (java.io.UnsupportedEncodingException ignore) {
            o = p.getInputStream();
        }
        String txt = null;
        String innerContentType = p.getContentType();

        if (o instanceof String) {
            txt = (String) p.getContent();
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        else if (o instanceof InputStream) {
            InputStream in = (InputStream) o;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[in.available()];
            for (int len = in.read(buf); len != -1; len = in.read(buf))
                out.write(buf, 0, len);
            String charset = (new ContentType(innerContentType)).getParameter("charset");
            if (charset == null)
                charset = "us-ascii";
            try {
                txt = out.toString(MimeUtility.javaCharset(charset));
            } catch (java.io.UnsupportedEncodingException ignore) {
                txt = out.toString("UTF-8");
            }
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        // remove bad image tags and naughty javascript
        if (txt != null) {
            txt = Web.cleanHtml(txt);
        }

        bodyBuf[1].append(txt);
    }

    // process subparts of multiparts
    else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            embedCount = parseParts(siteId, mp.getBodyPart(i), id, bodyBuf, bodyContentType, attachments,
                    embedCount);
        }
    }

    // Discard parts with mime-type application/applefile. If an e-mail message contains an attachment is sent from
    // a macintosh, you may get two parts, one for the data fork and one for the resource fork. The part that
    // corresponds to the resource fork confuses users, this has mime-type application/applefile. The best thing
    // is to discard it.
    else if (p.isMimeType("application/applefile")) {
        M_log.warn(this + " message with application/applefile discarded");
    }

    // discard enriched text version of the message.
    // Sakai only uses the plain/text or html/text version of the message.
    else if (p.isMimeType("text/enriched") && p.getFileName() == null) {
        M_log.warn(this + " message with text/enriched discarded");
    }

    // everything else gets treated as an attachment
    else {
        String name = p.getFileName();

        // look for filenames not parsed by getFileName() 
        if (name == null && type.indexOf(NAME_PREFIX) != -1) {
            name = type.substring(type.indexOf(NAME_PREFIX) + NAME_PREFIX.length());
        }
        // ContentType can't handle filenames with spaces or UTF8 characters
        if (name != null) {
            String decodedName = MimeUtility.decodeText(name); // first decode RFC 2047
            type = type.replace(name, URLEncoder.encode(decodedName, "UTF-8"));
            name = decodedName;
        }

        ContentType cType = new ContentType(type);
        String disposition = p.getDisposition();
        int approxSize = p.getSize();

        if (name == null) {
            name = "unknown";
            // if file's parent is multipart/alternative,
            // provide a better name for the file
            if (p instanceof BodyPart) {
                Multipart parent = ((BodyPart) p).getParent();
                if (parent != null) {
                    String pType = parent.getContentType();
                    ContentType pcType = new ContentType(pType);
                    if (pcType.getBaseType().equalsIgnoreCase("multipart/alternative")) {
                        name = "message" + embedCount;
                    }
                }
            }
            if (p.isMimeType("text/html")) {
                name += ".html";
            } else if (p.isMimeType("text/richtext")) {
                name += ".rtx";
            } else if (p.isMimeType("text/rtf")) {
                name += ".rtf";
            } else if (p.isMimeType("text/enriched")) {
                name += ".etf";
            } else if (p.isMimeType("text/plain")) {
                name += ".txt";
            } else if (p.isMimeType("text/xml")) {
                name += ".xml";
            } else if (p.isMimeType("message/rfc822")) {
                name += ".txt";
            }
        }

        // read the attachments bytes, and create it as an attachment in content hosting
        byte[] bodyBytes = readBody(approxSize, p.getInputStream());
        if ((bodyBytes != null) && (bodyBytes.length > 0)) {
            // can we ignore the attachment it it's just whitespace chars??
            Reference attachment = createAttachment(siteId, attachments, cType.getBaseType(), name, bodyBytes,
                    id);

            // add plain/text attachment reference (if plain/text message)
            if (attachment != null && bodyBuf[0].length() > 0)
                bodyBuf[0]
                        .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n");

            // add html/text attachment reference (if html/text message)
            if (attachment != null && bodyBuf[1].length() > 0)
                bodyBuf[1].append(
                        "<p>[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]</p>");

            // add plain/text attachment reference (if no plain/text and no html/text)
            if (attachment != null && bodyBuf[0].length() == 0 && bodyBuf[1].length() == 0)
                bodyBuf[0]
                        .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n");
        }
    }

    return embedCount;
}

From source file:com.cubusmail.gwtui.server.services.RetrieveAttachmentServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(request.getSession().getServletContext());

    try {/*from   w  w w.j av a 2 s . c  o m*/
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean view = "1".equals(request.getParameter("view"));

        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
            int index = Integer.valueOf(attachmentIndex);

            MimePart retrievePart = attachmentList.get(index);

            ContentType contentType = new ContentType(retrievePart.getContentType());

            String fileName = retrievePart.getFileName();
            if (StringUtils.isEmpty(fileName)) {
                fileName = context.getMessage("message.unknown.attachment", null,
                        SessionManager.get().getLocale());
            }
            StringBuffer contentDisposition = new StringBuffer();
            if (!view) {
                contentDisposition.append("attachment; filename=\"");
                contentDisposition.append(fileName).append("\"");
            }

            response.setHeader("cache-control", "no-store");
            response.setHeader("pragma", "no-cache");
            response.setIntHeader("max-age", 0);
            response.setIntHeader("expires", 0);

            if (!StringUtils.isEmpty(contentDisposition.toString())) {
                response.setHeader("Content-disposition", contentDisposition.toString());
            }
            response.setContentType(contentType.getBaseType());
            // response.setContentLength(
            // MessageUtils.calculateSizeFromPart( retrievePart ) );

            BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream());
            OutputStream outputStream = response.getOutputStream();

            byte[] inBuf = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = bufInputStream.read(inBuf)) > 0) {
                outputStream.write(inBuf, 0, len);
                total += len;
            }

            bufInputStream.close();
            outputStream.flush();
            outputStream.close();

        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:com.cubusmail.server.services.RetrieveAttachmentServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(request.getSession().getServletContext());

    try {//from  w  w w .j a v  a 2  s. c o  m
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean view = "1".equals(request.getParameter("view"));

        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
            int index = Integer.valueOf(attachmentIndex);

            MimePart retrievePart = attachmentList.get(index);

            ContentType contentType = new ContentType(retrievePart.getContentType());

            String fileName = retrievePart.getFileName();
            if (StringUtils.isEmpty(fileName)) {
                fileName = context.getMessage("message.unknown.attachment", null,
                        SessionManager.get().getLocale());
            }
            StringBuffer contentDisposition = new StringBuffer();
            if (!view) {
                contentDisposition.append("attachment; filename=\"");
                contentDisposition.append(fileName).append("\"");
            }

            response.setHeader("cache-control", "no-store");
            response.setHeader("pragma", "no-cache");
            response.setIntHeader("max-age", 0);
            response.setIntHeader("expires", 0);

            if (!StringUtils.isEmpty(contentDisposition.toString())) {
                response.setHeader("Content-disposition", contentDisposition.toString());
            }
            response.setContentType(contentType.getBaseType());
            // response.setContentLength(
            // MessageUtils.calculateSizeFromPart( retrievePart ) );

            BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream());
            OutputStream outputStream = response.getOutputStream();

            byte[] inBuf = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = bufInputStream.read(inBuf)) > 0) {
                outputStream.write(inBuf, 0, len);
                total += len;
            }

            bufInputStream.close();
            outputStream.flush();
            outputStream.close();

        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java

public boolean addPartToDocument(Part part, Map<String, Object> row, boolean outerMost) throws Exception {
    if (outerMost && part instanceof Message) {
        if (!addEnvelopToDocument(part, row)) {
            return false;
        }// ww  w  .  ja v a 2  s .  c o  m
        // store hash
        row.put(HASH, DigestUtils.md5Hex((String) row.get(FROM_CLEAN) + "" + (String) row.get(SUBJECT)));
    }

    String ct = part.getContentType();
    ContentType ctype = new ContentType(ct);
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        int count = mp.getCount();
        if (part.isMimeType("multipart/alternative")) {
            count = 1;
        }
        for (int i = 0; i < count; i++) {
            addPartToDocument(mp.getBodyPart(i), row, false);
        }
    } else if (part.isMimeType("message/rfc822")) {
        addPartToDocument((Part) part.getContent(), row, false);
    } else {
        String disp = part.getDisposition();
        @SuppressWarnings("resource") // Tika will close stream
        InputStream is = part.getInputStream();
        String fileName = part.getFileName();
        Metadata md = new Metadata();
        md.set(HttpHeaders.CONTENT_TYPE, ctype.getBaseType().toLowerCase(Locale.ROOT));
        md.set(TikaMetadataKeys.RESOURCE_NAME_KEY, fileName);
        String content = this.tika.parseToString(is, md);
        if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (row.get(ATTACHMENT) == null) {
                row.put(ATTACHMENT, new ArrayList<String>());
            }
            List<String> contents = (List<String>) row.get(ATTACHMENT);
            contents.add(content);
            row.put(ATTACHMENT, contents);
            if (row.get(ATTACHMENT_NAMES) == null) {
                row.put(ATTACHMENT_NAMES, new ArrayList<String>());
            }
            List<String> names = (List<String>) row.get(ATTACHMENT_NAMES);
            names.add(fileName);
            row.put(ATTACHMENT_NAMES, names);
        } else {
            if (row.get(CONTENT) == null) {
                row.put(CONTENT, new ArrayList<String>());
            }
            List<String> contents = (List<String>) row.get(CONTENT);
            contents.add(content);
            row.put(CONTENT, contents);
        }
    }
    return true;
}

From source file:com.linkedin.restli.server.TestRestLiServer.java

@Test
public void testMultipartRelatedRequestNoUserAttachments() throws Exception {
    //This test verifies the server's ability to handle a multipart related request that has only one part which is
    //the rest.li payload; meaning there are no user defined attachments. Technically the client builders shouldn't do
    //this but we allow this to keep the protocol somewhat flexible.

    final AsyncStatusCollectionResource statusResource = getMockResource(AsyncStatusCollectionResource.class);

    statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(),
            EasyMock.<Callback<Long>>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override/*w w  w  .ja v  a2  s  . co m*/
        public Object answer() throws Throwable {
            //Verify there are no attachments.
            final RestLiAttachmentReader attachmentReader = (RestLiAttachmentReader) EasyMock
                    .getCurrentArguments()[1];
            Assert.assertNull(attachmentReader);

            //Verify the action param.
            Assert.assertEquals((String) EasyMock.getCurrentArguments()[0], "someMetadata");

            //Now respond back to the request.
            @SuppressWarnings("unchecked")
            Callback<Long> callback = (Callback<Long>) EasyMock.getCurrentArguments()[2];
            callback.onSuccess(1234l);
            return null;
        }
    });
    EasyMock.replay(statusResource);

    //Now we create a multipart/related payload.
    final String payload = "{\"metadata\": \"someMetadata\"}";
    final ByteStringWriter byteStringWriter = new ByteStringWriter(
            ByteString.copyString(payload, Charset.defaultCharset()));
    final MultiPartMIMEWriter.Builder builder = new MultiPartMIMEWriter.Builder();
    final MultiPartMIMEWriter writer = AttachmentUtils.createMultiPartMIMEWriter(byteStringWriter,
            "application/json", builder);

    final StreamRequest streamRequest = MultiPartMIMEStreamRequestFactory.generateMultiPartMIMEStreamRequest(
            new URI("/asyncstatuses/?action=streamingAction"), "related", writer,
            Collections.<String, String>emptyMap(), "POST",
            ImmutableMap.of(RestConstants.HEADER_ACCEPT, RestConstants.HEADER_VALUE_MULTIPART_RELATED),
            Collections.emptyList());

    final Callback<StreamResponse> callback = new Callback<StreamResponse>() {
        @Override
        public void onSuccess(StreamResponse streamResponse) {
            Messages.toRestResponse(streamResponse, new Callback<RestResponse>() {
                @Override
                public void onError(Throwable e) {
                    Assert.fail();
                }

                @Override
                public void onSuccess(RestResponse result) {
                    Assert.assertEquals(result.getStatus(), 200);

                    try {
                        ContentType contentType = new ContentType(
                                streamResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE));
                        Assert.assertEquals(contentType.getBaseType(),
                                RestConstants.HEADER_VALUE_APPLICATION_JSON);
                    } catch (ParseException parseException) {
                        Assert.fail();
                    }

                    //Verify the response body
                    Assert.assertEquals(result.getEntity().asAvroString(), "{\"value\":1234}");

                    EasyMock.verify(statusResource);
                    EasyMock.reset(statusResource);
                }
            });
        }

        @Override
        public void onError(Throwable e) {
            fail();
        }
    };

    _server.handleRequest(streamRequest, new RequestContext(), callback);
}

From source file:com.linkedin.restli.server.TestRestLiServer.java

@Test
public void testRequestAttachmentsAndResponseAttachments() throws Exception {
    //This test verifies the server's ability to accept request attachments and send back response attachments. This is the
    //main test to verify the wire protocol for streaming. We send a payload that contains the rest.li payload and some attachments
    //and we send a response back with a rest.li payload and some attachments.

    //Define the server side resource attachments to be sent back.
    final RestLiResponseAttachments.Builder responseAttachmentsBuilder = new RestLiResponseAttachments.Builder();
    responseAttachmentsBuilder.appendSingleAttachment(
            new RestLiTestAttachmentDataSource("1", ByteString.copyString("one", Charset.defaultCharset())));

    Capture<ResourceContext> resourceContextCapture = new Capture<ResourceContext>();
    final AsyncStatusCollectionResource statusResource = getMockResource(AsyncStatusCollectionResource.class,
            EasyMock.capture(resourceContextCapture));

    statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(),
            EasyMock.<Callback<Long>>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override/*from w w  w  .  ja v a  2 s  . c  o m*/
        public Object answer() throws Throwable {
            //Verify there are still attachments to be read.
            final RestLiAttachmentReader attachmentReader = (RestLiAttachmentReader) EasyMock
                    .getCurrentArguments()[1];
            Assert.assertFalse(attachmentReader.haveAllAttachmentsFinished());

            //Verify the action param.
            Assert.assertEquals((String) EasyMock.getCurrentArguments()[0], "someMetadata");

            //Set the response attachments
            resourceContextCapture.getValue().setResponseAttachments(responseAttachmentsBuilder.build());

            //Now respond back to the request.
            @SuppressWarnings("unchecked")
            Callback<Long> callback = (Callback<Long>) EasyMock.getCurrentArguments()[2];
            callback.onSuccess(1234l);
            return null;
        }
    });
    EasyMock.replay(statusResource);

    //Now we create a multipart/related payload.
    final String payload = "{\"metadata\": \"someMetadata\"}";
    final ByteStringWriter byteStringWriter = new ByteStringWriter(
            ByteString.copyString(payload, Charset.defaultCharset()));
    final MultiPartMIMEWriter.Builder builder = new MultiPartMIMEWriter.Builder();
    AttachmentUtils.appendSingleAttachmentToBuilder(builder,
            new RestLiTestAttachmentDataSource("2", ByteString.copyString("two", Charset.defaultCharset())));
    final MultiPartMIMEWriter writer = AttachmentUtils.createMultiPartMIMEWriter(byteStringWriter,
            "application/json", builder);

    final StreamRequest streamRequest = MultiPartMIMEStreamRequestFactory.generateMultiPartMIMEStreamRequest(
            new URI("/asyncstatuses/?action=streamingAction"), "related", writer,
            Collections.<String, String>emptyMap(), "POST",
            ImmutableMap.of(RestConstants.HEADER_ACCEPT, RestConstants.HEADER_VALUE_MULTIPART_RELATED),
            Collections.emptyList());

    final Callback<StreamResponse> callback = new Callback<StreamResponse>() {
        @Override
        public void onSuccess(StreamResponse streamResponse) {
            //Before reading the data make sure top level type is multipart/related
            Assert.assertEquals(streamResponse.getStatus(), 200);
            try {
                ContentType contentType = new ContentType(
                        streamResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE));
                Assert.assertEquals(contentType.getBaseType(), RestConstants.HEADER_VALUE_MULTIPART_RELATED);
            } catch (ParseException parseException) {
                Assert.fail();
            }

            final CountDownLatch countDownLatch = new CountDownLatch(1);
            MultiPartMIMEFullReaderCallback fullReaderCallback = new MultiPartMIMEFullReaderCallback(
                    countDownLatch);
            final MultiPartMIMEReader reader = MultiPartMIMEReader.createAndAcquireStream(streamResponse);
            reader.registerReaderCallback(fullReaderCallback);
            try {
                countDownLatch.await(3000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException interruptedException) {
                Assert.fail();
            }

            final List<SinglePartMIMEFullReaderCallback> singlePartMIMEReaderCallbacks = fullReaderCallback
                    .getSinglePartMIMEReaderCallbacks();
            Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 2);

            //Verify first part is Action response.
            Assert.assertEquals(
                    singlePartMIMEReaderCallbacks.get(0).getHeaders().get(RestConstants.HEADER_CONTENT_TYPE),
                    RestConstants.HEADER_VALUE_APPLICATION_JSON);
            Assert.assertEquals(singlePartMIMEReaderCallbacks.get(0).getFinishedData().asAvroString(),
                    "{\"value\":1234}");
            //Verify the second part matches what the server should have sent back
            Assert.assertEquals(
                    singlePartMIMEReaderCallbacks.get(1).getHeaders().get(RestConstants.HEADER_CONTENT_ID),
                    "1");
            Assert.assertEquals(
                    singlePartMIMEReaderCallbacks.get(1).getFinishedData().asString(Charset.defaultCharset()),
                    "one");

            EasyMock.verify(statusResource);
            EasyMock.reset(statusResource);
        }

        @Override
        public void onError(Throwable e) {
            fail();
        }
    };

    _server.handleRequest(streamRequest, new RequestContext(), callback);
}