List of usage examples for javax.mail.internet ContentType ContentType
public ContentType(String s) throws ParseException
From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.RFC822ToTextConverter.java
protected static byte[] extractTextFromMessagePart(Part p) throws Exception { ContentType contentType = new ContentType(p.getContentType()); String baseType = contentType.getBaseType(); if (TXT_MT.equals(baseType)) { Object content = p.getContent(); if (content instanceof String) { return ((String) content).getBytes(); } else {//from w w w .j a v a2 s . c om return null; } } ConversionService cs = Framework.getLocalService(ConversionService.class); String converterName = cs.getConverterName(baseType, TXT_MT); if (converterName == null) { return null; } else { BlobHolder result = cs.convert(converterName, new SimpleBlobHolder(new FileBlob(p.getInputStream())), null); return result.getBlob().getByteArray(); } }
From source file:org.wso2.carbon.connector.util.ResultPayloadCreate.java
/** * @param file Read file//from w w w . ja v a 2 s . c o m * @param msgCtx Message Context * @param contentType content type * @param streaming streaming mode (true/false) * @return return the status * @throws SynapseException */ @SuppressWarnings("ResultOfMethodCallIgnored") public static boolean buildFile(FileObject file, MessageContext msgCtx, String contentType) throws SynapseException { ManagedDataSource dataSource = null; try { if (StringUtils.isEmpty(contentType) || StringUtils.isEmpty(contentType.trim())) { if (file.getName().getExtension().toLowerCase().endsWith("xml")) { contentType = "application/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 { charSetEnc = new ContentType(contentType).getParameter("charset"); } catch (ParseException ex) { log.warn("Invalid encoding type.", ex); } msgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); } if (log.isDebugEnabled()) { log.debug("Processed file : " + file + " of Content-type : " + contentType); } org.apache.axis2.context.MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx) .getAxis2MessageContext(); // Determine the message builder to use Builder builder; if (StringUtils.isEmpty(contentType)) { log.debug("No content type specified. Using RELAY builder."); builder = new BinaryRelayBuilder(); } else { int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx); if (builder == null) { if (log.isDebugEnabled()) { log.debug("No message builder found for type '" + type + "'. Falling back " + "to" + " RELAY builder."); } builder = new BinaryRelayBuilder(); } } // set the message payload to the message context InputStream in = null; in = new AutoCloseInputStream(file.getContent().getInputStream()); dataSource = null; // Inject the message to the sequence. OMElement documentElement; if (in != null) { documentElement = builder.processDocument(in, contentType, axis2MsgCtx); } else { documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType, axis2MsgCtx); } //We need this to build the complete message before closing the stream //noinspection ResultOfMethodCallIgnored documentElement.toString(); msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); } catch (SynapseException se) { throw se; } catch (Exception e) { log.error("Error while processing the file/folder", e); throw new SynapseException("Error while processing the file/folder", e); } finally { if (dataSource != null) { dataSource.destroy(); } } return true; }
From source file:org.apache.axis2.transport.amqp.common.AMQPUtils.java
/** * Set the SOAPEnvelope to the Axis2 MessageContext, from the AMQP Message * passed in/* w ww .j ava2 s.c o m*/ * * @param message * the AMQP message read * @param msgContext * the Axis2 MessageContext to be populated * @param contentType * content type for the message * @throws AxisFault * @throws AMQPException */ public static void setSOAPEnvelope(AMQPMessage message, MessageContext msgContext, String contentType) throws AxisFault, AMQPException { BasicProperties msg_prop = message.getProperties(); if (contentType == null) { contentType = msg_prop.getContentType(); log.debug("No content type specified; assuming " + contentType); } int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; Builder 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(); } OMElement documentElement; if (contentType.equals("application/octet-stream")) { // Extract the charset encoding from the 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 (builder instanceof DataSourceMessageBuilder) { documentElement = ((DataSourceMessageBuilder) builder) .processDocument(new ByteArrayInputStream(message.getBody()), contentType, msgContext); } else { documentElement = builder.processDocument(new ByteArrayInputStream(message.getBody()), contentType, msgContext); } } else if (contentType.equals("text/plain")) { TextMessageBuilder textMessageBuilder; if (builder instanceof TextMessageBuilder) { textMessageBuilder = (TextMessageBuilder) builder; } else { textMessageBuilder = new TextMessageBuilderAdapter(builder); } String content = new String(message.getBody()); documentElement = textMessageBuilder.processDocument(content, contentType, msgContext); } else { handleException("Unsupported AMQP message type " + message.getClass().getName()); return; // Make compiler happy } msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); }
From source file:com.vmware.identity.openidconnect.common.AuthenticationSuccessResponse.java
private HTTPResponse formPostResponse() throws SerializeException { HTTPResponse httpResponse = new HTTPResponse(HTTPResponse.SC_OK); try {/*from w w w. j a v a 2 s . co 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 form; if (super.getAuthorizationCode() != null) { form = String.format(FORM_AUTHZ_CODE, super.getRedirectionURI().toString(), super.getState().getValue(), super.getAuthorizationCode().getValue()); } else if (super.getIDToken() != null && super.getAccessToken() == null) { form = String.format(FORM_ID_TOKEN_ONLY, super.getRedirectionURI().toString(), super.getState().getValue(), super.getIDToken().serialize()); } else if (super.getIDToken() != null && super.getAccessToken() != null) { form = String.format(FORM_ID_TOKEN_ACCESS_TOKEN, super.getRedirectionURI().toString(), super.getState().getValue(), super.getIDToken().serialize(), super.getAccessToken().toString(), super.getAccessToken().getType().getValue(), super.getAccessToken().getLifetime()); } else { throw new IllegalArgumentException("unexpected authn success response"); } httpResponse.setContent(String.format(HTML_RESPONSE, form)); return httpResponse; }
From source file:org.wso2.carbon.inbound.endpoint.protocol.file.FileInjectHandler.java
/** * Inject the message to the sequence/*from w ww.j a v a 2 s. co m*/ * */ public boolean invoke(Object object, String name) throws SynapseException { ManagedDataSource dataSource = null; ; FileObject file = (FileObject) object; try { org.apache.synapse.MessageContext msgCtx = createMessageContext(); msgCtx.setProperty("inbound.endpoint.name", name); InboundEndpoint inboundEndpoint = msgCtx.getConfiguration().getInboundEndpoint(name); CustomLogSetter.getInstance().setLogAppender(inboundEndpoint.getArtifactContainerName()); String contentType = vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_CONTENT_TYPE); if (contentType == null || contentType.trim().equals("")) { 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 } msgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); } if (log.isDebugEnabled()) { log.debug("Processed file : " + file + " of Content-type : " + contentType); } MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx) .getAxis2MessageContext(); // 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, axis2MsgCtx); 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; String streaming = vfsProperties.getProperty(VFSConstants.STREAMING); if (builder instanceof DataSourceMessageBuilder && "true".equals(streaming)) { dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType)); in = null; } else { in = new AutoCloseInputStream(file.getContent().getInputStream()); dataSource = null; } //Inject the message to the sequence. OMElement documentElement; if (in != null) { documentElement = builder.processDocument(in, contentType, axis2MsgCtx); } else { documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType, axis2MsgCtx); } if ("true".equals(vfsProperties.getProperty(VFSConstants.TRANSPORT_BUILD))) { documentElement.build(); } msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); if (injectingSeq == null || injectingSeq.equals("")) { log.error("Sequence name not specified. Sequence : " + injectingSeq); } SequenceMediator seq = (SequenceMediator) synapseEnvironment.getSynapseConfiguration() .getSequence(injectingSeq); if (seq != null) { if (log.isDebugEnabled()) { log.debug("injecting message to sequence : " + injectingSeq); } if (!seq.isInitialized()) { seq.init(synapseEnvironment); } seq.setErrorHandler(onErrorSeq); if (!synapseEnvironment.injectInbound(msgCtx, seq, sequential)) { return false; } } else { log.error("Sequence: " + injectingSeq + " not found"); } } catch (SynapseException se) { throw se; } catch (Exception e) { log.error("Error while processing the file/folder", e); throw new SynapseException("Error while processing the file/folder", e); } finally { if (dataSource != null) { dataSource.destroy(); } } return true; }
From source file:com.predic8.membrane.core.multipart.XOPReconstitutor.java
/** * @return reassembled SOAP message or null if message is not SOAP or not multipart *//*from w w w . ja v a 2s . c o m*/ public Message getReconstitutedMessage(Message message) throws ParseException, MalformedStreamException, IOException, EndOfStreamException, XMLStreamException, FactoryConfigurationError { ContentType contentType = message.getHeader().getContentTypeObject(); if (contentType == null || contentType.getPrimaryType() == null) return null; if (!contentType.getPrimaryType().equals("multipart") || !contentType.getSubType().equals("related")) return null; String type = contentType.getParameter("type"); if (!"application/xop+xml".equals(type)) return null; String start = contentType.getParameter("start"); if (start == null) return null; String boundary = contentType.getParameter("boundary"); if (boundary == null) return null; HashMap<String, Part> parts = split(message, boundary); Part startPart = parts.get(start); if (startPart == null) return null; ContentType innerContentType = new ContentType(startPart.getHeader().getContentType()); if (!innerContentType.getPrimaryType().equals("application") || !innerContentType.getSubType().equals("xop+xml")) return null; byte[] body = fillInXOPParts(startPart.getInputStream(), parts); Message m = new Message() { @Override protected void parseStartLine(InputStream in) throws IOException, EndOfStreamException { throw new RuntimeException("not implemented."); } @Override public String getStartLine() { throw new RuntimeException("not implemented."); } }; m.setBodyContent(body); String reconstitutedContentType = innerContentType.getParameter("type"); if (reconstitutedContentType != null) m.getHeader().add(Header.CONTENT_TYPE, reconstitutedContentType); return m; }
From source file:org.apache.axis2.transport.jms.JMSUtils.java
/** * Set the SOAPEnvelope to the Axis2 MessageContext, from the JMS Message passed in * @param message the JMS message read// w w w .j av a 2 s . c o m * @param msgContext the Axis2 MessageContext to be populated * @param contentType content type for the message * @throws AxisFault * @throws JMSException */ public static void setSOAPEnvelope(Message message, MessageContext msgContext, String contentType) throws AxisFault, JMSException { if (contentType == null) { if (message instanceof TextMessage) { contentType = "text/plain"; } else { contentType = "application/octet-stream"; } if (log.isDebugEnabled()) { log.debug("No content type specified; assuming " + contentType); } } int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; Builder 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(); } OMElement documentElement; if (message instanceof BytesMessage) { // Extract the charset encoding from the 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 (builder instanceof DataSourceMessageBuilder) { documentElement = ((DataSourceMessageBuilder) builder).processDocument( new BytesMessageDataSource((BytesMessage) message), contentType, msgContext); } else { documentElement = builder.processDocument(new BytesMessageInputStream((BytesMessage) message), contentType, msgContext); } } else if (message instanceof TextMessage) { TextMessageBuilder textMessageBuilder; if (builder instanceof TextMessageBuilder) { textMessageBuilder = (TextMessageBuilder) builder; } else { textMessageBuilder = new TextMessageBuilderAdapter(builder); } String content = ((TextMessage) message).getText(); documentElement = textMessageBuilder.processDocument(content, contentType, msgContext); } else { handleException("Unsupported JMS message type " + message.getClass().getName()); return; // Make compiler happy } msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); }
From source file:immf.Util.java
public static void setFileName(Part part, String filename, String charset, String lang) throws MessagingException { ContentDisposition disposition;// w w w . j a v a 2s. c om String[] strings = part.getHeader("Content-Disposition"); if (strings == null || strings.length < 1) { disposition = new ContentDisposition(Part.ATTACHMENT); } else { disposition = new ContentDisposition(strings[0]); disposition.getParameterList().remove("filename"); } part.setHeader("Content-Disposition", disposition.toString() + encodeParameter("filename", filename, charset, lang)); ContentType cType; strings = part.getHeader("Content-Type"); if (strings == null || strings.length < 1) { cType = new ContentType(part.getDataHandler().getContentType()); } else { cType = new ContentType(strings[0]); } try { // I want to public the MimeUtility#doEncode()!!! String mimeString = MimeUtility.encodeWord(filename, charset, "B"); // cut <CRLF>... StringBuffer sb = new StringBuffer(); int i; while ((i = mimeString.indexOf('\r')) != -1) { sb.append(mimeString.substring(0, i)); mimeString = mimeString.substring(i + 2); } sb.append(mimeString); cType.setParameter("name", new String(sb)); } catch (UnsupportedEncodingException e) { throw new MessagingException("Encoding error", e); } part.setHeader("Content-Type", cType.toString()); }
From source file:com.cubusmail.server.mail.MessageHandler.java
/** * @param session/*ww w . j ava 2s . co m*/ * @param message */ public void init(Session session, MimeMessage message) { this.session = session; this.message = message; try { this.readBefore = this.message.isSet(Flag.SEEN); String contentType = message.getContentType(); ContentType type = new ContentType(contentType); String charset = type.getParameter("charset"); if (charset != null) { this.charset = charset; } else { // this.message.setHeader( name, value ) } } catch (MessagingException e) { log.warn(e.getMessage()); } }
From source file:mailbox.CreationViaEmail.java
@Transactional public static Issue saveIssue(String subject, Project project, User sender, Content parsedMessage, String messageId, Address[] recipients) throws MessagingException, IOException, NoSuchAlgorithmException { Issue issue = new Issue(project, sender, subject, parsedMessage.body); issue.save();//from w w w. j a va 2s . c om Map<String, Attachment> relatedAttachments = saveAttachments(parsedMessage.attachments, issue.asResource()); if (new ContentType(parsedMessage.type).match(MimeType.HTML)) { issue.refresh(); issue.body = postprocessForHTML(issue.body, relatedAttachments); issue.update(); } new OriginalEmail(messageId, issue.asResource()).save(); // Add the event NotificationEvent event = NotificationEvent.forNewIssue(issue, sender); addEvent(event, recipients, sender); return issue; }