Example usage for javax.mail.internet ContentType getPrimaryType

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

Introduction

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

Prototype

public String getPrimaryType() 

Source Link

Document

Return the primary type.

Usage

From source file:com.grameenfoundation.ictc.controllers.SaleforceIntegrationController.java

public static InputSource getInputSource(String ctype, InputStream in) throws Exception {

    // Creates ContentType
    ContentType contentType = null;
    try {//  w w w .  j a  va  2 s .  c  o  m
        contentType = new ContentType(ctype) {
        };
    } catch (Exception e) {
        System.out.println(
                "Unexpected Error occured while creating content-type object. Reason: " + e.getMessage());
        throw new Exception(e.getMessage());
    }

    // Checks primitive type
    String primaryType = contentType.getPrimaryType();
    if (!"text".equals(primaryType) && !"application".equals(primaryType)) {
        System.out.println("Primary type received is " + primaryType
                + ". Only text or application primary type is expected");
        throw new Exception(ctype);
    }

    // Checks sub type
    String subType = contentType.getSubType();
    if (!"xml".equals(subType) && !subType.endsWith("+xml")) {
        System.out.println("sub type received is " + subType + ". Only xml sub type is expected");
        throw new Exception(ctype);
    }
    // Gets charset parameter
    String charset = contentType.getParameter("charset");
    if (charset == null) { // no charset
        // MIME type "text/*" omitted charset should be treated
        // as us-ascii
        if ("text".equals(contentType.getPrimaryType())) {
            charset = "us-ascii";
        }
    }

    InputSource input;
    if (charset == null) { // application/xml omitted charset

        input = new InputSource(in);

    } else {
        // Creats a reader with java charset
        Reader reader = null;
        try {
            reader = new InputStreamReader(in, charset);

        } catch (UnsupportedEncodingException e) {
            System.out.println("UnsupportedEncodingException. Reason: " + e.getMessage());
            throw new Exception(e.getMessage());
        }

        input = new InputSource(reader);
    }

    return input;
}

From source file:com.eviware.soapui.impl.wsdl.monitor.ContentTypes.java

private boolean contentTypeMatches(ContentType contentType, ContentType respondedContentType) {
    // ContentType doesn't take wildcards into account for the primary type, but we want to do that
    return contentType.match(respondedContentType) || ((contentType.getPrimaryType().charAt(0) == '*'
            || respondedContentType.getPrimaryType().charAt(0) == '*')
            && (contentType.getSubType().charAt(0) == '*' || respondedContentType.getSubType().charAt(0) == '*'
                    || contentType.getSubType().equalsIgnoreCase(respondedContentType.getSubType())));
}

From source file:com.predic8.membrane.core.multipart.XOPReconstitutor.java

/**
 * @return reassembled SOAP message or null if message is not SOAP or not multipart
 *//*from  w w w .  j a  v  a2s .c  o m*/
public Message getReconstitutedMessage(Message message) throws ParseException, MalformedStreamException,
        IOException, EndOfStreamException, XMLStreamException, FactoryConfigurationError {
    ContentType contentType = message.getHeader().getContentTypeObject();
    if (contentType == null || contentType.getPrimaryType() == null)
        return null;
    if (!contentType.getPrimaryType().equals("multipart") || !contentType.getSubType().equals("related"))
        return null;

    String type = contentType.getParameter("type");
    if (!"application/xop+xml".equals(type))
        return null;
    String start = contentType.getParameter("start");
    if (start == null)
        return null;
    String boundary = contentType.getParameter("boundary");
    if (boundary == null)
        return null;

    HashMap<String, Part> parts = split(message, boundary);
    Part startPart = parts.get(start);
    if (startPart == null)
        return null;

    ContentType innerContentType = new ContentType(startPart.getHeader().getContentType());
    if (!innerContentType.getPrimaryType().equals("application")
            || !innerContentType.getSubType().equals("xop+xml"))
        return null;

    byte[] body = fillInXOPParts(startPart.getInputStream(), parts);

    Message m = new Message() {
        @Override
        protected void parseStartLine(InputStream in) throws IOException, EndOfStreamException {
            throw new RuntimeException("not implemented.");
        }

        @Override
        public String getStartLine() {
            throw new RuntimeException("not implemented.");
        }
    };
    m.setBodyContent(body);

    String reconstitutedContentType = innerContentType.getParameter("type");
    if (reconstitutedContentType != null)
        m.getHeader().add(Header.CONTENT_TYPE, reconstitutedContentType);

    return m;
}

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.//from   www .  jav  a  2  s  .  c  o m
 * @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:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

/**
 * @see it.greenvulcano.gvesb.virtual.CallOperation#perform(it.greenvulcano.gvesb.buffer.GVBuffer)
 *///from   www  .ja v  a 2s  . 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.trancecode.xproc.step.HttpResponseHandler.java

private ContentType verifyContentType(final ContentType contentMimeType, final String overrideContentType) {
    ContentType overrideMimeType = null;
    try {/*from  w  w w .  j  a va  2  s . c  o  m*/
        overrideMimeType = new ContentType(overrideContentType);
    } catch (ParseException e) {
        throw XProcExceptions.xc0030();
    }
    if (StringUtils.equalsIgnoreCase(overrideMimeType.toString(), contentMimeType.toString())) {
        return contentMimeType;
    }
    if (("multipart".equals(contentMimeType.getPrimaryType())
            && !"multipart".equals(overrideMimeType.getPrimaryType()))
            || ("multipart".equals(overrideMimeType.getPrimaryType())
                    && !"multipart".equals(contentMimeType.getPrimaryType()))
            || (contentMimeType.getSubType().contains("xml") || "text".equals(contentMimeType.getPrimaryType())
                    && "image".equals(overrideMimeType.getPrimaryType()))
            || ("image".equals(contentMimeType.getPrimaryType())
                    && (overrideMimeType.getSubType().contains("xml")
                            || "text".equals(overrideMimeType.getPrimaryType())))) {
        throw XProcExceptions.xc0030();
    }
    return overrideMimeType;
}

From source file:org.trancecode.xproc.step.HttpResponseHandler.java

@Override
public XProcHttpResponse handleResponse(final HttpResponse httpResponse) throws IOException {
    final XProcHttpResponse response = new XProcHttpResponse();
    final HttpEntity entity = httpResponse.getEntity();
    final String contentCharset = EntityUtils.getContentCharSet(entity) == null ? "utf-8"
            : EntityUtils.getContentCharSet(entity);
    final String contentType = constructContentType(entity.getContentType());
    ContentType contentMimeType = null;
    try {//from   ww w.  jav a2 s .c o m
        contentMimeType = new ContentType(contentType);
    } catch (ParseException e) {
        contentMimeType = new ContentType("text", "plain", null);
    }
    if (!StringUtils.isEmpty(overrideContentType)) {
        contentMimeType = verifyContentType(contentMimeType, overrideContentType);
    }
    final BodypartResponseParser parser = new BodypartResponseParser(entity.getContent(), null,
            httpResponse.getParams(), contentType, contentCharset);

    if (!detailed) {
        if (!statusOnly) {
            if ("multipart".equals(contentMimeType.getPrimaryType())) {
                response.setNodes(constructMultipart(contentMimeType, contentType, parser));
            } else {
                final BodypartResponseParser.BodypartEntity part = parser.parseBodypart(false);
                final Iterable<XdmNode> body = constructBody(contentMimeType, contentType, part);
                if (body != null) {
                    response.setNodes(body);
                }
            }
        }
    } else {
        final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration());
        builder.startDocument();
        builder.startElement(XProcXmlModel.Elements.RESPONSE);
        builder.attribute(XProcXmlModel.Attributes.STATUS,
                Integer.toString(httpResponse.getStatusLine().getStatusCode()));
        if (!statusOnly) {
            final Header[] headers = httpResponse.getAllHeaders();
            for (final Header header : headers) {
                builder.startElement(XProcXmlModel.Elements.HEADER);
                builder.attribute(XProcXmlModel.Attributes.NAME, header.getName());
                builder.attribute(XProcXmlModel.Attributes.VALUE, header.getValue());
                builder.endElement();
            }
            if ("multipart".equals(contentMimeType.getPrimaryType())) {
                builder.nodes(constructMultipart(contentMimeType, contentType, parser));
            } else {
                final BodypartResponseParser.BodypartEntity part = parser.parseBodypart(false);
                final Iterable<XdmNode> body = constructBody(contentMimeType, contentType, part);
                if (body != null) {
                    builder.nodes(body);
                }
            }
        }
        builder.endElement();
        builder.endDocument();
        response.setNodes(ImmutableList.of(builder.getNode()));
    }
    EntityUtils.consume(entity);
    return response;
}

From source file:org.trancecode.xproc.step.HttpResponseHandler.java

private Iterable<XdmNode> constructBody(final ContentType contentMimeType, final String contentType,
        final BodypartResponseParser.BodypartEntity part) throws IOException {
    final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration());
    builder.startDocument();/*from   w  ww . j  ava2  s.c o  m*/
    builder.startElement(XProcXmlModel.Elements.BODY);
    builder.attribute(XProcXmlModel.Attributes.CONTENT_TYPE, contentType);
    if (contentMimeType.getSubType().contains("xml")) {
        try {
            final XdmNode node = processor.newDocumentBuilder()
                    .build(new StreamSource(part.getEntity().getContent()));
            if (!detailed) {
                return ImmutableList.of(node);
            } else {
                builder.nodes(node);
            }
        } catch (SaxonApiException sae) {
            return null;
        }
    } else {
        if ("text".equals(contentMimeType.getPrimaryType())) {
            builder.startContent();
            builder.text(IOUtils.toString(part.getEntity().getContent()));
        } else {
            builder.attribute(XProcXmlModel.Attributes.ENCODING, Steps.ENCODING_BASE64);
            builder.startContent();
            final String b64 = Base64.encodeBytes(IOUtils.toByteArray(part.getEntity().getContent()),
                    Base64.DO_BREAK_LINES);
            final Iterable<String> splitter = Splitter.on("\r\n").split(b64);
            for (final String split : splitter) {
                builder.text(split);
                builder.text("\n");
            }
        }
    }
    builder.endDocument();
    return ImmutableList.of(builder.getNode());
}

From source file:com.silverwrist.venice.std.TrackbackManager.java

/**
 * Loads the HTTP content at the specified URL, scans it for RDF description blocks, and adds those blocks
 * as {@link com.silverwrist.venice.std.TrackbackItem TrackbackItem}s to our internal cache.  Uses modification
 * detection to keep from reloading a page unless necessary.
 *
 * @param url The URL of the resource to be loaded.
 * @param attrs The attributes of the specified page; if this is <code>null</code>, we'll check the page
 *              cache for the right attributes.
 * @return <code>true</code> if the page data was loaded and scanned for trackback items; <code>false</code>
 *         if no data was loaded (because it was not modified since the last time we loaded it, for instance).
 * @exception com.silverwrist.venice.except.TrackbackException If there was an error loading or interpreting
 *            the page data./*from ww  w  .  jav a  2s  . co m*/
 */
private synchronized boolean load(URL url, PageAttributes attrs) throws TrackbackException {
    if (attrs == null)
        attrs = (PageAttributes) (m_page_cache.get(url));

    // Create the GET method and set its headers.
    String s = url.toString();
    int x = s.lastIndexOf('#');
    if (x >= 0)
        s = s.substring(0, x);
    GetMethod getter = new GetMethod(s);
    HttpMethodParams params = getter.getParams();
    getter.setDoAuthentication(false);
    getter.setFollowRedirects(true);
    getter.setRequestHeader("User-Agent", USER_AGENT);
    getter.setRequestHeader("Accept", "text/*");
    getter.setRequestHeader("Accept-Encoding", "identity");
    params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    getter.setParams(params);

    boolean get_resp = false;
    PageAttributes newattrs = null;
    ContentType ctype = null;
    byte[] rawdata = null;
    try { // set the Last-Modified date as an If-Modified-Since header on the request
        java.util.Date lmod = null;
        if (attrs != null)
            lmod = attrs.getLastModified();
        if (lmod != null)
            getter.setRequestHeader("If-Modified-Since", s_httpdate_format.format(lmod));

        // execute the Get method!
        int rc = m_http_client.executeMethod(getter);
        get_resp = true;
        if ((lmod != null) && (rc == HttpStatus.SC_NOT_MODIFIED))
            return false; // we were not modified
        if (rc == HttpStatus.SC_NO_CONTENT)
            return false; // there's no content there
        if (rc != HttpStatus.SC_OK) // this is farked!
            throw new TrackbackException("GET of " + url + " returned " + rc);

        // Get the new page attributes and save them off.
        newattrs = new PageAttributes(getter);
        m_page_cache.put(url, newattrs);

        // Get the Content-Type header and see if it's valid.
        Header hdr = getter.getResponseHeader("Content-Type");
        if (hdr != null)
            s = hdr.getValue();
        else
            s = "text/plain"; // necessary assumption
        ctype = new ContentType(s);
        if (!(ctype.getPrimaryType().equals("text")))
            throw new TrackbackException("URL " + url + " does not point to a text-based resource");

        // Load the resource in as byte data; we will determine the right character set for it later.
        rawdata = getter.getResponseBody();
        get_resp = false;

    } // end try
    catch (IOException e) { // IO error getting the page
        throw new TrackbackException("I/O error retrieving " + url + ": " + e.getMessage(), e);

    } // end catch
    catch (javax.mail.internet.ParseException e) { // translate into TrackbackException
        throw new TrackbackException("invalid Content-Type received for URL " + url, e);

    } // end catch
    finally { // release the connection if possible
        try { // need to get the message body
            if (get_resp)
                getter.getResponseBody();

        } // end try
        catch (IOException e) { // ignore these
        } // end catch

        getter.releaseConnection();

    } // end finally

    // make a first guess at the charset from the HTTP header Content-Type
    String cset = ctype.getParameter("charset");
    if (cset == null)
        cset = "US-ASCII";
    String content = null;
    try { // interpret the content
        content = new String(rawdata, cset);

    } // end try
    catch (UnsupportedEncodingException e) { // fall back and try just using US-ASCII
        cset = null;
        try { // interpret the content
            content = new String(rawdata, "US-ASCII");

        } // end try
        catch (UnsupportedEncodingException e2) { // can't happen
            logger.debug("WTF? US-ASCII should damn well be a supported character set!", e2);

        } // end catch

    } // end catch

    // Look for <META HTTP-EQUIV=...> tags in the content.
    Map http_attrs = extractHttpEquivTags(content);

    // Try to get a Content-Type attribute from there.
    s = (String) (http_attrs.get("CONTENT-TYPE"));
    String cset2 = null;
    if (s != null) { // look for the content type
        try { // parse into Content-Type
            ContentType c = new ContentType(s);
            if (c.getPrimaryType().equals("text"))
                cset2 = c.getParameter("charset");

        } // end try
        catch (javax.mail.internet.ParseException e) { // can't get a second Content-Type
            logger.debug("parse of Content-Type from META tags failed", e);
            cset2 = null;

        } // end catch

    } // end if

    if ((cset == null) && (cset2 == null))
        throw new TrackbackException("unable to determine character set for " + url);
    if ((cset2 != null) && ((cset == null) || !(cset.equalsIgnoreCase(cset2)))) { // reinterpret content in new character set
        try { // reinterpret content in new character set
            s = new String(rawdata, cset2);
            content = s;

            // the contents of the HTTP-EQUIV tags may have changed as a result
            http_attrs = extractHttpEquivTags(content);

        } // end try
        catch (UnsupportedEncodingException e) { // just use original character set
            if (cset == null)
                throw new TrackbackException("unable to determine character set for " + url);

        } // end catch

    } // end if

    newattrs.updateFromPage(http_attrs); // update the page attributes from the META tag data

    // Search the page content for RDF blocks.
    RE m = new RE(s_rdf_start, RE.MATCH_NORMAL);
    int pos = 0;
    while (m.match(content, pos)) { // look for the end of this RDF block
        RE m2 = new RE(getEndRecognizer(m.getParen(1)), RE.MATCH_NORMAL);
        if (m2.match(content, m.getParenEnd(0))) { // we now have a block to feed to the XML parser
            try { // run the block through the XML parser
                InputSource isrc = new InputSource(
                        new StringReader(content.substring(m.getParenStart(0), m2.getParenEnd(0))));
                Document doc = m_rdf_parser.parse(isrc);

                // examine topmost element, which should be rdf:RDF
                Element root = doc.getDocumentElement();
                if (NS_RDF.equals(root.getNamespaceURI()) && (root.getLocalName() != null)
                        && root.getLocalName().equals("RDF")) { // this is most definitely an rdf:RDF node...look for rdf:Description nodes under it
                    NodeList nl = root.getChildNodes();
                    for (int i = 0; i < nl.getLength(); i++) { // check each node in the list
                        Node n = nl.item(i);
                        if ((n.getNodeType() == Node.ELEMENT_NODE) && NS_RDF.equals(n.getNamespaceURI())
                                && (n.getLocalName() != null) && n.getLocalName().equals("Description")) { // we've got an rdf:Description node...extract the attributes from it
                            Element elt = (Element) n;
                            try { // look for the item and trackback URLs
                                URL item = null, trackback = null;
                                s = elt.getAttributeNS(NS_DC, "identifier");
                                if ((s != null) && (s.length() > 0))
                                    item = new URL(s);
                                s = elt.getAttributeNS(NS_TRACKBACK, "ping");
                                if ((s != null) && (s.length() > 0))
                                    trackback = new URL(s);
                                if ((item != null) && (trackback != null)) { // create the item
                                    s = elt.getAttributeNS(NS_DC, "title");
                                    m_item_cache.put(item, new MyTrackbackItem(item, trackback, s, newattrs));

                                } // end if

                            } // end try
                            catch (MalformedURLException e) { // this means skip this item
                                logger.warn("URL parse failure", e);

                            } // end catch

                        } // end if

                    } // end for

                } // end if

            } // end try
            catch (IOException e) { // disregard this block
                logger.warn("RDF block parse failure", e);

            } // end catch
            catch (SAXException e) { // disregard this block
                logger.warn("RDF block parse failure", e);

            } // end catch

        } // end if
          // else ignore this possible block

        pos = m.getParenEnd(0);

    } // end while

    return true;

}

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.//from   w w w .j a v  a2s  . c o m
 * @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;
}