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:org.apache.synapse.registry.RegistryEntryImpl.java

public void setType(String type) {
    try {/*from  w  w  w.  ja v  a2s .c  o m*/
        new ContentType(type);
        if (log.isDebugEnabled()) {
            log.debug("Content type :" + type);
        }
        this.type = type;
    } catch (ParseException e) {
        String msg = "Invalid content-type ' " + type + " '";
        throw new SynapseException(msg, e);
    }
}

From source file:com.google.caja.plugin.DataUriFetcher.java

private String charsetFromMime(String mime) {
    String charset;/* w  ww . jav  a2 s.c o m*/
    try {
        ContentType parsedType = new ContentType(mime);
        charset = parsedType.getParameter("charset");
    } catch (ParseException e) {
        charset = null;
    }
    if (null == charset || "".equals(charset)) {
        return DATA_URI_DEFAULT_CHARSET;
    } else {
        return charset;
    }
}

From source file:mailbox.CreationViaEmail.java

/**
 * Create a comment from the given email.
 *
 * @param message/*from   w  ww. j  av a  2  s. com*/
 * @param target
 * @throws MessagingException
 * @throws MailHandlerException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
@Transactional
public static Comment saveComment(IMAPMessage message, Resource target)
        throws MessagingException, MailHandlerException, IOException, NoSuchAlgorithmException {
    User author = IMAPMessageUtil.extractSender(message);

    if (!AccessControl.isProjectResourceCreatable(author, target.getProject(), target.getType())) {
        throw new PermissionDenied(cannotCreateMessage(author, target.getProject(), target.getType()));
    }

    Content parsedMessage = extractContent(message);

    Comment comment = makeNewComment(target, author, parsedMessage.body);

    comment.save();

    Map<String, Attachment> relatedAttachments = saveAttachments(parsedMessage.attachments,
            comment.asResource());

    if (new ContentType(parsedMessage.type).match(MimeType.HTML)) {
        comment.contents = postprocessForHTML(comment.contents, relatedAttachments);
        comment.update();
    }

    new OriginalEmail(message.getMessageID(), comment.asResource()).save();

    // Add the event
    addEvent(NotificationEvent.forNewComment(comment, author), message.getAllRecipients(), author);

    return comment;
}

From source file:org.apache.axis2.format.TextMessageBuilderAdapter.java

public OMElement processDocument(Reader reader, String contentType, MessageContext messageContext)
        throws AxisFault {
    String charset;/*from w w w.j a v  a  2 s  . co m*/
    try {
        ContentType ct = new ContentType(contentType);
        charset = ct.getParameter("charset");
    } catch (ParseException ex) {
        charset = null;
    }
    if (charset == null) {
        charset = MessageContext.DEFAULT_CHAR_SET_ENCODING;
    }
    messageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charset);
    return processDocument(new ReaderInputStream(reader, charset), contentType, messageContext);
}

From source file:com.cubusmail.gwtui.server.services.ShowMessageSourceServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from w  w w  .  j av a2s  .co  m
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                logger.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.cubusmail.server.services.ShowMessageSourceServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*  ww w.j a  v a2  s . c  o  m*/
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                log.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.vmware.identity.openidconnect.common.LogoutSuccessResponse.java

@Override
public HTTPResponse toHTTPResponse() throws SerializeException {
    HTTPResponse httpResponse = new HTTPResponse(HTTPResponse.SC_OK);

    try {// w ww.j  a  v a2  s .  c o  m
        httpResponse.setContentType(new ContentType("text/html;charset=UTF-8"));
    } catch (ParseException e) {
        throw new SerializeException("could not set response type header", e);
    }

    httpResponse.setCacheControl("no-cache, no-store");
    httpResponse.setPragma("no-cache");

    String postLogoutRedirectUriWithState = "";
    if (this.postLogoutRedirectUri != null) {
        postLogoutRedirectUriWithState = (this.state == null) ? this.postLogoutRedirectUri.toString()
                : CommonUtils.appendQueryParameter(this.postLogoutRedirectUri, "state", this.state.getValue());
    }

    StringBuilder logoutUriImageLinks = new StringBuilder();
    for (URI logoutUri : this.logoutUris) {
        String logoutUriWithSid = CommonUtils.appendQueryParameter(logoutUri, "sid", this.sessionId.getValue());
        logoutUriImageLinks.append(String.format("<img src=\"%s\">", logoutUriWithSid));
    }

    httpResponse.setContent(
            String.format(HTML_RESPONSE, postLogoutRedirectUriWithState, logoutUriImageLinks.toString()));

    return httpResponse;
}

From source file:com.vmware.identity.openidconnect.common.AuthenticationErrorResponse.java

private static HTTPResponse ajaxRedirectResponse(URI redirectLocation) throws SerializeException {
    HTTPResponse httpResponse = new HTTPResponse(HTTPResponse.SC_OK);

    try {//from  ww w  . j a va2  s . c  o  m
        httpResponse.setContentType(new ContentType("text/html;charset=UTF-8"));
    } catch (ParseException e) {
        throw new SerializeException("could not set response type header", e);
    }

    httpResponse.setCacheControl("no-cache, no-store");
    httpResponse.setPragma("no-cache");
    httpResponse.setContent(redirectLocation.toString());

    return httpResponse;
}

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

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

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

From source file:com.cubusmail.gwtui.server.services.RetrieveAttachmentServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(request.getSession().getServletContext());

    try {//from  ww w .j  ava2 s . c  o m
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean view = "1".equals(request.getParameter("view"));

        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
            int index = Integer.valueOf(attachmentIndex);

            MimePart retrievePart = attachmentList.get(index);

            ContentType contentType = new ContentType(retrievePart.getContentType());

            String fileName = retrievePart.getFileName();
            if (StringUtils.isEmpty(fileName)) {
                fileName = context.getMessage("message.unknown.attachment", null,
                        SessionManager.get().getLocale());
            }
            StringBuffer contentDisposition = new StringBuffer();
            if (!view) {
                contentDisposition.append("attachment; filename=\"");
                contentDisposition.append(fileName).append("\"");
            }

            response.setHeader("cache-control", "no-store");
            response.setHeader("pragma", "no-cache");
            response.setIntHeader("max-age", 0);
            response.setIntHeader("expires", 0);

            if (!StringUtils.isEmpty(contentDisposition.toString())) {
                response.setHeader("Content-disposition", contentDisposition.toString());
            }
            response.setContentType(contentType.getBaseType());
            // response.setContentLength(
            // MessageUtils.calculateSizeFromPart( retrievePart ) );

            BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream());
            OutputStream outputStream = response.getOutputStream();

            byte[] inBuf = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = bufInputStream.read(inBuf)) > 0) {
                outputStream.write(inBuf, 0, len);
                total += len;
            }

            bufInputStream.close();
            outputStream.flush();
            outputStream.close();

        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}