RESOLVED - issue BATCH-1239: Add email-sending item writer

This commit is contained in:
dsyer
2010-01-12 17:05:56 +00:00
parent db14e83fdc
commit 953fb3a5b4
18 changed files with 1065 additions and 9 deletions

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2006-2010 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.batch.item.mail;
import javax.mail.MessagingException;
import org.springframework.mail.MailException;
import org.springframework.mail.MailMessage;
import org.springframework.mail.MailSendException;
/**
* This {@link MailErrorHandler} implementation simply rethrows the exception it
* receives.
*
* @author Dan Garrette
* @author Dave Syer
*
* @since 2.1
*/
public class DefaultMailErrorHandler implements MailErrorHandler {
private static final int DEFAULT_MAX_MESSAGE_LENGTH = 1024;
private int maxMessageLength = DEFAULT_MAX_MESSAGE_LENGTH;
/**
* The limit for the size of message that will be copied to the exception
* message. Output will be truncated beyond that. Default value is 1024.
*
* @param maxMessageLength the maximum message length
*/
public void setMaxMessageLength(int maxMessageLength) {
this.maxMessageLength = maxMessageLength;
}
/**
* Wraps the input exception with a runtime {@link MailException}. The
* exception message will contain the failed message.
*
* @param message a failed message
* @param exception a MessagingException
* @throws MailException a translation of the MessagingException
* @see MailErrorHandler#handle(MailMessage, MessagingException)
*/
public void handle(MailMessage message, MessagingException exception) throws MailException {
String msg = message.toString();
throw new MailSendException("Mail server send failed: "
+ msg.substring(0, Math.min(maxMessageLength, msg.length())), exception);
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2006-2010 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.batch.item.mail;
import javax.mail.MessagingException;
import org.springframework.mail.MailException;
import org.springframework.mail.MailMessage;
/**
* This class is used to handle errors that occur when email messages are unable
* to be sent.
*
* @author Dan Garrette
* @author Dave Syer
*
* @since 2.1
*/
public interface MailErrorHandler {
/**
* This method will be called for each message that failed sending in the
* chunk. If an exception is thrown from this method, then it will propagate
* to the caller.
*
* @param message the failed message
* @param exception the exception that caused the failure
* @throws MailException if the exception cannot be handled
*/
public void handle(MailMessage message, MessagingException exception) throws MailException;
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright 2006-2010 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.batch.item.mail;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.mail.MessagingException;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.util.Assert;
/**
* <p>
* A simple {@link ItemWriter} that can send mail messages. If it fails there is
* no guarantee about which of the messages were sent, but the ones that failed
* can be picked up in the error handler. Because the mail protocol is not
* transactional, failures should be dealt with here if possible rather than
* allowing them to be rethrown (which is the default).
* </p>
*
* <p>
* Delegates the actual sending of messages to a {@link MailSender}, using the
* batch method {@link MailSender#send(SimpleMailMessage[])}, which normally
* uses a single server connection for the whole batch (depending on the
* implementation). The efficiency of for large volumes of messages (repeated
* calls to the item writer) might be improved by the use of a special
* {@link MailSender} that caches connections to the server in between calls.
* </p>
*
* <p>
* Stateless, so automatically restartable.
* </p>
*
* @author Dave Syer
*
* @since 2.1
*
*/
public class SimpleMailMessageItemWriter implements ItemWriter<SimpleMailMessage>, InitializingBean {
private MailSender mailSender;
private MailErrorHandler mailErrorHandler = new DefaultMailErrorHandler();
/**
* A {@link MailSender} to be used to send messages in {@link #write(List)}.
*
* @param mailSender
*/
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
/**
* The handler for failed messages. Defaults to a
* {@link DefaultMailErrorHandler}.
*
* @param mailErrorHandler the mail error handler to set
*/
public void setMailErrorHandler(MailErrorHandler mailErrorHandler) {
this.mailErrorHandler = mailErrorHandler;
}
/**
* Check mandatory properties (mailSender).
*
* @throws IllegalStateException if the mandatory properties are not set
*
* @see InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws IllegalStateException {
Assert.state(mailSender != null, "A MailSender must be provided.");
}
/**
* @param items the items to send
* @see ItemWriter#write(List)
*/
public void write(List<? extends SimpleMailMessage> items) throws MailException {
try {
mailSender.send(items.toArray(new SimpleMailMessage[items.size()]));
}
catch (MailSendException e) {
@SuppressWarnings("unchecked")
Map<SimpleMailMessage, MessagingException> failedMessages = e.getFailedMessages();
for (Entry<SimpleMailMessage, MessagingException> entry : failedMessages.entrySet()) {
mailErrorHandler.handle(entry.getKey(), entry.getValue());
}
}
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2006-2010 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.batch.item.mail.javamail;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.mail.DefaultMailErrorHandler;
import org.springframework.batch.item.mail.MailErrorHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.util.Assert;
/**
* <p>
* A simple {@link ItemWriter} that can send mail messages. If it fails there is
* no guarantee about which of the messages were sent, but the ones that failed
* can be picked up in the error handler. Because the mail protocol is not
* transactional, failures should be dealt with here if possible rather than
* allowing them to be rethrown (which is the default).
* </p>
*
* <p>
* Delegates the actual sending of messages to a {@link JavaMailSender}, using the
* batch method {@link JavaMailSender#send(MimeMessage[])}, which normally uses
* a single server connection for the whole batch (depending on the
* implementation). The efficiency of for large volumes of messages (repeated
* calls to the item writer) might be improved by the use of a special
* {@link JavaMailSender} that caches connections to the server in between
* calls.
* </p>
*
* <p>
* Stateless, so automatically restartable.
* </p>
*
* @author Dave Syer
*
* @since 2.1
*
*/
public class MimeMessageItemWriter implements ItemWriter<MimeMessage> {
private JavaMailSender mailSender;
private MailErrorHandler mailErrorHandler = new DefaultMailErrorHandler();
/**
* A {@link JavaMailSender} to be used to send messages in {@link #write(List)}.
*
* @param mailSender
*/
public void setJavaMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
/**
* The handler for failed messages. Defaults to a
* {@link DefaultMailErrorHandler}.
*
* @param mailErrorHandler the mail error handler to set
*/
public void setMailErrorHandler(MailErrorHandler mailErrorHandler) {
this.mailErrorHandler = mailErrorHandler;
}
/**
* Check mandatory properties (mailSender).
*
* @throws IllegalStateException if the mandatory properties are not set
*
* @see InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws IllegalStateException {
Assert.state(mailSender != null, "A MailSender must be provided.");
}
/**
* @param items the items to send
* @see ItemWriter#write(List)
*/
@Override
public void write(List<? extends MimeMessage> items) throws MailException {
try {
mailSender.send(items.toArray(new MimeMessage[items.size()]));
}
catch (MailSendException e) {
@SuppressWarnings("unchecked")
Map<MimeMessage, MessagingException> failedMessages = e.getFailedMessages();
for (Entry<MimeMessage, MessagingException> entry : failedMessages.entrySet()) {
mailErrorHandler.handle(new MimeMailMessage(entry.getKey()), entry.getValue());
}
}
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2006-2010 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.batch.item.mail;
import static org.junit.Assert.*;
import javax.mail.MessagingException;
import org.junit.Test;
import org.springframework.mail.MailException;
import org.springframework.mail.MailMessage;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
/**
* @author Dave Syer
*
* @since 2.1
*
*/
public class DefaultMailErrorHandlerTests {
private DefaultMailErrorHandler handler = new DefaultMailErrorHandler();
/**
* Test method for {@link DefaultMailErrorHandler#setMaxMessageLength(int)}.
*/
@Test
public void testSetMaxMessageLength() {
handler.setMaxMessageLength(20);
try {
SimpleMailMessage message = new SimpleMailMessage();
handler.handle(message, new MessagingException());
fail("Expected MailException");
} catch (MailException e) {
String msg = e.getMessage();
assertTrue("Wrong message: "+msg, msg.matches(".*SimpleMailMessage: f;.*"));
}
}
/**
* Test method for {@link DefaultMailErrorHandler#handle(MailMessage, MessagingException)}.
*/
@Test(expected=MailSendException.class)
public void testHandle() {
handler.handle(new SimpleMailMessage(), new MessagingException());
}
}

View File

@@ -0,0 +1,114 @@
/*
* Copyright 2006-2010 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.batch.item.mail;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import javax.mail.MessagingException;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mail.MailException;
import org.springframework.mail.MailMessage;
import org.springframework.mail.MailSendException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
/**
* @author Dave Syer
*
* @since 2.1
*
*/
public class SimpleMailMessageItemWriterTests {
private SimpleMailMessageItemWriter writer = new SimpleMailMessageItemWriter();
private MailSender mailSender = EasyMock.createMock(MailSender.class);
@Before
public void setUp() {
writer.setMailSender(mailSender);
}
@Test
public void testSend() throws Exception {
SimpleMailMessage foo = new SimpleMailMessage();
SimpleMailMessage bar = new SimpleMailMessage();
SimpleMailMessage[] items = new SimpleMailMessage[] { foo, bar };
mailSender.send(EasyMock.aryEq(items));
EasyMock.expectLastCall();
EasyMock.replay(mailSender);
writer.write(Arrays.asList(items));
EasyMock.verify(mailSender);
}
@Test(expected = MailSendException.class)
public void testDefaultErrorHandler() throws Exception {
SimpleMailMessage foo = new SimpleMailMessage();
SimpleMailMessage bar = new SimpleMailMessage();
SimpleMailMessage[] items = new SimpleMailMessage[] { foo, bar };
mailSender.send(EasyMock.aryEq(items));
EasyMock.expectLastCall().andThrow(
new MailSendException(Collections.singletonMap(foo, new MessagingException("FOO"))));
EasyMock.replay(mailSender);
writer.write(Arrays.asList(items));
EasyMock.verify(mailSender);
}
@Test
public void testCustomErrorHandler() throws Exception {
final AtomicReference<String> content = new AtomicReference<String>();
writer.setMailErrorHandler(new MailErrorHandler() {
public void handle(MailMessage message, MessagingException exception) throws MailException {
content.set(exception.getMessage());
}
});
SimpleMailMessage foo = new SimpleMailMessage();
SimpleMailMessage bar = new SimpleMailMessage();
SimpleMailMessage[] items = new SimpleMailMessage[] { foo, bar };
mailSender.send(EasyMock.aryEq(items));
EasyMock.expectLastCall().andThrow(
new MailSendException(Collections.singletonMap(foo, new MessagingException("FOO"))));
EasyMock.replay(mailSender);
writer.write(Arrays.asList(items));
assertEquals("FOO", content.get());
EasyMock.verify(mailSender);
}
}

View File

@@ -0,0 +1,119 @@
/*
* Copyright 2006-2010 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.batch.item.mail.javamail;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.springframework.batch.item.mail.MailErrorHandler;
import org.springframework.mail.MailException;
import org.springframework.mail.MailMessage;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
/**
* @author Dave Syer
*
* @since 2.1
*
*/
public class MimeMessageItemWriterTests {
private MimeMessageItemWriter writer = new MimeMessageItemWriter();
private JavaMailSender mailSender = EasyMock.createMock(JavaMailSender.class);
private Session session = Session.getDefaultInstance(new Properties());
@Before
public void setUp() {
writer.setJavaMailSender(mailSender);
}
@Test
public void testSend() throws Exception {
MimeMessage foo = new MimeMessage(session);
MimeMessage bar = new MimeMessage(session);
MimeMessage[] items = new MimeMessage[] { foo, bar };
mailSender.send(EasyMock.aryEq(items));
EasyMock.expectLastCall();
EasyMock.replay(mailSender);
writer.write(Arrays.asList(items));
EasyMock.verify(mailSender);
}
@Test(expected = MailSendException.class)
public void testDefaultErrorHandler() throws Exception {
MimeMessage foo = new MimeMessage(session);
MimeMessage bar = new MimeMessage(session);
MimeMessage[] items = new MimeMessage[] { foo, bar };
mailSender.send(EasyMock.aryEq(items));
EasyMock.expectLastCall().andThrow(
new MailSendException(Collections.singletonMap(foo, new MessagingException("FOO"))));
EasyMock.replay(mailSender);
writer.write(Arrays.asList(items));
EasyMock.verify(mailSender);
}
@Test
public void testCustomErrorHandler() throws Exception {
final AtomicReference<String> content = new AtomicReference<String>();
writer.setMailErrorHandler(new MailErrorHandler() {
public void handle(MailMessage message, MessagingException exception) throws MailException {
content.set(exception.getMessage());
}
});
MimeMessage foo = new MimeMessage(session);
MimeMessage bar = new MimeMessage(session);
MimeMessage[] items = new MimeMessage[] { foo, bar };
mailSender.send(EasyMock.aryEq(items));
EasyMock.expectLastCall().andThrow(
new MailSendException(Collections.singletonMap(foo, new MessagingException("FOO"))));
EasyMock.replay(mailSender);
writer.write(Arrays.asList(items));
assertEquals("FOO", content.get());
EasyMock.verify(mailSender);
}
}

View File

@@ -52,7 +52,6 @@ public class FooService {
public List<Foo> getProcessedFooNameValuePairs() {
return processedFooNameValuePairs;
}
}
}