类javax.mail.internet.ContentType源码实例Demo

下面列出了怎么用javax.mail.internet.ContentType的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: ats-framework   文件: MimePackage.java

/**
 * 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);
    }
}
 
源代码2 项目: ats-framework   文件: MimePackage.java

/**
 * 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);
    }
}
 
源代码3 项目: ats-framework   文件: MimePackage.java

/**
 * 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);
    }
}
 
源代码4 项目: ats-framework   文件: MimePackage.java

/**
 * 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;
}
 
源代码7 项目: OpenAs2App   文件: BCCryptoHelper.java

public boolean isEncrypted(MimeBodyPart part) throws MessagingException {
    ContentType contentType = new ContentType(part.getContentType());
    String baseType = contentType.getBaseType().toLowerCase();

    if (baseType.equalsIgnoreCase("application/pkcs7-mime")) {
        String smimeType = contentType.getParameter("smime-type");
        boolean checkResult = (smimeType != null) && smimeType.equalsIgnoreCase("enveloped-data");
        if (!checkResult && logger.isDebugEnabled()) {
            logger.debug("Check for encrypted data failed on SMIME content type: " + smimeType);
        }
        return (checkResult);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Check for encrypted data failed on BASE content type: " + baseType);
    }
    return false;
}
 
源代码8 项目: OpenAs2App   文件: BCCryptoHelper.java

public boolean isCompressed(MimeBodyPart part) throws MessagingException {
    ContentType contentType = new ContentType(part.getContentType());
    String baseType = contentType.getBaseType().toLowerCase();

    if (logger.isTraceEnabled()) {
        try {
            logger.trace("Compression check.  MIME Base Content-Type:" + contentType.getBaseType());
            logger.trace("Compression check.  SMIME-TYPE:" + contentType.getParameter("smime-type"));
            logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Disposition:" + part.getDisposition());
        } catch (MessagingException e) {
            logger.trace("Compression check: no data available.");
        }
    }
    if (baseType.equalsIgnoreCase("application/pkcs7-mime")) {
        String smimeType = contentType.getParameter("smime-type");
        boolean checkResult = (smimeType != null) && smimeType.equalsIgnoreCase("compressed-data");
        if (!checkResult && logger.isDebugEnabled()) {
            logger.debug("Check for compressed data failed on SMIME content type: " + smimeType);
        }
        return (checkResult);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Check for compressed data failed on BASE content type: " + baseType);
    }
    return false;
}
 

/**
 * 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();
}
 
源代码10 项目: james-project   文件: FlowedMessageUtils.java

/**
 * If the message is <code>format=flowed</code> 
 * set the encoded version as message content.
 */
public static void deflowMessage(Message m) throws MessagingException, IOException {
    ContentType ct = new ContentType(m.getContentType());
    String format = ct.getParameter("format");
    if (ct.getBaseType().equals("text/plain") && format != null && format.equalsIgnoreCase("flowed")) {
        String delSp = ct.getParameter("delsp");
        String deflowed = deflow((String) m.getContent(), delSp != null && delSp.equalsIgnoreCase("yes"));
        
        ct.getParameterList().remove("format");
        ct.getParameterList().remove("delsp");
        
        if (ct.toString().contains("flowed")) {
            LOGGER.error("FlowedMessageUtils dind't remove the flowed correctly");
        }

        m.setContent(deflowed, ct.toString());
        m.saveChanges();
    }
}
 
源代码11 项目: james-project   文件: FlowedMessageUtils.java

/**
 * Encodes the message content (if text/plain).
 */
public static void flowMessage(Message m, boolean delSp, int width) throws MessagingException, IOException {
    ContentType ct = new ContentType(m.getContentType());
    if (!ct.getBaseType().equals("text/plain")) {
        return;
    }
    String format = ct.getParameter("format");
    String text = format != null && format.equals("flowed") ? deflow(m) : (String) m.getContent();
    String coded = flow(text, delSp, width);
    ct.setParameter("format", "flowed");
    if (delSp) {
        ct.setParameter("delsp", "yes");
    }
    m.setContent(coded, ct.toString());
    m.saveChanges();
}
 

/**
 * 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());
  }
}
 
源代码13 项目: commons-email   文件: MimeMessageParser.java

/**
 * 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
 * @throws MessagingException parsing the MimeMessage failed
 * @throws IOException        parsing the MimeMessage failed
 */
private boolean isMimeType(final MimePart part, final String mimeType)
    throws MessagingException, IOException
{
    // Do not use part.isMimeType(String) as it is broken for MimeBodyPart
    // and does not really check the actual content type.

    try
    {
        final ContentType ct = new ContentType(part.getDataHandler().getContentType());
        return ct.match(mimeType);
    }
    catch (final ParseException ex)
    {
        return part.getContentType().equalsIgnoreCase(mimeType);
    }
}
 
源代码14 项目: FairEmail   文件: text_plain.java

private String getCharset(String type) {
try {
    ContentType ct = new ContentType(type);
    String charset = ct.getParameter("charset");
    if (charset == null)
	// If the charset parameter is absent, use US-ASCII.
	charset = "us-ascii";
    return MimeUtility.javaCharset(charset);
} catch (Exception ex) {
    return null;
}
   }
 

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();
}
 
源代码16 项目: OpenAs2App   文件: DataHistory.java

boolean contains(ContentType type) {
    Iterator<DataHistoryItem> itemIt = getItems().iterator();

    while (itemIt.hasNext()) {
        DataHistoryItem item = itemIt.next();

        if ((item.getContentType() != null) && item.getContentType().match(type)) {
            return true;
        }
    }

    return false;
}
 

/**
 * 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")));
}
 
 类所在包
 同包方法