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:com.zotoh.crypto.MICUte.java

private static Object fromMP(Multipart mp) throws Exception {
    ContentType ct = new ContentType(mp.getContentType());
    BodyPart bp;//ww  w. ja va  2s  .  c  om
    Object contents;
    Object rc = null;
    int count = mp.getCount();

    if ("multipart/mixed".equalsIgnoreCase(ct.getBaseType())) {
        if (count > 0) {
            bp = mp.getBodyPart(0);
            contents = bp.getContent();

            // check for EDI payload sent as attachment
            String ctype = bp.getContentType();
            boolean getNextPart = false;

            if (ctype.indexOf("text/plain") >= 0) {
                if (contents instanceof String) {
                    String bodyText = "This is a generated cryptographic message in MIME format";
                    if (((String) contents).startsWith(bodyText)) {
                        getNextPart = true;
                    }
                }

                if (!getNextPart) {
                    // check for a content disposition
                    // if disposition type is attachment, then this is a doc
                    getNextPart = true;
                    String disp = bp.getDisposition();
                    if (disp != null && disp.toLowerCase().equals("attachment"))
                        getNextPart = false;
                }
            }

            if ((count >= 2) && getNextPart) {
                bp = mp.getBodyPart(1);
                contents = bp.getContent();
            }

            if (contents instanceof String) {
                rc = asBytes((String) contents);
            } else if (contents instanceof byte[]) {
                rc = contents;
            } else if (contents instanceof InputStream) {
                rc = contents;
            } else {
                String cn = contents == null ? "null" : contents.getClass().getName();
                throw new Exception("Unsupport MIC object: " + cn);
            }
        }
    } else if (count > 0) {
        bp = mp.getBodyPart(0);
        contents = bp.getContent();

        if (contents instanceof String) {
            rc = asBytes((String) contents);
        } else if (contents instanceof byte[]) {
            rc = contents;
        } else if (contents instanceof InputStream) {
            rc = contents;
        } else {
            String cn = contents == null ? "null" : contents.getClass().getName();
            throw new Exception("Unsupport MIC object: " + cn);
        }
    }

    return rc;
}

From source file:mx.uaq.facturacion.enlace.EmailParserUtils.java

/**
 * Parses any {@link Multipart} instances that contain text or Html attachments,
 * {@link InputStream} instances, additional instances of {@link Multipart}
 * or other attached instances of {@link javax.mail.Message}.
 *
 * Will create the respective {@link EmailFragment}s representing those attachments.
 *
 * Instances of {@link javax.mail.Message} are delegated to
 * {@link #handleMessage(File, javax.mail.Message, List)}. Further instances
 * of {@link Multipart} are delegated to
 * {@link #handleMultipart(File, Multipart, javax.mail.Message, List)}.
 *
 * @param directory Must not be null//from   www. j  a  v  a 2s .c o  m
 * @param multipart Must not be null
 * @param mailMessage Must not be null
 * @param emailFragments Must not be null
 */
public static void handleMultipart(File directory, Multipart multipart, javax.mail.Message mailMessage,
        List<EmailFragment> emailFragments) {

    Assert.notNull(directory, "The directory must not be null.");
    Assert.notNull(multipart, "The multipart object to be parsed must not be null.");
    Assert.notNull(mailMessage, "The mail message to be parsed must not be null.");
    Assert.notNull(emailFragments, "The collection of emailfragments must not be null.");

    final int count;

    try {
        count = multipart.getCount();

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(String.format("Number of enclosed BodyPart objects: %s.", count));
        }

    } catch (MessagingException e) {
        throw new IllegalStateException("Error while retrieving the number of enclosed BodyPart objects.", e);
    }

    for (int i = 0; i < count; i++) {

        final BodyPart bp;

        try {
            bp = multipart.getBodyPart(i);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving body part.", e);
        }

        final String contentType;
        String filename;
        final String disposition;
        final String subject;

        try {

            contentType = bp.getContentType();
            filename = bp.getFileName();
            disposition = bp.getDisposition();
            subject = mailMessage.getSubject();

            if (filename == null && bp instanceof MimeBodyPart) {
                filename = ((MimeBodyPart) bp).getContentID();
            }

        } catch (MessagingException e) {
            throw new IllegalStateException("Unable to retrieve body part meta data.", e);
        }

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(String.format(
                    "BodyPart - Content Type: '%s', filename: '%s', disposition: '%s', subject: '%s'",
                    new Object[] { contentType, filename, disposition, subject }));
        }

        if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType));
        }

        final Object content;

        try {
            content = bp.getContent();
        } catch (IOException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        }

        if (content instanceof String) {

            if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                emailFragments.add(new EmailFragment(directory, i + "-" + filename, content));
                LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType));
            } else {

                final String textFilename;
                final ContentType ct;

                try {
                    ct = new ContentType(contentType);
                } catch (ParseException e) {
                    throw new IllegalStateException("Error while parsing content type '" + contentType + "'.",
                            e);
                }

                if ("text/plain".equalsIgnoreCase(ct.getBaseType())) {
                    textFilename = "message.txt";
                } else if ("text/html".equalsIgnoreCase(ct.getBaseType())) {
                    textFilename = "message.html";
                } else {
                    textFilename = "message.other";
                }

                emailFragments.add(new EmailFragment(directory, textFilename, content));
            }

        } else if (content instanceof InputStream) {

            final InputStream inputStream = (InputStream) content;
            final ByteArrayOutputStream bis = new ByteArrayOutputStream();

            try {
                IOUtils.copy(inputStream, bis);
            } catch (IOException e) {
                throw new IllegalStateException(
                        "Error while copying input stream to the ByteArrayOutputStream.", e);
            }

            emailFragments.add(new EmailFragment(directory, filename, bis.toByteArray()));

        } else if (content instanceof javax.mail.Message) {
            handleMessage(directory, (javax.mail.Message) content, emailFragments);
        } else if (content instanceof Multipart) {
            final Multipart mp2 = (Multipart) content;
            handleMultipart(directory, mp2, mailMessage, emailFragments);
        } else {
            throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName());
        }
    }
}

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// www.j  a v  a  2s .com
 */
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: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/*www. j av  a  2  s .com*/
 */
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:com.cubusmail.gwtui.server.services.ShowMessageSourceServlet.java

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

    try {/*w ww  .  ja  va 2s .c  om*/
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                logger.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

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

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

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

    try {//from   ww w . j a  va 2s  .  c om
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                log.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

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

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

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

    try {//from  www  .  j  a  va2s  .c om
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean isThumbnail = Boolean.valueOf(request.getParameter("thumbnail")).booleanValue();

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

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

                MimePart retrievePart = attachmentList.get(index);

                ContentType contentType = new ContentType(retrievePart.getContentType());
                response.setContentType(contentType.getBaseType());

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

                writeScaledImage(bufInputStream, outputStream);

                bufInputStream.close();
                outputStream.flush();
                outputStream.close();
            } else {
                Part imagePart = findImagePart(msg);
                if (imagePart != null) {
                    ContentType contentType = new ContentType(imagePart.getContentType());
                    response.setContentType(contentType.getBaseType());

                    BufferedInputStream bufInputStream = new BufferedInputStream(imagePart.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:com.predic8.membrane.core.interceptor.statistics.StatisticsJDBCInterceptor.java

private boolean ignoreNotSoap(Exchange exc) {
    ContentType ct;//w  w w. j  av a 2  s  .  c o m
    try {
        ct = exc.getRequest().getHeader().getContentTypeObject();
    } catch (ParseException e) {
        return false;
    }
    return soapOnly && ct != null && !ct.getBaseType().equalsIgnoreCase(MimeType.APPLICATION_SOAP)
            && !ct.getBaseType().equalsIgnoreCase(MimeType.TEXT_XML);
}

From source file:org.alfresco.repo.imap.AttachmentsExtractor.java

/**
 * Create an attachment given a mime part
 * //  w  w  w .  j  a v  a 2 s. c o  m
 * @param messageFile the file containing the message
 * @param attachmentsFolderRef where to put the attachment
 * @param part the mime part
 * @throws MessagingException
 * @throws IOException
 */
private void createAttachment(NodeRef messageFile, NodeRef attachmentsFolderRef, Part part)
        throws MessagingException, IOException {
    String fileName = part.getFileName();
    if (fileName == null || fileName.isEmpty()) {
        fileName = "unnamed";
    }
    try {
        fileName = MimeUtility.decodeText(fileName);
    } catch (UnsupportedEncodingException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("Cannot decode file name '" + fileName + "'", e);
        }
    }

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

    if (contentType.getBaseType().equalsIgnoreCase("application/ms-tnef")) {
        // The content is TNEF
        HMEFMessage hmef = new HMEFMessage(part.getInputStream());

        // hmef.getBody();
        List<org.apache.poi.hmef.Attachment> attachments = hmef.getAttachments();
        for (org.apache.poi.hmef.Attachment attachment : attachments) {
            String subName = attachment.getLongFilename();

            NodeRef attachmentNode = fileFolderService.searchSimple(attachmentsFolderRef, subName);
            if (attachmentNode == null) {
                /*
                 * If the node with the given name does not already exist Create the content node to contain the attachment
                 */
                FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, subName,
                        ContentModel.TYPE_CONTENT);

                attachmentNode = createdFile.getNodeRef();

                serviceRegistry.getNodeService().createAssociation(messageFile, attachmentNode,
                        ImapModel.ASSOC_IMAP_ATTACHMENT);

                byte[] bytes = attachment.getContents();
                ContentWriter writer = fileFolderService.getWriter(attachmentNode);

                // TODO ENCODING - attachment.getAttribute(TNEFProperty.);
                String extension = attachment.getExtension();
                String mimetype = mimetypeService.getMimetype(extension);
                if (mimetype != null) {
                    writer.setMimetype(mimetype);
                }

                OutputStream os = writer.getContentOutputStream();
                ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                FileCopyUtils.copy(is, os);
            }
        }
    } else {
        // not TNEF
        NodeRef attachmentFile = fileFolderService.searchSimple(attachmentsFolderRef, fileName);
        // The one possible behaviour
        /*
         * if (result.size() > 0) { for (FileInfo fi : result) { fileFolderService.delete(fi.getNodeRef()); } }
         */
        // And another one behaviour which will overwrite the content of the existing file. It is performance preferable.
        if (attachmentFile == null) {
            FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, fileName,
                    ContentModel.TYPE_CONTENT);
            nodeService.createAssociation(messageFile, createdFile.getNodeRef(),
                    ImapModel.ASSOC_IMAP_ATTACHMENT);
            attachmentFile = createdFile.getNodeRef();
        } else {

            String newFileName = imapService.generateUniqueFilename(attachmentsFolderRef, fileName);

            FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, newFileName,
                    ContentModel.TYPE_CONTENT);
            nodeService.createAssociation(messageFile, createdFile.getNodeRef(),
                    ImapModel.ASSOC_IMAP_ATTACHMENT);
            attachmentFile = createdFile.getNodeRef();

        }

        nodeService.setProperty(attachmentFile, ContentModel.PROP_DESCRIPTION,
                nodeService.getProperty(messageFile, ContentModel.PROP_NAME));

        ContentWriter writer = fileFolderService.getWriter(attachmentFile);
        writer.setMimetype(contentType.getBaseType());
        OutputStream os = writer.getContentOutputStream();
        FileCopyUtils.copy(part.getInputStream(), os);
    }
}

From source file:org.apache.axis2.transport.testkit.http.JavaNetClient.java

public void sendMessage(ClientOptions options, ContentType contentType, byte[] message) throws Exception {
    URL url = new URL(channel.getEndpointReference().getAddress());
    log.debug("Opening connection to " + url + " using " + URLConnection.class.getName());
    try {/*from   ww w . ja  v  a 2  s  . c  o  m*/
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", contentType.toString());
        if (contentType.getBaseType().equals("text/xml")) {
            connection.setRequestProperty("SOAPAction", "");
        }
        OutputStream out = connection.getOutputStream();
        out.write(message);
        out.close();
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            log.debug("Response code: " + httpConnection.getResponseCode());
            log.debug("Response message: " + httpConnection.getResponseMessage());
            int i = 0;
            String headerValue;
            while ((headerValue = httpConnection.getHeaderField(i)) != null) {
                String headerName = httpConnection.getHeaderFieldKey(i);
                if (headerName != null) {
                    log.debug(headerName + ": " + headerValue);
                } else {
                    log.debug(headerValue);
                }
                i++;
            }
        }
        InputStream in = connection.getInputStream();
        IOUtils.copy(in, System.out);
        in.close();
    } catch (IOException ex) {
        log.debug("Got exception", ex);
        throw ex;
    }
}