Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.mail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import jakarta.mail.Flags;
import jakarta.mail.Folder;
import jakarta.mail.FolderNotFoundException;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Store;
import jakarta.mail.search.SearchTerm;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePropertyKey;
import org.apache.camel.Processor;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.attachment.Attachment;
import org.apache.camel.attachment.AttachmentMessage;
import org.apache.camel.spi.BeanIntrospection;
import org.apache.camel.support.PluginHelper;
import org.apache.camel.support.ScheduledBatchPollingConsumer;
import org.apache.camel.support.SynchronizationAdapter;
import org.apache.camel.util.CastUtils;
import org.apache.camel.util.KeyValueHolder;
import org.apache.camel.util.ObjectHelper;
import org.eclipse.angus.mail.imap.IMAPFolder;
import org.eclipse.angus.mail.imap.IMAPStore;
import org.eclipse.angus.mail.imap.SortTerm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link org.apache.camel.Consumer Consumer} which consumes messages from JavaMail using a
* {@link jakarta.mail.Transport Transport} and dispatches them to the {@link Processor}
*/
public class MailConsumer extends ScheduledBatchPollingConsumer {
public static final String MAIL_MESSAGE_UID = "CamelMailMessageId";
public static final long DEFAULT_CONSUMER_DELAY = 60 * 1000L;
private static final Logger LOG = LoggerFactory.getLogger(MailConsumer.class);
private final JavaMailSender sender;
private Folder folder;
private Store store;
private boolean skipFailedMessage;
private boolean handleFailedMessage;
/**
* Is true if server is an IMAP server and supports IMAP SORT extension.
*/
private boolean serverCanSort;
public MailConsumer(MailEndpoint endpoint, Processor processor, JavaMailSender sender) {
super(endpoint, processor);
this.sender = sender;
}
@Override
protected void doStart() throws Exception {
super.doStart();
}
@Override
protected void doStop() throws Exception {
if (folder != null && folder.isOpen()) {
folder.close(true);
}
if (store != null && store.isConnected()) {
store.close();
}
super.doStop();
}
/**
* Returns the max number of messages to be processed. Will return -1 if no maximum is set
*/
private int getMaxNumberOfMessages() {
int fetchSize = getEndpoint().getConfiguration().getFetchSize();
if (hasMessageLimit(fetchSize)) {
return fetchSize;
}
int maximumMessagesPerPoll = (getMaxMessagesPerPoll() == 0) ? -1 : getMaxMessagesPerPoll();
if (hasMessageLimit(maximumMessagesPerPoll)) {
return maximumMessagesPerPoll;
}
return -1;
}
private boolean hasMessageLimit(int limitValue) {
return limitValue >= 0;
}
@Override
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
try {
if (!folder.isOpen()) {
folder.open(Folder.READ_WRITE);
}
} catch (MessagingException e) {
// some kind of connectivity error, so lets re-create connection
String msg = "Error opening mail folder due to " + e.getMessage() + ". Will re-create connection on next poll.";
LOG.warn(msg);
if (LOG.isDebugEnabled()) {
LOG.debug(msg, e);
}
disconnect();
return 0; // return since we cannot poll mail messages, but will re-connect on next poll.
}
// okay consumer is connected to the mail server
forceConsumerAsReady();
try {
int count = folder.getMessageCount();
if (count > 0) {
Queue messages = retrieveMessages();
polledMessages = processBatch(CastUtils.cast(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()) {
try {
if (folder != null && folder.isOpen()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Close mailbox folder {} from {}", folder.getName(),
getEndpoint().getConfiguration().getMailStoreLogInformation());
}
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: {}. This exception is ignored.", folder.getName(), e);
}
}
}
// should we disconnect, the header can override the configuration
boolean disconnect = getEndpoint().getConfiguration().isDisconnect();
if (disconnect) {
disconnect();
}
return polledMessages;
}
private void disconnect() {
if (LOG.isDebugEnabled()) {
LOG.debug("Disconnecting from {}", getEndpoint().getConfiguration().getMailStoreLogInformation());
}
try {
if (store != null) {
store.close();
}
} catch (Exception e) {
LOG.debug("Could not disconnect from {}. This exception is ignored.",
getEndpoint().getConfiguration().getMailStoreLogInformation(), e);
}
store = null;
folder = null;
}
@Override
public int processBatch(Queue