Example usage for javax.mail.internet ContentType toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Retrieve a RFC2045 style string representation of this Content-Type.

Usage

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

private ContentType verifyContentType(final ContentType contentMimeType, final String overrideContentType) {
    ContentType overrideMimeType = null;
    try {/*  w  ww  . jav a  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:immf.Util.java

public static void setFileName(Part part, String filename, String charset, String lang)
        throws MessagingException {

    ContentDisposition disposition;//from  w w w .j  ava 2 s . co m
    String[] strings = part.getHeader("Content-Disposition");
    if (strings == null || strings.length < 1) {
        disposition = new ContentDisposition(Part.ATTACHMENT);
    } else {
        disposition = new ContentDisposition(strings[0]);
        disposition.getParameterList().remove("filename");
    }

    part.setHeader("Content-Disposition",
            disposition.toString() + encodeParameter("filename", filename, charset, lang));

    ContentType cType;
    strings = part.getHeader("Content-Type");
    if (strings == null || strings.length < 1) {
        cType = new ContentType(part.getDataHandler().getContentType());
    } else {
        cType = new ContentType(strings[0]);
    }

    try {
        // I want to public the MimeUtility#doEncode()!!!
        String mimeString = MimeUtility.encodeWord(filename, charset, "B");
        // cut <CRLF>...
        StringBuffer sb = new StringBuffer();
        int i;
        while ((i = mimeString.indexOf('\r')) != -1) {
            sb.append(mimeString.substring(0, i));
            mimeString = mimeString.substring(i + 2);
        }
        sb.append(mimeString);

        cType.setParameter("name", new String(sb));
    } catch (UnsupportedEncodingException e) {
        throw new MessagingException("Encoding error", e);
    }
    part.setHeader("Content-Type", cType.toString());
}

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

private StringEntity parseBody(final XdmNode node, final Processor processor) {
    final XdmNode body = SaxonAxis.childElement(node, XProcXmlModel.Elements.BODY);
    if (body != null) {
        final String contentTypeAtt = body.getAttributeValue(XProcXmlModel.Attributes.CONTENT_TYPE);
        final String encoding = body.getAttributeValue(XProcXmlModel.Attributes.ENCODING);
        final ContentType contentType = Steps.getContentType(contentTypeAtt, body);
        final String contentString = getContentString(body, contentType, encoding, processor);
        try {/*from ww w.j a va  2  s. c om*/
            return new StringEntity(contentString, contentType.toString(),
                    Steps.getCharset(contentType.getParameter("charset")).toString());
        } catch (final UnsupportedEncodingException e) {
            throw XProcExceptions.xc0020(body);
        }
    }
    return null;
}

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

private FormBodyPart getContentBody(final XdmNode node, final Processor processor) {
    final String contentTypeAtt = node.getAttributeValue(XProcXmlModel.Attributes.CONTENT_TYPE);
    final String encoding = node.getAttributeValue(XProcXmlModel.Attributes.ENCODING);
    final ContentType contentType = Steps.getContentType(contentTypeAtt, node);
    final String contentString = getContentString(node, contentType, encoding, processor);
    final StringBody body;
    try {/*from   ww w  .j  av  a 2 s.  co  m*/
        body = new StringBody(contentString, contentType.toString(),
                Steps.getCharset(contentType.getParameter("charset")));
    } catch (final UnsupportedEncodingException e) {
        throw XProcExceptions.xc0020(node);
    }

    final String id = node.getAttributeValue(XProcXmlModel.Attributes.ID);
    final String description = node.getAttributeValue(XProcXmlModel.Attributes.DESCRIPTION);
    final String disposition = node.getAttributeValue(XProcXmlModel.Attributes.DISPOSITION);
    final FormBodyPart bodyPart = new FormBodyPart("body", body) {
        @Override
        protected void generateContentDisp(final ContentBody body) {
            if (disposition != null) {
                addField(MIME.CONTENT_DISPOSITION, disposition);
            }
        }

        @Override
        protected void generateTransferEncoding(final ContentBody body) {
            if (encoding != null) {
                addField(MIME.CONTENT_TRANSFER_ENC, encoding);
            }
        }

        @Override
        protected void generateContentType(final ContentBody body) {
            final StringBuilder buffer = new StringBuilder();
            buffer.append(body.getMimeType());
            if (body.getCharset() != null) {
                try {
                    final String testCharset = new ContentType(body.getMimeType()).getParameter("charset");
                    if (testCharset != null) {
                        final Charset charset = Charset.forName(testCharset);
                        if (!StringUtils.equalsIgnoreCase(charset.displayName(), body.getCharset())) {
                            buffer.append("; charset=").append(body.getCharset().toLowerCase());
                        }
                    } else {
                        buffer.append("; charset=utf-8");
                    }
                } catch (final ParseException | IllegalCharsetNameException e) {
                    throw XProcExceptions.xc0020(node);
                }
            }
            addField(MIME.CONTENT_TYPE, buffer.toString());
        }
    };
    if (id != null) {
        bodyPart.addField("Content-ID", id);
    }
    if (description != null) {
        bodyPart.addField("Content-Description", description);
    }

    return bodyPart;
}

From source file:it.cnr.icar.eric.server.common.Utility.java

/**
 *     Create a SOAPMessage containing a registry request (e.g. SubmitObjectsRequest)
 *     @param req the InputStream to the registry request
 *     @return the created SOAPMessage//from  w  w  w. ja  v a2  s  .  c o m
 */
public SOAPMessage createSOAPMessageFromRequestStream(InputStream reqStream)
        throws javax.xml.soap.SOAPException, IOException, javax.mail.internet.ParseException {
    InputStream is = createSOAPStreamFromRequestStream(reqStream);

    javax.xml.soap.MimeHeaders mimeHeaders = new javax.xml.soap.MimeHeaders();

    javax.mail.internet.ContentType contentType = new javax.mail.internet.ContentType("text/xml"); //"multipart/related");

    String contentTypeStr = contentType.toString();

    //System.err.println("contentTypeStr = '" + contentTypeStr + "'");
    mimeHeaders.addHeader("Content-Type", contentTypeStr);
    mimeHeaders.addHeader("Content-Id", "ebXML Registry SOAP request");

    javax.xml.soap.MessageFactory factory = javax.xml.soap.MessageFactory.newInstance();
    SOAPMessage msg = factory.createMessage(mimeHeaders, is);

    msg.saveChanges();

    return msg;
}

From source file:it.cnr.icar.eric.server.common.Utility.java

/**
 *     Create a SOAPMessage object from a InputStream to a SOAPMessage
 *     @param soapStream the InputStream to the SOAPMessage
 *     @return the created SOAPMessage//from w ww.ja  v a  2s  .co m
 */
public SOAPMessage createSOAPMessageFromSOAPStream(InputStream soapStream)
        throws javax.xml.soap.SOAPException, IOException, javax.mail.internet.ParseException {

    javax.xml.soap.MimeHeaders mimeHeaders = new javax.xml.soap.MimeHeaders();

    javax.mail.internet.ContentType contentType = new javax.mail.internet.ContentType("text/xml"); //"multipart/related");

    String contentTypeStr = contentType.toString();

    //System.err.println("contentTypeStr = '" + contentTypeStr + "'");
    mimeHeaders.addHeader("Content-Type", contentTypeStr);
    mimeHeaders.addHeader("Content-Id", "ebXML Registry SOAP request");

    javax.xml.soap.MessageFactory factory = javax.xml.soap.MessageFactory.newInstance();
    SOAPMessage msg = factory.createMessage(mimeHeaders, soapStream);

    // this saveChanges() call breaks SaaJ attachment branch with JDK6 code switch!!!
    // resulting in broken multipart/related + length calculated wrong 
    //        msg.saveChanges();

    return msg;
}

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

private void attachObject(Object data, ContentType ct, HttpEntityEnclosingRequest request, Context cx)
        throws IOException {
    // FIXME: This may store the data three times in memory -- If
    // there were a way to turn the Object into an InputStream
    // instead, we would not have this problem.
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ct = ESXX.getInstance().serializeObject(data, ct, bos, true);
    ByteArrayEntity bae = new ByteArrayEntity(bos.toByteArray());
    bae.setContentType(ct.toString());
    request.setEntity(bae);//from w ww.  j a  v  a 2s  .  c  o m
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Get a textual description of a part./*w  ww  . jav  a 2s  .  c om*/
 *
 * @param part The part to interogate
 * @param buf a string buffer for the description
 * @param prefix a prefix for each line of the description
 * @param recurse boolean specifying wether to recurse through sub-parts or
 *        not
 *
 * @return StringBuffer containing the description of the part
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static StringBuffer getPartDescription(Part part, StringBuffer buf, String prefix, boolean recurse)
        throws MessagingException {
    if (buf == null) {
        return buf;
    }

    ContentType xctype = MessageUtilities.getContentType(part);

    String xvalue = xctype.toString();
    buf.append(prefix);
    buf.append("Content-Type: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = part.getDisposition();
    buf.append(prefix);
    buf.append("Content-Disposition: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = part.getDescription();
    buf.append(prefix);
    buf.append("Content-Description: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = MessageUtilities.getFileName(part);
    buf.append(prefix);
    buf.append("Content-Filename: ");
    buf.append(xvalue);
    buf.append('\n');

    if (part instanceof MimePart) {
        MimePart xmpart = (MimePart) part;
        xvalue = xmpart.getContentID();
        buf.append(prefix);
        buf.append("Content-ID: ");
        buf.append(xvalue);
        buf.append('\n');

        String[] langs = xmpart.getContentLanguage();

        if (langs != null) {
            buf.append(prefix);
            buf.append("Content-Language: ");

            for (int pi = 0; pi < langs.length; ++pi) {
                if (pi > 0) {
                    buf.append(", ");
                }

                buf.append(xvalue);
            }

            buf.append('\n');
        }

        xvalue = xmpart.getContentMD5();
        buf.append(prefix);
        buf.append("Content-MD5: ");
        buf.append(xvalue);
        buf.append('\n');

        xvalue = xmpart.getEncoding();
        buf.append(prefix);
        buf.append("Content-Encoding: ");
        buf.append(xvalue);
        buf.append('\n');
    }

    buf.append('\n');

    if (recurse && xctype.match("multipart/*")) {
        Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part);

        int xparts = xmulti.getCount();

        for (int xindex = 0; xindex < xparts; xindex++) {
            MessageUtilities.getPartDescription(xmulti.getBodyPart(xindex), buf, (prefix + "   "), true);
        }
    }

    return buf;
}

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)));
        }/*  www  .  j av  a 2 s.com*/
    }, 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:org.trancecode.xproc.step.RequestParser.java

private String getContentString(final XdmNode node, final ContentType contentType, final String encoding,
        final Processor processor) {
    if (!StringUtils.isEmpty(encoding) && !StringUtils.equalsIgnoreCase(encoding, Steps.ENCODING_BASE64)) {
        throw XProcExceptions.xc0052(SaxonLocation.of(node));
    }//from w ww  . j  ava2 s  .  c om
    final StringBuilder contentBuilder = new StringBuilder();
    if (!StringUtils.containsIgnoreCase(contentType.getSubType(), "xml")
            || StringUtils.equalsIgnoreCase(encoding, Steps.ENCODING_BASE64)) {
        final Iterable<XdmItem> children = SaxonAxis.axis(node, Axis.CHILD);
        for (final XdmItem aNode : children) {
            if (!XdmNodeKind.TEXT.equals(((XdmNode) aNode).getNodeKind())) {
                throw XProcExceptions.xc0028(SaxonLocation.of(node));
            } else {
                contentBuilder.append(StringEscapeUtils.unescapeHtml(aNode.toString()));
            }
        }
    } else {
        final Iterable<XdmItem> children = SaxonAxis.axis(node, Axis.CHILD);
        boolean oneElement = false;
        for (final XdmItem aNode : children) {
            final XdmNodeKind kind = ((XdmNode) aNode).getNodeKind();
            if (XdmNodeKind.TEXT.equals(kind) && !StringUtils.isEmpty(aNode.getStringValue().trim())) {
                throw XProcExceptions.xc0022(node);
            } else if (XdmNodeKind.ELEMENT.equals(kind)) {
                if (oneElement) {
                    throw XProcExceptions.xc0022(node);
                } else {
                    oneElement = true;
                }
            }
        }
    }
    if (StringUtils.equalsIgnoreCase("xml", contentType.getSubType())) {
        final ByteArrayOutputStream targetOutputStream = new ByteArrayOutputStream();
        final Serializer serializer = Steps.getSerializer(targetOutputStream, serializationOptions, processor);
        serializer.setOutputProperty(Serializer.Property.MEDIA_TYPE, contentType.toString());
        try {
            processor.writeXdmValue(SaxonAxis.childElement(node), serializer);
        } catch (final Exception e) {
            throw new PipelineException("Error while trying to write document", e);
        } finally {
            Closeables.closeQuietly(targetOutputStream);
        }
        contentBuilder.append(targetOutputStream.toString());
    }
    final String id = node.getAttributeValue(XProcXmlModel.Attributes.ID);
    verifyHeader(id, "Content-ID", node);
    final String description = node.getAttributeValue(XProcXmlModel.Attributes.DESCRIPTION);
    verifyHeader(description, "Content-Description", node);
    final String disposition = node.getAttributeValue(XProcXmlModel.Attributes.DISPOSITION);
    verifyHeader(disposition, "Content-Disposition", node);
    return contentBuilder.toString();
}