Example usage for javax.mail.internet ContentType getBaseType

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

Introduction

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

Prototype

public String getBaseType() 

Source Link

Document

Return the MIME type string, without the parameters.

Usage

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

@Override
protected void execute(final StepInput input, final StepOutput output) {
    final XdmNode sourceDocument = input.readNode(XProcPorts.SOURCE);

    final String namespaceOption = input.getOptionValue(XProcOptions.NAMESPACE, null);
    // Resolve namespace
    Steps.getUri(namespaceOption);// w  w w  . j  a va  2 s.  co m
    final String contentTypeOption = input.getOptionValue(XProcOptions.CONTENT_TYPE, MediaTypes.MEDIA_XML);
    final String encodingOption = input.getOptionValue(XProcOptions.ENCODING, null);
    if (encodingOption != null && !Steps.ENCODING_BASE64.equals(encodingOption)) {
        throw XProcExceptions.xc0052(SaxonLocation.of(sourceDocument));
    }
    final ContentType contentType = getContentType(contentTypeOption, input.getStep());
    final String charsetOption = input.getOptionValue(XProcOptions.CHARSET, null);
    final String charset = (charsetOption == null) ? contentType.getParameter("charset") : charsetOption;

    if (Steps.ENCODING_BASE64.equals(encodingOption)) {
        if (charset == null) {
            throw XProcExceptions.xc0010(input.getStep().getNode());
        } else {
            final SaxonBuilder builder = new SaxonBuilder(
                    input.getPipelineContext().getProcessor().getUnderlyingConfiguration());
            builder.startDocument();
            final Iterable<XdmNode> childNodes = SaxonAxis.childElements(sourceDocument);
            for (final XdmNode aNode : childNodes) {
                if (XdmNodeKind.ELEMENT.equals(aNode.getNodeKind())) {
                    final String unEscapeContent;
                    try {
                        unEscapeContent = getUnEscapeContent(aNode.getStringValue(), encodingOption,
                                contentType, charset);
                    } catch (IOException e) {
                        throw XProcExceptions.xc0010(aNode);
                    }
                    builder.startElement(aNode.getNodeName(), aNode);
                    for (final XdmNode attribute : SaxonAxis.attributes(aNode)) {
                        LOG.trace("copy existing attribute: {}", attribute);
                        builder.attribute(attribute.getNodeName(), attribute.getStringValue());
                    }
                    if (MediaTypes.MEDIA_TYPE_HTML.equals(contentType.getBaseType())) {
                        writeHtmlNodes(unEscapeContent, namespaceOption,
                                input.getPipelineContext().getProcessor(), builder);
                    } else {
                        writeXmlNodes(unEscapeContent, namespaceOption,
                                input.getPipelineContext().getProcessor(), builder);
                    }
                    builder.endElement();
                } else {
                    builder.nodes(aNode);
                }
            }
            builder.endDocument();
            output.writeNodes(XProcPorts.RESULT, builder.getNode());
        }
    } else {
        final SaxonProcessorDelegate escapeDelegate = new CopyingSaxonProcessorDelegate() {
            @Override
            public EnumSet<NextSteps> startElement(final XdmNode node, final SaxonBuilder builder) {
                builder.startElement(node.getNodeName(), node);
                return EnumSet.of(NextSteps.PROCESS_ATTRIBUTES, NextSteps.PROCESS_CHILDREN,
                        NextSteps.START_CONTENT);
            }

            @Override
            public void text(final XdmNode node, final SaxonBuilder builder) {
                final String unEscapeContent;
                try {
                    unEscapeContent = getUnEscapeContent(node.getStringValue(), encodingOption, contentType,
                            charset);
                } catch (IOException e) {
                    throw XProcExceptions.xc0010(node);
                }
                if (MediaTypes.MEDIA_TYPE_HTML.equals(contentType.getBaseType())) {
                    writeHtmlNodes(unEscapeContent, namespaceOption, input.getPipelineContext().getProcessor(),
                            builder);
                } else {
                    writeXmlNodes(unEscapeContent, namespaceOption, input.getPipelineContext().getProcessor(),
                            builder);
                }
            }
        };
        final SaxonProcessor escapeProcessor = new SaxonProcessor(input.getPipelineContext().getProcessor(),
                escapeDelegate);

        final XdmNode result = escapeProcessor.apply(sourceDocument);
        output.writeNodes(XProcPorts.RESULT, result);
    }
}

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>/* ww w  .ja va2s . c om*/
 * 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./*  w  w w .  j  av  a  2  s  . c  om*/
 *
 * @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;
}

From source file:org.esxx.Response.java

public static void writeObject(Object object, ContentType ct, OutputStream out) throws IOException {

    if (object == null) {
        return;/*from  w  w w  . ja  va2  s.c om*/
    }

    // Unwrap wrapped objects
    object = JS.toJavaObject(object);

    // Convert complex types to primitive types
    if (object instanceof Node) {
        ESXX esxx = ESXX.getInstance();

        if (ct.match("message/rfc822")) {
            try {
                String xml = esxx.serializeNode((Node) object);
                org.esxx.xmtp.XMTPParser xmtpp = new org.esxx.xmtp.XMTPParser();
                javax.mail.Message msg = xmtpp.convertMessage(new StringReader(xml));
                object = new ByteArrayOutputStream();
                msg.writeTo(new FilterOutputStream((OutputStream) object) {
                    @Override
                    public void write(int b) throws IOException {
                        if (b == '\r') {
                            return;
                        } else if (b == '\n') {
                            out.write('\r');
                            out.write('\n');
                        } else {
                            out.write(b);
                        }
                    }
                });
            } catch (javax.xml.stream.XMLStreamException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            } catch (javax.mail.MessagingException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            }
        } else {
            object = esxx.serializeNode((Node) object);
        }
    } else if (object instanceof Scriptable) {
        if (ct.match("application/x-www-form-urlencoded")) {
            String cs = Parsers.getParameter(ct, "charset", "UTF-8");

            object = StringUtil.encodeFormVariables(cs, (Scriptable) object);
        } else if (ct.match("text/csv")) {
            object = jsToCSV(ct, (Scriptable) object);
        } else {
            object = jsToJSON(object).toString();
        }
    } else if (object instanceof byte[]) {
        object = new ByteArrayInputStream((byte[]) object);
    } else if (object instanceof File) {
        object = new FileInputStream((File) object);
    }

    // Serialize primitive types
    if (object instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream bos = (ByteArrayOutputStream) object;

        bos.writeTo(out);
    } else if (object instanceof ByteBuffer) {
        // Write result as-is to output stream
        WritableByteChannel wbc = Channels.newChannel(out);
        ByteBuffer bb = (ByteBuffer) object;

        bb.rewind();

        while (bb.hasRemaining()) {
            wbc.write(bb);
        }

        wbc.close();
    } else if (object instanceof InputStream) {
        IO.copyStream((InputStream) object, out);
    } else if (object instanceof Reader) {
        // Write stream as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);

        IO.copyReader((Reader) object, ow);
    } else if (object instanceof String) {
        // Write string as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);
        ow.write((String) object);
        ow.flush();
    } else if (object instanceof RenderedImage) {
        Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(ct.getBaseType());

        if (!i.hasNext()) {
            throw new ESXXException("No ImageWriter available for " + ct.getBaseType());
        }

        ImageWriter writer = i.next();

        writer.setOutput(ImageIO.createImageOutputStream(out));
        writer.write((RenderedImage) object);
    } else {
        throw new UnsupportedOperationException("Unsupported object class type: " + object.getClass());
    }
}

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  om*/
 * @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;
}