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,61 @@
/*
* 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.sample.domain.mail;
/**
* @author Dan Garrette
* @author Dave Syer
*
* @since 2.1
*/
public class User {
private int id;
private String name;
private String email;
public User() {
}
public User( int id, String name, String email ) {
this.id = id;
this.name = name;
this.email = email;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail( String email ) {
this.email = email;
}
}

View File

@@ -0,0 +1,54 @@
/*
* 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.sample.domain.mail.internal;
import java.util.ArrayList;
import java.util.List;
import javax.mail.MessagingException;
import org.springframework.batch.item.mail.MailErrorHandler;
import org.springframework.mail.MailMessage;
import org.springframework.mail.SimpleMailMessage;
/**
* This handler prints out failed messages with their exceptions. It also
* maintains a list of all failed messages it receives for lookup later by an
* assertion.
*
* @author Dan Garrette
* @author Dave Syer
*
* @since 2.1
*/
public class TestMailErrorHandler implements MailErrorHandler {
private List<SimpleMailMessage> failedMessages = new ArrayList<SimpleMailMessage>();
public void handle(MailMessage failedMessage, MessagingException ex) {
this.failedMessages.add(failedMessage);
System.out.println("Mail message failed: " + failedMessage);
System.out.println(ex);
}
public List<SimpleMailMessage> getFailedMessages() {
return failedMessages;
}
public void clear() {
this.failedMessages.clear();
}
}

View File

@@ -0,0 +1,73 @@
/*
* 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.sample.domain.mail.internal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.mail.MessagingException;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
/**
* @author Dan Garrette
* @author Dave Syer
*
* @since 2.1
*/
public class TestMailSender implements MailSender {
private List<String> subjectsToFail = new ArrayList<String>();
private List<SimpleMailMessage> received = new ArrayList<SimpleMailMessage>();
public void clear() {
received.clear();
}
public void send(SimpleMailMessage simpleMessage) throws MailException {
throw new UnsupportedOperationException("Not implememted. Use send(SimpleMailMessage[]).");
}
public void setSubjectsToFail(List<String> subjectsToFail) {
this.subjectsToFail = subjectsToFail;
}
public void send(SimpleMailMessage[] simpleMessages) throws MailException {
Map<SimpleMailMessage, MessagingException> failedMessages = new LinkedHashMap<SimpleMailMessage, MessagingException>();
for (SimpleMailMessage simpleMessage : simpleMessages) {
if (subjectsToFail.contains(simpleMessage.getSubject())) {
failedMessages.put(simpleMessage, new MessagingException());
}
else {
received.add(simpleMessage);
}
}
if (!failedMessages.isEmpty()) {
throw new MailSendException(failedMessages);
}
}
public List<SimpleMailMessage> getReceivedMessages() {
return received;
}
}

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.sample.domain.mail.internal;
import java.util.Date;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.sample.domain.mail.User;
import org.springframework.mail.SimpleMailMessage;
/**
* @author Dan Garrette
* @author Dave Syer
*
* @since 2.1
*/
public class UserMailItemProcessor implements
ItemProcessor<User, SimpleMailMessage> {
/**
* @see org.springframework.batch.item.ItemProcessor#process(java.lang.Object)
*/
public SimpleMailMessage process( User user ) throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo( user.getEmail() );
message.setFrom( "communications@thecompany.com" );
message.setSubject( user.getName() + "'s Account Info" );
message.setSentDate( new Date() );
message.setText( "Hello " + user.getName() );
return message;
}
}

View File

@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<job id="mailJob" xmlns="http://www.springframework.org/schema/batch">
<step id="step1" xmlns="http://www.springframework.org/schema/batch">
<tasklet>
<chunk reader="itemReader" processor="itemProcessor" writer="itemWriter" commit-interval="5" skip-limit="100">
<skippable-exception-classes>
<include class="java.lang.RuntimeException" />
</skippable-exception-classes>
<!--
<fatal-exception-classes> <include class="org.springframework.mail.MailException"/> </fatal-exception-classes>
-->
</chunk>
</tasklet>
</step>
</job>
<bean id="itemReader" class="org.springframework.batch.item.database.JdbcCursorItemReader">
<property name="sql" value="select ID, NAME, EMAIL from USERS" />
<property name="rowMapper">
<bean class="org.springframework.jdbc.core.BeanPropertyRowMapper">
<property name="mappedClass" value="org.springframework.batch.sample.domain.mail.User" />
</bean>
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="itemWriter" class="org.springframework.batch.item.mail.SimpleMailMessageItemWriter">
<property name="mailSender" ref="mailSender" />
<property name="mailErrorHandler" ref="loggingMailErrorHandler" />
</bean>
<bean id="itemProcessor" class="org.springframework.batch.sample.domain.mail.internal.UserMailItemProcessor" />
<bean id="loggingMailErrorHandler" class="org.springframework.batch.sample.domain.mail.internal.TestMailErrorHandler" />
<bean id="mailSender" class="org.springframework.batch.sample.domain.mail.internal.TestMailSender">
<property name="subjectsToFail">
<list>
<value>John Adams's Account Info</value>
<value>James Madison's Account Info</value>
</list>
</property>
</bean>
</beans>

View File

@@ -28,6 +28,6 @@ log4j.appender.chainsaw.layout=org.apache.log4j.xml.XMLLayout
#log4j.logger.org.springframework.orm=debug
### debug your specific package or classes with the following example
log4j.logger.org.springframework.jdbc=debug
log4j.logger.org.springframework.batch=debug
log4j.logger.org.springframework.jdbc=info
log4j.logger.org.springframework.batch=info
log4j.logger.org.springframework.batch.sample=debug

View File

@@ -0,0 +1,126 @@
/*
* 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.sample;
import static org.junit.Assert.assertEquals;
import java.util.Iterator;
import java.util.List;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.sample.domain.mail.internal.TestMailErrorHandler;
import org.springframework.batch.sample.domain.mail.internal.TestMailSender;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Dan Garrette
* @author Dave Syer
*
* @Since 2.1
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/mailJob.xml", "/job-runner-context.xml" })
public class MailJobFunctionalTests {
private static final String email = "to@company.com";
private static final Object[] USER1 = new Object[] { 1, "George Washington", email };
private static final Object[] USER2_SKIP = new Object[] { 2, "John Adams", "FAILURE" };
private static final Object[] USER3 = new Object[] { 3, "Thomas Jefferson", email };
private static final Object[] USER4_SKIP = new Object[] { 4, "James Madison", "FAILURE" };
private static final Object[] USER5 = new Object[] { 5, "James Monroe", email };
private static final Object[] USER6 = new Object[] { 6, "John Quincy Adams", email };
private static final Object[] USER7 = new Object[] { 7, "Andrew Jackson", email };
private static final Object[] USER8 = new Object[] { 8, "Martin Van Buren", email };
private SimpleJdbcTemplate jdbcTemplate;
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
private TestMailErrorHandler errorHandler;
@Autowired
private TestMailSender mailSender;
@Autowired
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
@Before
public void before() {
mailSender.clear();
errorHandler.clear();
jdbcTemplate.update("create table USERS (ID INTEGER, NAME VARCHAR(40), EMAIL VARCHAR(20))");
}
@After
public void after() throws Exception {
jdbcTemplate.update("drop table USERS");
}
@Test
public void testSkip() throws Exception {
this.createUsers(new Object[][] { USER1, USER2_SKIP, USER3, USER4_SKIP, USER5, USER6, USER7, USER8 });
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
List<SimpleMailMessage> receivedMessages = mailSender.getReceivedMessages();
assertEquals(6, receivedMessages.size());
Iterator<SimpleMailMessage> emailIter = receivedMessages.iterator();
for (Object[] record : new Object[][] { USER1, USER3, USER5, USER6, USER7, USER8 }) {
SimpleMailMessage email = emailIter.next();
assertEquals("Hello " + record[1], email.getText());
}
assertEquals(2, this.errorHandler.getFailedMessages().size());
Iterator<SimpleMailMessage> failureItr = this.errorHandler.getFailedMessages().iterator();
for (Object[] record : new Object[][] { USER2_SKIP, USER4_SKIP }) {
SimpleMailMessage email = failureItr.next();
assertEquals("Hello " + record[1], email.getText());
}
}
private void createUsers(Object[][] records) {
for (Object[] record : records) {
jdbcTemplate.update("insert into USERS values (?,?,?)", record);
}
}
}