private Object getContent(final Part part, final ContentType contentType) throws MessagingException, IOException { try { return part.getContent(); } catch (IOException e) { if (isPlainText(contentType)) { final InputStream rawInputStream; if (part instanceof MimeMessage) { rawInputStream = ((MimeMessage) part).getRawInputStream(); } else if (part instanceof MimeBodyPart) { rawInputStream = ((MimeBodyPart) part).getRawInputStream(); } else { throw new ParseException("Unexpected part: " + part); } return new String(ByteStreams.toByteArray(rawInputStream), getCharset(contentType)); } } throw new ParseException("No content"); }
/** * Get the content type of a regular part * * @param partIndex * the index of the regular part * @return the content type as string * @throws PackageException */ @PublicAtsApi public String getRegularPartContentType( int partIndex ) throws PackageException { // first check if there is part at this position at all if (partIndex >= regularPartIndices.size()) { throw new NoSuchMimePartException("No regular part at position '" + partIndex + "'"); } try { MimePart part = getPart(regularPartIndices.get(partIndex)); // get the content type header ContentType contentType = new ContentType(part.getContentType()); return contentType.getBaseType(); } catch (MessagingException me) { throw new PackageException(me); } }
/** * Get the character set of a regular part * * @param partIndex * the index of the part * @return the charset * @throws PackageException */ @PublicAtsApi public String getRegularPartCharset( int partIndex ) throws PackageException { // first check if there is part at this position at all if (partIndex >= regularPartIndices.size()) { throw new NoSuchMimePartException("No regular part at position '" + partIndex + "'"); } try { MimePart part = getPart(regularPartIndices.get(partIndex)); // get the content type header ContentType contentType = new ContentType(part.getContentType()); return contentType.getParameter("charset"); } catch (MessagingException me) { throw new PackageException(me); } }
/** * Get the attachment content type * * @param partIndex * @return * @throws PackageException */ @PublicAtsApi public String getAttachmentContentType( int partIndex ) throws PackageException { // first check if there is part at this position at all if (partIndex >= attachmentPartIndices.size()) { throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'"); } try { MimePart part = getPart(attachmentPartIndices.get(partIndex)); // get the content type header ContentType contentType = new ContentType(part.getContentType()); return contentType.getBaseType(); } catch (MessagingException me) { throw new PackageException(me); } }
/** * Get the attachment character set * * @param partIndex * the index of the attachment * @return the character set for this attachment, null if there is no such * @throws PackageException */ @PublicAtsApi public String getAttachmentCharset( int partIndex ) throws PackageException { // first check if there is part at this position at all if (partIndex >= attachmentPartIndices.size()) { throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'"); } try { MimePart part = getPart(attachmentPartIndices.get(partIndex)); // get the content type header ContentType contentType = new ContentType(part.getContentType()); return contentType.getParameter("charset"); } catch (MessagingException me) { throw new PackageException(me); } }
@Override public void applyTo(final HTTPRequest httpRequest) { if (httpRequest.getMethod() != HTTPRequest.Method.GET) throw new SerializeException("The HTTP request method must be GET"); ContentType ct = httpRequest.getContentType(); if (ct == null) throw new SerializeException("Missing HTTP Content-Type header"); if (! ct.match(CommonContentTypes.APPLICATION_URLENCODED)) throw new SerializeException("The HTTP Content-Type header must be " + CommonContentTypes.APPLICATION_URLENCODED); Map<String,String> params = httpRequest.getQueryParameters(); params.putAll(toParameters()); String queryString = URLUtils.serializeParameters(params); httpRequest.setQuery(queryString); }
private String getTextFromMimeMultipart( MimeMultipart mimeMultipart ) throws IOException, MessagingException { int count = mimeMultipart.getCount(); if ( count == 0 ) throw new MessagingException( "Multipart with no body parts not supported." ); boolean multipartAlt = new ContentType( mimeMultipart.getContentType() ).match( "multipart/alternative" ); if ( multipartAlt ) return getTextFromBodyPart( mimeMultipart.getBodyPart( count - 1 ) ); String result = ""; for ( int i = 0; i < count; i++ ) { BodyPart bodyPart = mimeMultipart.getBodyPart( i ); result += getTextFromBodyPart( bodyPart ); } return result; }
public static void printAllTextPlainMessages(final Folder folder) throws MessagingException, IOException { for (final Message m : folder.getMessages()) { System.out.println("\nNachricht:"); System.out.println("Von: " + Arrays.toString(m.getFrom())); System.out.println("Betreff: " + m.getSubject()); System.out.println("Gesendet am: " + m.getSentDate()); System.out.println("Content-Type: " + new ContentType(m.getContentType())); if (m.isMimeType("text/plain")) { System.out.println(m.getContent()); } } }
/** * Attempt to repair the given contentType if broken. * @param mp Mimepart holding the contentType * @param contentType ContentType * @return fixed contentType String * @throws MessagingException */ public static String cleanContentType(MimePart mp, String contentType) throws MessagingException { ContentType ct = parseContentType(contentType); if (ct == null) { ct = getParsableContentType(contentType); } if (ct.getBaseType().equalsIgnoreCase("text/plain") || ct.getBaseType().equalsIgnoreCase("text/html")) { Charset charset = parseCharset(ct); if (charset == null) { Logger.debug("Charset of the ContentType could not be read, try to decode the contentType as quoted-printable"); ContentType ctTmp = decodeContentTypeAsQuotedPrintable(contentType); if (parseCharset(ctTmp) != null) { ct = ctTmp; } else { ct.setParameter("charset", ContentTypeCleaner.DEFAULT_CHARSET); } } } return ct.toString(); }
public OMElement processDocument(Reader reader, String contentType, MessageContext messageContext) throws AxisFault { String charset; 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); }
public XMLMessage decode(ContentType contentType, AxisMessage message) throws Exception { Attachments attachments = message.getAttachments(); XMLMessage.Type type; if (attachments != null) { type = XMLMessage.Type.SWA; } else { type = null; for (XMLMessage.Type candidate : XMLMessage.Type.values()) { if (candidate.getContentType().equals(message.getMessageType())) { type = candidate; break; } } if (type == null) { // TODO: make this an error later type = XMLMessage.Type.POX; // throw new UnsupportedOperationException("Content type " + message.getMessageType() + " not supported"); } } return new XMLMessage(message.getEnvelope().getBody().getFirstElement(), type, attachments); }
public MessageTestCase(TestClient client, ContentType contentType, String charset, Object... resources) { super(resources); if (client instanceof Adapter) { addResource(((Adapter)client).getTarget()); } else { addResource(client); } this.contentType = contentType; try { options = new ClientOptions(client, contentType, charset); } catch (Exception ex) { // TODO: handle this in a better way throw new Error(ex); } addResource(options); addResource(this); }
/** * Extract the text content for a {@link BodyPart}, assuming the default * encoding. */ public static String getTextContent(BodyPart part) throws MessagingException, IOException { ContentType contentType = new ContentType(part.getContentType()); String charset = contentType.getParameter("charset"); if (charset == null) { // N.B.(schwardo): The MIME spec doesn't seem to provide a // default charset, but the default charset for HTTP is // ISO-8859-1. That seems like a reasonable default. charset = "ISO-8859-1"; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteStreams.copy(part.getInputStream(), baos); try { return new String(baos.toByteArray(), charset); } catch (UnsupportedEncodingException ex) { return new String(baos.toByteArray()); } }
/** * Helper function to create multi-part MIME * * @param entity the body of a request * @param entityContentType content type of the body * @param query a query part of a request * * @return a ByteString that represents a multi-part encoded entity that contains both */ private static MimeMultipart createMultiPartEntity(ByteString entity, String entityContentType, String query) throws MessagingException { MimeMultipart multi = new MimeMultipart(MIXED); // Create current entity with the associated type MimeBodyPart dataPart = new MimeBodyPart(); ContentType contentType = new ContentType(entityContentType); dataPart.setContent(entity.copyBytes(), contentType.getBaseType()); dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType); // Encode query params as form-urlencoded MimeBodyPart argPart = new MimeBodyPart(); argPart.setContent(query, FORM_URL_ENCODED); argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED); multi.addBodyPart(argPart); multi.addBodyPart(dataPart); return multi; }
private void updateContentType(boolean cleanDefaultRoot) throws MessagingException { BodyPart part = null; if (rootId == null) { part = getBodyPart(0); } else { part = getBodyPart(rootId); if (part == null) { if (cleanDefaultRoot) rootId = null; else throw new MessagingException("Can not set root: " + rootId + ": not found"); } } if (part != null) { String primaryType = baseContentTypeObject.getPrimaryType(); String subType = baseContentTypeObject.getSubType(); ParameterList params = baseContentTypeObject.getParameterList(); ContentType newContentType = new ContentType(primaryType, subType, params); ContentType rootContentType = new ContentType(part.getDataHandler().getContentType()); newContentType.setParameter("type", rootContentType.getBaseType()); if (rootId != null) newContentType.setParameter("start", stripBrackets(rootId)); contentType = newContentType.toString(); } }
private void parseContents( @Nonnull final UpdateContext updateContext, @Nonnull final MailMessageBuilder messageBuilder, @Nonnull final MimeMessage message) throws MessagingException, IOException { final MessageParts messageParts = new MessageParts(); parseContents(updateContext, messageParts, message, null); for (final MessagePart messagePart : messageParts.parts) { final List<Credential> credentials = messagePart.credentials; if (credentials.size() > 1) { throw new ParseException("Multiple credentials for text content"); } final Charset charset = getCharset(new ContentType(message.getContentType())); messageBuilder.addContentWithCredentials(new ContentWithCredentials(messagePart.text, credentials, charset)); } }
String getContent(final Part part) throws MessagingException { try (InputStream inputStream = part.getInputStream()) { return new String(ByteStreams.toByteArray(inputStream), getCharset(new ContentType(part.getContentType()))); } catch (IOException e) { throw new MessagingException("Unable to read body part", e); } }
public AlfrescoMimeMultipart(String subtype, FileInfo messageFileInfo) { super(); String boundary = getBoundaryValue(messageFileInfo); ContentType cType = new ContentType("multipart", subtype, null); cType.setParameter("boundary", boundary); contentType = cType.toString(); }
public SoapMimeMultipart (@Nonnull final ESOAPVersion eSOAPVersion, @Nonnull final Charset aCharset) throws ParseException { super ("related"); // type parameter is essential for Axis to work! // But no charset! RFC 2387, section 3.4 has a special definition final ContentType aContentType = new ContentType (contentType); aContentType.setParameter ("type", eSOAPVersion.getMimeType ().getAsString ()); aContentType.setParameter ("charset", aCharset.name ()); contentType = aContentType.toString (); }
/** * @param type the type of the content * @param content the content to return * @param statusCode the status code to return */ public ContentResponse(ContentType type, String content, int statusCode) { this.httpResponse = new HTTPResponse(statusCode); this.httpResponse.setContentType(type); this.httpResponse.setContent(content); }
private ContentType getContentType(Exchange exchange) throws ParseException { String contentTypeStr = ExchangeHelper.getContentType(exchange); if (contentTypeStr == null) { contentTypeStr = DEFAULT_CONTENT_TYPE; } ContentType contentType = new ContentType(contentTypeStr); String contentEncoding = ExchangeHelper.getContentEncoding(exchange); // add a charset parameter for text subtypes if (contentEncoding != null && contentType.match("text/*")) { contentType.setParameter("charset", MimeUtility.mimeCharset(contentEncoding)); } return contentType; }
private void writeBodyPart(byte[] bodyContent, Part part, ContentType contentType) throws MessagingException { DataSource ds = new ByteArrayDataSource(bodyContent, contentType.toString()); part.setDataHandler(new DataHandler(ds)); part.setHeader(CONTENT_TYPE, contentType.toString()); if (contentType.match("text/*")) { part.setHeader(CONTENT_TRANSFER_ENCODING, "8bit"); } else if (binaryContent) { part.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); } else { part.setHeader(CONTENT_TRANSFER_ENCODING, "base64"); } }
/** * Checks whether the MimePart contains an object of the given mime type. * * @param part the current MimePart * @param mimeType the mime type to check * @return {@code true} if the MimePart matches the given mime type, {@code false} otherwise */ @SuppressWarnings("WeakerAccess") public static boolean isMimeType(@Nonnull final MimePart part, @Nonnull final String mimeType) { // Do not use part.isMimeType(String) as it is broken for MimeBodyPart // and does not really check the actual content type. try { final ContentType contentType = new ContentType(retrieveDataHandler(part).getContentType()); return contentType.match(mimeType); } catch (final ParseException ex) { return retrieveContentType(part).equalsIgnoreCase(mimeType); } }
/** * Try to parse the given contentType String into a ContentType instance. * @param contentType * @return new ContentType instance, or null if not parsable */ private static ContentType parseContentType(String contentType) { try { return new ContentType(contentType); } catch (ParseException e) { return null; } }
/** * Try to parse the charset parameter of the ContentType into a Charset instance. * @param contentType * @return new Charset instance, or null if not parsable */ private static Charset parseCharset(ContentType ct) { try { return Charset.forName(ct.getParameter("charset")); } catch (Exception e) { return null; } }
/** * Try to decode the contentType String as quoted-printable String into a ContentType. * @param contentType * @return new ContentType instance or null */ private static ContentType decodeContentTypeAsQuotedPrintable(String contentType) { try { ByteArrayInputStream baos = new ByteArrayInputStream(contentType.getBytes("utf-8")); InputStream decode = MimeUtility.decode(baos, "quoted-printable"); String contentTypeString = new String(ByteStreams.toByteArray(decode), "utf-8"); return new ContentType(contentTypeString); } catch (Exception e) { return null; } }
/** * Check if the contentType can be parsed. If not return a fixed version. * When thats not possible return a default contentType string. * @param contentType * @return Fixed contentType string or default * @throws ParseException */ private static ContentType getParsableContentType(String contentType) throws ParseException { Logger.debug("Encountered an unparsable contenttype, try to fix it."); // we can't fix an empty contentType, fallback to default if (Strings.isNullOrEmpty(contentType)) { Logger.debug("ContentType empty, fallback to \"%s\"", DEFAULT_CONTENTTYPE); return new ContentType(DEFAULT_CONTENTTYPE); } ContentType tmp = parseContentType(fixContentType_semicolonSequenceInParams(contentType)); if (tmp != null) { Logger.debug("Fix succeeded (1)"); return tmp; } tmp = parseContentType(fixContentType_colonAsParamDelim(contentType)); if (tmp != null) { Logger.debug("Fix succeeded (2)"); return tmp; } // Neither did work, lets try to use clean1 and clean2 in conjunction tmp = parseContentType(fixContentType_semicolonSequenceInParams(fixContentType_colonAsParamDelim(contentType))); if (tmp != null) { Logger.debug("Fix succeeded (1&2)"); return tmp; } // this is a rather desperate approach but lets try it nevertheless tmp = parseContentType(fixContentType_findByBruteForce(contentType)); if (tmp != null) { Logger.debug("Fix succeeded (3)"); return tmp; } Logger.debug("Encountered broken ContentType, fallback to default: %s", DEFAULT_CONTENTTYPE); return new ContentType(DEFAULT_CONTENTTYPE); }
@Test public void cleanContentType_empty() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "")); assertThat(ContentTypeCleaner.DEFAULT_BASETYPE, equalToIgnoringCase(contentType.getBaseType())); assertThat(ContentTypeCleaner.DEFAULT_CHARSET, equalToIgnoringCase(contentType.getParameter("charset"))); }
@Test public void cleanContentType_semicolonSequenceInParameterList() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; ;;;; ;;; charset=\"utf-16\" ;;;;")); assertThat("text/html", equalToIgnoringCase(contentType.getBaseType())); assertThat("utf-16", equalToIgnoringCase(contentType.getParameter("charset"))); }
@Test public void cleanContentType_colonInsteadOfEqualSign() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; charset:\"utf-16\"")); assertThat("text/html", equalToIgnoringCase(contentType.getBaseType())); assertThat("utf-16", equalToIgnoringCase(contentType.getParameter("charset"))); }
@Test public void cleanContentType_semicolonSequenceInParameterListAndColonInsteadOfEqualSign() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; ;;;; charset:\"utf-16\" ;;;;")); assertThat("text/html", equalToIgnoringCase(contentType.getBaseType())); assertThat("utf-16", equalToIgnoringCase(contentType.getParameter("charset"))); }
@Test public void cleanContentType_typeAndCharsetMissing() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "%%% text/html;")); assertThat("text/html", equalToIgnoringCase(contentType.getBaseType())); assertThat(ContentTypeCleaner.DEFAULT_CHARSET, equalToIgnoringCase(contentType.getParameter("charset"))); }
@Test public void cleanContentType_typeAndCharsetSomewhereHtml() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; utf-16")); assertThat("text/html", equalToIgnoringCase(contentType.getBaseType())); assertThat("utf-16", equalToIgnoringCase(contentType.getParameter("charset"))); }
@Test public void cleanContentType_typeAndCharsetSomewherePlainAndCharsetAlias() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/plain; latin1")); assertThat("text/plain", equalToIgnoringCase(contentType.getBaseType())); assertThat("ISO-8859-1", equalToIgnoringCase(contentType.getParameter("charset"))); }
@Test public void cleanContentType_quotedPrintable() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; charset=3Dutf-16")); assertThat("text/html", equalToIgnoringCase(contentType.getBaseType())); assertThat("utf-16", equalToIgnoringCase(contentType.getParameter("charset"))); }
@Test public void cleanContentType_noCharset() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html;")); assertThat("text/html", equalToIgnoringCase(contentType.getBaseType())); assertThat(ContentTypeCleaner.DEFAULT_CHARSET, equalToIgnoringCase(contentType.getParameter("charset"))); }
@Test public void cleanContentType_unknownCharset() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; charset=ABCDEF")); assertThat("text/html", equalToIgnoringCase(contentType.getBaseType())); assertThat(ContentTypeCleaner.DEFAULT_CHARSET, equalToIgnoringCase(contentType.getParameter("charset"))); }
@Test public void cleanContentType_brokenContentType() throws MessagingException { ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "BROKEN_STRING")); assertThat(ContentTypeCleaner.DEFAULT_BASETYPE, equalToIgnoringCase(contentType.getBaseType())); assertThat(ContentTypeCleaner.DEFAULT_CHARSET, equalToIgnoringCase(contentType.getParameter("charset"))); }
@Override public boolean handleInbound(SOAPMessageContext msgContext) { log.info("handleInbound"); ContentType contentType = getContentType(msgContext); if (contentType != null) { log.info("contentType="+contentType); String startInfo = contentType.getParameter("start-info"); if (!startInfo.equals(SOAPConstants.SOAP_1_1_CONTENT_TYPE)) { return false; } } else { return false; } try { SOAPEnvelope soapEnvelope = ((SOAPMessageContext)msgContext).getMessage().getSOAPPart().getEnvelope(); String nsURI = soapEnvelope.getNamespaceURI(); log.info("nsURI=" + nsURI); if (!SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE.equals(nsURI)) { return false; } } catch (SOAPException se) { throw new WebServiceException(se); } return true; }