Java Code Examples for javax.mail.internet.ContentType#getParameter()

The following examples show how to use javax.mail.internet.ContentType#getParameter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 2
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 3
Source File: BCCryptoHelper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
}
 
Example 4
Source File: BCCryptoHelper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
}
 
Example 5
Source File: FlowedMessageUtils.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 6
Source File: FlowedMessageUtils.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 7
Source File: MultipartMimeUtils.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
  }
}
 
Example 8
Source File: text_plain.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
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;
}
   }
 
Example 9
Source File: DataUriFetcher.java    From caja with Apache License 2.0 5 votes vote down vote up
private static String charsetFromMime(String mime) {
  String charset;
  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;
  }
}
 
Example 10
Source File: FlowedMessageUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains the content of the encoded message, if previously encoded as <code>format=flowed</code>.
 */
public static String deflow(Message m) throws IOException, MessagingException {
    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");
        return deflow((String) m.getContent(), delSp != null && delSp.equalsIgnoreCase("yes"));
        
    } else if (ct.getPrimaryType().equals("text")) {
        return (String) m.getContent();
    } else {
        return null;
    }
}
 
Example 11
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
String[] getReferences() throws MessagingException {
    ensureMessage(false);

    List<String> result = new ArrayList<>();
    String refs = imessage.getHeader("References", null);
    if (refs != null)
        result.addAll(Arrays.asList(getReferences(refs)));

    try {
        // Merge references of original message for threading
        if (imessage.isMimeType("multipart/report")) {
            ContentType ct = new ContentType(imessage.getContentType());
            String reportType = ct.getParameter("report-type");
            if ("delivery-status".equalsIgnoreCase(reportType) ||
                    "disposition-notification".equalsIgnoreCase(reportType)) {
                String arefs = null;
                String amsgid = null;

                MessageParts parts = new MessageParts();
                getMessageParts(imessage, parts, null);
                for (AttachmentPart apart : parts.attachments)
                    if ("text/rfc822-headers".equalsIgnoreCase(apart.attachment.type)) {
                        InternetHeaders iheaders = new InternetHeaders(apart.part.getInputStream());
                        arefs = iheaders.getHeader("References", null);
                        amsgid = iheaders.getHeader("Message-Id", null);
                        break;
                    } else if ("message/rfc822".equalsIgnoreCase(apart.attachment.type)) {
                        Properties props = MessageHelper.getSessionProperties();
                        Session isession = Session.getInstance(props, null);
                        MimeMessage amessage = new MimeMessage(isession, apart.part.getInputStream());
                        arefs = amessage.getHeader("References", null);
                        amsgid = amessage.getHeader("Message-Id", null);
                        break;
                    }

                if (arefs != null)
                    for (String ref : getReferences(arefs))
                        if (!result.contains(ref)) {
                            Log.i("rfc822 ref=" + ref);
                            result.add(ref);
                        }

                if (amsgid != null) {
                    String msgid = MimeUtility.unfold(amsgid);
                    if (!result.contains(msgid)) {
                        Log.i("rfc822 id=" + msgid);
                        result.add(msgid);
                    }
                }
            }
        }
    } catch (Throwable ex) {
        Log.w(ex);
    }

    return result.toArray(new String[0]);
}
 
Example 12
Source File: FlowedMessageUtils.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Checks whether the input message is <code>format=flowed</code>.
 */
public static boolean isFlowedTextMessage(Message m) throws MessagingException {
    ContentType ct = new ContentType(m.getContentType());
    String format = ct.getParameter("format");
    return ct.getBaseType().equals("text/plain") && format != null && format.equalsIgnoreCase("flowed");
}
 
Example 13
Source File: ContentReplacer.java    From james-project with Apache License 2.0 4 votes vote down vote up
private String previousCharset(Mail mail) throws MessagingException {
    ContentType contentType = new ContentType(mail.getMessage().getContentType());
    return contentType.getParameter("Charset");
}
 
Example 14
Source File: ParseBlobUploadFilter.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) request;
  if (req.getHeader(UPLOAD_HEADER) != null) {
    Map<String, List<String>> blobKeys = new HashMap<String, List<String>>();
    Map<String, List<Map<String, String>>> blobInfos =
        new HashMap<String, List<Map<String, String>>>();
    Map<String, List<String>> otherParams = new HashMap<String, List<String>>();

    try {
      MimeMultipart multipart = MultipartMimeUtils.parseMultipartRequest(req);

      int parts = multipart.getCount();
      for (int i = 0; i < parts; i++) {
        BodyPart part = multipart.getBodyPart(i);
        String fieldName = MultipartMimeUtils.getFieldName(part);
        if (part.getFileName() != null) {
          ContentType contentType = new ContentType(part.getContentType());
          if ("message/external-body".equals(contentType.getBaseType())) {
            String blobKeyString = contentType.getParameter("blob-key");
            List<String> keys = blobKeys.get(fieldName);
            if (keys == null) {
              keys = new ArrayList<String>();
              blobKeys.put(fieldName, keys);
            }
            keys.add(blobKeyString);
            List<Map<String, String>> infos = blobInfos.get(fieldName);
            if (infos == null) {
              infos = new ArrayList<Map<String, String>>();
              blobInfos.put(fieldName, infos);
            }
            infos.add(getInfoFromBody(MultipartMimeUtils.getTextContent(part), blobKeyString));
          }
        } else {
          List<String> values = otherParams.get(fieldName);
          if (values == null) {
            values = new ArrayList<String>();
            otherParams.put(fieldName, values);
          }
          values.add(MultipartMimeUtils.getTextContent(part));
        }
      }
      req.setAttribute(UPLOADED_BLOBKEY_ATTR, blobKeys);
      req.setAttribute(UPLOADED_BLOBINFO_ATTR, blobInfos);
    } catch (MessagingException ex) {
      logger.log(Level.WARNING, "Could not parse multipart message:", ex);
    }

    chain.doFilter(new ParameterServletWrapper(request, otherParams), response);
  } else {
    chain.doFilter(request, response);
  }
}