Example usage for javax.mail.internet ContentType ContentType

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

Introduction

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

Prototype

public ContentType(String s) throws ParseException 

Source Link

Document

Constructor that takes a Content-Type string.

Usage

From source file:immf.SendMailBridge.java

private void parseBodypartmixed(SenderMail sendMail, BodyPart bp, String subtype, String parentSubtype)
        throws IOException {
    boolean limiterr = false;
    String badfile = null;/*from   w  w  w . ja  v  a  2  s . c  om*/
    try {
        String contentType = bp.getContentType().toLowerCase();
        log.info("Bodypart ContentType:" + contentType);
        log.info("subtype:" + subtype);

        if (contentType.startsWith("multipart/")) {
            parseMultipart(sendMail, (Multipart) bp.getContent(), getSubtype(contentType), subtype);

        } else if (sendMail.getPlainTextContent() == null && contentType.startsWith("text/plain")) {
            // ???plain/text?
            String content = (String) bp.getContent();
            log.info("set Content text [" + content + "]");
            String charset = (new ContentType(contentType)).getParameter("charset");
            content = this.charConv.convert(content, charset);
            log.debug(" conv " + content);
            sendMail.setPlainTextContent(content);

            // HTML??????<br>????????HtmlConverter?
            // ??????HTML???HTML???????
            if (sendMail.getHtmlWorkingContent() == null) {
                sendMail.setHtmlWorkingContent(
                        "<body>" + Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>");
            } else {
                sendMail.addHtmlWorkingContent(
                        Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>");
            }

        } else if (sendMail.getHtmlContent() == null && contentType.startsWith("text/html")
                && (parentSubtype.equalsIgnoreCase("alternative")
                        || parentSubtype.equalsIgnoreCase("related"))) {
            // ???text/html
            String content = (String) bp.getContent();
            log.info("set Content html [" + content + "]");
            String charset = (new ContentType(contentType)).getParameter("charset");
            // 2?3?HTML?????????</body>???????
            content = this.charConv.convert(content, charset);
            content = HtmlConvert.replaceAllCaseInsenstive(content, "</body>.*", "");
            log.debug(" conv " + content);
            sendMail.setHtmlContent(content);

        } else {
            log.debug("attach");
            // ????

            String contentDisposition = bp.getDisposition();
            if (contentDisposition != null && contentDisposition.equalsIgnoreCase(Part.INLINE)) {
                // 
                SenderAttachment file = new SenderAttachment();
                String uniqId = uniqId();
                String fname = uniqId;
                String fname2 = Util.getFileName(bp);

                // iPhone?gifpng?????????????gif??(?png???gif?)
                if (getSubtype(contentType).equalsIgnoreCase("png")) {
                    file.setContentType("image/gif");
                    fname = fname + ".gif";
                    fname2 = getBasename(fname2) + ".gif";
                    file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream())));
                } else {
                    file.setContentType(contentType);
                    fname = fname + "." + getSubtype(contentType);
                    file.setData(inputstream2bytes(bp.getInputStream()));
                }

                file.setInline(true);
                boolean inline = !this.forcePlainText & sendMail.checkAttachmentCapability(file);
                if (!inline) {
                    file.setInline(false);
                    if (!sendMail.checkAttachmentCapability(file)) {
                        limiterr = true;
                        badfile = fname2;
                        throw new Exception("Attachments: size limit or file count limit exceeds!");
                    }
                }

                if (inline) {
                    file.setFilename(fname);
                    if (bp.getHeader("Content-Id") == null) {
                        file.setContentId(uniqId);
                    } else {
                        file.setContentId(bp.getHeader("Content-Id")[0]);
                    }
                    log.info("Inline Attachment(mixed) " + file.loggingString() + ", Hash:" + file.getHash());

                    // ??HTML?
                    if (sendMail.getHtmlContent() != null) {
                        sendMail.addHtmlContent("<img src=\"cid:" + file.getContentId() + "\"><br>");
                    }
                    if (sendMail.getHtmlWorkingContent() == null) {
                        sendMail.setHtmlWorkingContent(
                                "<body><img src=\"cid:" + file.getContentId() + "\"><br>");
                    } else {
                        sendMail.addHtmlWorkingContent("<img src=\"cid:" + file.getContentId() + "\"><br>");
                    }
                } else {
                    file.setFilename(fname2);
                    log.info("Attachment " + file.loggingString());
                }
                sendMail.addAttachmentFileIdList(file);

            } else {
                // ?
                SenderAttachment file = new SenderAttachment();
                file.setInline(false);
                file.setContentType(contentType);
                String fname = Util.getFileName(bp);
                if (fname == null && sendMail.getPlainTextContent() != null
                        && contentType.startsWith("text/plain")) {
                    // ???????
                    String content = (String) bp.getContent();
                    log.info("add Content text [" + content + "]");
                    String charset = (new ContentType(contentType)).getParameter("charset");
                    content = this.charConv.convert(content, charset);
                    log.debug(" conv " + content);

                    // ??HTML????<br>
                    sendMail.addPlainTextContent("\n" + content);
                    sendMail.addHtmlWorkingContent(
                            Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>");

                } else if (fname == null && sendMail.getHtmlContent() != null
                        && contentType.startsWith("text/html") && (parentSubtype.equalsIgnoreCase("alternative")
                                || parentSubtype.equalsIgnoreCase("related"))) {
                    // ????text/html????
                    String content = (String) bp.getContent();
                    log.info("add Content html [" + content + "]");
                    String charset = (new ContentType(contentType)).getParameter("charset");
                    content = this.charConv.convert(content, charset);
                    content = HtmlConvert.replaceAllCaseInsenstive(content, ".*<body[^>]*>", "");
                    content = HtmlConvert.replaceAllCaseInsenstive(content, "</body>.*", "");
                    log.debug(" conv " + content);
                    sendMail.addHtmlContent(content);

                } else {
                    // ??????
                    if (getSubtype(contentType).equalsIgnoreCase("png")) {
                        file.setContentType("image/gif");
                        file.setFilename(getBasename(fname) + ".gif");
                        file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream())));
                    } else {
                        file.setFilename(fname);
                        file.setData(inputstream2bytes(bp.getInputStream()));
                    }
                    if (!sendMail.checkAttachmentCapability(file)) {
                        limiterr = true;
                        badfile = file.getFilename();
                        throw new Exception("Attachments: size limit or file count limit exceeds!");
                    }
                    sendMail.addAttachmentFileIdList(file);
                    log.info("Attachment " + file.loggingString());

                }
            }
        }
    } catch (Exception e) {
        log.error("parse bodypart error(mixed).", e);
        if (limiterr) {
            sendMail.addPlainTextContent("\n[(" + badfile + ")]");
            if (sendMail.getHtmlContent() != null) {
                sendMail.addHtmlContent("[(" + badfile + ")]<br>");
            }
            if (sendMail.getHtmlWorkingContent() == null) {
                sendMail.setHtmlWorkingContent("<body>[(" + badfile + ")]<br>");
            } else {
                sendMail.addHtmlWorkingContent("[(" + badfile + ")]<br>");
            }
        } else {
            throw new IOException("BodyPart error(mixed)." + e.getMessage(), e);
        }
    }
}

From source file:org.aksw.resparql.IMyHandler.java

public static Map<String, ContentType> getPreferredFormats(Headers requestHeaders) throws ParseException {
    // Content negotiation
    List<String> accepts = requestHeaders.get("Accept");
    if (accepts == null)
        accepts = Collections.emptyList();

    logger.info("Accept header: " + accepts);

    Map<String, ContentType> result = new HashMap<String, ContentType>();
    int acceptCounter = 0;
    for (String accept : accepts) {
        String[] items = accept.split(",");
        for (String item : items) {
            ++acceptCounter;//from   w  ww. j a v  a  2  s . c  o m

            ContentType ct = null;
            try {
                ct = new ContentType(item);
            } catch (Exception e) {
                logger.warn("Error parsing content type", e);
                continue;
            }

            // FIXME Would be nice if this was configurable
            if (ct.match("text/plain") || ct.match("text/html") || ct.match("*/*")) {
                if (!result.containsKey("N-TRIPLE")) {
                    //result.put("N-TRIPLE", ct);
                    // We serve N-Triples by default
                    result.put("N-TRIPLE", new ContentType("text/plain"));
                }

                //responseContentType = "text/plain; charset=UTF-8";
            }

            for (Map.Entry<ContentType, String> entry : contentTypeToJenaFormat.entrySet()) {
                if (!ct.match(entry.getKey()))
                    continue;

                String tmp = entry.getValue();
                if (tmp != null) {
                    // If a format was specified in the query string, we also need
                    // a compatible content type
                    // E.g. if format=N3, but accept=rdf+xml we can't use that accept type
                    if (!result.containsKey(tmp)) {
                        result.put(tmp, ct);
                    }
                }
            }
        }
    }

    return result;
}

From source file:org.aksw.resparql.IMyHandler.java

/**
 * Returns a pair of serializiation format and content-type
 * //from   w w w  . j  a v a2 s .c om
 */
public static Map.Entry<String, ContentType> getContentType(String requestedFormat,
        Map<String, ContentType> accepts) throws ParseException {
    if (requestedFormat == null) {
        if (accepts.isEmpty()) {
            return new Pair<String, ContentType>("N-TRIPLE", new ContentType("text/plain; charset=utf-8"));
        } else {
            return accepts.entrySet().iterator().next();
        }
    } else if (!accepts.containsKey(requestedFormat)) {

        //return null;
        //return new SimpleResponse(406, "text/plain", "Requested " + requestedFormat + " but accept-header " + formats + " is not compatible.");             
        //}

        ContentType contentType = StringUtils.coalesce(jenaFormatToContentType.get(requestedFormat),
                new ContentType("text/plain; charset=utf-8"));

        return new Pair<String, ContentType>(requestedFormat, contentType);
    } else {
        return new Pair<String, ContentType>(requestedFormat, accepts.get(requestedFormat));
        //return new Pair<String, ContentType>(requestedFormat, new ContentType("text/plain; charset=utf-8"));
    }
}

From source file:com.yenlo.synapse.transport.vfs.VFSTransportListener.java

/**
 * Process a single file through Axis2// www .ja  va2  s . c o  m
 * @param entry the PollTableEntry for the file (or its parent directory or archive)
 * @param file the file that contains the actual message pumped into Axis2
 * @throws AxisFault on error
 */
private void processFile(PollTableEntry entry, FileObject file) throws AxisFault {

    try {
        FileContent content = file.getContent();
        String fileName = file.getName().getBaseName();
        String filePath = file.getName().getPath();
        String fileURI = file.getName().getURI();

        metrics.incrementBytesReceived(content.getSize());

        Map<String, Object> transportHeaders = new HashMap<String, Object>();
        transportHeaders.put(VFSConstants.FILE_PATH, filePath);
        transportHeaders.put(VFSConstants.FILE_NAME, fileName);
        transportHeaders.put(VFSConstants.FILE_URI, fileURI);

        try {
            transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize());
            transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime());
        } catch (FileSystemException ignore) {
        }

        MessageContext msgContext = entry.createMessageContext();

        String contentType = entry.getContentType();
        if (BaseUtils.isBlank(contentType)) {
            if (file.getName().getExtension().toLowerCase().endsWith(".xml")) {
                contentType = "text/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            String charSetEnc = null;
            try {
                if (contentType != null) {
                    charSetEnc = new ContentType(contentType).getParameter("charset");
                }
            } catch (ParseException ex) {
                // ignore
            }
            msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }

        // if the content type was not found, but the service defined it.. use it
        if (contentType == null) {
            if (entry.getContentType() != null) {
                contentType = entry.getContentType();
            } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) {
                contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE);
            }
        }

        // does the service specify a default reply file URI ?
        String replyFileURI = entry.getReplyFileURI();
        if (replyFileURI != null) {
            msgContext.setProperty(Constants.OUT_TRANSPORT_INFO,
                    new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled()));
        }

        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using SOAP builder.");
            builder = new SOAPBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, msgContext);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
                }
                builder = new SOAPBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in;
        ManagedDataSource dataSource;
        if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) {
            in = null;
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
        } else {
            in = new AutoCloseInputStream(content.getInputStream());
            dataSource = null;
        }

        try {
            OMElement documentElement;
            if (in != null) {
                documentElement = builder.processDocument(in, contentType, msgContext);
            } else {
                documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType,
                        msgContext);
            }
            msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));

            handleIncomingMessage(msgContext, transportHeaders, null, //* SOAP Action - not applicable *//
                    contentType);
        } finally {
            if (dataSource != null) {
                dataSource.destroy();
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + file + " of Content-type : " + contentType);
        }

    } catch (FileSystemException e) {
        handleException("Error reading file content or attributes : " + file, e);

    } finally {
        try {
            file.close();
        } catch (FileSystemException warn) {
            //  log.warn("Cannot close file after processing : " + file.getName().getPath(), warn);
            // ignore the warning, since we handed over the stream close job to AutocloseInputstream..
        }
    }
}

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

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

    // Creates ContentType
    ContentType contentType = null;// ww w  . j  a  va 2s.c o  m
    try {
        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.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./*ww w . j  av a2s  .c o 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.apache.synapse.transport.vfs.VFSTransportListener.java

/**
 * Process a single file through Axis2/*from w w w . jav a  2s .  com*/
 * @param entry the PollTableEntry for the file (or its parent directory or archive)
 * @param file the file that contains the actual message pumped into Axis2
 * @throws AxisFault on error
 */
private void processFile(PollTableEntry entry, FileObject file) throws AxisFault {

    try {
        FileContent content = file.getContent();
        String fileName = file.getName().getBaseName();
        String filePath = file.getName().getPath();
        String fileURI = file.getName().getURI();

        metrics.incrementBytesReceived(content.getSize());

        Map<String, Object> transportHeaders = new HashMap<String, Object>();
        transportHeaders.put(VFSConstants.FILE_PATH, filePath);
        transportHeaders.put(VFSConstants.FILE_NAME, fileName);
        transportHeaders.put(VFSConstants.FILE_URI, fileURI);

        try {
            transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize());
            transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime());
        } catch (FileSystemException ignore) {
        }

        MessageContext msgContext = entry.createMessageContext();

        String contentType = entry.getContentType();
        if (BaseUtils.isBlank(contentType)) {
            if (file.getName().getExtension().toLowerCase().endsWith(".xml")) {
                contentType = "text/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            String charSetEnc = null;
            try {
                if (contentType != null) {
                    charSetEnc = new ContentType(contentType).getParameter("charset");
                }
            } catch (ParseException ex) {
                // ignore
            }
            msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }

        // if the content type was not found, but the service defined it.. use it
        if (contentType == null) {
            if (entry.getContentType() != null) {
                contentType = entry.getContentType();
            } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) {
                contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE);
            }
        }

        // does the service specify a default reply file URI ?
        String replyFileURI = entry.getReplyFileURI();
        if (replyFileURI != null) {
            msgContext.setProperty(Constants.OUT_TRANSPORT_INFO,
                    new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled()));
        }

        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using SOAP builder.");
            builder = new SOAPBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, msgContext);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
                }
                builder = new SOAPBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in;
        ManagedDataSource dataSource;
        if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) {
            in = null;
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
        } else {
            in = new AutoCloseInputStream(content.getInputStream());
            dataSource = null;
        }

        try {
            OMElement documentElement;
            if (in != null) {
                documentElement = builder.processDocument(in, contentType, msgContext);
            } else {
                documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType,
                        msgContext);
            }
            msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));

            handleIncomingMessage(msgContext, transportHeaders, null, //* SOAP Action - not applicable *//
                    contentType);
        } finally {
            if (dataSource != null) {
                dataSource.destroy();
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + VFSUtils.maskURLPassword(file.toString()) + " of Content-type : "
                    + contentType);
        }

    } catch (FileSystemException e) {
        handleException(
                "Error reading file content or attributes : " + VFSUtils.maskURLPassword(file.toString()), e);

    } finally {
        try {
            if (file != null) {
                file.close();
            }
        } catch (FileSystemException warn) {
            // ignore the warning,  since we handed over the stream close job to
            // AutocloseInputstream..
        }
    }
}

From source file:com.zimbra.cs.service.formatter.VCard.java

public static VCard formatContact(Contact con, Collection<String> vcattrs, boolean includeXProps,
        boolean includeZimbraXProps) {
    Map<String, String> fields = con.getFields();
    List<Attachment> attachments = con.getAttachments();
    List<String> emails = con.getEmailAddresses(DerefGroupMembersOption.NONE);

    StringBuilder sb = new StringBuilder();
    sb.append("BEGIN:VCARD\r\n");

    // This is from RFC 2426 (vCard version 3.0) Section 1:
    // Profile special notes: The vCard object MUST contain the FN, N and VERSION types.

    if (vcattrs == null || vcattrs.contains("VERSION"))
        sb.append("VERSION:3.0\r\n");

    // FN is a mandatory component of the vCard -- try our best to find or generate one
    String fn = fields.get(ContactConstants.A_fullName);
    if (vcattrs == null || vcattrs.contains("FN")) {
        if (fn == null || fn.trim().equals(""))
            try {
                fn = con.getFileAsString();
            } catch (ServiceException e) {
                fn = "";
            }//from w  ww  . j a  v  a2s  . c o m
        if (fn.trim().equals("") && !emails.isEmpty())
            fn = emails.get(0);
        if (fn.trim().equals("")) {
            String org = fields.get(ContactConstants.A_company);
            if (org != null && !org.trim().equals("")) {
                fn = org;
            }
        }
        sb.append("FN:").append(vcfEncode(fn)).append("\r\n");
    }

    if (vcattrs == null || vcattrs.contains("N")) {
        StringBuilder nSb = new StringBuilder();
        nSb.append(vcfEncode(fields.get(ContactConstants.A_lastName))).append(';')
                .append(vcfEncode(fields.get(ContactConstants.A_firstName))).append(';')
                .append(vcfEncode(fields.get(ContactConstants.A_middleName))).append(';')
                .append(vcfEncode(fields.get(ContactConstants.A_namePrefix))).append(';')
                .append(vcfEncode(fields.get(ContactConstants.A_nameSuffix)));
        String n = nSb.toString();
        // N is mandatory according to  RFC 2426 Section 1, so include it even if all components are empty
        // In fact, clients like Mac OS X Mavericks Contacts will just have blank names if it is blank,
        // so, try to avoid that.
        if (";;;;".equals(n)) {
            n = vcfEncode(fn) + ";;;;";
        }
        sb.append("N:").append(n).append("\r\n");
    }

    if (vcattrs == null || vcattrs.contains("NICKNAME"))
        encodeField(sb, "NICKNAME", fields.get(ContactConstants.A_nickname));
    if (vcattrs == null || vcattrs.contains("PHOTO"))
        encodeField(sb, "PHOTO;VALUE=URI", fields.get(ContactConstants.A_image));
    if (vcattrs == null || vcattrs.contains("BDAY")) {
        String bday = fields.get(ContactConstants.A_birthday);
        if (bday != null) {
            Date date = DateUtil.parseDateSpecifier(bday);
            if (date != null)
                sb.append("BDAY;VALUE=date:").append(new SimpleDateFormat("yyyy-MM-dd").format(date))
                        .append("\r\n");
        }
    }

    if (vcattrs == null || vcattrs.contains("ADR")) {
        encodeAddress(sb, "home,postal,parcel", ContactConstants.A_homeStreet, ContactConstants.A_homeCity,
                ContactConstants.A_homeState, ContactConstants.A_homePostalCode, ContactConstants.A_homeCountry,
                2, fields);
        encodeAddress(sb, "work,postal,parcel", ContactConstants.A_workStreet, ContactConstants.A_workCity,
                ContactConstants.A_workState, ContactConstants.A_workPostalCode, ContactConstants.A_workCountry,
                2, fields);
        encodeAddress(sb, "postal,parcel", ContactConstants.A_otherStreet, ContactConstants.A_otherCity,
                ContactConstants.A_otherState, ContactConstants.A_otherPostalCode,
                ContactConstants.A_otherCountry, 2, fields);
    }

    if (vcattrs == null || vcattrs.contains("TEL")) {
        // omitting callback phone for now
        encodePhone(sb, "car,voice", ContactConstants.A_carPhone, 2, fields);
        encodePhone(sb, "home,fax", ContactConstants.A_homeFax, 2, fields);
        encodePhone(sb, "home,voice", ContactConstants.A_homePhone, 2, fields);
        encodePhone(sb, "cell,voice", ContactConstants.A_mobilePhone, 2, fields);
        encodePhone(sb, "fax", ContactConstants.A_otherFax, 2, fields);
        encodePhone(sb, "voice", ContactConstants.A_otherPhone, 2, fields);
        encodePhone(sb, "pager", ContactConstants.A_pager, 2, fields);
        encodePhone(sb, "work,fax", ContactConstants.A_workFax, 2, fields);
        encodePhone(sb, "work,voice", ContactConstants.A_workPhone, 2, fields);
    }

    if (vcattrs == null || vcattrs.contains("EMAIL")) {
        encodeField(sb, "EMAIL;TYPE=internet", ContactConstants.A_email, false, 2, fields);
        encodeField(sb, "EMAIL;TYPE=internet", "workEmail", true, 1, fields);
    }

    if (vcattrs == null || vcattrs.contains("URL")) {
        encodeField(sb, "URL;TYPE=home", ContactConstants.A_homeURL, false, 2, fields);
        encodeField(sb, "URL", ContactConstants.A_otherURL, false, 2, fields);
        encodeField(sb, "URL;TYPE=work", ContactConstants.A_workURL, false, 2, fields);
    }

    if (vcattrs == null || vcattrs.contains("ORG")) {
        String org = fields.get(ContactConstants.A_company);
        if (org != null && !org.trim().equals("")) {
            org = vcfEncode(org);
            String dept = fields.get(ContactConstants.A_department);
            if (dept != null && !dept.trim().equals("")) {
                org += ';' + vcfEncode(dept);
            }
            sb.append("ORG:").append(org).append("\r\n");
        }
    }
    if (vcattrs == null || vcattrs.contains("TITLE"))
        encodeField(sb, "TITLE", fields.get(ContactConstants.A_jobTitle));

    if (vcattrs == null || vcattrs.contains("NOTE"))
        encodeField(sb, "NOTE", fields.get(ContactConstants.A_notes));

    if ((vcattrs == null || vcattrs.contains("PHOTO")) && attachments != null) {
        for (Attachment attach : attachments) {
            try {
                if (attach.getName().equalsIgnoreCase(ContactConstants.A_image)) {
                    String field = "PHOTO;ENCODING=B";
                    if (attach.getContentType().startsWith("image/")) {
                        // We want just the subtype, ignoring any name etc
                        try {
                            ContentType ct = new ContentType(attach.getContentType());
                            if (ct != null) {
                                String subType = ct.getSubType();
                                if (!Strings.isNullOrEmpty(subType)) {
                                    field += ";TYPE=" + ct.getSubType().toUpperCase();
                                }
                            }
                        } catch (ParseException e) {
                        }
                    }
                    String encoded = new String(Base64.encodeBase64Chunked(attach.getContent())).trim()
                            .replace("\r\n", "\r\n ");
                    sb.append(field).append(":\r\n ").append(encoded).append("\r\n");
                }
            } catch (OutOfMemoryError e) {
                Zimbra.halt("out of memory", e);
            } catch (Throwable t) {
                ZimbraLog.misc.info("error fetching attachment content: " + attach.getName(), t);
            }
        }
    }

    if (vcattrs == null || vcattrs.contains("KEY")) {
        String smimeCert = fields.get(ContactConstants.A_userSMIMECertificate);
        if (smimeCert == null) {
            smimeCert = fields.get(ContactConstants.A_userCertificate);
        }
        if (smimeCert != null) {
            smimeCert = smimeCert.trim().replace("\r\n", "\r\n ");
            String field = "KEY;ENCODING=B";
            sb.append(field).append(":\r\n ").append(smimeCert).append("\r\n");
        }
    }

    if (vcattrs == null || vcattrs.contains("CATEGORIES")) {
        String[] tags = con.getTags();
        if (tags.length > 0) {
            StringBuilder sbtags = new StringBuilder();
            for (String tagName : tags) {
                sbtags.append(sbtags.length() == 0 ? "" : ",").append(vcfEncode(tagName));
            }
            sb.append("CATEGORIES:").append(sbtags).append("\r\n");
        }
    }

    String uid = getUid(con);
    if (vcattrs == null || vcattrs.contains("REV")) {
        sb.append("REV:")
                .append(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date(con.getDate())))
                .append("\r\n");
    }
    if (vcattrs == null || vcattrs.contains("UID")) {
        sb.append("UID:").append(uid).append("\r\n");
    }
    // sb.append("MAILER:Zimbra ").append(BuildInfo.VERSION).append("\r\n");
    if ((vcattrs == null && includeZimbraXProps)
            || (vcattrs != null && vcattrs.contains("X-ZIMBRA-IMADDRESS"))) {
        encodeField(sb, "X-ZIMBRA-IMADDRESS", "imAddress", true, 1, fields);
    }
    if ((vcattrs == null && includeZimbraXProps)
            || (vcattrs != null && vcattrs.contains("X-ZIMBRA-ANNIVERSARY"))) {
        encodeField(sb, "X-ZIMBRA-ANNIVERSARY", ContactConstants.A_anniversary, false, 2, fields);
    }
    if ((vcattrs == null && includeZimbraXProps)
            || (vcattrs != null && vcattrs.contains("X-ZIMBRA-MAIDENNAME"))) {
        String maidenName = con.get(ContactConstants.A_maidenName);
        if (maidenName != null)
            sb.append("X-ZIMBRA-MAIDENNAME:").append(maidenName).append("\r\n");
    }
    if (includeXProps) {
        ListMultimap<String, VCardParamsAndValue> unknownVCardProps = con.getUnknownVCardProps();
        for (String key : unknownVCardProps.keySet()) {
            for (VCardParamsAndValue paramsAndValue : unknownVCardProps.get(key)) {
                StringWriter sw = new StringWriter();
                try (FoldingWriter writer = new FoldingWriter(sw)) {
                    writer.write(key);
                    String value = paramsAndValue.getValue();
                    Set<String> params = paramsAndValue.getParams();
                    if (!params.isEmpty()) {
                        writer.write(";");
                        writer.write(Joiner.on(";").join(params));
                    }
                    String vcfEncodedValue;
                    if (params.contains("ENCODING=B")) {
                        vcfEncodedValue = value; // should be raw BASE64
                    } else {
                        vcfEncodedValue = vcfEncode(value);
                    }
                    writer.write(":");
                    writer.write(vcfEncodedValue);
                    writer.write("\r\n");
                    sb.append(sw.toString());
                } catch (IOException e) {
                    ZimbraLog.misc.debug("Problem with adding property '%s' to VCARD - ignoring", key, e);
                }
            }
        }
    }
    sb.append("END:VCARD\r\n");
    return new VCard(fn, sb.toString(), fields, attachments, uid);
}

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.//from  w  w w. j  a va2 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.sakaiproject.james.SakaiMailet.java

/**
 * Breaks email messages into parts which can be saved as files (saves as attachments) or viewed as plain text (added to body of message).
 * /*  www.jav a  2  s . c  o m*/
 * @param siteId
 *        Site associated with attachments, if any
 * @param p
 *        The message-part embedded in a message..
 * @param id
 *        The string containing the message's id.
 * @param bodyBuf
 *        The string-buffers in which the plain/text and/or html/text message body is being built.
 * @param bodyContentType
 *        The value of the Content-Type header for the mesage body.
 * @param attachments
 *        The ReferenceVector in which references to attachments are collected.
 * @param embedCount
 *        An Integer that counts embedded messages (outer message is zero).
 * @return Value of embedCount (updated if this call processed any embedded messages).
 */
protected Integer parseParts(String siteId, Part p, String id, StringBuilder bodyBuf[],
        StringBuilder bodyContentType, List attachments, Integer embedCount)
        throws MessagingException, IOException {
    // increment embedded message counter
    if (p instanceof Message) {
        embedCount = Integer.valueOf(embedCount.intValue() + 1);
    }

    String type = p.getContentType();

    // discard if content-type is unknown
    if (type == null || "".equals(type)) {
        M_log.warn(this + " message with unknown content-type discarded");
    }

    // add plain text to bodyBuf[0]
    else if (p.isMimeType("text/plain") && p.getFileName() == null) {
        Object o = null;
        // let them convert to text if possible
        // but if bad encaps get the stream and do it ourselves
        try {
            o = p.getContent();
        } catch (java.io.UnsupportedEncodingException ignore) {
            o = p.getInputStream();
        }

        String txt = null;
        String innerContentType = p.getContentType();

        if (o instanceof String) {
            txt = (String) p.getContent();
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        else if (o instanceof InputStream) {
            InputStream in = (InputStream) o;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[in.available()];
            for (int len = in.read(buf); len != -1; len = in.read(buf))
                out.write(buf, 0, len);
            String charset = (new ContentType(innerContentType)).getParameter("charset");
            // RFC 2045 says if no char set specified use US-ASCII.
            // If specified but illegal that's less clear. The common case is X-UNKNOWN.
            // my sense is that UTF-8 is most likely these days but the sample we got
            // was actually ISO 8859-1. Could also justify using US-ASCII. Duh...
            if (charset == null)
                charset = "us-ascii";
            try {
                txt = out.toString(MimeUtility.javaCharset(charset));
            } catch (java.io.UnsupportedEncodingException ignore) {
                txt = out.toString("UTF-8");
            }
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        // remove extra line breaks added by mac Mail, perhaps others
        // characterized by a space followed by a line break
        if (txt != null) {
            txt = txt.replaceAll(" \n", " ");
        }

        // make sure previous message parts ended with newline
        if (bodyBuf[0].length() > 0 && bodyBuf[0].charAt(bodyBuf[0].length() - 1) != '\n')
            bodyBuf[0].append("\n");

        bodyBuf[0].append(txt);
    }

    // add html text to bodyBuf[1]
    else if (p.isMimeType("text/html") && p.getFileName() == null) {
        Object o = null;
        // let them convert to text if possible
        // but if bad encaps get the stream and do it ourselves
        try {
            o = p.getContent();
        } catch (java.io.UnsupportedEncodingException ignore) {
            o = p.getInputStream();
        }
        String txt = null;
        String innerContentType = p.getContentType();

        if (o instanceof String) {
            txt = (String) p.getContent();
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        else if (o instanceof InputStream) {
            InputStream in = (InputStream) o;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[in.available()];
            for (int len = in.read(buf); len != -1; len = in.read(buf))
                out.write(buf, 0, len);
            String charset = (new ContentType(innerContentType)).getParameter("charset");
            if (charset == null)
                charset = "us-ascii";
            try {
                txt = out.toString(MimeUtility.javaCharset(charset));
            } catch (java.io.UnsupportedEncodingException ignore) {
                txt = out.toString("UTF-8");
            }
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        // remove bad image tags and naughty javascript
        if (txt != null) {
            txt = Web.cleanHtml(txt);
        }

        bodyBuf[1].append(txt);
    }

    // process subparts of multiparts
    else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            embedCount = parseParts(siteId, mp.getBodyPart(i), id, bodyBuf, bodyContentType, attachments,
                    embedCount);
        }
    }

    // Discard parts with mime-type application/applefile. If an e-mail message contains an attachment is sent from
    // a macintosh, you may get two parts, one for the data fork and one for the resource fork. The part that
    // corresponds to the resource fork confuses users, this has mime-type application/applefile. The best thing
    // is to discard it.
    else if (p.isMimeType("application/applefile")) {
        M_log.warn(this + " message with application/applefile discarded");
    }

    // discard enriched text version of the message.
    // Sakai only uses the plain/text or html/text version of the message.
    else if (p.isMimeType("text/enriched") && p.getFileName() == null) {
        M_log.warn(this + " message with text/enriched discarded");
    }

    // everything else gets treated as an attachment
    else {
        String name = p.getFileName();

        // look for filenames not parsed by getFileName() 
        if (name == null && type.indexOf(NAME_PREFIX) != -1) {
            name = type.substring(type.indexOf(NAME_PREFIX) + NAME_PREFIX.length());
        }
        // ContentType can't handle filenames with spaces or UTF8 characters
        if (name != null) {
            String decodedName = MimeUtility.decodeText(name); // first decode RFC 2047
            type = type.replace(name, URLEncoder.encode(decodedName, "UTF-8"));
            name = decodedName;
        }

        ContentType cType = new ContentType(type);
        String disposition = p.getDisposition();
        int approxSize = p.getSize();

        if (name == null) {
            name = "unknown";
            // if file's parent is multipart/alternative,
            // provide a better name for the file
            if (p instanceof BodyPart) {
                Multipart parent = ((BodyPart) p).getParent();
                if (parent != null) {
                    String pType = parent.getContentType();
                    ContentType pcType = new ContentType(pType);
                    if (pcType.getBaseType().equalsIgnoreCase("multipart/alternative")) {
                        name = "message" + embedCount;
                    }
                }
            }
            if (p.isMimeType("text/html")) {
                name += ".html";
            } else if (p.isMimeType("text/richtext")) {
                name += ".rtx";
            } else if (p.isMimeType("text/rtf")) {
                name += ".rtf";
            } else if (p.isMimeType("text/enriched")) {
                name += ".etf";
            } else if (p.isMimeType("text/plain")) {
                name += ".txt";
            } else if (p.isMimeType("text/xml")) {
                name += ".xml";
            } else if (p.isMimeType("message/rfc822")) {
                name += ".txt";
            }
        }

        // read the attachments bytes, and create it as an attachment in content hosting
        byte[] bodyBytes = readBody(approxSize, p.getInputStream());
        if ((bodyBytes != null) && (bodyBytes.length > 0)) {
            // can we ignore the attachment it it's just whitespace chars??
            Reference attachment = createAttachment(siteId, attachments, cType.getBaseType(), name, bodyBytes,
                    id);

            // add plain/text attachment reference (if plain/text message)
            if (attachment != null && bodyBuf[0].length() > 0)
                bodyBuf[0]
                        .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n");

            // add html/text attachment reference (if html/text message)
            if (attachment != null && bodyBuf[1].length() > 0)
                bodyBuf[1].append(
                        "<p>[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]</p>");

            // add plain/text attachment reference (if no plain/text and no html/text)
            if (attachment != null && bodyBuf[0].length() == 0 && bodyBuf[1].length() == 0)
                bodyBuf[0]
                        .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n");
        }
    }

    return embedCount;
}