Example usage for javax.mail.internet ContentType getParameter

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

Introduction

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

Prototype

public String getParameter(String name) 

Source Link

Document

Return the specified parameter value.

Usage

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   w ww  .jav  a  2 s .c  om
        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:org.apache.axis.attachments.MultiPartRelatedInputStream.java

/**
 * Create a new Multipart stream.//from   ww w.  j  a  v  a2  s.  c o m
 * @param contentType  the string that holds the contentType
 * @param stream       the true input stream from where the source
 *
 * @throws org.apache.axis.AxisFault if the stream could not be created
 */
public MultiPartRelatedInputStream(String contentType, java.io.InputStream stream)
        throws org.apache.axis.AxisFault {

    super(null); // don't cache this stream.

    if (!(stream instanceof BufferedInputStream)) {
        stream = new BufferedInputStream(stream);
    }

    try {

        // First find the start and boundary parameters. There are real weird rules regard what
        // can be in real headers what needs to be escaped etc  let mail parse it.
        javax.mail.internet.ContentType ct = new javax.mail.internet.ContentType(contentType);
        String rootPartContentId = ct.getParameter("start"); // Get the root part content.

        if (rootPartContentId != null) {
            rootPartContentId = rootPartContentId.trim();

            if (rootPartContentId.startsWith("<")) {
                rootPartContentId = rootPartContentId.substring(1);
            }

            if (rootPartContentId.endsWith(">")) {
                rootPartContentId = rootPartContentId.substring(0, rootPartContentId.length() - 1);
            }

        }

        if (ct.getParameter("boundary") != null) {
            String boundaryStr = "--" + ct.getParameter("boundary"); // The boundary with -- add as always the case.

            // if start is null then the first attachment is the rootpart
            // First read the start boundary -- this is done with brute force since the servlet may swallow the crlf between headers.
            // after this we use the more efficient boundarydelimeted stream.  There should never be any data here anyway.
            byte[][] boundaryMarker = new byte[2][boundaryStr.length() + 2];

            IOUtils.readFully(stream, boundaryMarker[0]);

            boundary = (boundaryStr + "\r\n").getBytes("US-ASCII");

            int current = 0;

            // This just goes brute force one byte at a time to find the first boundary.
            // in most cases this just a crlf.
            for (boolean found = false; !found; ++current) {
                if (!(found = java.util.Arrays.equals(boundaryMarker[current & 0x1], boundary))) {
                    System.arraycopy(boundaryMarker[current & 0x1], 1, boundaryMarker[(current + 1) & 0x1], 0,
                            boundaryMarker[0].length - 1);

                    if (stream.read(boundaryMarker[(current + 1) & 0x1], boundaryMarker[0].length - 1, 1) < 1) {
                        throw new org.apache.axis.AxisFault(
                                Messages.getMessage("mimeErrorNoBoundary", new String(boundary)));
                    }
                }
            }

            // after the first boundary each boundary will have a cr lf at the beginning since after the data in any part there
            // is a cr lf added to put the boundary at the begining of a line.
            boundaryStr = "\r\n" + boundaryStr;
            boundary = boundaryStr.getBytes("US-ASCII");
        } else {
            // Since boundary is not specified, we try to find one.
            for (boolean found = false; !found;) {
                boundary = readLine(stream);
                if (boundary == null)
                    throw new org.apache.axis.AxisFault(Messages.getMessage("mimeErrorNoBoundary", "--"));
                found = boundary.length > 4 && boundary[2] == '-' && boundary[3] == '-';
            }
        }

        // create the boundary delmited stream.
        boundaryDelimitedStream = new org.apache.axis.attachments.BoundaryDelimitedStream(stream, boundary,
                1024);

        // Now read through all potential streams until we have found the root part.
        String contentTransferEncoding = null;

        do {
            contentId = null;
            contentLocation = null;
            contentTransferEncoding = null;

            // Read this attachments headers from the stream.
            javax.mail.internet.InternetHeaders headers = new javax.mail.internet.InternetHeaders(
                    boundaryDelimitedStream);

            // Use java mail utility to read through the headers.
            contentId = headers.getHeader(HTTPConstants.HEADER_CONTENT_ID, null);

            // Clean up the headers and remove any < >
            if (contentId != null) {
                contentId = contentId.trim();

                if (contentId.startsWith("<")) {
                    contentId = contentId.substring(1);
                }

                if (contentId.endsWith(">")) {
                    contentId = contentId.substring(0, contentId.length() - 1);
                }

                contentId = contentId.trim();

                //  if (!contentId.startsWith("cid:")) {
                //      contentId =
                //              "cid:"
                //              + contentId;        // make sure its identified as cid
                //  }
            }

            contentLocation = headers.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION, null);

            if (contentLocation != null) {
                contentLocation = contentLocation.trim();

                if (contentLocation.startsWith("<")) {
                    contentLocation = contentLocation.substring(1);
                }

                if (contentLocation.endsWith(">")) {
                    contentLocation = contentLocation.substring(0, contentLocation.length() - 1);
                }

                contentLocation = contentLocation.trim();
            }

            contentType = headers.getHeader(HTTPConstants.HEADER_CONTENT_TYPE, null);

            if (contentType != null) {
                contentType = contentType.trim();
            }

            contentTransferEncoding = headers.getHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, null);

            if (contentTransferEncoding != null) {
                contentTransferEncoding = contentTransferEncoding.trim();
            }

            java.io.InputStream decodedStream = boundaryDelimitedStream;

            if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) {
                decodedStream = MimeUtility.decode(decodedStream, contentTransferEncoding);
            }

            if ((rootPartContentId != null) && !rootPartContentId.equals(contentId)) { // This is a part that has come in prior to the root part. Need to buffer it up.
                javax.activation.DataHandler dh = new javax.activation.DataHandler(
                        new org.apache.axis.attachments.ManagedMemoryDataSource(decodedStream, MAX_CACHED,
                                contentType, true));
                AttachmentPart ap = new AttachmentPart(dh);

                if (contentId != null) {
                    ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId);
                }

                if (contentLocation != null) {
                    ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation);
                }

                for (java.util.Enumeration en = headers.getNonMatchingHeaders(
                        new String[] { HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_LOCATION,
                                HTTPConstants.HEADER_CONTENT_TYPE }); en.hasMoreElements();) {
                    javax.mail.Header header = (javax.mail.Header) en.nextElement();
                    String name = header.getName();
                    String value = header.getValue();

                    if ((name != null) && (value != null)) {
                        name = name.trim();

                        if (name.length() != 0) {
                            ap.addMimeHeader(name, value);
                        }
                    }
                }

                addPart(contentId, contentLocation, ap);

                boundaryDelimitedStream = boundaryDelimitedStream.getNextStream(); // Gets the next stream.
            }
        } while ((null != boundaryDelimitedStream) && (rootPartContentId != null)
                && !rootPartContentId.equals(contentId));

        if (boundaryDelimitedStream == null) {
            throw new org.apache.axis.AxisFault(Messages.getMessage("noRoot", rootPartContentId));
        }

        soapStreamBDS = boundaryDelimitedStream;

        if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) {
            soapStream = MimeUtility.decode(boundaryDelimitedStream, contentTransferEncoding);
        } else {
            soapStream = boundaryDelimitedStream; // This should be the SOAP part
        }

        // Read from the input stream all attachments prior to the root part.
    } catch (javax.mail.internet.ParseException e) {
        throw new org.apache.axis.AxisFault(Messages.getMessage("mimeErrorParsing", e.getMessage()));
    } catch (java.io.IOException e) {
        throw new org.apache.axis.AxisFault(Messages.getMessage("readError", e.getMessage()));
    } catch (javax.mail.MessagingException e) {
        throw new org.apache.axis.AxisFault(Messages.getMessage("readError", e.getMessage()));
    }
}

From source file:com.cubusmail.server.mail.MessageHandler.java

/**
 * @param session/*from w  w w. ja va  2  s  . co m*/
 * @param message
 */
public void init(Session session, MimeMessage message) {

    this.session = session;
    this.message = message;
    try {
        this.readBefore = this.message.isSet(Flag.SEEN);
        String contentType = message.getContentType();
        ContentType type = new ContentType(contentType);
        String charset = type.getParameter("charset");
        if (charset != null) {
            this.charset = charset;
        } else {
            // this.message.setHeader( name, value )
        }
    } catch (MessagingException e) {
        log.warn(e.getMessage());
    }
}

From source file:com.cubusmail.mail.MessageHandler.java

/**
 * @param session/*from  w  w  w .  j a va 2  s .c om*/
 * @param message
 */
private void init(Session session, MimeMessage message) {

    this.session = session;
    this.message = message;
    try {
        this.readBefore = this.message.isSet(Flag.SEEN);
        String contentType = message.getContentType();
        ContentType type = new ContentType(contentType);
        String charset = type.getParameter("charset");
        if (charset != null) {
            this.charset = charset;
        } else {
            // this.message.setHeader( name, value )
        }
    } catch (MessagingException e) {
        log.warn(e.getMessage());
    }
}

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

/**
 * DOCUMENT ME!//w  w w  . j a va2  s. c o  m
 *
 * @param dmailParts DOCUMENT ME!
 * @param contentType DOCUMENT ME!
 * @param buffer DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
protected static StringBuffer scanDmailParts(Vector dmailParts, StringBuffer buffer, boolean chooseHtml,
        String breakLine) throws MessagingException {
    if ((buffer.length() == 0) && (dmailParts != null)) {
        int size = dmailParts.size();
        int j = 0;

        for (int i = 0; i < size; i++) {
            //message/rfc822
            MailPart dmailPart = (MailPart) dmailParts.get(j);

            //ContentType xctype = MessageUtilities.getContentType(dmailPart.getContentType());
            ContentType xctype = MessageUtilities.getContentType(dmailPart.getPart());

            if (xctype.match("text/plain") && !chooseHtml) {
                String xjcharset = xctype.getParameter("charset");

                if (xjcharset == null) {
                    // not present, assume ASCII character encoding                       
                    try {
                        Header xheader;
                        Enumeration xe = dmailPart.getPart().getAllHeaders();

                        for (; xe.hasMoreElements();) {
                            xheader = (Header) xe.nextElement();

                            String aux = xheader.getName().toLowerCase().trim();

                            if (aux.indexOf("subject") > -1) {
                                int pos1 = aux.indexOf("=?");
                                int pos2 = aux.indexOf("?q?");

                                if ((pos1 > -1) && (pos2 > -1)) {
                                    xjcharset = aux.substring(pos1, pos2);
                                }

                                break;
                            }
                        }
                    } catch (Exception ex) {
                    }

                    if (xjcharset == null) {
                        xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms
                    }
                }

                //String str = JavaScriptFilter.apply(buff.toString());
                xjcharset = MimeUtility.javaCharset(xjcharset);

                MessageUtilities.decodeTextPlain(buffer, dmailPart.getPart(), breakLine, xjcharset);

                dmailParts.removeElementAt(j);

                break;
            } else if (xctype.match("text/html") && chooseHtml) {
                String xjcharset = xctype.getParameter("charset");

                if (xjcharset == null) {
                    // not present, assume ASCII character encoding                       
                    try {
                        Header xheader;
                        Enumeration xe = dmailPart.getPart().getAllHeaders();

                        for (; xe.hasMoreElements();) {
                            xheader = (Header) xe.nextElement();

                            String aux = xheader.getName().toLowerCase().trim();

                            if (aux.indexOf("subject") > -1) {
                                int pos1 = aux.indexOf("=?");
                                int pos2 = aux.indexOf("?q?");

                                if ((pos1 > -1) && (pos2 > -1)) {
                                    xjcharset = aux.substring(pos1, pos2);
                                }

                                break;
                            }
                        }
                    } catch (Exception ex) {
                    }

                    if (xjcharset == null) {
                        xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms
                    }
                }

                xjcharset = MimeUtility.javaCharset(xjcharset);

                MessageUtilities.decodeTextHtml(buffer, dmailPart.getPart(), xjcharset);

                dmailParts.removeElementAt(j);

                break;
            } else {
                j++;
            }
        }
    }

    return buffer;
}

From source file:org.trancecode.xproc.binding.DataPortBinding.java

private void writeContent(final SaxonBuilder builder) {
    final URI uri = URI.create(href);
    if (uri.getScheme() != null && !StringUtils.equals("file", uri.getScheme())
            && !StringUtils.equals("http", uri.getScheme())) {
        throw XProcExceptions.xd0012(this.getLocation(), uri.toASCIIString());
    }/*  www .  j a  v  a 2 s  .  c o m*/
    try {
        final URL url;
        if (uri.isAbsolute()) {
            url = uri.toURL();
        } else {
            url = node.getBaseURI().resolve(uri).toURL();
        }
        final QName contentTypeAtt = (wrapper == null) ? XProcXmlModel.Attributes.CONTENT_TYPE
                : XProcXmlModel.Attributes.C_CONTENT_TYPE;
        final QName encodingAtt = (wrapper == null) ? XProcXmlModel.Attributes.ENCODING
                : XProcXmlModel.Attributes.C_ENCODING;
        final URLConnection urlConnection = url.openConnection();
        final ContentType guessContentType;
        if (StringUtils.equals("http", url.getProtocol())) {
            guessContentType = Steps.getContentType(urlConnection.getContentType(), node);
        } else {
            if (contentType != null) {
                guessContentType = contentType;
            } else {
                guessContentType = Steps
                        .getContentType("application/octet-stream ; encoding=" + Steps.ENCODING_BASE64, node);
            }
        }
        final Charset charset;
        if (contentType != null && contentType.getParameter("charset") != null) {
            charset = Charset.forName(contentType.getParameter("charset"));
        } else {
            charset = Charset.forName("UTF-8");
        }

        final InputStream stream = urlConnection.getInputStream();
        builder.attribute(contentTypeAtt, Steps.contentTypeToString(guessContentType));
        if (StringUtils.equals("text", guessContentType.getPrimaryType())
                || StringUtils.contains(guessContentType.getSubType(), "xml")) {
            if (guessContentType.getParameter("encoding") != null) {
                builder.attribute(encodingAtt, guessContentType.getParameter("encoding"));
            }
            builder.startContent();
            builder.text(IOUtils.toString(stream, charset.name()));
        } else {
            builder.attribute(encodingAtt, Steps.ENCODING_BASE64);
            builder.startContent();
            builder.text(Base64.encodeBytes(IOUtils.toByteArray(stream), Base64.DO_BREAK_LINES));
        }
    } catch (final IOException ioe) {
        throw XProcExceptions.xd0029(this.getLocation());
    }
}

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

/**
 * Given a message that we are replying to, or forwarding,
 *
 * @param part The part to decode./*from  w w w.  j  a  v  a 2 s  .  c o m*/
 * @param buffer The new message body text buffer.
 * @param dmailParts Vector for new message's attachments.
 *
 * @return The buffer being filled in with the body.
 *
 * @throws MessagingException DOCUMENT ME!
 * @throws IOException
 */
protected static StringBuffer subDecodeContent(Part part, StringBuffer buffer, Vector dmailParts,
        boolean chooseHtml, String breakLine) throws MessagingException, IOException {
    boolean attachIt = true;

    // decode based on content type and disposition
    ContentType xctype = MessageUtilities.getContentType(part);

    ContentDisposition xcdisposition = MessageUtilities.getContentDisposition(part);

    if (xctype.match("multipart/*")) {
        attachIt = false;

        Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part);

        int xparts = 0;

        try {
            xparts = xmulti.getCount();
        } catch (MessagingException e) {
            attachIt = true;
            xparts = 0;
        }

        for (int xindex = 0; xindex < xparts; xindex++) {
            MessageUtilities.subDecodeContent(xmulti.getBodyPart(xindex), buffer, dmailParts, chooseHtml,
                    breakLine);
        }
    } else if (xctype.match("message/rfc822")) {
        MimeMessage newMessage = new MimeMessage((Session) null, part.getInputStream());
        decodeContent(newMessage, buffer, dmailParts, chooseHtml, breakLine);
    } else if (xctype.match("text/plain") && !chooseHtml) {
        if (xcdisposition.match("inline")) {
            attachIt = false;

            String xjcharset = xctype.getParameter("charset");

            if (xjcharset == null) {
                // not present, assume ASCII character encoding                       
                try {
                    Header xheader;
                    Enumeration xe = part.getAllHeaders();

                    for (; xe.hasMoreElements();) {
                        xheader = (Header) xe.nextElement();

                        String aux = xheader.getName().toLowerCase().trim();

                        if (aux.indexOf("subject") > -1) {
                            int pos1 = aux.indexOf("=?");
                            int pos2 = aux.indexOf("?q?");

                            if ((pos1 > -1) && (pos2 > -1)) {
                                xjcharset = aux.substring(pos1, pos2);
                            }

                            break;
                        }
                    }
                } catch (Exception ex) {
                    System.out.print(ex.getMessage());
                }

                if (xjcharset == null) {
                    xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms
                }
            }

            MessageUtilities.decodeTextPlain(buffer, part, breakLine, xjcharset);
        }
    } else if (xctype.match("text/html") && chooseHtml) {
        if (xcdisposition.match("inline")) {
            attachIt = false;

            String xjcharset = xctype.getParameter("charset");

            if (xjcharset == null) {
                // not present, assume ASCII character encoding                       
                try {
                    Header xheader;
                    Enumeration xe = part.getAllHeaders();

                    for (; xe.hasMoreElements();) {
                        xheader = (Header) xe.nextElement();

                        String aux = xheader.getName().toLowerCase().trim();

                        if (aux.indexOf("subject") > -1) {
                            int pos1 = aux.indexOf("=?");
                            int pos2 = aux.indexOf("?q?");

                            if ((pos1 > -1) && (pos2 > -1)) {
                                xjcharset = aux.substring(pos1, pos2);
                            }

                            break;
                        }
                    }
                } catch (Exception ex) {
                }

                if (xjcharset == null) {
                    xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms
                }
            }

            MessageUtilities.decodeTextHtml(buffer, part, xjcharset);
        }
    }

    if (attachIt) {
        // UNDONE should simple single line entries be
        //        created for other types and attachments?
        //
        // UNDONE should attachements only be created for "attachments" or all
        // unknown content types?
        if (dmailParts != null) {
            MailPart aux = new MailPart();
            aux.setPart(part);
            aux.setId(dmailParts.size());
            aux.setName(MessageUtilities.encodeStringToXml(MessageUtilities.getPartName(part)));
            aux.setContentType(xctype.getBaseType());
            aux.setSize(part.getSize());

            dmailParts.addElement(aux);
        }
    }

    return buffer;
}

From source file:org.apache.axis2.saaj.SOAPPartImpl.java

/**
 * Construct a SOAP part from the given input stream.
 * The content type (as provided by the MIME headers) must be SOAP 1.1, SOAP 1.2
 * or XOP (MTOM). MIME packages (multipart/related) are not supported and should be
 * parsed using {@link SOAPMessageImpl#SOAPMessageImpl(InputStream, MimeHeaders).
 * <p>/*from  www.  j  a  v a2s  .  c  o m*/
 * If the content type is XOP, xop:Include elements will only be replaced if
 * the <code>attachments</code> parameter is not null.
 *
 * @see MessageFactoryImpl#setProcessMTOM(boolean)
 * 
 * @param parentSoapMsg the parent SOAP message
 * @param inputStream the input stream with the content of the SOAP part
 * @param mimeHeaders the MIME headers
 * @param attachments the set of attachments to be used to substitute xop:Include elements
 * @throws SOAPException
 */
public SOAPPartImpl(SOAPMessageImpl parentSoapMsg, InputStream inputStream, MimeHeaders mimeHeaders,
        Attachments attachments) throws SOAPException {
    ContentType contentType = null;
    if (mimeHeaders == null) {
        //TODO : read string from constants
        this.mimeHeaders = new MimeHeaders();
        this.mimeHeaders.addHeader("Content-ID", IDGenerator.generateID());
        this.mimeHeaders.addHeader("content-type", HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML);
    } else {
        String contentTypes[] = mimeHeaders.getHeader(HTTPConstants.CONTENT_TYPE);
        if (contentTypes != null && contentTypes.length > 0) {
            try {
                contentType = new ContentType(contentTypes[0]);
            } catch (ParseException ex) {
                throw new SOAPException("Invalid content type '" + contentTypes[0] + "'");
            }
        }
        this.mimeHeaders = SAAJUtil.copyMimeHeaders(mimeHeaders);
    }

    soapMessage = parentSoapMsg;

    String charset;
    boolean isMTOM;
    String soapEnvelopeNamespaceURI;
    SOAPFactory soapFactory;
    if (contentType == null) {
        charset = null;
        isMTOM = false;
        soapFactory = new SOAP11Factory();
        soapEnvelopeNamespaceURI = null;
    } else {
        String baseType = contentType.getBaseType().toLowerCase();
        String soapContentType;
        if (baseType.equals(MTOMConstants.MTOM_TYPE)) {
            isMTOM = true;
            String typeParam = contentType.getParameter("type");
            if (typeParam == null) {
                throw new SOAPException("Missing 'type' parameter in XOP content type");
            } else {
                soapContentType = typeParam.toLowerCase();
            }
        } else {
            isMTOM = false;
            soapContentType = baseType;
        }

        if (soapContentType.equals(HTTPConstants.MEDIA_TYPE_TEXT_XML)) {
            soapEnvelopeNamespaceURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            soapFactory = new SOAP11Factory();
        } else if (soapContentType.equals(HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML)) {
            soapEnvelopeNamespaceURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            soapFactory = new SOAP12Factory();
        } else {
            throw new SOAPException("Unrecognized content type '" + soapContentType + "'");
        }

        charset = contentType.getParameter("charset");
    }

    XMLStreamReader streamReader;
    try {
        if (charset != null) {
            streamReader = StAXUtils.createXMLStreamReader(inputStream, charset);
        } else {
            streamReader = StAXUtils.createXMLStreamReader(inputStream);
        }
    } catch (XMLStreamException e) {
        throw new SOAPException(e);
    }

    StAXSOAPModelBuilder builder;
    if (isMTOM && attachments != null) {
        builder = new MTOMStAXSOAPModelBuilder(streamReader, soapFactory, attachments,
                soapEnvelopeNamespaceURI);
    } else {
        builder = new StAXSOAPModelBuilder(streamReader, soapFactory, soapEnvelopeNamespaceURI);
    }

    try {
        org.apache.axiom.soap.SOAPEnvelope soapEnvelope = builder.getSOAPEnvelope();
        envelope = new SOAPEnvelopeImpl((org.apache.axiom.soap.impl.dom.SOAPEnvelopeImpl) soapEnvelope);
        envelope.element.build();
        this.document = envelope.getOwnerDocument();
        envelope.setSOAPPartParent(this);
    } catch (Exception e) {
        throw new SOAPException(e);
    }
}

From source file:com.zimbra.cs.mailbox.calendar.Invite.java

/**
 * Returns the meeting notes.  Meeting notes is the text/plain part in an
 * invite.  It typically includes CUA-generated meeting summary as well as
 * text entered by the user./* ww w  .j  a  v  a  2  s  .  c o  m*/
 *
 * @return null if notes is not found
 * @throws ServiceException
 */
public static String getDescription(Part mmInv, String mimeType) throws ServiceException {
    if (mmInv == null)
        return null;
    try {
        // If top-level is text/calendar, parse the iCalendar object and return
        // the DESCRIPTION of the first VEVENT/VTODO encountered.
        String mmCtStr = mmInv.getContentType();
        if (mmCtStr != null) {
            ContentType mmCt = new ContentType(mmCtStr);
            if (mmCt.match(MimeConstants.CT_TEXT_CALENDAR)) {
                boolean wantHtml = MimeConstants.CT_TEXT_HTML.equalsIgnoreCase(mimeType);
                Object mmInvContent = mmInv.getContent();
                InputStream is = null;
                try {
                    String charset = MimeConstants.P_CHARSET_UTF8;
                    if (mmInvContent instanceof InputStream) {
                        charset = mmCt.getParameter(MimeConstants.P_CHARSET);
                        if (charset == null)
                            charset = MimeConstants.P_CHARSET_UTF8;
                        is = (InputStream) mmInvContent;
                    } else if (mmInvContent instanceof String) {
                        String str = (String) mmInvContent;
                        charset = MimeConstants.P_CHARSET_UTF8;
                        is = new ByteArrayInputStream(str.getBytes(charset));
                    }
                    if (is != null) {
                        ZVCalendar iCal = ZCalendarBuilder.build(is, charset);
                        for (Iterator<ZComponent> compIter = iCal.getComponentIterator(); compIter.hasNext();) {
                            ZComponent component = compIter.next();
                            ICalTok compTypeTok = component.getTok();
                            if (compTypeTok == ICalTok.VEVENT || compTypeTok == ICalTok.VTODO) {
                                if (!wantHtml)
                                    return component.getPropVal(ICalTok.DESCRIPTION, null);
                                else
                                    return component.getDescriptionHtml();
                            }
                        }
                    }
                } finally {
                    ByteUtil.closeStream(is);
                }
            }
        }

        Object mmInvContent = mmInv.getContent();
        if (!(mmInvContent instanceof MimeMultipart)) {
            if (mmInvContent instanceof InputStream) {
                ByteUtil.closeStream((InputStream) mmInvContent);
            }
            return null;
        }
        MimeMultipart mm = (MimeMultipart) mmInvContent;

        // If top-level is multipart, get description from text/* part.
        int numParts = mm.getCount();
        String charset = null;
        for (int i = 0; i < numParts; i++) {
            BodyPart part = mm.getBodyPart(i);
            String ctStr = part.getContentType();
            try {
                ContentType ct = new ContentType(ctStr);
                if (ct.match(mimeType)) {
                    charset = ct.getParameter(MimeConstants.P_CHARSET);
                    if (charset == null)
                        charset = MimeConstants.P_CHARSET_DEFAULT;
                    byte[] descBytes = ByteUtil.getContent(part.getInputStream(), part.getSize());
                    return new String(descBytes, charset);
                }
                // If part is a multipart, recurse.
                if (ct.getBaseType().matches(MimeConstants.CT_MULTIPART_WILD)) {
                    String str = getDescription(part, mimeType);
                    if (str != null) {
                        return str;
                    }
                }
            } catch (javax.mail.internet.ParseException e) {
                ZimbraLog.calendar.warn("Invalid Content-Type found: \"" + ctStr + "\"; skipping part", e);
            }
        }
    } catch (IOException e) {
        throw ServiceException.FAILURE("Unable to get calendar item notes MIME part", e);
    } catch (MessagingException e) {
        throw ServiceException.FAILURE("Unable to get calendar item notes MIME part", e);
    }
    return null;
}