use of javax.mail.MessagingException in project camel by apache.
the class MailConsumer method retrieveAllMessages.
private Message[] retrieveAllMessages() throws MessagingException {
int total = folder.getMessageCount();
List<Message> msgs = new ArrayList<Message>();
// Note that message * numbers start at 1, not 0
for (int i = 1; i <= total; i++) {
try {
Message msg = folder.getMessage(i);
msgs.add(msg);
} catch (Exception e) {
if (skipFailedMessage) {
LOG.debug("Skipping failed message at index " + i + " due " + e.getMessage(), e);
} else if (handleFailedMessage) {
handleException(e);
} else {
throw e;
}
}
}
return msgs.toArray(new Message[msgs.size()]);
}
use of javax.mail.MessagingException in project camel by apache.
the class MailConsumer method createExchanges.
protected Queue<Exchange> createExchanges(List<KeyValueHolder<String, Message>> messages) throws MessagingException {
Queue<Exchange> answer = new LinkedList<Exchange>();
int fetchSize = getEndpoint().getConfiguration().getFetchSize();
int count = fetchSize == -1 ? messages.size() : Math.min(fetchSize, messages.size());
if (LOG.isDebugEnabled()) {
LOG.debug("Fetching {} messages. Total {} messages.", count, messages.size());
}
for (int i = 0; i < count; i++) {
try {
KeyValueHolder<String, Message> holder = messages.get(i);
String key = holder.getKey();
Message message = holder.getValue();
if (LOG.isTraceEnabled()) {
LOG.trace("Mail #{} is of type: {} - {}", new Object[] { i, ObjectHelper.classCanonicalName(message), message });
}
if (!message.getFlags().contains(Flags.Flag.DELETED)) {
Exchange exchange = getEndpoint().createExchange(message);
if (getEndpoint().getConfiguration().isMapMailMessage()) {
// ensure the mail message is mapped, which can be ensured by touching the body/header/attachment
LOG.trace("Mapping #{} from javax.mail.Message to Camel MailMessage", i);
exchange.getIn().getBody();
exchange.getIn().getHeaders();
exchange.getIn().getAttachments();
}
// If the protocol is POP3 we need to remember the uid on the exchange
// so we can find the mail message again later to be able to delete it
// we also need to remember the UUID for idempotent repository
exchange.setProperty(MAIL_MESSAGE_UID, key);
answer.add(exchange);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Skipping message as it was flagged as deleted: {}", MailUtils.dumpMessage(message));
}
}
} catch (Exception e) {
if (skipFailedMessage) {
LOG.debug("Skipping failed message at index " + i + " due " + e.getMessage(), e);
} else if (handleFailedMessage) {
handleException(e);
} else {
throw e;
}
}
}
return answer;
}
use of javax.mail.MessagingException in project camel by apache.
the class MailConsumer method processCommit.
/**
* Strategy to flag the message after being processed.
*
* @param mail the mail message
* @param exchange the exchange
*/
protected void processCommit(Message mail, Exchange exchange) {
try {
// ensure folder is open
if (!folder.isOpen()) {
folder.open(Folder.READ_WRITE);
}
String uid = (String) exchange.removeProperty(MAIL_MESSAGE_UID);
// Otherwise setting the DELETE/SEEN flag won't delete the message.
if (getEndpoint().getConfiguration().getProtocol().startsWith("pop3")) {
int count = folder.getMessageCount();
Message found = null;
LOG.trace("Looking for POP3Message with UID {} from folder with {} mails", uid, count);
for (int i = 1; i <= count; ++i) {
Message msg = folder.getMessage(i);
if (uid.equals(getEndpoint().getMailUidGenerator().generateUuid(getEndpoint(), msg))) {
LOG.debug("Found POP3Message with UID {} from folder with {} mails", uid, count);
found = msg;
break;
}
}
if (found == null) {
boolean delete = getEndpoint().getConfiguration().isDelete();
LOG.warn("POP3message not found in folder. Message cannot be marked as " + (delete ? "DELETED" : "SEEN"));
} else {
mail = found;
}
}
org.apache.camel.Message in = exchange.getIn();
MailConfiguration config = getEndpoint().getConfiguration();
// header values override configuration values
String copyTo = in.getHeader("copyTo", config.getCopyTo(), String.class);
boolean delete = in.getHeader("delete", config.isDelete(), boolean.class);
// Copy message into different imap folder if asked
if (config.getProtocol().equals(MailUtils.PROTOCOL_IMAP) || config.getProtocol().equals(MailUtils.PROTOCOL_IMAPS)) {
if (copyTo != null) {
LOG.trace("IMAP message needs to be copied to {}", copyTo);
Folder destFolder = store.getFolder(copyTo);
if (!destFolder.exists()) {
destFolder.create(Folder.HOLDS_MESSAGES);
}
folder.copyMessages(new Message[] { mail }, destFolder);
LOG.trace("IMAP message {} copied to {}", mail, copyTo);
}
}
if (delete) {
LOG.trace("Exchange processed, so flagging message as DELETED");
mail.setFlag(Flags.Flag.DELETED, true);
} else {
LOG.trace("Exchange processed, so flagging message as SEEN");
mail.setFlag(Flags.Flag.SEEN, true);
}
// need to confirm or remove on commit at last
if (getEndpoint().getIdempotentRepository() != null) {
if (getEndpoint().isIdempotentRepositoryRemoveOnCommit()) {
getEndpoint().getIdempotentRepository().remove(uid);
} else {
getEndpoint().getIdempotentRepository().confirm(uid);
}
}
} catch (MessagingException e) {
getExceptionHandler().handleException("Error occurred during committing mail message: " + mail, exchange, e);
}
}
use of javax.mail.MessagingException in project camel by apache.
the class MailConsumer method poll.
protected int poll() throws Exception {
// must reset for each poll
shutdownRunningTask = null;
pendingExchanges = 0;
int polledMessages = 0;
ensureIsConnected();
if (store == null || folder == null) {
throw new IllegalStateException("MailConsumer did not connect properly to the MailStore: " + getEndpoint().getConfiguration().getMailStoreLogInformation());
}
if (LOG.isDebugEnabled()) {
LOG.debug("Polling mailbox folder: " + getEndpoint().getConfiguration().getMailStoreLogInformation());
}
if (getEndpoint().getConfiguration().getFetchSize() == 0) {
LOG.warn("Fetch size is 0 meaning the configuration is set to poll no new messages at all. Camel will skip this poll.");
return 0;
}
// ensure folder is open
if (!folder.isOpen()) {
folder.open(Folder.READ_WRITE);
}
try {
int count = folder.getMessageCount();
if (count > 0) {
List<KeyValueHolder<String, Message>> messages = retrieveMessages();
// we process the message and rollback due an exception
if (getEndpoint().getConfiguration().isPeek()) {
for (KeyValueHolder<String, Message> entry : messages) {
Message message = entry.getValue();
peekMessage(message);
}
}
polledMessages = processBatch(CastUtils.cast(createExchanges(messages)));
final MailBoxPostProcessAction postProcessor = getEndpoint().getPostProcessAction();
if (postProcessor != null) {
postProcessor.process(folder);
}
} else if (count == -1) {
throw new MessagingException("Folder: " + folder.getFullName() + " is closed");
}
} catch (Exception e) {
handleException(e);
} finally {
// need to ensure we release resources, but only if closeFolder or disconnect = true
if (getEndpoint().getConfiguration().isCloseFolder() || getEndpoint().getConfiguration().isDisconnect()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Close mailbox folder {} from {}", folder.getName(), getEndpoint().getConfiguration().getMailStoreLogInformation());
}
try {
if (folder.isOpen()) {
folder.close(true);
}
} catch (Exception e) {
// some mail servers will lock the folder so we ignore in this case (CAMEL-1263)
LOG.debug("Could not close mailbox folder: " + folder.getName() + ". This exception is ignored.", e);
}
}
}
// should we disconnect, the header can override the configuration
boolean disconnect = getEndpoint().getConfiguration().isDisconnect();
if (disconnect) {
if (LOG.isDebugEnabled()) {
LOG.debug("Disconnecting from {}", getEndpoint().getConfiguration().getMailStoreLogInformation());
}
try {
store.close();
} catch (Exception e) {
LOG.debug("Could not disconnect from {}: " + getEndpoint().getConfiguration().getMailStoreLogInformation() + ". This exception is ignored.", e);
}
store = null;
folder = null;
}
return polledMessages;
}
use of javax.mail.MessagingException in project camel by apache.
the class DefaultMailUidGenerator method generateMessageHash.
public String generateMessageHash(Message message) {
LOG.trace("generateMessageHash for msg: {}", message);
String uid = null;
// create an UID based on message headers on the message, that ought to be unique
StringBuilder buffer = new StringBuilder();
try {
Enumeration<?> it = message.getAllHeaders();
while (it.hasMoreElements()) {
Header header = (Header) it.nextElement();
buffer.append(header.getName()).append("=").append(header.getValue()).append("\n");
}
if (buffer.length() > 0) {
LOG.trace("Generating UID from the following:\n {}", buffer);
uid = UUID.nameUUIDFromBytes(buffer.toString().getBytes()).toString();
}
} catch (MessagingException e) {
LOG.warn("Cannot read headers from mail message. This exception will be ignored.", e);
}
return uid;
}
Aggregations