Example usage for javax.mail.internet ContentType ContentType

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

Introduction

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

Prototype

public ContentType(String s) throws ParseException 

Source Link

Document

Constructor that takes a Content-Type string.

Usage

From source file:org.silverpeas.components.mailinglist.service.job.MailProcessor.java

protected String getFileName(Part part) throws MessagingException {
    String fileName = part.getFileName();
    if (fileName == null) {
        try {//from  w  w w.j  a va  2 s. c  om
            ContentType type = new ContentType(part.getContentType());
            fileName = type.getParameter("name");
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
    }
    return fileName;
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

protected String getFileName(Part part) throws MessagingException {
    String fileName = part.getFileName();
    if (fileName == null) {
        try {/*from w  w  w .  j  a va 2  s .c  o m*/
            ContentType type = new ContentType(part.getContentType());
            fileName = type.getParameter("name");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return fileName;
}

From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

/**
 * @see it.greenvulcano.gvesb.virtual.CallOperation#perform(it.greenvulcano.gvesb.buffer.GVBuffer)
 *//*  ww  w  .j  a v a2s . c  o m*/
@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {
    logger.debug("BEGIN perform(GVBuffer gvBuffer)");
    HttpMethod method = null;
    try {
        String currMethodURI = null;
        Map<String, Object> params = GVBufferPropertiesHelper.getPropertiesMapSO(gvBuffer, true);

        String currHost = PropertiesHandler.expand(host, params, gvBuffer);
        String currPort = PropertiesHandler.expand(port, params, gvBuffer);
        logger.debug("Server Host: " + currHost + " - Port: " + currPort);
        httpClient.getHostConfiguration().setHost(currHost, Integer.parseInt(currPort), protocol);

        auth.setAuthentication(httpClient, host, Integer.parseInt(currPort), gvBuffer, params);
        proxy.setProxy(httpClient, gvBuffer, params);

        currMethodURI = PropertiesHandler.expand(contextPath + methodURI, params, gvBuffer);
        logger.debug("MethodURI[escaped:" + uriEscaped + "]=[" + currMethodURI + "]");
        switch (methodName) {
        case OPTIONS:
            method = new OptionsMethod();
            break;
        case GET:
            method = new GetMethod();
            break;
        case HEAD:
            method = new HeadMethod();
            break;
        case POST:
            method = new PostMethod();
            break;
        case PUT:
            method = new PutMethod();
            break;
        case DELETE:
            method = new DeleteMethod();
            break;
        default:
            throw new CallException("GV_CALL_SERVICE_ERROR",
                    new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                            { "id", gvBuffer.getId().toString() },
                            { "message", "Unknown method = " + methodName } });
        }
        method.setURI(new URI(currMethodURI, uriEscaped));

        if ((refDP != null) && (refDP.length() > 0)) {
            logger.debug("Calling configured Data Provider: " + refDP);
            DataProviderManager dataProviderManager = DataProviderManager.instance();
            IDataProvider dataProvider = dataProviderManager.getDataProvider(refDP);
            try {
                dataProvider.setContext(method);
                dataProvider.setObject(gvBuffer);
                method = (HttpMethod) dataProvider.getResult();
            } finally {
                dataProviderManager.releaseDataProvider(refDP, dataProvider);
            }
        }

        int status = httpClient.executeMethod(method);
        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(status));
        String statusTxt = method.getStatusText();
        gvBuffer.setProperty(RESPONSE_MESSAGE, (statusTxt != null ? statusTxt : "NULL"));
        Header[] responseHeaders = method.getResponseHeaders();
        for (Header header : responseHeaders) {
            String headerName = RESPONSE_HEADER_PREFIX + header.getName();
            String value = header.getValue();
            if (value == null) {
                value = "";
            }
            gvBuffer.setProperty(headerName, value);
        }
        String cType = "text/html";
        Header cTypeHeader = method.getResponseHeader("Content-Type");
        if (cTypeHeader != null) {
            String cTypeValue = cTypeHeader.getValue();
            if (cTypeValue != null) {
                cType = cTypeValue;
            }
        }
        logger.debug("Response content-type: " + cType);
        ContentType contentType = new ContentType(cType);
        byte[] responseBody = method.getResponseBody();
        Object object = responseBody;
        if (contentType.getPrimaryType().equals("multipart")) {
            object = handleMultipart(responseBody, cType);
        }
        gvBuffer.setObject(object);
    } catch (CallException exc) {
        throw exc;
    } catch (Exception exc) {
        logger.error("ERROR perform(GVBuffer gvBuffer)", exc);
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "id", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    } finally {
        try {
            if (method != null) {
                method.releaseConnection();
            }
        } catch (Exception exc) {
            logger.warn("Error while releasing connection", exc);
        }
        logger.debug("END perform(GVBuffer gvBuffer)");
    }
    return gvBuffer;
}

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  w  w.  j a v  a2s.  co m*/
    } 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.silverpeas.components.mailinglist.service.job.MailProcessor.java

/**
 * Analyze the part to check if it is an attachment, a base64 encoded file or some text.
 * @param part the part to be analyzed./*w ww. j a v a 2 s .c om*/
 * @return true if it is some text - false otherwise.
 * @throws MessagingException
 */
protected boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
    } else if (Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType()) && getFileName(part) == null;
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
    }
    return false;
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

/**
 * Analyze the part to check if it is an attachment, a base64 encoded file or some text.
 *
 * @param part the part to be analyzed./* w w w  .  ja  v  a2 s  .com*/
 * @return true if it is some text - false otherwise.
 * @throws MessagingException
 */
protected boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    } else if (Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType()) && getFileName(part) == null;
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:org.esxx.js.protocol.HTTPHandler.java

private Result sendRequest(Context cx, Scriptable thisObj, ContentType ct, final HttpUriRequest msg)
        throws Exception {
    // Add HTTP headers
    jsuri.enumerateHeaders(cx, new JSURI.PropEnumerator() {
        public void handleProperty(Scriptable p, int s) {
            msg.addHeader(Context.toString(p.get("name", p)), Context.toString(p.get("value", p)));
        }// w  ww . j a  v a  2  s .co  m
    }, jsuri.getURI());

    HttpResponse response = getHttpClient().execute(msg);
    HttpEntity entity = response.getEntity();

    try {
        Result result = new Result();
        result.status = response.getStatusLine().getStatusCode();
        result.headers = response.getAllHeaders();

        if (entity != null && entity.getContentLength() != 0) {
            if (ct == null) {
                Header hdr = entity.getContentType();
                result.contentType = hdr == null ? "application/octet-stream" : hdr.getValue();

                ct = new ContentType(result.contentType);
            } else {
                result.contentType = ct.toString();
            }

            result.object = ESXX.getInstance().parseStream(ct, entity.getContent(), jsuri.getURI(), null, null, //js_esxx.jsGet_debug(),
                    cx, thisObj);

            if (result.object instanceof java.io.InputStream) {
                // Do not consume content yet
                entity = null;
            }
        }

        return result;
    } finally {
        if (entity != null) {
            entity.consumeContent();
        }
    }
}

From source file:mailbox.CreationViaEmail.java

private static Content getContentWithAttachments(MimePart part) throws MessagingException, IOException {
    Content result = new Content();
    String rootId = new ContentType(part.getContentType()).getParameter("start");
    MimeMultipart mp = (MimeMultipart) part.getContent();
    for (int i = 0; i < mp.getCount(); i++) {
        MimePart p = (MimePart) mp.getBodyPart(i);
        if (isRootPart(p, i, rootId)) {
            result = result.merge(processPart(p, part));
        } else {//from  ww  w .j a  v  a  2  s .  c o  m
            result.attachments.add(p);
        }
    }
    return result;
}

From source file:com.adaptris.core.http.client.net.StandardHttpProducer.java

private String getContentEncoding(HttpURLConnection http) {
    if (http.getContentEncoding() != null) {
        return http.getContentEncoding();
    }//from w w  w .  j a v  a  2 s. co  m
    // Parse Content-Type header for encoding
    try {
        ContentType contentType = new ContentType(http.getContentType());
        if (!isEmpty(contentType.getParameter(PARAM_CHARSET))) {
            return contentType.getParameter(PARAM_CHARSET);
        }
    } catch (ParseException e) {
        log.trace("Unable to parse Content-Type header \"{}\": {}", http.getContentType(), e.toString());
    }
    return null;
}

From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java

/**
 * Helper function to create multi-part MIME
 *
 * @param entity         the body of a request
 * @param entityContentType content type of the body
 * @param query          a query part of a request
 *
 * @return a ByteString that represents a multi-part encoded entity that contains both
 *///from  ww w .j  a v a  2 s  .  co  m
private static MimeMultipart createMultiPartEntity(final ByteString entity, final String entityContentType,
        String query) throws MessagingException {
    MimeMultipart multi = new MimeMultipart(MIXED);

    // Create current entity with the associated type
    MimeBodyPart dataPart = new MimeBodyPart();

    ContentType contentType = new ContentType(entityContentType);
    if (MULTIPART.equals(contentType.getBaseType())) {
        MimeMultipart nested = new MimeMultipart(new DataSource() {
            @Override
            public InputStream getInputStream() throws IOException {
                return entity.asInputStream();
            }

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

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

            @Override
            public String getName() {
                return null;
            }
        });
        dataPart.setContent(nested, contentType.getBaseType());

    } else {
        dataPart.setContent(entity.copyBytes(), contentType.getBaseType());
    }
    dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType);

    // Encode query params as form-urlencoded
    MimeBodyPart argPart = new MimeBodyPart();
    argPart.setContent(query, FORM_URL_ENCODED);
    argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);

    multi.addBodyPart(argPart);
    multi.addBodyPart(dataPart);
    return multi;
}