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

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

源代码1 项目: packagedrone   文件: HttpImporter.java

private static String fromContentDisposition ( final String field )
{
    if ( field == null || field.isEmpty () )
    {
        return null;
    }

    try
    {
        final ContentDisposition cd = new ContentDisposition ( field );
        return cd.getParameter ( "filename" );
    }
    catch ( final ParseException e )
    {
        return null;
    }
}
 
源代码2 项目: 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);
    }
}
 
源代码3 项目: OpenAs2App   文件: BaseMessage.java

public String extractPayloadFilename() throws ParseException {
    String s = getContentDisposition();
    if (s == null || s.length() < 1) {
        return null;
    }
    // TODO: This should be a case insensitive lookup per RFC6266
    String tmpFilename = null;

    ContentDisposition cd = new ContentDisposition(s);
    tmpFilename = cd.getParameter("filename");

    if (tmpFilename == null || tmpFilename.length() < 1) {
        /* Try to extract manually */
        int n = s.indexOf("filename=");
        if (n > -1) {
            tmpFilename = s.substring(n);
            tmpFilename = tmpFilename.replaceFirst("filename=", "");

            int n1 = tmpFilename.indexOf(",");
            if (n1 > -1) {
                s = s.substring(0, n1 - 1);
            }
            tmpFilename = tmpFilename.replaceAll("\"", "");
            s = s.trim();
        } else {
            /* Try just using file separator */
            int pos = s.lastIndexOf(File.separator);
            if (pos >= 0) {
                tmpFilename = s.substring(pos + 1);
            }
        }
    }
    return tmpFilename;
}
 

/**
 * 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;
	}
}
 

/**
 * 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);
}
 
源代码6 项目: caja   文件: DataUriFetcher.java

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;
  }
}
 
源代码7 项目: caja   文件: FetchedData.java

private static String getCharSet(URLConnection conn) {
  try {
    String contentType = conn.getContentType();
    if (contentType == null) { return ""; }
    String charset = new ContentType(contentType).getParameter("charset");
    return (charset == null) ? "" : charset;
  } catch (ParseException e) {
    return "";
  }
}
 
源代码8 项目: james-project   文件: ContentReplacer.java

private boolean applyBodyReplacingUnits(Mail mail, ReplaceConfig replaceConfig, Optional<Charset> charset) throws IOException, MessagingException, ParseException {
    if (!replaceConfig.getBodyReplacingUnits().isEmpty()) {
        Object bodyObj = mail.getMessage().getContent();
        if (bodyObj instanceof String) {
            String body = applyPatterns(replaceConfig.getBodyReplacingUnits(), 
                    Strings.nullToEmpty((String) bodyObj));
            setContent(mail, body, charset);
            return true;
        }
    }
    return false;
}
 
源代码9 项目: james-project   文件: ContentReplacer.java

private String getContentType(Mail mail, Optional<Charset> charset) throws MessagingException, ParseException {
    String contentTypeAsString = mail.getMessage().getContentType();
    if (charset.isPresent()) {
        ContentType contentType = new ContentType(contentTypeAsString);
        contentType.setParameter("charset", charset.get().name());
        return contentType.toString();
    }
    return contentTypeAsString;
}
 
源代码10 项目: james-project   文件: AbstractSign.java

/**
 * Utility method that checks if there is at least one address in the "From:" header
 * same as the <i>reverse-path</i>.
 * @param mail The mail to check.
 * @return True if an address is found, false otherwise.
 */    
protected final boolean fromAddressSameAsReverse(Mail mail) {
    
    if (!mail.hasSender()) {
        return false;
    }
    MailAddress reversePath = mail.getMaybeSender().get();
    
    try {
        InternetAddress[] fromArray = (InternetAddress[]) mail.getMessage().getFrom();
        if (fromArray != null) {
            for (InternetAddress aFromArray : fromArray) {
                MailAddress mailAddress;
                try {
                    mailAddress = new MailAddress(aFromArray);
                } catch (ParseException pe) {
                    LOGGER.info("Unable to parse a \"FROM\" header address: {}; ignoring.", aFromArray);
                    continue;
                }
                if (mailAddress.equals(reversePath)) {
                    return true;
                }
            }
        }
    } catch (MessagingException me) {
        LOGGER.info("Unable to parse the \"FROM\" header; ignoring.");
    }
    
    return false;
    
}
 
源代码11 项目: james-project   文件: FakeMail.java

/**
 * Read the FakeMail from an <code>ObjectInputStream</code>.
 */
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    try {
        Object obj = in.readObject();
        if (obj == null) {
            sender = null;
        } else if (obj instanceof String) {
            sender = new MailAddress((String) obj);
        } else if (obj instanceof MailAddress) {
            sender = (MailAddress) obj;
        }
    } catch (ParseException pe) {
        throw new IOException("Error parsing sender address: " + pe.getMessage());
    }
    recipients = (Collection<MailAddress>) in.readObject();
    state = (String) in.readObject();
    errorMessage = (String) in.readObject();
    name = (String) in.readObject();
    remoteHost = (String) in.readObject();
    remoteAddr = (String) in.readObject();
    setLastUpdated((Date) in.readObject());
    // the following is under try/catch to be backwards compatible
    // with messages created with James version <= 2.2.0a8
    try {
        setAttributesRaw((Map<String, Object>) in.readObject());
    } catch (OptionalDataException ode) {
        if (ode.eof) {
            attributes = new HashMap<>();
        } else {
            throw ode;
        }
    }
    perRecipientHeaders = (PerRecipientHeaders) in.readObject();
}
 

private Set<MailAddress> getReplyTos(InternetAddress[] replyToArray) {
    ImmutableSet.Builder<MailAddress> builder = ImmutableSet.builder();
    for (InternetAddress replyTo : replyToArray) {
        try {
            builder.add(new MailAddress(replyTo));
        } catch (ParseException pe) {
            LOGGER.warn("Unable to parse a \"REPLY_TO\" header address in the original message: {}; ignoring.", replyTo);
        }
    }
    return builder.build();
}
 
源代码13 项目: james-project   文件: MessageProcessor.java

/**
 * Method handleParseException.
 *
 * @param ex
 * @throws MessagingException
 */
protected void handleParseException(ParseException ex) throws MessagingException {
    // Update the flags of the received message
    if (!isLeaveUndeliverable()) {
        setMessageDeleted();
    }
    if (isMarkUndeliverableSeen()) {
        setMessageSeen();
    }
    logStatusWarn("Message could not be delivered due to an error parsing a mail address.");
    LOGGER.debug("UNDELIVERABLE Message ID: {}", getMessageIn().getMessageID(), ex);
}
 
源代码14 项目: james-project   文件: ParsedConfiguration.java

/**
 * Sets the blacklist.
 * 
 * @param blacklistValue
 *            The blacklist to set
 */
protected void setBlacklist(String blacklistValue) throws ConfigurationException {
    StringTokenizer st = new StringTokenizer(blacklistValue, ", \t", false);
    Set<MailAddress> blacklist = new HashSet<>();
    String token = null;
    while (st.hasMoreTokens()) {
        try {
            token = st.nextToken();
            blacklist.add(new MailAddress(token));
        } catch (ParseException pe) {
            throw new ConfigurationException("Invalid blacklist mail address specified: " + token);
        }
    }
    setBlacklist(blacklist);
}
 
源代码15 项目: james-project   文件: Account.java

/**
 * Sets the recipient.
 * 
 * @param recipient
 *            The recipient to set
 */
protected void setRecipient(String recipient) throws ConfigurationException {
    if (null == recipient) {
        fieldRecipient = null;
        return;
    }

    try {
        setRecipient(new MailAddress(recipient));
    } catch (ParseException pe) {
        throw new ConfigurationException("Invalid recipient address specified: " + recipient);
    }
}
 
源代码16 项目: james-project   文件: MailImpl.java

/**
 * Read the MailImpl from an <code>ObjectInputStream</code>.
 *
 * @param in the ObjectInputStream from which the object is read
 * @throws IOException            if an error occurs while reading from the stream
 * @throws ClassNotFoundException ?
 * @throws ClassCastException     if the serialized objects are not of the appropriate type
 */
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    try {
        Object obj = in.readObject();
        if (obj == null) {
            sender = null;
        } else if (obj instanceof String) {
            sender = new MailAddress((String) obj);
        } else if (obj instanceof MailAddress) {
            sender = (MailAddress) obj;
        }
    } catch (ParseException pe) {
        throw new IOException("Error parsing sender address: " + pe.getMessage());
    }
    recipients = (Collection<MailAddress>) in.readObject();
    state = (String) in.readObject();
    errorMessage = (String) in.readObject();
    name = (String) in.readObject();
    remoteHost = (String) in.readObject();
    remoteAddr = (String) in.readObject();
    setLastUpdated((Date) in.readObject());
    try {
        setAttributesUsingJsonable(in);
    } catch (Exception e) {
        setAttributesUsingJavaSerializable(in);
    }
    perRecipientSpecificHeaders = (PerRecipientHeaders) in.readObject();
}
 
源代码17 项目: commons-email   文件: EmailTest.java

@Test
public void testSendBadHostName()
{
    try
    {
        getMailServer();

        email = new MockEmailConcrete();
        email.setSubject("Test Email #1 Subject");
        email.setHostName("bad.host.com");
        email.setFrom("[email protected]");
        email.addTo("[email protected]");
        email.addCc("[email protected]");
        email.addBcc("[email protected]");
        email.addReplyTo("[email protected]");

        email.setContent(
                "test string object",
                " ; charset=" + EmailConstants.US_ASCII);

        email.send();
        fail("Should have thrown an exception");
    }
    catch (final EmailException e)
    {
        assertTrue(e.getCause() instanceof ParseException);
        fakeMailServer.stop();
    }
}
 

@Test
public void getContentDispositionFileName() throws ParseException, MimeException, IOException{		
	setDispositionDecodedFilename().assertDecodedFileString(getPlainTextCheckSum());		
}
 

private ContentDispositionParserTest setDispositionDecodedFilename() throws ParseException, MimeException {
	fileName = ContentDispositionDecoder.decodeDispositionFileName(getEncodedContentDispositionMap());
	return this;
}
 
源代码20 项目: OpenAs2App   文件: DataHistoryItem.java

public DataHistoryItem(String contentType) throws ParseException {
    super();
    setContentType(contentType);
}
 
源代码21 项目: OpenAs2App   文件: DataHistoryItem.java

public void setContentType(String type) throws ParseException {
    setContentType(new ContentType(type));
}
 
源代码22 项目: OpenAs2App   文件: DataHistoryItem.java

private void readObject(java.io.ObjectInputStream in) throws ParseException, IOException, ClassNotFoundException {
    contentType = new ContentType((String) in.readObject());

    attributes = (Map<String, String>) in.readObject();
}
 
源代码23 项目: OpenAs2App   文件: MessageParameters.java

public String getParameter(String key) throws InvalidParameterException {
    StringTokenizer keyParts = new StringTokenizer(key, ".", false);

    if (keyParts.countTokens() != 2) {
        throw new InvalidParameterException("Invalid key format", this, key, null);
    }

    String area = keyParts.nextToken();
    String areaID = keyParts.nextToken();

    if (area.equals(KEY_SENDER)) {
        return getTarget().getPartnership().getSenderID(areaID);
    } else if (area.equals(KEY_RECEIVER)) {
        return getTarget().getPartnership().getReceiverID(areaID);
    } else if (area.equals(KEY_ATTRIBUTES)) {
        return getTarget().getAttribute(areaID);
    } else if (area.equals(KEY_HEADERS)) {
        return getTarget().getHeader(areaID);
    } else if (area.equals(KEY_CONTENT_FILENAME) && areaID.equals("filename")) {
        String s = null;
        try {
            s = getTarget().extractPayloadFilename();
        } catch (ParseException e) {
            logger.warn("Failed to extract filename from content-disposition: " + org.openas2.logging.Log.getExceptionMsg(e), e);
        }
        if (s == null || s.length() < 1) {
            s = getTarget().getPayloadFilename();
        }
        if (s != null && s.length() > 0) {
            return s;
        }
        // If it gets to here then the sender did not send a filename so...
        String filename = Properties.getProperty(Properties.AS2_RX_MESSAGE_FILENAME_FALLBACK, null);
        if (filename == null) {
            return getTarget().getMessageID();
        } else {
            CompositeParameters parser = new CompositeParameters(false).add("date", new DateParameters()).add("msg", new MessageParameters(getTarget())).add("rand", new RandomParameters());
            return ParameterParser.parse(filename, parser);
        }
    } else {
        throw new InvalidParameterException("Invalid area in key", this, key, null);
    }
}
 
源代码24 项目: james-project   文件: ContentReplacer.java

private void setContent(Mail mail, String body, Optional<Charset> charset) throws MessagingException, ParseException {
    mail.getMessage().setContent(body, getContentType(mail, charset));
}
 
源代码25 项目: OpenAs2App   文件: Message.java

String extractPayloadFilename() throws ParseException; 
 类所在包
 类方法
 同包方法