Migrated Mail Channel Adapter code from 'org.springframework.integration.adapter' to the new 'org.springframework.integration.mail' module.

This commit is contained in:
Mark Fisher
2008-09-22 15:16:47 +00:00
parent f8b3f99d19
commit db7bc0b9ea
49 changed files with 220 additions and 112 deletions

View File

@@ -1,126 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.message.Message;
import org.springframework.mail.MailMessage;
/**
* Base implementation for {@link MailHeaderGenerator MailHeaderGenerators}.
* This class is abstract. Subclasses must implement the corresponding template
* methods to retrieve the values for the mail message's subject, recipients,
* and from/reply-to addresses based on the integration {@link Message}.
*
* @author Marius Bogoevici
* @author Mark Fisher
*/
public abstract class AbstractMailHeaderGenerator implements MailHeaderGenerator {
private final Log logger = LogFactory.getLog(this.getClass());
/**
* Retrieve the subject of an e-mail message from an integration message.
*
* @param message the integration {@link Message}
* @return the e-mail message subject
*/
protected abstract String getSubject(Message<?> message);
/**
* Retrieve the recipients list from an integration message.
*
* @param message the integration {@link Message}
* @return recipients list (TO)
*/
protected abstract String[] getTo(Message<?> message);
/**
* Retrieve the CC recipients list from an integration message.
*
* @param message the integration {@link Message}
* @return CC recipients list (e-mail addresses)
*/
protected abstract String[] getCc(Message<?> message);
/**
* Retrieve the BCC recipients list from an integration message.
*
* @param message the integration {@link Message}
* @return BCC recipients list (e-mail addresses)
*/
protected abstract String[] getBcc(Message<?> message);
/**
* Retrieve the From: e-mail address from an integration message.
*
* @param message the integration {@link Message}
* @return the From: e-mail address
*/
protected abstract String getFrom(Message<?> message);
/**
* Retrieve the Reply To: e-mail address from an integration message.
*
* @param message the integration {@link Message}
* @return the ReplyTo: e-mail address
*/
protected abstract String getReplyTo(Message<?> message);
/**
* Populate the mail message using the results of the template methods.
*/
public final void populateMailMessageHeader(MailMessage mailMessage, Message<?> message) {
final String subject = getSubject(message);
final String[] to = getTo(message);
final String[] cc = getCc(message);
final String[] bcc = getBcc(message);
final String from = getFrom(message);
final String replyTo = getReplyTo(message);
if (subject != null) {
mailMessage.setSubject(subject);
}
else if (logger.isWarnEnabled()) {
logger.warn("no 'SUBJECT' property available for mail message");
}
if (to != null) {
mailMessage.setTo(to);
}
else if (logger.isWarnEnabled()) {
logger.warn("no 'TO' property available for mail message");
}
if (cc != null) {
mailMessage.setCc(cc);
}
if (bcc != null) {
mailMessage.setBcc(bcc);
}
if (from != null) {
mailMessage.setFrom(from);
}
else if (logger.isWarnEnabled()) {
logger.warn("no 'FROM' property available for mail message");
}
if (replyTo != null) {
mailMessage.setReplyTo(replyTo);
}
}
}

View File

@@ -1,182 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import java.util.HashMap;
import java.util.Map;
import javax.mail.Address;
import javax.mail.Message.RecipientType;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.adapter.MessageHeaderMapper;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageHeaders;
import org.springframework.integration.message.MessagingException;
import org.springframework.mail.javamail.MimeMailMessage;
/**
*
* @author Jonas Partner
*
*/
public abstract class AbstractMailHeaderMapper implements MessageHeaderMapper<MimeMessage> {
/**
* Retrieve the subject of an e-mail message from an integration message.
*
* @param message the integration {@link Message}
* @return the e-mail message subject
*/
protected abstract String getSubject(MessageHeaders message);
/**
* Retrieve the recipients list from an integration message.
*
* @param message the integration {@link Message}
* @return recipients list (TO)
*/
protected abstract String[] getTo(MessageHeaders message);
/**
* Retrieve the CC recipients list from an integration message.
*
* @param message the integration {@link Message}
* @return CC recipients list (e-mail addresses)
*/
protected abstract String[] getCc(MessageHeaders message);
/**
* Retrieve the BCC recipients list from an integration message.
*
* @param message the integration {@link Message}
* @return BCC recipients list (e-mail addresses)
*/
protected abstract String[] getBcc(MessageHeaders message);
/**
* Retrieve the From: e-mail address from an integration message.
*
* @param message the integration {@link Message}
* @return the From: e-mail address
*/
protected abstract String getFrom(MessageHeaders message);
/**
* Retrieve the Reply To: e-mail address from an integration message.
*
* @param message the integration {@link Message}
* @return the ReplyTo: e-mail address
*/
protected abstract String getReplyTo(MessageHeaders message);
private final Log logger = LogFactory.getLog(this.getClass());
public void mapFromMessageHeaders(MessageHeaders headers, MimeMessage mailMessage) {
MimeMailMessage message = new MimeMailMessage(mailMessage);
final String subject = getSubject(headers);
final String[] to = getTo(headers);
final String[] cc = getCc(headers);
final String[] bcc = getBcc(headers);
final String from = getFrom(headers);
final String replyTo = getReplyTo(headers);
if (subject != null) {
message.setSubject(subject);
}
else if (logger.isWarnEnabled()) {
logger.warn("no 'SUBJECT' property available for mail message");
}
if (to != null) {
message.setTo(to);
}
else if (logger.isWarnEnabled()) {
logger.warn("no 'TO' property available for mail message");
}
if (cc != null) {
message.setCc(cc);
}
if (bcc != null) {
message.setBcc(bcc);
}
if (from != null) {
message.setFrom(from);
}
else if (logger.isWarnEnabled()) {
logger.warn("no 'FROM' property available for mail message");
}
if (replyTo != null) {
message.setReplyTo(replyTo);
}
}
public Map<String,Object> mapToMessageHeaders(MimeMessage mailMessage) {
try {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put(MailHeaders.FROM, convertToString(mailMessage.getFrom()));
headers.put(MailHeaders.BCC, convertToStringArray(mailMessage.getRecipients(RecipientType.BCC)));
headers.put(MailHeaders.CC, convertToStringArray(mailMessage.getRecipients(RecipientType.CC)));
headers.put(MailHeaders.TO, convertToStringArray(mailMessage.getRecipients(RecipientType.TO)));
headers.put(MailHeaders.REPLY_TO, convertToString(mailMessage.getReplyTo()));
headers.put(MailHeaders.SUBJECT, mailMessage.getSubject());
return headers;
}
catch (Exception e) {
throw new MessagingException("Conversion of MailMessage headers failed", e);
}
}
protected String retrieveAsString(MessageHeaders headers, String key) {
Object value = headers.get(key);
return (value instanceof String) ? (String) value : null;
}
protected String[] retrieveAsStringArray(MessageHeaders headers, String key) {
Object value = headers.get(key);
if (value instanceof String[]) {
return (String[]) value;
}
if (value instanceof String) {
return new String[] { (String) value };
}
return null;
}
private String convertToString(Address[] addresses) {
if (addresses == null || addresses.length == 0) {
return null;
}
if (addresses.length != 1) {
throw new IllegalStateException("expected a single value but received an Array");
}
return addresses[0].toString();
}
private String[] convertToStringArray(Address[] addresses) {
if (addresses != null) {
String[] addressStrings = new String[addresses.length];
for (int i = 0; i < addresses.length; i++) {
addressStrings[i] = addresses[i].toString();
}
return addressStrings;
}
return new String[0];
}
}

View File

@@ -1,74 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.integration.adapter.MessageMappingException;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageMapper;
import org.springframework.mail.MailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.Assert;
/**
* Message mapper used for mapping byte array messages to mail messages.
* Generates an e-mail message with the byte array as an attachment. The
* multipart mode and attachment name are configurable.
*
* @author Marius Bogoevici
*/
public class ByteArrayMailMessageMapper implements MessageMapper<byte[], MailMessage> {
private final JavaMailSender mailSender;
private volatile int multipartMode = MimeMessageHelper.MULTIPART_MODE_MIXED;
private volatile String attachmentFilename = "content";
public ByteArrayMailMessageMapper(JavaMailSender mailSender) {
Assert.notNull(mailSender, "'mailSender' must not be null");
this.mailSender = mailSender;
}
public void setMultipartMode(int multipartMode) {
this.multipartMode = multipartMode;
}
public void setAttachmentFilename(String attachmentFilename) {
this.attachmentFilename = attachmentFilename;
}
public MailMessage mapMessage(Message<byte[]> message) {
try {
MimeMessage mimeMessage = this.mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, this.multipartMode);
helper.addAttachment(this.attachmentFilename, new ByteArrayResource(message.getPayload()));
return new MimeMailMessage(helper);
}
catch (MessagingException e) {
throw new MessageMappingException(message, "failed to create MimeMessage", e);
}
}
}

View File

@@ -1,169 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.Lifecycle;
import org.springframework.integration.ConfigurationException;
import org.springframework.integration.adapter.mail.monitor.AsyncMonitoringStrategy;
import org.springframework.integration.adapter.mail.monitor.MailTransportUtils;
import org.springframework.integration.adapter.mail.monitor.MonitoringStrategy;
import org.springframework.util.Assert;
/**
* A Connection to a mail folder capable of retrieving mail by utilising the
* given instance of {@link MonitoringStrategy}
*
* @author Jonas Partner
*
*/
public class DefaultFolderConnection implements Lifecycle, InitializingBean,
DisposableBean, FolderConnection {
private final Log logger = LogFactory.getLog(this.getClass());
private final URLName storeUri;
private Session session;
private final MonitoringStrategy monitoringStrategy;
private final boolean polling;
private Store store;
private Folder folder;
private Properties javaMailProperties = new Properties();
public DefaultFolderConnection(String storeUri,
MonitoringStrategy monitoringStrategy, boolean polling) {
this.storeUri = new URLName(storeUri);
this.monitoringStrategy = monitoringStrategy;
this.polling = polling;
if (!polling
&& monitoringStrategy.getClass().isAssignableFrom(
AsyncMonitoringStrategy.class)) {
throw new ConfigurationException(
"Folder connection requires an AsyncMonitoringStragey if polling is disabled");
}
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(storeUri, "Property 'storeUri' is required");
Assert.notNull(monitoringStrategy,
"An instantce of MonitoringStrategy' is required");
//
}
/*
* (non-Javadoc)
*
* @see org.springframework.integration.adapter.mail.FolderConnectionI#receive()
*/
public synchronized Message[] receive() {
if (!isRunning()) {
start();
}
try {
if (!polling) {
((AsyncMonitoringStrategy) monitoringStrategy)
.waitForNewMessages(folder);
}
return monitoringStrategy.receive(folder);
} catch (Exception e) {
throw new org.springframework.integration.message.MessagingException(
"Exception receiving from folder", e);
}
}
public void destroy() throws Exception {
stop();
}
public synchronized boolean isRunning() {
return (folder != null && folder.isOpen());
}
public synchronized void start() {
try {
openSession();
openFolder();
} catch (MessagingException messageE) {
throw new org.springframework.integration.message.MessagingException(
"Excpetion starting MailSource", messageE);
}
}
public synchronized void stop() {
MailTransportUtils.closeFolder(folder);
MailTransportUtils.closeService(store);
folder = null;
store = null;
}
private void openFolder() throws MessagingException {
if (folder != null && folder.isOpen()) {
return;
}
folder = store.getFolder(storeUri);
if (folder == null || !folder.exists()) {
throw new IllegalStateException("No default folder to receive from");
}
if (logger.isDebugEnabled()) {
logger.debug("Opening folder ["
+ MailTransportUtils.toPasswordProtectedString(storeUri)
+ "]");
}
folder.open(monitoringStrategy.getFolderOpenMode());
}
private void openSession() throws MessagingException {
session = Session.getInstance(javaMailProperties);
store = session.getStore(storeUri);
if (logger.isDebugEnabled()) {
logger.debug("Connecting to store ["
+ MailTransportUtils.toPasswordProtectedString(storeUri)
+ "]");
}
store.connect();
}
public Properties getJavaMailProperties() {
return javaMailProperties;
}
public void setJavaMailProperties(Properties javaMailProperties) {
this.javaMailProperties = javaMailProperties;
}
}

View File

@@ -1,77 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import org.springframework.integration.message.Message;
/**
* The default implementation of {@link MailHeaderGenerator}. Configures the
* {@link org.springframework.mail.MailMessage} properties based on attributes
* provided with known attribute keys as defined in {@link MailHeaders}.
*
* @author Mark Fisher
*/
public class DefaultMailHeaderGenerator extends AbstractMailHeaderGenerator {
@Override
protected String getSubject(Message<?> message) {
return this.retrieveAsString(message, MailHeaders.SUBJECT);
}
@Override
protected String[] getTo(Message<?> message) {
return this.retrieveAsStringArray(message, MailHeaders.TO);
}
@Override
protected String[] getCc(Message<?> message) {
return this.retrieveAsStringArray(message, MailHeaders.CC);
}
@Override
protected String[] getBcc(Message<?> message) {
return this.retrieveAsStringArray(message, MailHeaders.BCC);
}
@Override
protected String getFrom(Message<?> message) {
return this.retrieveAsString(message, MailHeaders.FROM);
}
@Override
protected String getReplyTo(Message<?> message) {
return this.retrieveAsString(message, MailHeaders.REPLY_TO);
}
private String retrieveAsString(Message<?> message, String key) {
Object value = message.getHeaders().get(key);
return (value instanceof String) ? (String) value : null;
}
private String[] retrieveAsStringArray(Message<?> message, String key) {
Object value = message.getHeaders().get(key);
if (value instanceof String[]) {
return (String[]) value;
}
if (value instanceof String) {
return new String[] { (String) value };
}
return null;
}
}

View File

@@ -1,48 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import java.util.Map;
import javax.mail.internet.MimeMessage;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessagingException;
/**
*
* @author Jonas Partner
*
*/
public class DefaultMailMessageConverter implements MailMessageConverter {
private DefaultMailMessageHeaderMapper headerMapper = new DefaultMailMessageHeaderMapper();
@SuppressWarnings("unchecked")
public Message create(MimeMessage mailMessage) {
try {
Map<String, Object> header = headerMapper.mapToMessageHeaders(mailMessage);
GenericMessage<Object> message = new GenericMessage<Object>(mailMessage.getContent(), header);
return message;
}
catch (Exception e) {
throw new MessagingException("Conversion of MailMessage failed", e);
}
}
}

View File

@@ -1,57 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import org.springframework.integration.message.MessageHeaders;
/**
* @author Jonas Partner
*
*/
public class DefaultMailMessageHeaderMapper extends AbstractMailHeaderMapper {
@Override
protected String getSubject(MessageHeaders headers) {
return this.retrieveAsString(headers, MailHeaders.SUBJECT);
}
@Override
protected String[] getTo(MessageHeaders headers) {
return this.retrieveAsStringArray(headers, MailHeaders.TO);
}
@Override
protected String[] getCc(MessageHeaders headers) {
return this.retrieveAsStringArray(headers, MailHeaders.CC);
}
@Override
protected String[] getBcc(MessageHeaders headers) {
return this.retrieveAsStringArray(headers, MailHeaders.BCC);
}
@Override
protected String getFrom(MessageHeaders headers) {
return this.retrieveAsString(headers, MailHeaders.FROM);
}
@Override
protected String getReplyTo(MessageHeaders headers) {
return this.retrieveAsString(headers, MailHeaders.REPLY_TO);
}
}

View File

@@ -1,32 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import javax.mail.Folder;
import javax.mail.Message;
import org.springframework.context.Lifecycle;
/**
* * Encapsulates state for a restartable connection to a {@link Folder} and ensures thread safety
* @author Jonas Partner
*
*/
public interface FolderConnection extends Lifecycle{
Message[] receive();
}

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import org.springframework.integration.message.Message;
import org.springframework.mail.MailMessage;
/**
* Strategy interface for generating header information for an e-mail message
* from the content of the integration message. Minimal configuration should
* include the recipients list, the subject, from/reply-to, etc. However, this
* strategy allows the implementation of more complex business logic, when these
* parameters are depending on the integration message itself.
*
* @author Marius Bogoevici
*/
public interface MailHeaderGenerator {
/**
* Populate the e-mail message header based on the content of the
* integration message.
*/
void populateMailMessageHeader(MailMessage mailMessage, Message<?> message);
}

View File

@@ -1,41 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
/**
* Pre-defined names and prefixes to be used for setting and/or retrieving Mail attributes
* from/to integration Message Headers.
*
* @author Mark Fisher
*/
public class MailHeaders {
public static final String TRANSFPORT_PREFIX = "spring.integration.transport.mail.";
public static final String SUBJECT = TRANSFPORT_PREFIX + "SUBJECT";
public static final String TO = TRANSFPORT_PREFIX + "TO";
public static final String CC = TRANSFPORT_PREFIX + "CC";
public static final String BCC = TRANSFPORT_PREFIX + "BCC";
public static final String FROM = TRANSFPORT_PREFIX + "FROM";
public static final String REPLY_TO = TRANSFPORT_PREFIX+ "REPLY_TO";
}

View File

@@ -1,34 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import javax.mail.internet.MimeMessage;
import org.springframework.integration.message.Message;
/**
* Converts a {@link MimeMessage} to a {@link Message}
* @author Jonas Partner
*
*/
public interface MailMessageConverter {
@SuppressWarnings("unchecked")
public Message create(MimeMessage mailMessage);
}

View File

@@ -1,132 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageMapper;
import org.springframework.integration.message.MessageTarget;
import org.springframework.mail.MailMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.util.Assert;
/**
* A target adapter for sending mail.
*
* @author Marius Bogoevici
* @author Mark Fisher
*/
public class MailTarget implements MessageTarget, InitializingBean {
private final JavaMailSender mailSender;
private volatile MailHeaderGenerator mailHeaderGenerator = new DefaultMailHeaderGenerator();
private volatile MessageMapper<String, MailMessage> textMessageMapper;
private volatile MessageMapper<byte[], MailMessage> byteArrayMessageMapper;
private volatile MessageMapper<Object, MailMessage> objectMessageMapper;
/**
* Create a MailTargetAdapter.
*
* @param mailSender the {@link JavaMailSender} instance to which this
* adapter will delegate.
*/
public MailTarget(JavaMailSender mailSender) {
Assert.notNull(mailSender, "'mailSender' must not be null");
this.mailSender = mailSender;
}
public void afterPropertiesSet() throws Exception {
this.textMessageMapper = (this.textMessageMapper != null) ?
this.textMessageMapper : new TextMailMessageMapper();
this.byteArrayMessageMapper = (byteArrayMessageMapper != null) ?
this.byteArrayMessageMapper : new ByteArrayMailMessageMapper(this.mailSender);
this.objectMessageMapper = (objectMessageMapper != null) ?
this.objectMessageMapper : new DefaultObjectMailMessageMapper();
}
public void setHeaderGenerator(MailHeaderGenerator mailHeaderGenerator) {
Assert.notNull(mailHeaderGenerator, "'mailHeaderGenerator' must not be null");
this.mailHeaderGenerator = mailHeaderGenerator;
}
public void setTextMessageMapper(MessageMapper<String, MailMessage> textMessageMapper) {
this.textMessageMapper = textMessageMapper;
}
public void setByteArrayMessageMapper(MessageMapper<byte[], MailMessage> byteArrayMessageMapper) {
this.byteArrayMessageMapper = byteArrayMessageMapper;
}
public void setObjectMessageMapper(MessageMapper<Object, MailMessage> objectMessageMapper) {
this.objectMessageMapper = objectMessageMapper;
}
public final boolean send(Message<?> message) {
MailMessage mailMessage = this.convertMessageToMailMessage(message);
this.mailHeaderGenerator.populateMailMessageHeader(mailMessage, message);
this.sendMailMessage(mailMessage);
return true;
}
@SuppressWarnings("unchecked")
private MailMessage convertMessageToMailMessage(Message<?> message) {
if (message.getPayload() instanceof String) {
return this.textMessageMapper.mapMessage((Message<String>) message);
}
else if (message.getPayload() instanceof byte[]) {
return this.byteArrayMessageMapper.mapMessage((Message<byte[]>) message);
}
return this.objectMessageMapper.mapMessage((Message<Object>) message);
}
private void sendMailMessage(MailMessage mailMessage) {
if (mailMessage instanceof SimpleMailMessage) {
this.mailSender.send((SimpleMailMessage) mailMessage);
}
else if (mailMessage instanceof MimeMailMessage) {
this.mailSender.send(((MimeMailMessage) mailMessage).getMimeMessage());
}
else {
throw new IllegalArgumentException(
"MailMessage subclass '" + mailMessage.getClass().getName() + "' not supported");
}
}
private static class DefaultObjectMailMessageMapper implements MessageMapper<Object, MailMessage> {
public Message<Object> toMessage(MailMessage source) {
throw new UnsupportedOperationException("mapping from MailMessage to Object not supported");
}
public MailMessage mapMessage(Message<Object> objectMessage) {
SimpleMailMessage message = new SimpleMailMessage();
message.setText(objectMessage.getPayload().toString());
return message;
}
}
}

View File

@@ -1,96 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.adapter.mail.monitor.DefaultLocalMailMessageStore;
import org.springframework.integration.adapter.mail.monitor.LocalMailMessageStore;
import org.springframework.integration.adapter.mail.monitor.MonitoringStrategy;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageSource;
import org.springframework.integration.message.PollableSource;
/**
* {@link MessageSource} implementation which delegates to a
* {@link MonitoringStrategy} to poll a mailbox. Each poll of the mailbox may
* return more than one message which will then be stored locally using the
* provided {@link LocalMailMessageStore}
*
* @author Jonas Partner
*/
@SuppressWarnings("unchecked")
public class PollingMailSource implements PollableSource {
private final Log logger = LogFactory.getLog(this.getClass());
private final FolderConnection folderConnection;
private MailMessageConverter converter = new DefaultMailMessageConverter();
private LocalMailMessageStore mailMessageStore = new DefaultLocalMailMessageStore();
public PollingMailSource(FolderConnection folderConnetion) {
this.folderConnection = folderConnetion;
}
@SuppressWarnings("unchecked")
public Message receive() {
Message received = null;
javax.mail.Message mailMessage = mailMessageStore.getNext();
if (mailMessage == null) {
try {
javax.mail.Message[] messages = folderConnection.receive();
mailMessageStore.addLast(messages);
mailMessage = mailMessageStore.getNext();
} catch (Exception e) {
throw new org.springframework.integration.message.MessagingException(
"Excpetion receiving mail", e);
}
}
if (mailMessage != null) {
received = converter.create((MimeMessage) mailMessage);
if (logger.isDebugEnabled()) {
logger.debug("Received message " + received);
}
}
return received;
}
public void setConverter(MailMessageConverter converter) {
this.converter = converter;
}
public void setMailMessageStore(LocalMailMessageStore mailMessageStore) {
this.mailMessageStore = mailMessageStore;
}
public FolderConnection getFolderConnection() {
return folderConnection;
}
public MailMessageConverter getConverter() {
return converter;
}
public LocalMailMessageStore getMailMessageStore() {
return mailMessageStore;
}
}

View File

@@ -1,90 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import org.springframework.integration.message.Message;
/**
* Mail header generator implementation that populates a mail message header
* from statically configured properties.
*
* @author Marius Bogoevici
*/
public class StaticMailHeaderGenerator extends AbstractMailHeaderGenerator {
private String subject;
private String[] to;
private String[] cc;
private String[] bcc;
private String from;
private String replyTo;
public void setSubject(String subject) {
this.subject = subject;
}
protected String getSubject(Message<?> message) {
return this.subject;
}
public void setTo(String[] to) {
this.to = to;
}
protected String[] getTo(Message<?> message) {
return this.to;
}
public void setCc(String[] cc) {
this.cc = cc;
}
protected String[] getCc(Message<?> message) {
return this.cc;
}
public void setBcc(String[] bcc) {
this.bcc = bcc;
}
protected String[] getBcc(Message<?> message) {
return this.bcc;
}
public void setFrom(String from) {
this.from = from;
}
protected String getFrom(Message<?> message) {
return this.from;
}
public void setReplyTo(String replyTo) {
this.replyTo = replyTo;
}
protected String getReplyTo(Message<?> message) {
return this.replyTo;
}
}

View File

@@ -1,147 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import javax.mail.Message;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.Lifecycle;
import org.springframework.core.task.TaskExecutor;
import org.springframework.integration.adapter.mail.monitor.AsyncMonitoringStrategy;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.message.MessageSource;
import org.springframework.integration.message.MessageTarget;
import org.springframework.util.Assert;
/**
* Broadcasts all mail messages recovered to subscribed {@link MessageTarget MessageTargets}.
* The given {@link FolderConnection} should be using an {@link AsyncMonitoringStrategy} to
* retrieve mail.
*
* @author Jonas Partner
*/
public class SubscribableMailSource implements MessageSource, Lifecycle, DisposableBean {
private final Log logger = LogFactory.getLog(this.getClass());
private volatile MessageChannel outputChannel;
private final TaskExecutor taskExecutor;
private final MonitorRunnable monitorRunnable;
private volatile boolean monitorRunning = false;
private volatile MailMessageConverter converter = new DefaultMailMessageConverter();
public SubscribableMailSource(FolderConnection folderConnection, TaskExecutor taskExecutor) {
Assert.notNull(folderConnection, "FolderConnection must not be null");
Assert.notNull(taskExecutor, "TaskExecutor must not be null");
this.monitorRunnable = new MonitorRunnable(folderConnection);
this.taskExecutor = taskExecutor;
}
public void setOutputChannel(MessageChannel outputChannel) {
this.outputChannel = outputChannel;
}
public void setConverter(MailMessageConverter converter) {
this.converter = converter;
}
public void destroy() throws Exception {
this.stop();
}
public void start() {
if (logger.isInfoEnabled()) {
logger.info("Starting to monitor mailbox");
}
this.startMonitor();
if (logger.isInfoEnabled()) {
logger.info("Started to monitor mailbox");
}
}
public void stop() {
if (logger.isInfoEnabled()) {
logger.info("Stopping monitoring of mailbox");
}
this.stopMonitor();
if (logger.isInfoEnabled()) {
logger.info("Stopped monitoring mailbox");
}
}
public boolean isRunning() {
return this.monitorRunning;
}
protected void startMonitor() {
synchronized (this.monitorRunnable) {
if (!this.monitorRunning) {
this.taskExecutor.execute(this.monitorRunnable);
}
this.monitorRunning = true;
}
}
protected void stopMonitor() {
synchronized (this.monitorRunnable) {
if (this.monitorRunning) {
this.monitorRunnable.interrupt();
}
this.monitorRunning = false;
}
}
private class MonitorRunnable implements Runnable {
private volatile Thread thread;
private final FolderConnection folderConnection;
private MonitorRunnable(FolderConnection folderConnection) {
this.folderConnection = folderConnection;
}
public synchronized void interrupt() {
this.thread.interrupt();
}
public void run() {
this.thread = Thread.currentThread();
while (!Thread.currentThread().isInterrupted()) {
Message[] messages = this.folderConnection.receive();
for (Message message : messages) {
outputChannel.send(converter.create((MimeMessage) message));
}
}
}
}
}

View File

@@ -1,40 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageMapper;
import org.springframework.mail.MailMessage;
import org.springframework.mail.SimpleMailMessage;
/**
* Message mapper for transforming integration messages into simple text
* e-mail messages. The body of the e-mail message will be the result of
* invoking the message payload's toString() method.
*
* @author Marius Bogoevici
* @author Mark Fisher
*/
public class TextMailMessageMapper implements MessageMapper<String, MailMessage> {
public MailMessage mapMessage(Message<String> message) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setText(message.getPayload().toString());
return mailMessage;
}
}

View File

@@ -1,80 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.config;
import org.w3c.dom.Element;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.ConfigurationException;
import org.springframework.integration.adapter.mail.MailTarget;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.StringUtils;
/**
* Parser for the &lt;mail-target/&gt; element.
*
* @author Mark Fisher
*/
public class MailTargetParser extends AbstractSingleBeanDefinitionParser {
protected Class<?> getBeanClass(Element element) {
return MailTarget.class;
}
protected boolean shouldGenerateId() {
return false;
}
protected boolean shouldGenerateIdAsFallback() {
return true;
}
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String mailSenderRef = element.getAttribute("mail-sender");
String host = element.getAttribute("host");
String username = element.getAttribute("username");
String password = element.getAttribute("password");
String headerGeneratorRef = element.getAttribute("header-generator");
if (StringUtils.hasText(mailSenderRef)) {
if (StringUtils.hasText(host) || StringUtils.hasText(username) || StringUtils.hasText(password)) {
throw new ConfigurationException("The 'host', 'username', and 'password' properties " +
"should not be provided when using a 'mail-sender' reference.");
}
builder.addConstructorArgReference(mailSenderRef);
}
else if (StringUtils.hasText(host)) {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
if (StringUtils.hasText(username)) {
mailSender.setUsername(username);
}
if (StringUtils.hasText(password)) {
mailSender.setPassword(password);
}
builder.addConstructorArgValue(mailSender);
}
else {
throw new ConfigurationException("Either a 'mail-sender' reference or 'host' property is required.");
}
if (StringUtils.hasText(headerGeneratorRef)) {
builder.addPropertyReference("headerGenerator", headerGeneratorRef);
}
}
}

View File

@@ -1,93 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.config;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.ConfigurationException;
import org.springframework.integration.adapter.mail.DefaultFolderConnection;
import org.springframework.integration.adapter.mail.PollingMailSource;
import org.springframework.integration.adapter.mail.monitor.MonitoringStrategy;
import org.springframework.integration.adapter.mail.monitor.PollingMonitoringStrategy;
import org.springframework.integration.adapter.mail.monitor.Pop3PollingMonitoringStrategy;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
/**
*
* @author Jonas Partner
*
*/
public class PollingMailSourceParser extends AbstractSingleBeanDefinitionParser {
protected Class<?> getBeanClass(Element element) {
return PollingMailSource.class;
}
protected boolean shouldGenerateId() {
return false;
}
protected boolean shouldGenerateIdAsFallback() {
return true;
}
protected void doParse(Element element, ParserContext parserContext,
BeanDefinitionBuilder builder) {
String mailConvertorRef = element.getAttribute("convertor");
String uri = element.getAttribute("store-uri");
String propertiesRef = element.getAttribute("javaMailProperties");
if (!StringUtils.hasLength(uri)) {
throw new ConfigurationException("A store-uri is required");
}
BeanDefinitionBuilder folderConnectionBuilder = BeanDefinitionBuilder
.genericBeanDefinition(DefaultFolderConnection.class);
String storeType = uri.substring(0, 4).toLowerCase();
MonitoringStrategy monitoringStrategy = null;
if (storeType.equals("pop3")) {
monitoringStrategy = new Pop3PollingMonitoringStrategy();
} else if (storeType.equals("imap")) {
monitoringStrategy = new PollingMonitoringStrategy();
} else {
throw new ConfigurationException(
"No monitoring strategy for store-uri " + uri);
}
folderConnectionBuilder.addConstructorArgValue(uri);
folderConnectionBuilder.addConstructorArgValue(monitoringStrategy);
// set polling true
folderConnectionBuilder.addConstructorArgValue(true);
if (StringUtils.hasText(propertiesRef)) {
folderConnectionBuilder.addPropertyReference("javaMailProperties",
propertiesRef);
}
String folderConnectionName = parserContext.getReaderContext()
.registerWithGeneratedName(
folderConnectionBuilder.getBeanDefinition());
builder.addDependsOn(folderConnectionName);
builder.addConstructorArgValue(folderConnectionBuilder
.getBeanDefinition());
if (StringUtils.hasText(mailConvertorRef)) {
builder.addPropertyReference("convertor", mailConvertorRef);
}
}
}

View File

@@ -1,88 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.config;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.ConfigurationException;
import org.springframework.integration.adapter.mail.DefaultFolderConnection;
import org.springframework.integration.adapter.mail.SubscribableMailSource;
import org.springframework.integration.adapter.mail.monitor.ImapIdleMonitoringStrategy;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
/**
*
* @author Jonas Partner
*
*/
public class SubscribableImapIdleMailSourceParser extends
AbstractSingleBeanDefinitionParser {
protected Class<?> getBeanClass(Element element) {
return SubscribableMailSource.class;
}
protected boolean shouldGenerateId() {
return false;
}
protected boolean shouldGenerateIdAsFallback() {
return true;
}
protected void doParse(Element element, ParserContext parserContext,
BeanDefinitionBuilder builder) {
String mailConvertorRef = element.getAttribute("convertor");
String uri = element.getAttribute("store-uri");
String taskExecutorRef = element.getAttribute("task-executor");
String propertiesRef = element.getAttribute("javaMailProperties");
if (!StringUtils.hasLength(uri)) {
throw new ConfigurationException(
"A value for the store-uri attribue is required");
}
if (!StringUtils.hasLength(taskExecutorRef)) {
throw new ConfigurationException(
"A value for the task-executor attribute is required");
}
BeanDefinitionBuilder folderConnectionBuilder = BeanDefinitionBuilder
.genericBeanDefinition(DefaultFolderConnection.class);
String storeType = uri.substring(0, 4).toLowerCase();
if (!storeType.equals("imap")) {
throw new ConfigurationException(
"store-uri must start with imap for the imap idle source");
}
folderConnectionBuilder.addConstructorArgValue(uri);
folderConnectionBuilder
.addConstructorArgValue(new ImapIdleMonitoringStrategy());
// set polling false
folderConnectionBuilder.addConstructorArgValue(false);
if (StringUtils.hasText(propertiesRef)) {
folderConnectionBuilder.addPropertyReference("javaMailProperties",
propertiesRef);
}
builder.addConstructorArgValue(folderConnectionBuilder
.getBeanDefinition());
builder.addConstructorArgReference(taskExecutorRef);
if (StringUtils.hasText(mailConvertorRef)) {
builder.addPropertyReference("convertor", mailConvertorRef);
}
}
}

View File

@@ -1,169 +0,0 @@
/*
* Copyright 2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.monitor;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.search.AndTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.SearchTerm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Abstract base class for the {@link MonitoringStrategy} interface. Exposes a {@link #setDeleteMessages(boolean)
* deleteMessages} property, and includes a basic workflow for message monitoring.
*
* @author Arjen Poutsma
*/
public abstract class AbstractMonitoringStrategy implements MonitoringStrategy {
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
private boolean deleteMessages = true;
private int maxMessagesPerReceive = -1;
/**
* Sets whether messages should be marked as {@link javax.mail.Flags.Flag#DELETED DELETED} after they have been
* read. Default is <code>true</code>.
*/
public void setDeleteMessages(boolean deleteMessages) {
this.deleteMessages = deleteMessages;
}
public int getFolderOpenMode() {
return deleteMessages ? Folder.READ_WRITE : Folder.READ_ONLY;
}
public void setMaxMessagePerDownload(int maxMessagesPerReceive){
this.maxMessagesPerReceive = maxMessagesPerReceive;
}
/**
* Monitors the given folder, and returns any new messages when they arrive. This implementation calls {@link
* #waitForNewMessages(Folder)}, then searches for new messages using {@link #searchForNewMessages(Folder)}, fetches
* the messages using {@link #fetchMessages(Folder, Message[])}, and finally {@link #setDeleteMessages(boolean)
* deletes} the messages, if {@link #setDeleteMessages(boolean) deleteMessages} is <code>true</code>.
*
* @param folder the folder to monitor
* @return the new messages
* @throws MessagingException in case of JavaMail errors
* @throws InterruptedException when a thread is interrupted
*/
public final Message[] receive(Folder folder) throws MessagingException, InterruptedException {
logger.info("Receiving for folder" + folder.getFullName());
if(!folder.isOpen()){
folder.open(getFolderOpenMode());
}
folder.getMessageCount();
Message[] messages = searchForNewMessages(folder);
if (logger.isDebugEnabled()) {
logger.debug("Found " + messages.length + " new messages");
}
if(maxMessagesPerReceive > 0 && messages.length > maxMessagesPerReceive){
Message[] reducedMessages = new Message[maxMessagesPerReceive];
System.arraycopy(messages, 0, reducedMessages, 0, maxMessagesPerReceive);
messages = reducedMessages;
}
if (messages.length > 0) {
fetchMessages(folder, messages);
}
if (deleteMessages) {
deleteMessages(folder, messages);
}
return messages;
}
/**
* Retrieves new messages from the given folder. This implementation creates a {@link SearchTerm} that searches for
* all messages in the folder that are {@link javax.mail.Flags.Flag#RECENT RECENT}, not {@link
* javax.mail.Flags.Flag#ANSWERED ANSWERED}, and not {@link javax.mail.Flags.Flag#DELETED DELETED}. The search term
* is used to {@link Folder#search(SearchTerm) search} for new messages.
*
* @param folder the folder to retrieve new messages from
* @return the new messages
* @throws MessagingException in case of JavaMail errors
*/
protected Message[] searchForNewMessages(Folder folder) throws MessagingException {
if (!folder.isOpen()) {
return new Message[0];
}
Flags supportedFlags = folder.getPermanentFlags();
SearchTerm searchTerm = null;
if (supportedFlags != null) {
if (supportedFlags.contains(Flags.Flag.RECENT)) {
searchTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
}
if (supportedFlags.contains(Flags.Flag.ANSWERED)) {
FlagTerm answeredTerm = new FlagTerm(new Flags(Flags.Flag.ANSWERED), false);
if (searchTerm == null) {
searchTerm = answeredTerm;
}
else {
searchTerm = new AndTerm(searchTerm, answeredTerm);
}
}
if (supportedFlags.contains(Flags.Flag.DELETED)) {
FlagTerm deletedTerm = new FlagTerm(new Flags(Flags.Flag.DELETED), false);
if (searchTerm == null) {
searchTerm = deletedTerm;
}
else {
searchTerm = new AndTerm(searchTerm, deletedTerm);
}
}
}
return searchTerm != null ? folder.search(searchTerm) : folder.getMessages();
}
/**
* Fetches the specified messages from the specified folder. Default implementation {@link Folder#fetch(Message[],
* FetchProfile) fetches} every {@link javax.mail.FetchProfile.Item}.
*
* @param folder the folder to fetch messages from
* @param messages the messages to fetch
* @throws MessagingException in case of JavMail errors
*/
protected void fetchMessages(Folder folder, Message[] messages) throws MessagingException {
FetchProfile contentsProfile = new FetchProfile();
contentsProfile.add(FetchProfile.Item.ENVELOPE);
contentsProfile.add(FetchProfile.Item.CONTENT_INFO);
contentsProfile.add(FetchProfile.Item.FLAGS);
folder.fetch(messages, contentsProfile);
}
/**
* Deletes the given messages from the given folder. Only invoked when {@link #setDeleteMessages(boolean)} is
* <code>true</code>.
*
* @param folder the folder to delete messages from
* @param messages the messages to delete
* @throws MessagingException in case of JavaMail errors
*/
protected void deleteMessages(Folder folder, Message[] messages) throws MessagingException {
for (int i = 0; i < messages.length; i++) {
messages[i].setFlag(Flags.Flag.DELETED, true);
}
}
}

View File

@@ -1,26 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.monitor;
import javax.mail.Folder;
import javax.mail.MessagingException;
public interface AsyncMonitoringStrategy {
public abstract void waitForNewMessages(Folder folder)
throws MessagingException, InterruptedException;
}

View File

@@ -1,52 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.monitor;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.mail.Message;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Jonas Partner
*
*/
public class DefaultLocalMailMessageStore implements LocalMailMessageStore {
private final Log logger = LogFactory.getLog(this.getClass());
private ConcurrentLinkedQueue<Message> messages = new ConcurrentLinkedQueue<Message>();
public void addLast(Message[] newMessages) {
if(newMessages == null){
return;
}
for (Message message : newMessages) {
messages.add(message);
}
logger.info("LocalMailMessageStore size is now" + messages.size());
}
public Message getNext() {
logger.info("Message store size " + messages.size());
return messages.poll();
}
}

View File

@@ -1,81 +0,0 @@
/*
* Copyright 2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.monitor;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.event.MessageCountAdapter;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.MessageCountListener;
import org.springframework.util.Assert;
import com.sun.mail.imap.IMAPFolder;
/**
* Implementation of the {@link MonitoringStrategy} interface that uses the IMAP IDLE command for asynchronous message
* detection.
* <p/>
* <b>Note</b> that this implementation is only suitable for use with IMAP servers which support the IDLE command.
* Additionally, this strategy requires JavaMail version 1.4.1.
*
* @author Arjen Poutsma
*/
public class ImapIdleMonitoringStrategy extends AbstractMonitoringStrategy implements AsyncMonitoringStrategy {
private MessageCountListener messageCountListener;
/* (non-Javadoc)
* @see org.springframework.integration.adapter.mail.monitor.AynchronouseMonitoringStrategy#waitForNewMessages(javax.mail.Folder)
*/
public void waitForNewMessages(Folder folder) throws MessagingException, InterruptedException {
Assert.isInstanceOf(IMAPFolder.class, folder);
IMAPFolder imapFolder = (IMAPFolder) folder;
//retrieve unseen messages before we enter the blocking idle call
if (searchForNewMessages(folder).length > 0) {
return;
}
if (messageCountListener == null) {
createMessageCountListener();
}
folder.addMessageCountListener(messageCountListener);
try {
imapFolder.idle();
}
finally {
folder.removeMessageCountListener(messageCountListener);
}
}
private void createMessageCountListener() {
messageCountListener = new MessageCountAdapter() {
public void messagesAdded(MessageCountEvent e) {
Message[] messages = e.getMessages();
for (int i = 0; i < messages.length; i++) {
try {
// this will return the flow to the idle call, above
messages[i].getLineCount();
}
catch (MessagingException ex) {
// ignore
}
}
}
};
}
}

View File

@@ -1,32 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.monitor;
import javax.mail.Message;
/**
* Acts as a buffer for downloaded MailMessages
* @author Jonas Partner
*
*/
public interface LocalMailMessageStore {
public Message getNext();
public void addLast(Message[] newMessages);
}

View File

@@ -1,36 +0,0 @@
/*
* Copyright 2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.monitor;
/**
* Declares Mail-specific transport constants.
*
* @author Arjen Poutsma
*/
public interface MailTransportConstants {
/**
* The "mail" URI scheme.
*/
String MAIL_URI_SCHEME = "mailto";
/**
* The "In-Reply-To" header.
*/
String HEADER_IN_REPLY_TO = "In-Reply-To";
}

View File

@@ -1,187 +0,0 @@
/*
* Copyright 2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.monitor;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Service;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
/**
* Collection of utility methods to work with Mail transports.
*
* @author Arjen Poutsma
*/
public abstract class MailTransportUtils {
private static final Pattern TO_PATTERN = Pattern.compile("^([^\\?]+)");
private static final Pattern SUBJECT_PATTERN = Pattern.compile("subject=([^\\&]+)");
private static final Log logger = LogFactory.getLog(MailTransportUtils.class);
private MailTransportUtils() {
}
public static InternetAddress getTo(URI uri) {
Matcher matcher = TO_PATTERN.matcher(uri.getSchemeSpecificPart());
if (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
String group = matcher.group(i);
if (group != null) {
try {
return new InternetAddress(group);
}
catch (AddressException e) {
// try next group
}
}
}
}
return null;
}
public static String getSubject(URI uri) {
Matcher matcher = SUBJECT_PATTERN.matcher(uri.getSchemeSpecificPart());
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
/**
* Close the given JavaMail Service and ignore any thrown exception. This is useful for typical <code>finally</code>
* blocks in manual JavaMail code.
*
* @param service the JavaMail Service to close (may be <code>null</code>)
* @see Transport
* @see Store
*/
public static void closeService(Service service) {
if (service != null) {
try {
service.close();
}
catch (MessagingException ex) {
logger.debug("Could not close JavaMail Service", ex);
}
}
}
/**
* Close the given JavaMail Folder and ignore any thrown exception. This is useful for typical <code>finally</code>
* blocks in manual JavaMail code.
*
* @param folder the JavaMail Folder to close (may be <code>null</code>)
*/
public static void closeFolder(Folder folder) {
closeFolder(folder, false);
}
/**
* Close the given JavaMail Folder and ignore any thrown exception. This is useful for typical <code>finally</code>
* blocks in manual JavaMail code.
*
* @param folder the JavaMail Folder to close (may be <code>null</code>)
* @param expunge whether all deleted messages should be expunged from the folder
*/
public static void closeFolder(Folder folder, boolean expunge) {
if (folder != null && folder.isOpen()) {
try {
folder.close(expunge);
}
catch (MessagingException ex) {
logger.debug("Could not close JavaMail Folder", ex);
}
}
}
/** Returns a string representation of the given {@link URLName}, where the password has been protected. */
public static String toPasswordProtectedString(URLName name) {
String protocol = name.getProtocol();
String username = name.getUsername();
String password = name.getPassword();
String host = name.getHost();
int port = name.getPort();
String file = name.getFile();
String ref = name.getRef();
StringBuffer tempURL = new StringBuffer();
if (protocol != null) {
tempURL.append(protocol).append(':');
}
if (StringUtils.hasLength(username) || StringUtils.hasLength(host)) {
tempURL.append("//");
if (StringUtils.hasLength(username)) {
tempURL.append(username);
if (StringUtils.hasLength(password)) {
tempURL.append(":*****");
}
tempURL.append("@");
}
if (StringUtils.hasLength(host)) {
tempURL.append(host);
}
if (port != -1) {
tempURL.append(':').append(Integer.toString(port));
}
if (StringUtils.hasLength(file)) {
tempURL.append('/');
}
}
if (StringUtils.hasLength(file)) {
tempURL.append(file);
}
if (StringUtils.hasLength(ref)) {
tempURL.append('#').append(ref);
}
return tempURL.toString();
}
/**
* Converts the given internet address into a <code>mailto</code> URI.
*
* @param to the To: address
* @param subject the subject, may be <code>null</code>
* @return a mailto URI
*/
public static URI toUri(InternetAddress to, String subject) throws URISyntaxException {
if (StringUtils.hasLength(subject)) {
return new URI(MailTransportConstants.MAIL_URI_SCHEME, to.getAddress() + "?subject=" + subject, null);
}
else {
return new URI(MailTransportConstants.MAIL_URI_SCHEME, to.getAddress(), null);
}
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright 2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.monitor;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* Defines the contract for objects that monitor a given folder for new messages. Allows for multiple implementation
* strategies, including polling, or event-driven techniques such as IMAP's <code>IDLE</code> command.
*
* @author Arjen Poutsma
*/
public interface MonitoringStrategy {
/**
* Monitors the given folder, and returns any new messages when they arrive.
*
* @param folder the folder in which to look for new messages
* @return the new messages
* @throws MessagingException in case of JavaMail errors
* @throws InterruptedException if a thread is interrupted
*/
Message[] receive(Folder folder) throws MessagingException, InterruptedException;
/**
* Returns the folder open mode to be used by this strategy. Can be either {@link Folder#READ_ONLY} or {@link
* Folder#READ_WRITE}.
*/
int getFolderOpenMode();
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.monitor;
/**
* Implementation of the {@link MonitoringStrategy} interface that uses a simple polling mechanism. Defines a {@link
* #setPollingInterval(long) polling interval} property which defines the interval in between message polls.
* <p/>
* <b>Note</b> that this implementation is not suitable for use with POP3 servers. Use the {@link
* Pop3PollingMonitoringStrategy} instead.
*
* @author Arjen Poutsma
*/
public class PollingMonitoringStrategy extends AbstractMonitoringStrategy {
}

View File

@@ -1,66 +0,0 @@
/*
* Copyright 2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.monitor;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
* Implementation of the {@link MonitoringStrategy} interface that uses a simple polling mechanism suitable for POP3
* servers. Since POP3 does not have a native mechanism to determine which messages are "new", this implementation
* simply retrieves all messages in the {@link Folder}, and delete them afterwards. All messages in the POP3 mailbox are
* therefore, by definition, new.
* <p/>
* Setting the {@link #setDeleteMessages(boolean) deleteMessages} property is therefore ignored: messages are always
* deleted.
*
* @author Arjen Poutsma
*/
public class Pop3PollingMonitoringStrategy extends PollingMonitoringStrategy {
public Pop3PollingMonitoringStrategy() {
super.setDeleteMessages(true);
}
public void setDeleteMessages(boolean deleteMessages) {
}
/**
* Simply returns {@link Folder#getMessages()}.
*/
protected Message[] searchForNewMessages(Folder folder) throws MessagingException {
return folder.getMessages();
}
/**
* Deletes the given messages from the given folder, and closes it to expunge deleted messages.
*
* @param folder the folder to delete messages from
* @param messages the messages to delete
* @throws MessagingException in case of JavaMail errors
*/
protected void deleteMessages(Folder folder, Message[] messages) throws MessagingException {
super.deleteMessages(folder, messages);
// expunge deleted mails, and make sure we've retrieved them before closing the folder
for (int i = 0; i < messages.length; i++) {
new MimeMessage((MimeMessage) messages[i]);
}
MailTransportUtils.closeFolder(folder, true);
}
}

View File

@@ -1,3 +0,0 @@
mail-target=org.springframework.integration.adapter.mail.config.MailTargetParser
polling-mail-source=org.springframework.integration.adapter.mail.config.PollingMailSourceParser
imap-idle-mail-source=org.springframework.integration.adapter.mail.config.SubscribableImapIdleMailSourceParser

View File

@@ -1,153 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.easymock.classextension.EasyMock;
import org.junit.Test;
import org.springframework.integration.message.MessageHeaders;
import org.springframework.util.ObjectUtils;
/**
* @author Mark Fisher
*/
public class DefaultMailMessageHeaderMapperTests {
@Test
public void mapExactlyOneFromAttributeFromMimeMessage() throws MessagingException {
DefaultMailMessageHeaderMapper mapper = new DefaultMailMessageHeaderMapper();
MimeMessage mailMessageMock = EasyMock.createMock(MimeMessage.class);
Address[] fromAddresses = new Address[] { new InternetAddress("from@example.org") };
EasyMock.expect(mailMessageMock.getFrom()).andReturn(fromAddresses);
EasyMock.expect(mailMessageMock.getRecipients(RecipientType.BCC)).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getRecipients(RecipientType.CC)).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getRecipients(RecipientType.TO)).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getReplyTo()).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getSubject()).andReturn("mail test");
EasyMock.replay(mailMessageMock);
Map<String, Object> headers = mapper.mapToMessageHeaders(mailMessageMock);
Object fromHeader = headers.get(MailHeaders.FROM);
assertNotNull(fromHeader);
assertTrue(fromHeader instanceof String);
assertEquals("from@example.org", fromHeader);
}
@Test
public void mapExactlyOneReplyToAttributeFromMimeMessage() throws MessagingException {
DefaultMailMessageHeaderMapper mapper = new DefaultMailMessageHeaderMapper();
MimeMessage mailMessageMock = EasyMock.createMock(MimeMessage.class);
Address[] replyToAddresses = new Address[] { new InternetAddress("replyTo@example.org") };
EasyMock.expect(mailMessageMock.getFrom()).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getRecipients(RecipientType.BCC)).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getRecipients(RecipientType.CC)).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getRecipients(RecipientType.TO)).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getReplyTo()).andReturn(replyToAddresses);
EasyMock.expect(mailMessageMock.getSubject()).andReturn("mail test");
EasyMock.replay(mailMessageMock);
Map<String, Object> headers = mapper.mapToMessageHeaders(mailMessageMock);
Object replyToHeader = headers.get(MailHeaders.REPLY_TO);
assertNotNull(replyToHeader);
assertTrue(replyToHeader instanceof String);
assertEquals("replyTo@example.org", replyToHeader);
}
@Test
public void mapMultipleToAttributesFromMimeMessage() throws MessagingException {
DefaultMailMessageHeaderMapper mapper = new DefaultMailMessageHeaderMapper();
MimeMessage mailMessageMock = EasyMock.createMock(MimeMessage.class);
Address[] toAddresses = new Address[] {
new InternetAddress("a@example.org"), new InternetAddress("b@example.org"), new InternetAddress("c@example.org")
};
EasyMock.expect(mailMessageMock.getFrom()).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getRecipients(RecipientType.BCC)).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getRecipients(RecipientType.CC)).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getRecipients(RecipientType.TO)).andReturn(toAddresses);
EasyMock.expect(mailMessageMock.getReplyTo()).andReturn(new Address[0]);
EasyMock.expect(mailMessageMock.getSubject()).andReturn("mail test");
EasyMock.replay(mailMessageMock);
Map<String, Object> headers = mapper.mapToMessageHeaders(mailMessageMock);
Object toHeader = headers.get(MailHeaders.TO);
assertNotNull(toHeader);
assertTrue(toHeader instanceof String[]);
String[] addresses = (String[]) toHeader;
assertTrue(ObjectUtils.containsElement(addresses, "a@example.org"));
assertTrue(ObjectUtils.containsElement(addresses, "b@example.org"));
assertTrue(ObjectUtils.containsElement(addresses, "c@example.org"));
}
@Test
public void mapReplyToValueFromHeadersToMimeMessage() throws MessagingException {
DefaultMailMessageHeaderMapper mapper = new DefaultMailMessageHeaderMapper();
Map<String, Object> headerMap = new HashMap<String, Object>();
headerMap.put(MailHeaders.REPLY_TO, "replyTo@example.org");
MessageHeaders headers = new MessageHeaders(headerMap);
MimeMessage mailMessageMock = EasyMock.createNiceMock(MimeMessage.class);
EasyMock.replay(mailMessageMock);
MimeMessage mimeMessage = new MimeMessage(mailMessageMock);
mapper.mapFromMessageHeaders(headers, mimeMessage);
Address[] replyToAddresses = mimeMessage.getReplyTo();
assertEquals(1, replyToAddresses.length);
assertEquals("replyTo@example.org", replyToAddresses[0].toString());
}
@Test
public void mapFromValueFromHeadersToMimeMessage() throws MessagingException {
DefaultMailMessageHeaderMapper mapper = new DefaultMailMessageHeaderMapper();
Map<String, Object> headerMap = new HashMap<String, Object>();
headerMap.put(MailHeaders.FROM, "from@example.org");
MessageHeaders headers = new MessageHeaders(headerMap);
MimeMessage mailMessageMock = EasyMock.createNiceMock(MimeMessage.class);
EasyMock.replay(mailMessageMock);
MimeMessage mimeMessage = new MimeMessage(mailMessageMock);
mapper.mapFromMessageHeaders(headers, mimeMessage);
Address[] fromAddresses = mimeMessage.getFrom();
assertEquals(1, fromAddresses.length);
assertEquals("from@example.org", fromAddresses[0].toString());
}
@Test
public void mapMultileToValuesFromHeadersToMimeMessage() throws MessagingException {
DefaultMailMessageHeaderMapper mapper = new DefaultMailMessageHeaderMapper();
Map<String, Object> headerMap = new HashMap<String, Object>();
String[] addressStrings = new String[] { "a@example.org", "b@example.org", "c@example.org" };
headerMap.put(MailHeaders.TO, addressStrings);
MessageHeaders headers = new MessageHeaders(headerMap);
MimeMessage mailMessageMock = EasyMock.createNiceMock(MimeMessage.class);
EasyMock.replay(mailMessageMock);
MimeMessage mimeMessage = new MimeMessage(mailMessageMock);
mapper.mapFromMessageHeaders(headers, mimeMessage);
Address[] toAddresses = mimeMessage.getRecipients(RecipientType.TO);
assertEquals(3, toAddresses.length);
assertTrue(ObjectUtils.containsElement(toAddresses, new InternetAddress("a@example.org")));
assertTrue(ObjectUtils.containsElement(toAddresses, new InternetAddress("b@example.org")));
assertTrue(ObjectUtils.containsElement(toAddresses, new InternetAddress("c@example.org")));
}
}

View File

@@ -1,91 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.DataInputStream;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.internet.MimeMessage;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.adapter.mail.MailTarget;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.StringMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Marius Bogoevici
*/
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/org/springframework/integration/adapter/mail/mailTarget.xml"})
public class MailTargetContextTests {
@Autowired
private MailTarget mailTarget;
@Autowired
private StubJavaMailSender mailSender;
@Before
public void reset() {
this.mailSender.reset();
}
@Test
public void testStringMesssagesWithConfiguration() {
this.mailTarget.send(new StringMessage(MailTestsHelper.MESSAGE_TEXT));
SimpleMailMessage message = MailTestsHelper.createSimpleMailMessage();
assertEquals("no mime message should have been sent",
0, this.mailSender.getSentMimeMessages().size());
assertEquals("only one simple message must be sent",
1, this.mailSender.getSentSimpleMailMessages().size());
assertEquals("message content different from expected",
message, this.mailSender.getSentSimpleMailMessages().get(0));
}
@Test
public void testByteArrayMessage() throws Exception {
byte[] payload = {1, 2, 3};
mailTarget.send(new GenericMessage<byte[]>(payload));
assertEquals("no mime message should have been sent",
1, mailSender.getSentMimeMessages().size());
assertEquals("only one simple message must be sent",
0, mailSender.getSentSimpleMailMessages().size());
byte[] buffer = new byte[1024];
MimeMessage mimeMessage = mailSender.getSentMimeMessages().get(0);
assertTrue("message must be multipart", mimeMessage.getContent() instanceof Multipart);
int size = new DataInputStream(((Multipart) mimeMessage.getContent()).getBodyPart(0).getInputStream()).read(buffer);
assertEquals("buffer size does not match", payload.length, size);
byte[] messageContent = new byte[size];
System.arraycopy(buffer, 0, messageContent, 0, payload.length);
assertArrayEquals("buffer content does not match", payload, messageContent);
assertEquals(mimeMessage.getRecipients(Message.RecipientType.TO).length, MailTestsHelper.TO.length);
}
}

View File

@@ -1,119 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.DataInputStream;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.MessageBuilder;
import org.springframework.integration.message.StringMessage;
import org.springframework.mail.SimpleMailMessage;
/**
* @author Marius Bogoevici
*/
public class MailTargetTests {
private MailTarget mailTarget;
private StubJavaMailSender mailSender;
private StaticMailHeaderGenerator staticMailHeaderGenerator;
@Before
public void setUp() throws Exception {
this.mailSender = new StubJavaMailSender(new MimeMessage((Session) null));
this.staticMailHeaderGenerator = new StaticMailHeaderGenerator();
this.staticMailHeaderGenerator.setBcc(MailTestsHelper.BCC);
this.staticMailHeaderGenerator.setCc(MailTestsHelper.CC);
this.staticMailHeaderGenerator.setFrom(MailTestsHelper.FROM);
this.staticMailHeaderGenerator.setReplyTo(MailTestsHelper.REPLY_TO);
this.staticMailHeaderGenerator.setSubject(MailTestsHelper.SUBJECT);
this.staticMailHeaderGenerator.setTo(MailTestsHelper.TO);
this.mailTarget = new MailTarget(this.mailSender);
this.mailTarget.afterPropertiesSet();
}
@Test
public void testTextMessage() {
this.mailTarget.setHeaderGenerator(this.staticMailHeaderGenerator);
this.mailTarget.send(new StringMessage(MailTestsHelper.MESSAGE_TEXT));
SimpleMailMessage message = MailTestsHelper.createSimpleMailMessage();
assertEquals("no mime message should have been sent",
0, mailSender.getSentMimeMessages().size());
assertEquals("only one simple message must be sent",
1, mailSender.getSentSimpleMailMessages().size());
assertEquals("message content different from expected",
message, mailSender.getSentSimpleMailMessages().get(0));
}
@Test
public void testByteArrayMessage() throws Exception {
this.mailTarget.setHeaderGenerator(this.staticMailHeaderGenerator);
byte[] payload = {1, 2, 3};
this.mailTarget.send(new GenericMessage<byte[]>(payload));
byte[] buffer = new byte[1024];
MimeMessage mimeMessage = this.mailSender.getSentMimeMessages().get(0);
assertTrue("message must be multipart", mimeMessage.getContent() instanceof Multipart);
int size = new DataInputStream(((Multipart) mimeMessage.getContent()).getBodyPart(0).getInputStream()).read(buffer);
assertEquals("buffer size does not match", payload.length, size);
byte[] messageContent = new byte[size];
System.arraycopy(buffer, 0, messageContent, 0, payload.length);
assertArrayEquals("buffer content does not match", payload, messageContent);
assertEquals(mimeMessage.getRecipients(Message.RecipientType.TO).length, MailTestsHelper.TO.length);
}
@Test
public void testDefaultMailHeaderGenerator() {
org.springframework.integration.message.Message<String> message =
MessageBuilder.withPayload(MailTestsHelper.MESSAGE_TEXT)
.setHeader(MailHeaders.SUBJECT, MailTestsHelper.SUBJECT)
.setHeader(MailHeaders.TO, MailTestsHelper.TO)
.setHeader(MailHeaders.CC, MailTestsHelper.CC)
.setHeader(MailHeaders.BCC, MailTestsHelper.BCC)
.setHeader(MailHeaders.FROM, MailTestsHelper.FROM)
.setHeader(MailHeaders.REPLY_TO, MailTestsHelper.REPLY_TO).build();
this.mailTarget.send(message);
SimpleMailMessage mailMessage = MailTestsHelper.createSimpleMailMessage();
assertEquals("no mime message should have been sent",
0, mailSender.getSentMimeMessages().size());
assertEquals("only one simple message must be sent",
1, mailSender.getSentSimpleMailMessages().size());
assertEquals("message content different from expected",
mailMessage, mailSender.getSentSimpleMailMessages().get(0));
}
@After
public void reset() {
this.mailSender.reset();
}
}

View File

@@ -1,56 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import org.springframework.mail.SimpleMailMessage;
/**
* @author Marius Bogoevici
*/
public class MailTestsHelper {
public static final String SUBJECT = "Some subject";
public static final String MESSAGE_TEXT = "Some text";
public static final String[] TO = new String[] {
"toRecipient1@springframework.org", "toRecipient2@springframework.org" };
public static final String[] CC = new String[] {
"ccRecipient1@springframework.org", "ccRecipient2@springframework.org" };
public static final String[] BCC = new String[] {
"bccRecipient1@springframework.org", "bccRecipient2@springframework.org" };
public static final String FROM = "from@springframework.org";
public static final String REPLY_TO = "replyTo@springframework.org";
public static SimpleMailMessage createSimpleMailMessage() {
SimpleMailMessage message = new SimpleMailMessage();
message.setBcc(BCC);
message.setCc(CC);
message.setTo(TO);
message.setSubject(SUBJECT);
message.setReplyTo(REPLY_TO);
message.setFrom(FROM);
message.setText(MESSAGE_TEXT);
return message;
}
}

View File

@@ -1,89 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import static org.junit.Assert.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.mail.internet.MimeMessage;
import org.easymock.classextension.EasyMock;
import org.junit.Test;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.Message;
public class PollingMessageSourceTests {
@Test
public void testPolling(){
StubFolderConnection folderConnection = new StubFolderConnection();
MimeMessage messageOne = EasyMock.createMock(MimeMessage.class);
MimeMessage messageTwo = EasyMock.createMock(MimeMessage.class);
MimeMessage messageThree = EasyMock.createMock(MimeMessage.class);
MimeMessage messageFour = EasyMock.createMock(MimeMessage.class);
folderConnection.messages.add(new javax.mail.Message[]{messageOne});
folderConnection.messages.add(new javax.mail.Message[]{messageTwo,messageThree});
folderConnection.messages.add(new javax.mail.Message[]{messageFour});
PollingMailSource pollingMailSource = new PollingMailSource(folderConnection);
pollingMailSource.setConverter(new StubMessageConvertor());
assertEquals("Wrong message for number 1", messageOne, pollingMailSource.receive().getPayload());
assertEquals("Wrong message for number 2", messageTwo, pollingMailSource.receive().getPayload());
assertEquals("Wrong message for number 3", messageThree, pollingMailSource.receive().getPayload());
assertEquals("Wrong message for number 4", messageFour, pollingMailSource.receive().getPayload());
assertNull("Expected null after exhausting all messages",pollingMailSource.receive());
}
private static class StubFolderConnection implements FolderConnection {
ConcurrentLinkedQueue<javax.mail.Message[]> messages = new ConcurrentLinkedQueue<javax.mail.Message[]>();
public javax.mail.Message[] receive() {
return messages.poll();
}
public boolean isRunning() {
return false;
}
public void start() {
}
public void stop() {
}
}
private static class StubMessageConvertor implements MailMessageConverter {
@SuppressWarnings("unchecked")
public Message create(MimeMessage mailMessage) {
return new GenericMessage<MimeMessage>(mailMessage);
}
}
}

View File

@@ -1,93 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
/**
* @author Marius Bogoevici
*/
public class StubJavaMailSender implements JavaMailSender {
private MimeMessage uniqueMessage;
private final List<MimeMessage> sentMimeMessages = new ArrayList<MimeMessage>();
private final List<SimpleMailMessage> sentSimpleMailMessages = new ArrayList<SimpleMailMessage>();
public StubJavaMailSender(MimeMessage uniqueMessage) {
this.uniqueMessage = uniqueMessage;
}
public List<MimeMessage> getSentMimeMessages() {
return this.sentMimeMessages;
}
public List<SimpleMailMessage> getSentSimpleMailMessages() {
return this.sentSimpleMailMessages;
}
public MimeMessage createMimeMessage() {
return this.uniqueMessage;
}
public MimeMessage createMimeMessage(InputStream contentStream) throws MailException {
return this.uniqueMessage;
}
public void send(MimeMessage mimeMessage) throws MailException {
this.sentMimeMessages.add(mimeMessage);
}
public void send(MimeMessage[] mimeMessages) throws MailException {
this.sentMimeMessages.addAll(Arrays.asList(mimeMessages));
}
public void send(MimeMessagePreparator mimeMessagePreparator) throws MailException {
throw new UnsupportedOperationException("MimeMessagePreparator not supported");
}
public void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException {
throw new UnsupportedOperationException("MimeMessagePreparator not supported");
}
public void send(SimpleMailMessage simpleMessage) throws MailException {
this.sentSimpleMailMessages.add(simpleMessage);
}
public void send(SimpleMailMessage[] simpleMessages) throws MailException {
this.sentSimpleMailMessages.addAll(Arrays.asList(simpleMessages));
}
public void reset() {
this.sentMimeMessages.clear();
this.sentSimpleMailMessages.clear();
}
}

View File

@@ -1,99 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.mail.internet.MimeMessage;
import org.easymock.classextension.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.task.TaskExecutor;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.Message;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
/**
* @author Jonas Partner
*/
public class SubscribableMailSourceTests {
TaskExecutor executor;
@Before
public void setUp() {
executor = new ConcurrentTaskExecutor();
}
@Test
public void testReceive() throws Exception {
javax.mail.Message message = EasyMock.createMock(MimeMessage.class);
StubFolderConnection folderConnection = new StubFolderConnection(message);
QueueChannel channel = new QueueChannel();
SubscribableMailSource mailSource = new SubscribableMailSource(folderConnection, executor);
mailSource.setOutputChannel(channel);
mailSource.setConverter(new StubMessageConvertor());
mailSource.start();
Message<?> result = channel.receive(1000);
mailSource.stop();
assertNotNull(result);
assertEquals("Wrong payload", message, result.getPayload());
}
private static class StubFolderConnection implements FolderConnection {
ConcurrentLinkedQueue<javax.mail.Message> messages = new ConcurrentLinkedQueue<javax.mail.Message>();
public StubFolderConnection(javax.mail.Message message) {
messages.add(message);
}
public javax.mail.Message[] receive() {
javax.mail.Message msg = messages.poll();
if (msg == null) {
return new javax.mail.Message[] {};
}
return new javax.mail.Message[] { msg };
}
public boolean isRunning() {
return false;
}
public void start() {
}
public void stop() {
}
}
private static class StubMessageConvertor implements MailMessageConverter {
@SuppressWarnings("unchecked")
public Message create(MimeMessage mailMessage) {
return new GenericMessage<MimeMessage>(mailMessage);
}
}
}

View File

@@ -1,76 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.adapter.mail.MailHeaderGenerator;
import org.springframework.integration.adapter.mail.MailTarget;
import org.springframework.integration.message.Message;
import org.springframework.mail.MailMessage;
import org.springframework.mail.MailSender;
/**
* @author Mark Fisher
*/
public class MailTargetParserTests {
@Test
public void testTargetWithMailSenderReference() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"mailTargetParserTests.xml", this.getClass());
MailTarget target = (MailTarget) context.getBean("targetWithMailSenderReference");
DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(target);
MailSender mailSender = (MailSender) fieldAccessor.getPropertyValue("mailSender");
assertNotNull(mailSender);
}
@Test
public void testTargetWithHostProperty() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"mailTargetParserTests.xml", this.getClass());
MailTarget target = (MailTarget) context.getBean("targetWithHostProperty");
DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(target);
MailSender mailSender = (MailSender) fieldAccessor.getPropertyValue("mailSender");
assertNotNull(mailSender);
}
@Test
public void testTargetWithHeaderGeneratorReference() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"mailTargetParserTests.xml", this.getClass());
MailTarget target = (MailTarget) context.getBean("targetWithHeaderGeneratorReference");
DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(target);
MailHeaderGenerator headerGenerator =
(MailHeaderGenerator) fieldAccessor.getPropertyValue("mailHeaderGenerator");
assertEquals(TestHeaderGenerator.class, headerGenerator.getClass());
}
public static class TestHeaderGenerator implements MailHeaderGenerator {
public void populateMailMessageHeader(MailMessage mailMessage, Message<?> message) {
}
}
}

View File

@@ -1,31 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.springframework.integration.adapter.mail.config;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.adapter.mail.PollingMailSource;
public class PollingMailSourceParserTests {
@Test
public void testPop3(){
ApplicationContext context = new ClassPathXmlApplicationContext("pollingMailSourceParserTests.xml", PollingMailSourceParserTests.class);
PollingMailSource mailSource = (PollingMailSource)context.getBean("pollingPop3");
}
}

View File

@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:si="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-1.0.xsd">
<si:mail-target id="targetWithMailSenderReference" mail-sender="mailSender"/>
<si:mail-target id="targetWithHostProperty"
host="somehost" username="someuser" password="somepassword"/>
<bean id="mailSender" class="org.springframework.integration.adapter.mail.StubJavaMailSender">
<constructor-arg>
<bean class="javax.mail.internet.MimeMessage">
<constructor-arg type="javax.mail.Session"><null/></constructor-arg>
</bean>
</constructor-arg>
</bean>
<si:mail-target id="targetWithHeaderGeneratorReference"
mail-sender="mailSender"
header-generator="testHeaderGenerator"/>
<bean id="testHeaderGenerator"
class="org.springframework.integration.adapter.mail.config.MailTargetParserTests$TestHeaderGenerator"/>
</beans>

View File

@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:si="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-1.0.xsd">
<si:polling-mail-source id="pollingPop3" store-uri="pop3://mailtest:mailtest@ubuntuservervm/INBOX" />
</beans>

View File

@@ -1,43 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="javaMailSender" class="org.springframework.integration.adapter.mail.StubJavaMailSender">
<constructor-arg>
<bean class="javax.mail.internet.MimeMessage">
<constructor-arg type="javax.mail.Session"><null/></constructor-arg>
</bean>
</constructor-arg>
</bean>
<bean id="mailTarget" class="org.springframework.integration.adapter.mail.MailTarget">
<constructor-arg ref="javaMailSender"/>
<property name="headerGenerator">
<bean class="org.springframework.integration.adapter.mail.StaticMailHeaderGenerator">
<property name="subject">
<util:constant static-field="org.springframework.integration.adapter.mail.MailTestsHelper.SUBJECT"/>
</property>
<property name="to">
<util:constant static-field="org.springframework.integration.adapter.mail.MailTestsHelper.TO"/>
</property>
<property name="cc">
<util:constant static-field="org.springframework.integration.adapter.mail.MailTestsHelper.CC"/>
</property>
<property name="bcc">
<util:constant static-field="org.springframework.integration.adapter.mail.MailTestsHelper.BCC"/>
</property>
<property name="from">
<util:constant static-field="org.springframework.integration.adapter.mail.MailTestsHelper.FROM"/>
</property>
<property name="replyTo">
<util:constant static-field="org.springframework.integration.adapter.mail.MailTestsHelper.REPLY_TO"/>
</property>
</bean>
</property>
</bean>
</beans>