Add spring-batch- to module directory names (so folks can use mvn eclipse:eclipse if they want to).

BATCH-238: Remove hibernate support for the Daos.
This commit is contained in:
dsyer
2007-12-10 21:23:48 +00:00
parent 17705f27ab
commit 8ea331bfc7
884 changed files with 956 additions and 2352 deletions

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2006-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.batch.sample;
import org.springframework.batch.core.configuration.JobConfiguration;
import org.springframework.batch.execution.launch.JobLauncher;
import org.springframework.batch.execution.runtime.DefaultJobIdentifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Abstract unit test for running functional tests by getting context locations
* for both the container and configuration separately and having them auto
* wired in by type. This allows the two to be completely separated, and remove
* any 'configuration coupling' between the two. However, it is still purely
* theoretical until a decision is made as to how job configuration and
* container configuration files are pulled together.
*
* @author Lucas Ward
*
*/
public abstract class AbstractBatchLauncherTests extends
AbstractDependencyInjectionSpringContextTests {
private static final String CONTAINER_DEFINITION_LOCATION = "simple-container-definition.xml";
JobLauncher launcher;
private JobConfiguration jobConfiguration;
/*
* (non-Javadoc)
*
* @see org.springframework.test.AbstractSingleSpringContextTests#createApplicationContext(java.lang.String[])
*/
protected ConfigurableApplicationContext createApplicationContext(
String[] locations) {
ApplicationContext parent = new ClassPathXmlApplicationContext(
CONTAINER_DEFINITION_LOCATION);
return new ClassPathXmlApplicationContext(locations, parent);
}
public void setLauncher(JobLauncher bootstrap) {
this.launcher = bootstrap;
}
/**
* Public setter for the {@link JobConfiguration} property.
*
* @param jobConfiguration
* the jobConfiguration to set
*/
public void setJobConfiguration(JobConfiguration jobConfiguration) {
this.jobConfiguration = jobConfiguration;
}
protected String getJobName() {
return jobConfiguration.getName();
}
/**
* @throws Exception
*
*/
public void testLaunchJob() throws Exception {
// Make sure the job is unique by the test case that runs it, not just its name:
launcher.run(new DefaultJobIdentifier(getJobName(), this.getClass().getName()));
launcher.stop();
}
}

View File

@@ -0,0 +1,92 @@
package org.springframework.batch.sample;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.sample.item.processor.CustomerCreditIncreaseProcessor;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
/**
* Test case for jobs that are expected to update customer credit value by fixed
* amount.
*
* @author Robert Kasanicky
* @author Dave Syer
*/
public abstract class AbstractCustomerCreditIncreaseTests extends
AbstractValidatingBatchLauncherTests {
protected JdbcOperations jdbcTemplate;
private static final BigDecimal CREDIT_INCREASE = CustomerCreditIncreaseProcessor.FIXED_AMOUNT;
private static final String ALL_CUSTOMERS = "select * from CUSTOMER order by ID";
private static final String CREDIT_COLUMN = "CREDIT";
protected static final String ID_COLUMN = "ID";
private List creditsBeforeUpdate;
public void setJdbcTemplate(JdbcOperations jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* All customers have the same credit
*/
protected void validatePreConditions() throws Exception {
super.validatePreConditions();
creditsBeforeUpdate = jdbcTemplate.query(ALL_CUSTOMERS, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getBigDecimal(CREDIT_COLUMN);
}
});
}
/**
* Credit was increased by CREDIT_INCREASE
*/
protected void validatePostConditions() throws Exception {
final List matches = new ArrayList();
jdbcTemplate.query(ALL_CUSTOMERS, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
final BigDecimal creditBeforeUpdate = (BigDecimal) creditsBeforeUpdate.get(rowNum);
final BigDecimal expectedCredit = creditBeforeUpdate
.add(CREDIT_INCREASE);
if (expectedCredit.equals(rs.getBigDecimal(CREDIT_COLUMN))) {
matches.add(rs.getBigDecimal(ID_COLUMN));
}
return null;
}
});
assertEquals(getExpectedMatches(), matches.size());
checkMatches(matches);
}
/**
* @param matches
*/
protected void checkMatches(List matches) {
// no-op...
}
/**
* @return the expected number of matches in the updated credits.
*/
protected int getExpectedMatches() {
return creditsBeforeUpdate.size();
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2006-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.batch.sample;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Abstract TestCase that automatically starts a Spring (@link Lifecycle) after
* obtaining it automatically via autowiring by type. It should be noted the
* getConfigLocations must be implemented for dependency injection to work
* properly.
*
* @author Lucas Ward
* @see AbstractDependencyInjectionSpringContextTests
*/
public abstract class AbstractValidatingBatchLauncherTests extends AbstractBatchLauncherTests {
public void testLaunchJob() throws Exception {
validatePreConditions();
super.testLaunchJob();
validatePostConditions();
}
/**
* Make sure input data meets expectations
*/
protected void validatePreConditions() throws Exception {
}
/**
* Make sure job did what it was expected to do.
*/
protected abstract void validatePostConditions() throws Exception;
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2006-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.batch.sample;
public class BeanWrapperMapperSampleJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
protected String[] getConfigLocations() {
return new String[]{"jobs/beanWrapperMapperSampleJob.xml"};
}
protected void validatePostConditions() {
// nothing to check, the job writes no output
}
}

View File

@@ -0,0 +1,96 @@
package org.springframework.batch.sample;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowCallbackHandler;
public class CompositeProcessorSampleFunctionalTests extends AbstractValidatingBatchLauncherTests {
private static final String GET_TRADES = "SELECT isin, quantity, price, customer FROM trade order by isin";
private static final String EXPECTED_OUTPUT_FILE =
"Trade: [isin=UK21341EAH41,quantity=211,price=31.11,customer=customer1]" +
"Trade: [isin=UK21341EAH42,quantity=212,price=32.11,customer=customer2]" +
"Trade: [isin=UK21341EAH43,quantity=213,price=33.11,customer=customer3]" +
"Trade: [isin=UK21341EAH44,quantity=214,price=34.11,customer=customer4]" +
"Trade: [isin=UK21341EAH45,quantity=215,price=35.11,customer=customer5]";
private JdbcOperations jdbcTemplate;
private int activeRow = 0;
private int before;
// @Override
protected String[] getConfigLocations() {
return new String[]{"jobs/compositeProcessorSampleJob.xml"};
}
/* (non-Javadoc)
* @see org.springframework.batch.sample.AbstractLifecycleSpringContextTests#validatePreConditions()
*/
protected void validatePreConditions() throws Exception {
jdbcTemplate.update("DELETE from TRADE");
before = jdbcTemplate.queryForInt("SELECT COUNT(*) from TRADE");
}
protected void validatePostConditions() throws Exception {
checkOutputFile();
checkOutputTable();
}
private void checkOutputTable() {
final List trades = new ArrayList() {{
add(new Trade("UK21341EAH41", 211, new BigDecimal("31.11"), "customer1"));
add(new Trade("UK21341EAH42", 212, new BigDecimal("32.11"), "customer2"));
add(new Trade("UK21341EAH43", 213, new BigDecimal("33.11"), "customer3"));
add(new Trade("UK21341EAH44", 214, new BigDecimal("34.11"), "customer4"));
add(new Trade("UK21341EAH45", 215, new BigDecimal("35.11"), "customer5"));
}};
int after = jdbcTemplate.queryForInt("SELECT COUNT(*) from TRADE");
assertEquals(before+5, after);
jdbcTemplate.query(GET_TRADES, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
Trade trade = (Trade)trades.get(activeRow++);
assertEquals(trade.getIsin(), rs.getString(1));
assertEquals(trade.getQuantity(), rs.getLong(2));
assertEquals(trade.getPrice(), rs.getBigDecimal(3));
assertEquals(trade.getCustomer(), rs.getString(4));
}
});
}
private void checkOutputFile() throws FileNotFoundException, IOException {
List outputLines = IOUtils.readLines(
new FileInputStream("target/test-outputs/20070122.testStream.ParallelCustomerReportStep.TEMP.txt"));
String output = "";
for (Iterator iterator = outputLines.listIterator(); iterator.hasNext();) {
String line = (String) iterator.next();
output += line;
}
assertEquals(EXPECTED_OUTPUT_FILE, output);
}
public void setJdbcTemplate(JdbcOperations jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}

View File

@@ -0,0 +1,25 @@
package org.springframework.batch.sample;
import org.springframework.batch.sample.domain.PersonService;
public class DelegatingJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
private PersonService personService;
protected String[] getConfigLocations() {
return new String[] {"jobs/delegatingJob.xml"};
}
protected void validatePostConditions() throws Exception {
assertTrue(personService.getReturnedCount() > 0);
assertEquals(personService.getReturnedCount(), personService.getReceivedCount());
}
// setter for auto-injection
public void setPersonService(PersonService personService) {
this.personService = personService;
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2006-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.batch.sample;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.io.file.support.DefaultFlatFileInputSource;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowCallbackHandler;
public class FixedLengthImportJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
//expected line length in input file (sum of pattern lengths + 2, because the counter is appended twice)
private static final int LINE_LENGTH = 29;
//auto-injected attributes
private JdbcOperations jdbcTemplate;
private Resource fileLocator;
private DefaultFlatFileInputSource inputSource;
protected void onSetUp() throws Exception {
super.onSetUp();
jdbcTemplate.update("delete from TRADE");
}
protected String[] getConfigLocations() {
return new String[] {"jobs/fixedLengthImportJob.xml"};
}
/**
* check that records have been correctly written to database
*/
protected void validatePostConditions() {
inputSource.open();
jdbcTemplate.query("SELECT ID, ISIN, QUANTITY, PRICE, CUSTOMER FROM trade ORDER BY id", new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
Trade trade = (Trade)inputSource.read();
assertEquals(trade.getIsin(), rs.getString(2));
assertEquals(trade.getQuantity(),rs.getLong(3));
assertEquals(trade.getPrice(), rs.getBigDecimal(4));
assertEquals(trade.getCustomer(), rs.getString(5));
}
});
assertNull(inputSource.read());
}
/*
* fixed-length file is expected on input
*/
protected void validatePreConditions() throws Exception{
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(fileLocator.getFile()));
String line;
while ((line = reader.readLine()) != null) {
assertEquals (LINE_LENGTH, line.length());
}
}
public void setJdbcTemplate(JdbcOperations jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void setFileLocator(Resource fileLocator) {
this.fileLocator = fileLocator;
}
public void setDefaultFlatFileInputSource(DefaultFlatFileInputSource inputSource){
this.inputSource = inputSource;
}
}

View File

@@ -0,0 +1,14 @@
package org.springframework.batch.sample;
public class FootballJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
protected String[] getConfigLocations() {
return new String[] {"jobs/footballJob.xml###"};
}
protected void validatePostConditions() throws Exception {
// TODO Auto-generated method stub
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2006-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.batch.sample;
import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.core.executor.StepInterruptedException;
/**
* Functional test for graceful shutdown. A batch container is started in a new thread,
* then it's stopped via the Lifecycle interface.
*
* @author Lucas Ward
*
*/
public class GracefulShutdownFunctionalTest extends AbstractBatchLauncherTests {
protected String[] getConfigLocations(){
return new String[] {"jobs/infiniteLoopJob.xml"};
}
public void testLaunchJob() throws Exception {
final List errors = new ArrayList();
Thread jobThread = new Thread(){
public void run(){
try {
launcher.run(getJobName());
}
catch (RuntimeException e) {
if (!(e.getCause() instanceof StepInterruptedException)) {
errors.add(e);
}
}
catch (Exception e) {
errors.add(e);
}
}
};
jobThread.start();
//give the thread a second to start up
Thread.sleep(200);
assertTrue(launcher.isRunning());
assertTrue(jobThread.isAlive());
//stop the job
launcher.stop();
//it takes a little while for it to shut down.
Thread.sleep(1000);
assertFalse(launcher.isRunning());
assertFalse(jobThread.isAlive());
if (!errors.isEmpty()) {
Exception e = (Exception) errors.get(0);
e.printStackTrace();
fail("Unexpected Exception: "+e);
}
}
}

View File

@@ -0,0 +1,100 @@
package org.springframework.batch.sample;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.batch.sample.dao.HibernateCreditWriter;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.orm.hibernate3.HibernateJdbcException;
/**
* Test for HibernateJob - checks that customer credit has been updated to
* expected value.
*
* @author Dave Syer
*/
public class HibernateFailureJobFunctionalTests extends
HibernateJobFunctionalTests {
private HibernateCreditWriter writer;
/**
* Public setter for the {@link HibernateCreditWriter} property.
*
* @param writer
* the writer to set
*/
public void setWriter(HibernateCreditWriter writer) {
this.writer = writer;
}
/*
* (non-Javadoc)
*
* @see org.springframework.test.AbstractSingleSpringContextTests#onTearDown()
*/
protected void onTearDown() throws Exception {
super.onTearDown();
writer.setFailOnFlush(-1);
}
protected String[] getConfigLocations() {
return new String[] { "jobs/hibernateJob.xml" };
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.sample.AbstractValidatingBatchLauncherTests#testLaunchJob()
*/
public void testLaunchJob() throws Exception {
writer.setFailOnFlush(2);
int before = jdbcTemplate.queryForInt("SELECT COUNT(*) from CUSTOMER");
assertTrue(before > 0);
try {
super.testLaunchJob();
} catch (HibernateJdbcException e) {
// This is what would happen if the flush happened outside the
// RepeatContext:
throw e;
} catch (UncategorizedSQLException e) {
// This is what would happen if the job wasn't configured to skip
// exceptions at teh step level.
assertEquals(1, writer.getErrors().size());
throw e;
}
validatePostConditions();
int after = jdbcTemplate.queryForInt("SELECT COUNT(*) from CUSTOMER");
assertEquals(before, after);
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.sample.AbstractCustomerCreditIncreaseTests#validatePostConditions()
*/
protected void validatePostConditions() throws Exception {
// TODO: fix so that the postconditions in super class are true
super.validatePostConditions();
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.sample.AbstractCustomerCreditIncreaseTests#checkMatches(java.util.List)
*/
protected void checkMatches(List matches) {
assertFalse(matches.contains(new BigDecimal(2)));
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.sample.AbstractCustomerCreditIncreaseTests#getExpectedMatches()
*/
protected int getExpectedMatches() {
// One record was skipped, so it won't be processed in the final state.
return super.getExpectedMatches() - 1;
}
}

View File

@@ -0,0 +1,13 @@
package org.springframework.batch.sample;
/**
* Test for HibernateJob - checks that customer credit has been updated to expected value.
*
* @author Robert Kasanicky
*/
public class HibernateJobFunctionalTests extends AbstractCustomerCreditIncreaseTests {
protected String[] getConfigLocations() {
return new String[] {"jobs/hibernateJob.xml"};
}
}

View File

@@ -0,0 +1,15 @@
package org.springframework.batch.sample;
/**
* Test for IbatisJob - checks that customer credit has been updated to expected value.
*
* @author Robert Kasanicky
*/
public class IbatisJobFunctionalTests extends AbstractCustomerCreditIncreaseTests{
protected String[] getConfigLocations() {
return new String[] {"jobs/ibatisJob.xml"};
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2006-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.batch.sample;
import org.springframework.batch.io.file.support.transform.LineAggregator;
/**
* Stub implementation of {@link LineAggregator} interface for testing purposes.
*
* @author robert.kasanicky
*/
public class LineAggregatorStub implements LineAggregator {
/**
* Concatenates arguments. Ignores the LineDescriptor.
*/
public String aggregate(String[] args) {
String result = "";
for (int i = 1; i < args.length; i++) {
result = result + args[i];
}
return result;
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2006-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.batch.sample;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
public class MultilineJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
private static final String EXPECTED_RESULT =
"[Trade: [isin=UK21341EAH45,quantity=978,price=98.34,customer=customer1], Trade: [isin=UK21341EAH46,quantity=112,price=18.12,customer=customer2]]" +
"[Trade: [isin=UK21341EAH47,quantity=245,price=12.78,customer=customer2], Trade: [isin=UK21341EAH48,quantity=108,price=9.25,customer=customer3], Trade: [isin=UK21341EAH49,quantity=854,price=23.39,customer=customer4]]";
private Resource output = new FileSystemResource("target/test-outputs/20070122.testStream.multilineStep.txt");
// @Override
protected String[] getConfigLocations() {
return new String[] {"jobs/multilineJob.xml"};
}
protected void validatePostConditions() throws Exception {
assertEquals(EXPECTED_RESULT, StringUtils.replace(IOUtils.toString(output.getInputStream()), System.getProperty("line.separator"), ""));
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2006-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.batch.sample;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
public class MultilineOrderJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
//private static final Log log = LogFactory.getLog(MultilineOrderJobFunctionalTests.class);
private static final String EXPECTED_OUTPUT =
"BEGIN_ORDER:13100345 2007/02/15 "+
"CUSTOMER:20014539 Peter Smith "+
"ADDRESS:Oak Street 31/A Small Town00235 "+
"BILLING:VISA VISA-12345678903 "+
"ITEM:104439104137.49 "+
"ITEM:2134776319221.99 "+
"END_ORDER:267.34 "+
"BEGIN_ORDER:13100346 2007/02/15 "+
"CUSTOMER:72155919 "+
"ADDRESS:St. Andrews Road 31 London 55342 "+
"BILLING:AMEX AMEX-72345678903 "+
"ITEM:10443191011070.50 "+
"ITEM:213472721921.79 "+
"ITEM:104433930179.95 "+
"ITEM:213474731955.29 "+
"ITEM:1044359501339.99 "+
"END_ORDER:14043.74 ";
private Resource fileOutputLocator = new FileSystemResource("target/test-outputs/20070122.teststream.multilineOrderStep.TEMP.txt");
// @Override
protected String[] getConfigLocations() {
return new String[] {"jobs/multilineOrderJob.xml"};
}
/**
* Read the output file and compare it with expected string
* @throws IOException
*/
protected void validatePostConditions() throws Exception {
assertEquals(EXPECTED_OUTPUT, StringUtils.replace(IOUtils.toString(fileOutputLocator.getInputStream()), System.getProperty("line.separator"), ""));
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2006-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.batch.sample;
import org.springframework.batch.io.exception.BatchCriticalException;
import org.springframework.jdbc.core.JdbcOperations;
/**
* Simple restart scenario.
*
* @author Robert Kasanicky
* @author Dave Syer
*/
public class RestartFunctionalTests extends AbstractBatchLauncherTests {
private static final String JOB_FILE = "jobs/restartSample.xml";
//auto-injected attributes
private JdbcOperations jdbcTemplate;
/**
* Public setter for the jdbcTemplate.
*
* @param jdbcTemplate the jdbcTemplate to set
*/
public void setJdbcTemplate(JdbcOperations jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
protected String[] getConfigLocations(){
return new String[]{JOB_FILE};
}
/* (non-Javadoc)
* @see org.springframework.test.AbstractSingleSpringContextTests#onTearDown()
*/
protected void onTearDown() throws Exception {
jdbcTemplate.update("DELETE FROM TRADE");
}
/**
* Job fails on first run, because the module throws exception after
* processing more than half of the input. On the second run, the job should
* finish successfully, because it continues execution where the previous
* run stopped (module throws exception after fixed number of processed
* records).
* @throws Exception
*/
public void testRestart() throws Exception {
int before = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM TRADE");
try {
runJob();
fail("First run of the job is expected to fail.");
}
catch (BatchCriticalException expected) {
//expected
}
runJob();
int after = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM TRADE");
assertEquals(before+5, after);
}
// load the application context and launch the job
private void runJob() throws Exception, Exception {
launcher.run(getJobName());
}
}

View File

@@ -0,0 +1,36 @@
package org.springframework.batch.sample;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* Test for job that rolls back a trade that is processed.
*
* @author Robert Kasanicky
*/
public class RollbackJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
int before = -1;
JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
protected String[] getConfigLocations() {
return new String[] {"jobs/rollbackJob.xml"};
}
protected void onSetUp() throws Exception {
before = jdbcTemplate.queryForInt("SELECT COUNT(*) from TRADE");
}
protected void validatePostConditions() throws Exception {
int after = jdbcTemplate.queryForInt("SELECT COUNT(*) from TRADE");
assertEquals(before+4, after);
}
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2006-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.batch.sample;
/**
* This job differs from FixedLengthImportJob only in internal job configuration, therefore
* the test is reused, only the job config location is overridden
*/
public class SimpleTaskletJobFunctionalTests extends FixedLengthImportJobFunctionalTests {
// @Override
protected String[] getConfigLocations() {
return new String[]{"jobs/simpleTaskletJob.xml"};
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2006-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.batch.sample;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Dave Syer
*
*/
public class TaskExecutorLauncher {
public static void main(String[] args) throws Exception {
// Paths to individual job configurations. Each one must include the
// step scope and the jobConfigurationRegistryBeanPostProcessor.
final String[] paths = new String[] { "jobs/adhocLoopJob.xml",
"jobs/footballJob.xml" };
// The simple execution environment will be used as a parent
// context for each of the job contexts. The standard version of this
// from the Spring Batch samples does not have an MBean for the
// JobLauncher, nor does the JobLauncher have an asynchronous
// TaskExecutor. The adhocLoopJob has both, which is why it has to be
// included in the paths above.
final ApplicationContext parent = new ClassPathXmlApplicationContext(
"simple-container-definition.xml");
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < paths.length; i++) {
String path = paths[i];
new ClassPathXmlApplicationContext(new String[] { path },
parent);
}
};
}).start();
System.out.println("Started application. Please connect using JMX.");
System.in.read();
}
}

View File

@@ -0,0 +1,205 @@
/*
* Copyright 2006-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.batch.sample;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowCallbackHandler;
public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
private static final String GET_TRADES = "SELECT isin, quantity, price, customer FROM trade";
private static final String GET_CUSTOMERS = "SELECT name, credit FROM customer";
private List customers;
private List trades;
private int activeRow = 0;
private JdbcOperations jdbcTemplate;
private Map credits = new HashMap();
/**
* @param jdbcTemplate the jdbcTemplate to set
*/
public void setJdbcTemplate(JdbcOperations jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
protected String[] getConfigLocations() {
return new String[] {"jobs/tradeJob.xml"};
}
/* (non-Javadoc)
* @see org.springframework.test.AbstractSingleSpringContextTests#onSetUp()
*/
protected void onSetUp() throws Exception {
super.onSetUp();
jdbcTemplate.update("delete from TRADE");
List list = jdbcTemplate.queryForList("select name, CREDIT from customer");
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Map map = (Map) iterator.next();
credits.put(map.get("NAME"), map.get("CREDIT"));
}
}
public void testLaunchJob() throws Exception{
super.testLaunchJob();
}
protected void validatePostConditions() {
// assertTrue(((Resource)applicationContext.getBean("customerFileLocator")).exists());
customers = new ArrayList() {{add(new Customer("customer1", (((Double)credits.get("customer1")).doubleValue() - 98.34)));
add(new Customer("customer2", (((Double)credits.get("customer2")).doubleValue() - 18.12 - 12.78)));
add(new Customer("customer3", (((Double)credits.get("customer3")).doubleValue() - 109.25)));
add(new Customer("customer4", (((Double)credits.get("customer4")).doubleValue() - 123.39)));}};
trades = new ArrayList() {{add(new Trade("UK21341EAH45", 978, new BigDecimal("98.34"), "customer1"));
add(new Trade("UK21341EAH46", 112, new BigDecimal("18.12"), "customer2"));
add(new Trade("UK21341EAH47", 245, new BigDecimal("12.78"), "customer2"));
add(new Trade("UK21341EAH48", 108, new BigDecimal("109.25"), "customer3"));
add(new Trade("UK21341EAH49", 854, new BigDecimal("123.39"), "customer4"));}};
// check content of the trade table
jdbcTemplate.query(GET_TRADES, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
Trade trade = (Trade)trades.get(activeRow++);
assertTrue(trade.getIsin().equals(rs.getString(1)));
assertTrue(trade.getQuantity() == rs.getLong(2));
assertTrue(trade.getPrice().equals(rs.getBigDecimal(3)));
assertTrue(trade.getCustomer().equals(rs.getString(4)));
}
});
assertTrue(trades.size() == activeRow);
// check content of the customer table
activeRow = 0;
jdbcTemplate.query(GET_CUSTOMERS, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
Customer customer = (Customer)customers.get(activeRow++);
assertEquals(customer.getName(),rs.getString(1));
assertEquals(customer.getCredit(), rs.getDouble(2), .01);
}
});
assertEquals(customers.size(), activeRow);
// check content of the output file
// Clean up
((FileSystemResource)applicationContext.getBean("customerFileLocator")).getFile().delete();
}
protected void validatePreConditions() {
assertTrue(((Resource)applicationContext.getBean("fileLocator")).exists());
}
private static class Customer {
private String name;
private double credit;
public Customer(String name, double credit) {
this.name = name;
this.credit = credit;
}
public Customer(){
}
/**
* @return the credit
*/
public double getCredit() {
return credit;
}
/**
* @param credit the credit to set
*/
public void setCredit(double credit) {
this.credit = credit;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
final int PRIME = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(credit);
result = PRIME * result + (int) (temp ^ (temp >>> 32));
result = PRIME * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Customer other = (Customer) obj;
if (Double.doubleToLongBits(credit) != Double.doubleToLongBits(other.credit))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2006-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.batch.sample;
import java.io.FileReader;
import org.custommonkey.xmlunit.XMLAssert;
import org.custommonkey.xmlunit.XMLUnit;
public class XmlStaxJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
private static final String OUTPUT_FILE = "target/test-outputs/20070918.testStream.xmlFileStep.output.xml";
private static final String EXPECTED_OUTPUT_FILE = "src/main/resources/data/staxJob/output/expected-output.xml";
// @Override
protected String[] getConfigLocations() {
return new String[]{"jobs/xmlStaxJob.xml"};
}
/**
* Output should be the same as input
*/
protected void validatePostConditions() throws Exception {
applicationContext.close(); //make sure the output file is closed
XMLUnit.setIgnoreWhitespace(true);
XMLAssert.assertXMLEqual(new FileReader(EXPECTED_OUTPUT_FILE), new FileReader(OUTPUT_FILE));
}
}

View File

@@ -0,0 +1,81 @@
package org.springframework.batch.sample.dao;
import java.math.BigDecimal;
import org.springframework.batch.io.ItemWriter;
import org.springframework.batch.item.ResourceLifecycle;
import org.springframework.batch.sample.domain.CustomerCredit;
import org.easymock.MockControl;
import junit.framework.TestCase;
public class FlatFileCustomerCreditWriterTests extends TestCase {
private MockControl outputControl;
private ResourceLifecycleItemWriter output;
private FlatFileCustomerCreditWriter writer;
public void setUp() throws Exception {
super.setUp();
//create mock for OutputSource
outputControl = MockControl.createControl(ResourceLifecycleItemWriter.class);
output = (ResourceLifecycleItemWriter)outputControl.getMock();
//create new writer
writer = new FlatFileCustomerCreditWriter();
writer.setOutputSource(output);
}
public void testOpen() {
//set-up outputSource mock
output.open();
outputControl.replay();
//call tested method
writer.open();
//verify method calls
outputControl.verify();
}
public void testClose() {
//set-up outputSource mock
output.close();
outputControl.replay();
//call tested method
writer.close();
//verify method calls
outputControl.verify();
}
public void testWrite() {
//Create and set-up CustomerCredit
CustomerCredit credit = new CustomerCredit();
credit.setCredit(new BigDecimal(1));
credit.setName("testName");
//set separator
writer.setSeparator(";");
//set-up OutputSource mock
output.write("testName;1");
output.open();
outputControl.replay();
//call tested method
writer.writeCredit(credit);
//verify method calls
outputControl.verify();
}
private interface ResourceLifecycleItemWriter extends ItemWriter, ResourceLifecycle {
}
}

View File

@@ -0,0 +1,85 @@
package org.springframework.batch.sample.dao;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.springframework.batch.io.ItemWriter;
import org.springframework.batch.io.file.support.transform.LineAggregator;
import org.springframework.batch.sample.LineAggregatorStub;
import org.springframework.batch.sample.domain.Address;
import org.springframework.batch.sample.domain.BillingInfo;
import org.springframework.batch.sample.domain.Customer;
import org.springframework.batch.sample.domain.LineItem;
import org.springframework.batch.sample.domain.Order;
public class FlatFileOrderWriterTests extends TestCase {
List list = new ArrayList();
private ItemWriter output = new ItemWriter() {
public void write(Object output) {
list.add(output);
}
};
private FlatFileOrderWriter writer;
public void setUp() throws Exception {
super.setUp();
//create new writer
writer = new FlatFileOrderWriter();
writer.setOutputSource(output);
}
public void testWrite() {
//Create and set-up Order
Order order = new Order();
order.setOrderDate(new GregorianCalendar(2007, GregorianCalendar.JUNE, 1).getTime());
order.setCustomer(new Customer());
order.setBilling(new BillingInfo());
order.setBillingAddress(new Address());
List lineItems = new ArrayList();
LineItem item = new LineItem();
item.setPrice(BigDecimal.valueOf(0));
lineItems.add(item);
lineItems.add(item);
order.setLineItems(lineItems);
order.setTotalPrice(BigDecimal.valueOf(0));
//create aggregator stub
LineAggregator aggregator = new LineAggregatorStub();
//create map of aggregators and set it to writer
Map aggregators = new HashMap();
OrderConverter converter = new OrderConverter();
aggregators.put("header", aggregator);
aggregators.put("customer", aggregator);
aggregators.put("address", aggregator);
aggregators.put("billing", aggregator);
aggregators.put("item", aggregator);
aggregators.put("footer", aggregator);
converter.setAggregators(aggregators);
writer.setConverter(converter);
//call tested method
writer.write(order);
//verify method calls
assertEquals(1, list.size());
assertTrue(list.get(0) instanceof List);
assertEquals("02007/06/01", ((List) list.get(0)).get(0));
}
}

View File

@@ -0,0 +1,42 @@
package org.springframework.batch.sample.dao;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.sample.domain.CustomerDebit;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
public class JdbcCustomerDebitWriterTests extends AbstractTransactionalDataSourceSpringContextTests {
protected String[] getConfigLocations() {
return new String[] { "data-source-context.xml" };
}
public void testWrite() {
//insert customer credit
jdbcTemplate.execute("INSERT INTO customer VALUES (99, 0, 'testName', 100)");
//create writer and set jdbcTemplate
JdbcCustomerDebitWriter writer = new JdbcCustomerDebitWriter();
writer.setJdbcTemplate(jdbcTemplate);
//create customer debit
CustomerDebit customerDebit = new CustomerDebit();
customerDebit.setName("testName");
customerDebit.setDebit(BigDecimal.valueOf(5));
//call writer
writer.write(customerDebit);
//verify customer credit
jdbcTemplate.query("SELECT name, credit FROM customer WHERE name = 'testName'", new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
assertEquals(95, rs.getLong("credit"));
}
});
}
}

View File

@@ -0,0 +1,44 @@
package org.springframework.batch.sample.dao;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.support.incrementer.AbstractDataFieldMaxValueIncrementer;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
public class JdbcTradeWriterTests extends AbstractTransactionalDataSourceSpringContextTests {
protected String[] getConfigLocations() {
return new String[] { "data-source-context.xml" };
}
public void testWrite() {
JdbcTradeWriter writer = new JdbcTradeWriter();
AbstractDataFieldMaxValueIncrementer incrementer = (AbstractDataFieldMaxValueIncrementer)applicationContext.getBean("jobIncrementer");
incrementer.setIncrementerName("TRADE_SEQ");
writer.setIncrementer(incrementer);
writer.setJdbcTemplate(jdbcTemplate);
Trade trade = new Trade();
trade.setCustomer("testCustomer");
trade.setIsin("5647238492");
trade.setPrice(new BigDecimal(Double.toString(99.69)));
trade.setQuantity(5);
writer.write(trade);
jdbcTemplate.query("SELECT * FROM TRADE WHERE ISIN = 5647238492", new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
assertEquals("testCustomer", rs.getString("CUSTOMER"));
assertEquals(new BigDecimal(Double.toString(99.69)), rs.getBigDecimal("PRICE"));
assertEquals(5,rs.getLong("QUANTITY"));
}
});
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2006-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.batch.sample.dao;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import junit.framework.TestCase;
import org.springframework.batch.io.file.support.transform.DelimitedLineAggregator;
import org.springframework.batch.sample.domain.Address;
import org.springframework.batch.sample.domain.BillingInfo;
import org.springframework.batch.sample.domain.Customer;
import org.springframework.batch.sample.domain.Order;
/**
* @author Dave Syer
*
*/
public class OrderConverterTests extends TestCase {
private OrderConverter converter = new OrderConverter();
public void testConvert() throws Exception {
converter.setAggregators(new HashMap() {
{
put("header", new DelimitedLineAggregator());
put("customer", new DelimitedLineAggregator());
put("address", new DelimitedLineAggregator());
put("billing", new DelimitedLineAggregator());
put("item", new DelimitedLineAggregator());
put("footer", new DelimitedLineAggregator());
}
});
Order order = new Order();
order.setOrderDate(new Date());
order.setCustomer(new Customer());
order.setBillingAddress(new Address());
order.setBilling(new BillingInfo());
order.setLineItems(Collections.EMPTY_LIST);
order.setTotalPrice(BigDecimal.TEN);
Object result = converter.convert(order);
assertTrue(result instanceof Collection);
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2006-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.batch.sample.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.sample.domain.Game;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
/**
* @author Lucas Ward
*
*/
public class SqlGameDaoIntegrationTests extends
AbstractTransactionalDataSourceSpringContextTests {
SqlGameDao gameDao;
Game game = new Game();
protected String[] getConfigLocations() {
return new String[]{"data-source-context.xml"};
}
protected void onSetUpBeforeTransaction() throws Exception {
super.onSetUpBeforeTransaction();
gameDao = new SqlGameDao();
gameDao.setJdbcTemplate(getJdbcTemplate());
game.setId("AbduKa00");
game.setYear(1996);
game.setTeam("mia");
game.setWeek(10);
game.setOpponent("nwe");
game.setAttempts(0);
game.setCompletes(0);
game.setPassingYards(0);
game.setPassingTd(0);
game.setInterceptions(0);
game.setRushes(29);
game.setRushYards(109);
game.setReceptions(1);
game.setReceptionYards(16);
game.setTotalTd(2);
}
public void testWrite(){
gameDao.write(game);
Game tempGame = (Game)getJdbcTemplate().queryForObject("SELECT * FROM GAMES", new GameRowMapper());
assertEquals(tempGame, game);
}
public static class GameRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int arg1) throws SQLException{
if(rs == null){
return null;
}
Game game = new Game();
game.setId(rs.getString("PLAYER_ID"));
game.setYear(rs.getInt("year"));
game.setTeam(rs.getString("team"));
game.setWeek(rs.getInt("week"));
game.setOpponent(rs.getString("opponent"));
game.setCompletes(rs.getInt("completes"));
game.setAttempts(rs.getInt("attempts"));
game.setPassingYards(rs.getInt("passing_Yards"));
game.setPassingTd(rs.getInt("passing_Td"));
game.setInterceptions(rs.getInt("interceptions"));
game.setRushes(rs.getInt("rushes"));
game.setRushYards(rs.getInt("rush_Yards"));
game.setReceptions(rs.getInt("receptions"));
game.setReceptionYards(rs.getInt("receptions_Yards"));
game.setTotalTd(rs.getInt("total_Td"));
return game;
}
}
}

View File

@@ -0,0 +1,61 @@
/**
*
*/
package org.springframework.batch.sample.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.sample.domain.Player;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
/**
* @author Lucas Ward
*
*/
public class SqlPlayerDaoIntegrationTests extends AbstractTransactionalDataSourceSpringContextTests {
private SqlPlayerDao playerDao;
private Player player;
private static final String GET_PLAYER = "SELECT * from PLAYERS";
protected String[] getConfigLocations() {
// TODO Auto-generated method stub
return new String[] {"data-source-context.xml"};
}
protected void onSetUpBeforeTransaction() throws Exception {
// TODO Auto-generated method stub
super.onSetUpBeforeTransaction();
playerDao = new SqlPlayerDao();
playerDao.setJdbcTemplate(this.jdbcTemplate);
player = new Player();
player.setID("AKFJDL00");
player.setFirstName("John");
player.setLastName("Doe");
player.setPosition("QB");
player.setBirthYear(1975);
player.setDebutYear(1998);
}
public void testSavePlayer(){
playerDao.savePlayer(player);
getJdbcTemplate().query(GET_PLAYER, new RowCallbackHandler(){
public void processRow(ResultSet rs) throws SQLException {
assertEquals(rs.getString("PLAYER_ID"), "AKFJDL00");
assertEquals(rs.getString("LAST_NAME"), "Doe");
assertEquals(rs.getString("FIRST_NAME"), "John");
assertEquals(rs.getString("POS"), "QB");
assertEquals(rs.getInt("YEAR_OF_BIRTH"), 1975);
assertEquals(rs.getInt("YEAR_DRAFTED"), 1998);
}
});
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2006-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.batch.sample.dao;
import org.springframework.batch.sample.domain.PlayerSummary;
import org.springframework.batch.sample.mapping.PlayerSummaryMapper;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
/**
* @author Lucas Ward
*
*/
public class SqlPlayerSummaryDaoIntegrationTests extends
AbstractTransactionalDataSourceSpringContextTests {
SqlPlayerSummaryDao playerSummaryDao;
PlayerSummary summary;
protected String[] getConfigLocations() {
return new String[] { "data-source-context.xml" };
}
protected void onSetUpBeforeTransaction() throws Exception {
super.onSetUpBeforeTransaction();
playerSummaryDao = new SqlPlayerSummaryDao();
playerSummaryDao.setJdbcTemplate(getJdbcTemplate());
summary = new PlayerSummary();
summary.setId("AikmTr00");
summary.setYear(1997);
summary.setCompletes(294);
summary.setAttempts(517);
summary.setPassingYards(3283);
summary.setPassingTd(19);
summary.setInterceptions(12);
summary.setRushes(25);
summary.setRushYards(79);
summary.setReceptions(0);
summary.setReceptionYards(0);
summary.setTotalTd(0);
}
public void testWrite() {
playerSummaryDao.write(summary);
PlayerSummary testSummary = (PlayerSummary) getJdbcTemplate()
.queryForObject("SELECT * FROM PLAYER_SUMMARY",
new PlayerSummaryMapper());
assertEquals(testSummary, summary);
}
}

View File

@@ -0,0 +1,52 @@
package org.springframework.batch.sample.item.processor;
import java.math.BigDecimal;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.ItemWriter;
import org.springframework.batch.sample.domain.CustomerCredit;
/**
* Tests for {@link CustomerCreditIncreaseProcessor}.
*
* @author Robert Kasanicky
*/
public class CustomerCreditIncreaseProcessorTests extends TestCase{
private CustomerCreditIncreaseProcessor processor = new CustomerCreditIncreaseProcessor();
private ItemWriter outputSource;
private MockControl outputSourceControl = MockControl.createStrictControl(ItemWriter.class);
private CustomerCredit customerCredit = new CustomerCredit();
protected void setUp() throws Exception {
customerCredit.setId(1);
customerCredit.setName("testCustomer");
outputSource = (ItemWriter) outputSourceControl.getMock();
processor.setOutputSource(outputSource);
}
/**
* Increases customer's credit by fixed value
*/
public void testProcess() throws Exception {
BigDecimal oldCredit = new BigDecimal(10.54);
customerCredit.setCredit(oldCredit);
outputSource.write(customerCredit);
outputSourceControl.setVoidCallable();
outputSourceControl.replay();
processor.process(customerCredit);
BigDecimal newCredit = customerCredit.getCredit();
BigDecimal expectedCredit = oldCredit.add(CustomerCreditIncreaseProcessor.FIXED_AMOUNT);
assertTrue(newCredit.compareTo(expectedCredit) == 0);
outputSourceControl.verify();
}
}

View File

@@ -0,0 +1,57 @@
package org.springframework.batch.sample.item.processor;
import java.math.BigDecimal;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.sample.dao.CustomerCreditWriter;
import org.springframework.batch.sample.domain.CustomerCredit;
import org.springframework.batch.sample.item.processor.CustomerCreditUpdateProcessor;
public class CustomerCreditUpdateProcessorTests extends TestCase {
private MockControl writerControl;
private CustomerCreditWriter writer;
private CustomerCreditUpdateProcessor processor;
private static final double CREDIT_FILTER = 355.0;
public void setUp() {
//create mock writer
writerControl = MockControl.createControl(CustomerCreditWriter.class);
writer = (CustomerCreditWriter) writerControl.getMock();
//create processor, set writer and credit filter
processor = new CustomerCreditUpdateProcessor();
processor.setWriter(writer);
processor.setCreditFilter(CREDIT_FILTER);
}
public void testProcess() {
//set-up mock writer - no writer's method should be called
writerControl.replay();
//create credit and set it to same value as credit filter
CustomerCredit credit = new CustomerCredit();
credit.setCredit(new BigDecimal(CREDIT_FILTER));
//call tested method
processor.process(credit);
//verify method calls - no method should be called
//because credit is not greater then credit filter
writerControl.verify();
//change credit to be greater than credit filter
credit.setCredit(new BigDecimal(CREDIT_FILTER + 1));
//reset and set-up writer - write method is expected to be called
writerControl.reset();
writer.writeCredit(credit);
writerControl.replay();
//call tested method
processor.process(credit);
//verify method calls
writerControl.verify();
}
}

View File

@@ -0,0 +1,36 @@
package org.springframework.batch.sample.item.processor;
import java.math.BigDecimal;
import junit.framework.TestCase;
import org.springframework.batch.sample.dao.JdbcCustomerDebitWriter;
import org.springframework.batch.sample.domain.CustomerDebit;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.batch.sample.item.processor.CustomerUpdateProcessor;
public class CustomerUpdateProcessorTests extends TestCase {
public void testProcess() {
//create trade object
Trade trade = new Trade();
trade.setCustomer("testCustomerName");
trade.setPrice(new BigDecimal(123.0));
//create dao
JdbcCustomerDebitWriter dao = new JdbcCustomerDebitWriter() {
public void write(CustomerDebit customerDebit) {
assertEquals("testCustomerName", customerDebit.getName());
assertEquals(new BigDecimal(123.0), customerDebit.getDebit());
}
};
//create processor and set dao
CustomerUpdateProcessor processor = new CustomerUpdateProcessor();
processor.setDao(dao);
//call tested method - see asserts in dao.write() method
processor.process(trade);
}
}

View File

@@ -0,0 +1,28 @@
package org.springframework.batch.sample.item.processor;
import junit.framework.TestCase;
import org.springframework.batch.io.file.support.FlatFileItemWriter;
import org.springframework.batch.sample.item.processor.DefaultFlatFileProcessor;
public class DefaultFlatFileProcessorTests extends TestCase {
public void testProcess() throws Exception {
final Object testLine = new Object();
//create output source
FlatFileItemWriter output = new FlatFileItemWriter() {
public void write(Object line) {
assertEquals(""+testLine, line);
}
};
//create processor and set output source
DefaultFlatFileProcessor processor = new DefaultFlatFileProcessor();
processor.setFlatFileOutputSource(output);
//call tested method - see assert in output.write() method
processor.process(testLine);
}
}

View File

@@ -0,0 +1,54 @@
package org.springframework.batch.sample.item.processor;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.exception.BatchCriticalException;
import org.springframework.batch.sample.dao.OrderWriter;
import org.springframework.batch.sample.domain.Order;
import org.springframework.batch.sample.item.processor.OrderProcessor;
public class OrderProcessorTests extends TestCase {
private MockControl writerControl;
private OrderWriter writer;
private OrderProcessor processor;
public void setUp() {
//create mock writer
writerControl = MockControl.createControl(OrderWriter.class);
writer = (OrderWriter)writerControl.getMock();
//create processor
processor = new OrderProcessor();
processor.setWriter(writer);
}
public void testProcess() {
Order order = new Order();
//set-up mock writer
writer.write(order);
writerControl.replay();
//call tested method
processor.process(order);
//verify method calls
writerControl.verify();
}
public void testProcessWithException() {
writerControl.replay();
//call tested method
try {
processor.process(this);
fail("Batch critical exception was expected");
} catch (BatchCriticalException bce) {
assertTrue(true);
}
writerControl.verify();
}
}

View File

@@ -0,0 +1,48 @@
package org.springframework.batch.sample.item.processor;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.sample.dao.TradeWriter;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.batch.sample.item.processor.TradeProcessor;
public class TradeProcessorTests extends TestCase {
private MockControl writerControl;
private TradeWriter writer;
private TradeProcessor processor;
public void setUp() {
//create mock writer
writerControl = MockControl.createControl(TradeWriter.class);
writer = (TradeWriter)writerControl.getMock();
//create processor
processor = new TradeProcessor();
processor.setWriter(writer);
}
public void testProcess() {
Trade trade = new Trade();
//set-up mock writer
writer.writeTrade(trade);
writerControl.replay();
//call tested method
processor.process(trade);
//verify method calls
writerControl.verify();
}
public void testProcessNonTradeObject() {
writerControl.replay();
//call tested method
processor.process(this);
writerControl.verify();
}
}

View File

@@ -0,0 +1,163 @@
package org.springframework.batch.sample.item.provider;
import java.util.Iterator;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.InputSource;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.item.validator.Validator;
import org.springframework.batch.sample.domain.Address;
import org.springframework.batch.sample.domain.BillingInfo;
import org.springframework.batch.sample.domain.Customer;
import org.springframework.batch.sample.domain.LineItem;
import org.springframework.batch.sample.domain.Order;
import org.springframework.batch.sample.domain.ShippingInfo;
import org.springframework.batch.sample.item.provider.OrderItemProvider;
public class OrderItemProviderTests extends TestCase {
private OrderItemProvider provider;
private MockControl inputControl;
private InputSource input;
private MockControl mapperControl;
private FieldSetMapper mapper;
private MockControl validatorControl;
private Validator validator;
public void setUp() {
inputControl = MockControl.createControl(InputSource.class);
input = (InputSource)inputControl.getMock();
provider = new OrderItemProvider();
provider.setInputSource(input);
}
/*
* OrderItemProvider is resposible for retrieving validated value object from input source.
* OrderItemProvider.next():
* - reads lines from the input source - returned as fieldsets
* - pass fieldsets to the mapper - mapper will create value object
* - pass value object to validator
* - returns validated object
*
* In testNext method we are going to test these responsibilities. So we need create mock
* objects for input source, mapper and validator.
*/
public void testNext() {
//create fieldsets and set return values for input source
FieldSet headerFS = new FieldSet(new String[] {Order.LINE_ID_HEADER});
FieldSet customerFS = new FieldSet(new String[] {Customer.LINE_ID_NON_BUSINESS_CUST});
FieldSet billingFS = new FieldSet(new String[] {Address.LINE_ID_BILLING_ADDR});
FieldSet shippingFS = new FieldSet(new String[] {Address.LINE_ID_SHIPPING_ADDR});
FieldSet billingInfoFS = new FieldSet(new String[] {BillingInfo.LINE_ID_BILLING_INFO});
FieldSet shippingInfoFS = new FieldSet(new String[] {ShippingInfo.LINE_ID_SHIPPING_INFO});
FieldSet itemFS = new FieldSet(new String[] {LineItem.LINE_ID_ITEM});
FieldSet footerFS = new FieldSet(new String[] {Order.LINE_ID_FOOTER, "100","3","3"},
new String[] {"ID","TOTAL_PRICE","TOTAL_LINE_ITEMS","TOTAL_ITEMS"});
input.read();
inputControl.setReturnValue(headerFS);
input.read();
inputControl.setReturnValue(customerFS);
input.read();
inputControl.setReturnValue(billingFS);
input.read();
inputControl.setReturnValue(shippingFS);
input.read();
inputControl.setReturnValue(billingInfoFS);
input.read();
inputControl.setReturnValue(shippingInfoFS);
input.read();
inputControl.setReturnValue(itemFS,3);
input.read();
inputControl.setReturnValue(footerFS);
input.read();
inputControl.setReturnValue(null);
inputControl.replay();
//create value objects
Order order = new Order();
Customer customer = new Customer();
Address billing = new Address();
Address shipping = new Address();
BillingInfo billingInfo = new BillingInfo();
ShippingInfo shippingInfo = new ShippingInfo();
LineItem item = new LineItem();
//create mock mapper
mapperControl = MockControl.createControl(FieldSetMapper.class);
mapper = (FieldSetMapper)mapperControl.getMock();
//set how mapper should respond - set return values for mapper
mapper.mapLine(headerFS);
mapperControl.setReturnValue(order);
mapper.mapLine(customerFS);
mapperControl.setReturnValue(customer);
mapper.mapLine(billingFS);
mapperControl.setReturnValue(billing);
mapper.mapLine(shippingFS);
mapperControl.setReturnValue(shipping);
mapper.mapLine(billingInfoFS);
mapperControl.setReturnValue(billingInfo);
mapper.mapLine(shippingInfoFS);
mapperControl.setReturnValue(shippingInfo);
mapper.mapLine(itemFS);
mapperControl.setReturnValue(item,3);
mapperControl.replay();
//create mock validator
validatorControl = MockControl.createControl(Validator.class);
validator = (Validator)validatorControl.getMock();
validator.validate(null);
validatorControl.setMatcher(MockControl.ALWAYS_MATCHER);
validatorControl.setVoidCallable(1);
validatorControl.replay();
//set-up provider: set mappers and validator
provider.setValidator(validator);
provider.setAddressMapper(mapper);
provider.setBillingMapper(mapper);
provider.setCustomerMapper(mapper);
provider.setHeaderMapper(mapper);
provider.setItemMapper(mapper);
provider.setShippingMapper(mapper);
//call tested method
Object result = provider.next();
//verify result
assertNotNull(result);
//result should be Order
assertTrue(result instanceof Order);
//verify whether order is constructed correctly
//Order object should contain same instances as returned by mapper
Order o = (Order) result;
assertEquals(o,order);
assertEquals(o.getCustomer(),customer);
//is it non-bussines customer
assertFalse(o.getCustomer().isBusinessCustomer());
assertEquals(o.getBillingAddress(),billing);
assertEquals(o.getShippingAddress(),shipping);
assertEquals(o.getBilling(),billingInfo);
assertEquals(o.getShipping(), shippingInfo);
//there should be 3 line items
assertEquals(3, o.getLineItems().size());
for (Iterator i = o.getLineItems().iterator(); i.hasNext();) {
assertEquals(i.next(),item);
}
//try to retrieve next object - nothing should be returned
assertNull(provider.next());
//verify method calls on input source, mapper and validator
inputControl.verify();
mapperControl.verify();
validatorControl.verify();
}
}

View File

@@ -0,0 +1,41 @@
package org.springframework.batch.sample.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import junit.framework.TestCase;
/**
* Encapsulates basic logic for testing custom {@link FieldSetMapper} implementations.
*
* @author Robert Kasanicky
*/
public abstract class AbstractFieldSetMapperTests extends TestCase {
/**
* @return <code>FieldSet</code> used for mapping
*/
protected abstract FieldSet fieldSet();
/**
* @return domain object excepted as a result of mapping the <code>FieldSet</code>
* returned by <code>this.fieldSet()</code>
*/
protected abstract Object expectedDomainObject();
/**
* @return mapper which takes <code>this.fieldSet()</code> and maps it to
* domain object.
*/
protected abstract FieldSetMapper fieldSetMapper();
/**
* Regular usage scenario.
* Assumes the domain object implements sensible <code>equals(Object other)</code>
*/
public void testRegularUse() {
assertEquals(expectedDomainObject(), fieldSetMapper().mapLine(fieldSet()));
}
}

View File

@@ -0,0 +1,51 @@
package org.springframework.batch.sample.mapping;
import java.sql.ResultSet;
import java.sql.SQLException;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jdbc.core.RowMapper;
/**
* Encapsulates logic for testing custom {@link RowMapper} implementations.
*
* @author Robert Kasanicky
*/
public abstract class AbstractRowMapperTests extends TestCase {
//row number should be irrelevant
private static final int IGNORED_ROW_NUMBER = 0;
//mock result set
private MockControl rsControl = MockControl.createControl(ResultSet.class);
private ResultSet rs = (ResultSet) rsControl.getMock();
/**
* @return Expected result of mapping the mock <code>ResultSet</code> by
* the mapper being tested.
*/
abstract protected Object expectedDomainObject();
/**
* @return <code>RowMapper</code> implementation that is being tested.
*/
abstract protected RowMapper rowMapper();
/**
* Define the behaviour of mock <code>ResultSet</code>.
*/
abstract protected void setUpResultSetMock(ResultSet rs, MockControl rsControl) throws SQLException;
/**
* Regular usage scenario.
*/
public void testRegularUse() throws SQLException {
setUpResultSetMock(rs, rsControl);
rsControl.replay();
assertEquals(expectedDomainObject(), rowMapper().mapRow(rs, IGNORED_ROW_NUMBER));
}
}

View File

@@ -0,0 +1,52 @@
package org.springframework.batch.sample.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.Address;
import org.springframework.batch.sample.mapping.AddressFieldSetMapper;
public class AddressFieldSetMapperTests extends AbstractFieldSetMapperTests {
private static final String ADDRESSEE = "Jan Hrach";
private static final String ADDRESS_LINE_1 = "Plynarenska 7c";
private static final String ADDRESS_LINE_2 = "";
private static final String CITY = "Bratislava";
private static final String STATE = "";
private static final String COUNTRY = "Slovakia";
private static final String ZIP_CODE = "80000";
protected Object expectedDomainObject() {
Address address = new Address();
address.setAddressee(ADDRESSEE);
address.setAddrLine1(ADDRESS_LINE_1);
address.setAddrLine2(ADDRESS_LINE_2);
address.setCity(CITY);
address.setState(STATE);
address.setCountry(COUNTRY);
address.setZipCode(ZIP_CODE);
return address;
}
protected FieldSet fieldSet() {
String[] tokens =
new String[]{ADDRESSEE, ADDRESS_LINE_1, ADDRESS_LINE_2, CITY, STATE, COUNTRY, ZIP_CODE};
String[] columnNames =
new String[]{
AddressFieldSetMapper.ADDRESSEE_COLUMN,
AddressFieldSetMapper.ADDRESS_LINE1_COLUMN,
AddressFieldSetMapper.ADDRESS_LINE2_COLUMN,
AddressFieldSetMapper.CITY_COLUMN,
AddressFieldSetMapper.STATE_COLUMN,
AddressFieldSetMapper.COUNTRY_COLUMN,
AddressFieldSetMapper.ZIP_CODE_COLUMN };
return new FieldSet(tokens, columnNames);
}
protected FieldSetMapper fieldSetMapper() {
return new AddressFieldSetMapper();
}
}

View File

@@ -0,0 +1,34 @@
package org.springframework.batch.sample.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.BillingInfo;
import org.springframework.batch.sample.mapping.BillingFieldSetMapper;
public class BillingFieldSetMapperTests extends AbstractFieldSetMapperTests{
private static final String PAYMENT_ID = "777";
private static final String PAYMENT_DESC = "My last penny";
protected Object expectedDomainObject() {
BillingInfo bInfo = new BillingInfo();
bInfo.setPaymentDesc(PAYMENT_DESC);
bInfo.setPaymentId(PAYMENT_ID);
return bInfo;
}
protected FieldSet fieldSet() {
String[] tokens = new String[]{
PAYMENT_ID,
PAYMENT_DESC};
String[] columnNames = new String[]{
BillingFieldSetMapper.PAYMENT_TYPE_ID_COLUMN,
BillingFieldSetMapper.PAYMENT_DESC_COLUMN};
return new FieldSet(tokens, columnNames);
}
protected FieldSetMapper fieldSetMapper() {
return new BillingFieldSetMapper();
}
}

View File

@@ -0,0 +1,35 @@
package org.springframework.batch.sample.mapping;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.easymock.MockControl;
import org.springframework.batch.sample.domain.CustomerCredit;
import org.springframework.batch.sample.mapping.CustomerCreditRowMapper;
import org.springframework.jdbc.core.RowMapper;
public class CustomerCreditRowMapperTests extends AbstractRowMapperTests {
private static final String CUSTOMER = "Jozef Mak";
private static final BigDecimal CREDIT = new BigDecimal(0.1);
protected Object expectedDomainObject() {
CustomerCredit credit = new CustomerCredit();
credit.setCredit(CREDIT);
credit.setName(CUSTOMER);
return credit;
}
protected RowMapper rowMapper() {
return new CustomerCreditRowMapper();
}
protected void setUpResultSetMock(ResultSet rs, MockControl rsControl) throws SQLException {
rs.getString(CustomerCreditRowMapper.NAME_COLUMN);
rsControl.setReturnValue(CUSTOMER);
rs.getBigDecimal(CustomerCreditRowMapper.CREDIT_COLUMN);
rsControl.setReturnValue(CREDIT);
}
}

View File

@@ -0,0 +1,56 @@
package org.springframework.batch.sample.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.Customer;
import org.springframework.batch.sample.mapping.CustomerFieldSetMapper;
public class CustomerFieldSetMapperTests extends AbstractFieldSetMapperTests {
private static final boolean BUSINESS_CUSTOMER = false;
//private static final String COMPANY_NAME = "Accenture";
private static final String FIRST_NAME = "Jan";
private static final String LAST_NAME = "Hrach";
private static final String MIDDLE_NAME = "";
private static final boolean REGISTERED = true;
private static final long REG_ID = 1;
private static final boolean VIP = true;
protected Object expectedDomainObject() {
Customer cs = new Customer();
cs.setBusinessCustomer(BUSINESS_CUSTOMER);
cs.setFirstName(FIRST_NAME);
cs.setLastName(LAST_NAME);
cs.setMiddleName(MIDDLE_NAME);
cs.setRegistered(REGISTERED);
cs.setRegistrationId(REG_ID);
cs.setVip(VIP);
return cs;
}
protected FieldSet fieldSet() {
String[] tokens = new String[]{
Customer.LINE_ID_NON_BUSINESS_CUST,
FIRST_NAME,
LAST_NAME,
MIDDLE_NAME,
CustomerFieldSetMapper.TRUE_SYMBOL,
String.valueOf(REG_ID),
CustomerFieldSetMapper.TRUE_SYMBOL};
String[] columnNames = new String[]{
CustomerFieldSetMapper.LINE_ID_COLUMN,
CustomerFieldSetMapper.FIRST_NAME_COLUMN,
CustomerFieldSetMapper.LAST_NAME_COLUMN,
CustomerFieldSetMapper.MIDDLE_NAME_COLUMN,
CustomerFieldSetMapper.REGISTERED_COLUMN,
CustomerFieldSetMapper.REG_ID_COLUMN,
CustomerFieldSetMapper.VIP_COLUMN};
return new FieldSet(tokens, columnNames);
}
protected FieldSetMapper fieldSetMapper() {
return new CustomerFieldSetMapper();
}
}

View File

@@ -0,0 +1,41 @@
package org.springframework.batch.sample.mapping;
import java.util.Calendar;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.Order;
import org.springframework.batch.sample.mapping.HeaderFieldSetMapper;
public class HeaderFieldSetMapperTests extends AbstractFieldSetMapperTests {
private static final long ORDER_ID = 1;
private static final String DATE = "2007-01-01";
protected Object expectedDomainObject() {
Order order = new Order();
Calendar calendar = Calendar.getInstance();
calendar.set(2007, 0, 1, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
order.setOrderDate(calendar.getTime());
order.setOrderId(ORDER_ID);
return order;
}
protected FieldSet fieldSet() {
String[] tokens = new String[]{
String.valueOf(ORDER_ID),
DATE
};
String[] columnNames = new String[]{
HeaderFieldSetMapper.ORDER_ID_COLUMN,
HeaderFieldSetMapper.ORDER_DATE_COLUMN
};
return new FieldSet(tokens, columnNames);
}
protected FieldSetMapper fieldSetMapper() {
return new HeaderFieldSetMapper();
}
}

View File

@@ -0,0 +1,62 @@
package org.springframework.batch.sample.mapping;
import java.math.BigDecimal;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.LineItem;
import org.springframework.batch.sample.mapping.OrderItemFieldSetMapper;
public class OrderItemFieldSetMapperTests extends AbstractFieldSetMapperTests{
private static final BigDecimal DISCOUNT_AMOUNT = new BigDecimal(1);
private static final BigDecimal DISCOUNT_PERC = new BigDecimal(2);
private static final BigDecimal HANDLING_PRICE = new BigDecimal(3);
private static final long ITEM_ID = 4;
private static final BigDecimal PRICE = new BigDecimal(5);
private static final int QUANTITY = 6;
private static final BigDecimal SHIPPING_PRICE = new BigDecimal(7);
private static final BigDecimal TOTAL_PRICE = new BigDecimal(8);
protected Object expectedDomainObject() {
LineItem item = new LineItem();
item.setDiscountAmount(DISCOUNT_AMOUNT);
item.setDiscountPerc(DISCOUNT_PERC);
item.setHandlingPrice(HANDLING_PRICE);
item.setItemId(ITEM_ID);
item.setPrice(PRICE);
item.setQuantity(QUANTITY);
item.setShippingPrice(SHIPPING_PRICE);
item.setTotalPrice(TOTAL_PRICE);
return item;
}
protected FieldSet fieldSet() {
String[] tokens = new String[]{
String.valueOf(DISCOUNT_AMOUNT),
String.valueOf(DISCOUNT_PERC),
String.valueOf(HANDLING_PRICE),
String.valueOf(ITEM_ID),
String.valueOf(PRICE),
String.valueOf(QUANTITY),
String.valueOf(SHIPPING_PRICE),
String.valueOf(TOTAL_PRICE)
};
String[] columnNames = new String[]{
OrderItemFieldSetMapper.DISCOUNT_AMOUNT_COLUMN,
OrderItemFieldSetMapper.DISCOUNT_PERC_COLUMN,
OrderItemFieldSetMapper.HANDLING_PRICE_COLUMN,
OrderItemFieldSetMapper.ITEM_ID_COLUMN,
OrderItemFieldSetMapper.PRICE_COLUMN,
OrderItemFieldSetMapper.QUANTITY_COLUMN,
OrderItemFieldSetMapper.SHIPPING_PRICE_COLUMN,
OrderItemFieldSetMapper.TOTAL_PRICE_COLUMN
};
return new FieldSet(tokens, columnNames);
}
protected FieldSetMapper fieldSetMapper() {
return new OrderItemFieldSetMapper();
}
}

View File

@@ -0,0 +1,36 @@
package org.springframework.batch.sample.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.ShippingInfo;
import org.springframework.batch.sample.mapping.ShippingFieldSetMapper;
public class ShippingFieldSetMapperTests extends AbstractFieldSetMapperTests{
private static final String SHIPPER_ID = "1";
private static final String SHIPPING_INFO = "most interesting and informative shipping info ever";
private static final String SHIPPING_TYPE_ID = "X";
protected Object expectedDomainObject() {
ShippingInfo info = new ShippingInfo();
info.setShipperId(SHIPPER_ID);
info.setShippingInfo(SHIPPING_INFO);
info.setShippingTypeId(SHIPPING_TYPE_ID);
return info;
}
protected FieldSet fieldSet() {
String[] tokens = new String[]{SHIPPER_ID, SHIPPING_INFO, SHIPPING_TYPE_ID};
String[] columnNames = new String[]{
ShippingFieldSetMapper.SHIPPER_ID_COLUMN,
ShippingFieldSetMapper.ADDITIONAL_SHIPPING_INFO_COLUMN,
ShippingFieldSetMapper.SHIPPING_TYPE_ID_COLUMN
};
return new FieldSet(tokens, columnNames);
}
protected FieldSetMapper fieldSetMapper() {
return new ShippingFieldSetMapper();
}
}

View File

@@ -0,0 +1,48 @@
package org.springframework.batch.sample.mapping;
import java.math.BigDecimal;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.batch.sample.mapping.TradeFieldSetMapper;
public class TradeFieldSetMapperTests extends AbstractFieldSetMapperTests{
private static final String CUSTOMER = "Mike Tomcat";
private static final BigDecimal PRICE = new BigDecimal(1.3);
private static final long QUANTITY = 7;
private static final String ISIN = "fj893gnsalX";
protected Object expectedDomainObject() {
Trade trade = new Trade();
trade.setIsin(ISIN);
trade.setQuantity(QUANTITY);
trade.setPrice(PRICE);
trade.setCustomer(CUSTOMER);
return trade;
}
protected FieldSet fieldSet() {
String[] tokens = new String[4];
tokens[TradeFieldSetMapper.ISIN_COLUMN] = ISIN;
tokens[TradeFieldSetMapper.QUANTITY_COLUMN] = String.valueOf(QUANTITY);
tokens[TradeFieldSetMapper.PRICE_COLUMN] = String.valueOf(PRICE);
tokens[TradeFieldSetMapper.CUSTOMER_COLUMN] = CUSTOMER;
return new FieldSet(tokens);
}
protected FieldSetMapper fieldSetMapper() {
return new TradeFieldSetMapper();
}
public void testBeginRecord() throws Exception {
assertEquals(FieldSetMapper.BEGIN_RECORD, fieldSetMapper().mapLine(new FieldSet(new String[] {"BEGIN"})));
}
public void testEndRecord() throws Exception {
assertEquals(FieldSetMapper.END_RECORD, fieldSetMapper().mapLine(new FieldSet(new String[] {"END"})));
}
}

View File

@@ -0,0 +1,46 @@
package org.springframework.batch.sample.mapping;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.easymock.MockControl;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.batch.sample.mapping.TradeRowMapper;
import org.springframework.jdbc.core.RowMapper;
public class TradeRowMapperTests extends AbstractRowMapperTests {
private static final String ISIN = "jsgk342";
private static final long QUANTITY = 0;
private static final BigDecimal PRICE = new BigDecimal(1.1);
private static final String CUSTOMER = "Martin Hrancok";
protected Object expectedDomainObject() {
Trade trade = new Trade();
trade.setIsin(ISIN);
trade.setQuantity(QUANTITY);
trade.setPrice(PRICE);
trade.setCustomer(CUSTOMER);
return trade;
}
protected RowMapper rowMapper() {
return new TradeRowMapper();
}
protected void setUpResultSetMock(ResultSet rs, MockControl rsControl) throws SQLException {
rs.getString(TradeRowMapper.ISIN_COLUMN);
rsControl.setReturnValue(ISIN);
rs.getLong(TradeRowMapper.QUANTITY_COLUMN);
rsControl.setReturnValue(QUANTITY);
rs.getBigDecimal(TradeRowMapper.PRICE_COLUMN);
rsControl.setReturnValue(PRICE);
rs.getString(TradeRowMapper.CUSTOMER_COLUMN);
rsControl.setReturnValue(CUSTOMER);
}
}

View File

@@ -0,0 +1,65 @@
package org.springframework.batch.sample.tasklet;
import java.util.ArrayList;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.exception.BatchCriticalException;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.provider.ListItemProvider;
import org.springframework.batch.repeat.context.RepeatContextSupport;
import org.springframework.batch.repeat.synch.RepeatSynchronizationManager;
import org.springframework.batch.sample.tasklet.ExceptionRestartableTasklet;
public class ExceptionRestartableTaskletTests extends TestCase {
//expected call count before exception is thrown (exception should be thrown in next iteration)
private static final int ITER_COUNT = 5;
protected void tearDown() throws Exception {
RepeatSynchronizationManager.clear();
}
public void testProcess() throws Exception {
//create mock item processor wich will be called by module.process() method
MockControl processorControl = MockControl.createControl(ItemProcessor.class);
ItemProcessor itemProcessor = (ItemProcessor)processorControl.getMock();
//set expected call count and argument matcher
itemProcessor.process(null);
processorControl.setMatcher(MockControl.ALWAYS_MATCHER);
processorControl.setVoidCallable(ITER_COUNT);
processorControl.replay();
//create module and set item processor and iteration count
ExceptionRestartableTasklet module = new ExceptionRestartableTasklet();
module.setItemProcessor(itemProcessor);
module.setThrowExceptionOnRecordNumber(ITER_COUNT + 1);
module.setItemProvider(new ListItemProvider(new ArrayList() {{
add("a");
add("b");
add("c");
add("d");
add("e");
add("f");
}}));
RepeatSynchronizationManager.register(new RepeatContextSupport(null));
//call process method multiple times and verify whether exception is thrown when expected
for (int i = 0; i <= ITER_COUNT; i++) {
try {
module.execute();
assertTrue(i < ITER_COUNT);
} catch (BatchCriticalException bce) {
assertEquals(ITER_COUNT,i);
}
}
//verify method calls
processorControl.verify();
}
}

View File

@@ -0,0 +1,63 @@
package org.springframework.batch.sample.tasklet;
import java.math.BigDecimal;
import junit.framework.TestCase;
import org.springframework.batch.io.file.support.DefaultFlatFileInputSource;
import org.springframework.batch.sample.dao.TradeWriter;
import org.springframework.batch.sample.domain.Trade;
public class SimpleTradeTaskletTests extends TestCase {
private boolean inputCalled = false;
private boolean writerCalled = false;
public void testReadAndProcess() throws Exception {
//create input
DefaultFlatFileInputSource input = new DefaultFlatFileInputSource() {
private boolean done = false;
public Object read() {
if (!done) {
Trade trade = new Trade("1234", 5, new BigDecimal(100), "testName");
inputCalled = true;
done = true;
return trade;
} else {
return null;
}
}
};
//create writer
TradeWriter writer = new TradeWriter() {
public void writeTrade(Trade trade) {
assertEquals("1234",trade.getIsin());
assertEquals(5, trade.getQuantity());
assertEquals(new BigDecimal(100), trade.getPrice());
assertEquals("testName", trade.getCustomer());
writerCalled = true;
}
public void write(Object output) {}
};
//create module
SimpleTradeTasklet module = new SimpleTradeTasklet();
module.setInputSource(input);
module.setTradeDao(writer);
//call tested methods
//read method should return true, because input returned fieldset
assertTrue(module.execute().isContinuable());
//verify whether input and writer were called
assertTrue(inputCalled);
assertTrue(writerCalled);
//read should return false, because input returned null
assertFalse(module.execute().isContinuable());
}
}

View File

@@ -0,0 +1,61 @@
package org.springframework.batch.sample.validation.valang.custom;
import java.util.Date;
import org.easymock.MockControl;
import org.springmodules.validation.valang.functions.Function;
import junit.framework.TestCase;
public class FutureDateFunctionTests extends TestCase {
private FutureDateFunction function;
private MockControl argumentControl;
private Function argument;
public void setUp() {
argumentControl = MockControl.createControl(Function.class);
argument = (Function) argumentControl.getMock();
//create function
function = new FutureDateFunction(new Function[] {argument}, 0, 0);
}
public void testFunctionWithNonDateValue() {
//set-up mock argument - set return value to non Date value
argument.getResult(null);
argumentControl.setReturnValue(this);
argumentControl.replay();
//call tested method - exception is expected because non date value
try {
function.doGetResult(null);
fail("Exception was expected.");
} catch (Exception e) {
assertTrue(true);
}
}
public void testFunctionWithFutureDate() throws Exception {
//set-up mock argument - set return value to future Date
argument.getResult(null);
argumentControl.setReturnValue(new Date(Long.MAX_VALUE));
argumentControl.replay();
//vefify result - should be true because of future date
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testFunctionWithPastDate() throws Exception {
//set-up mock argument - set return value to future Date
argument.getResult(null);
argumentControl.setReturnValue(new Date(0));
argumentControl.replay();
//vefify result - should be false because of past date
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
}

View File

@@ -0,0 +1,82 @@
package org.springframework.batch.sample.validation.valang.custom;
import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.sample.domain.LineItem;
import org.easymock.MockControl;
import org.springmodules.validation.valang.functions.Function;
import junit.framework.TestCase;
public class TotalOrderItemsFunctionTests extends TestCase {
private TotalOrderItemsFunction function;
private MockControl argument1Control;
private Function argument1;
private MockControl argument2Control;
private Function argument2;
public void setUp() {
//create mock for first argument - set count to 3
argument1Control = MockControl.createControl(Function.class);
argument1 = (Function) argument1Control.getMock();
argument1.getResult(null);
argument1Control.setReturnValue(new Integer(3));
argument1Control.replay();
argument2Control = MockControl.createControl(Function.class);
argument2 = (Function) argument2Control.getMock();
//create function
function = new TotalOrderItemsFunction(new Function[] {argument1, argument2}, 0, 0);
}
public void testFunctionWithNonListValue() {
argument2.getResult(null);
argument2Control.setReturnValue(this);
argument2Control.replay();
//call tested method - exception is expected because non list value
try {
function.doGetResult(null);
fail("Exception was expected.");
} catch (Exception e) {
assertTrue(true);
}
}
public void testFunctionWithCorrectItemCount() throws Exception {
//create list with correct item count
LineItem item = new LineItem();
item.setQuantity(3);
List list = new ArrayList();
list.add(item);
argument2.getResult(null);
argument2Control.setReturnValue(list);
argument2Control.replay();
//vefify result
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testFunctionWithIncorrectItemCount() throws Exception {
//create list with incorrect item count
LineItem item = new LineItem();
item.setQuantity(99);
List list = new ArrayList();
list.add(item);
argument2.getResult(null);
argument2Control.setReturnValue(list);
argument2Control.replay();
//vefify result
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
}

View File

@@ -0,0 +1,166 @@
package org.springframework.batch.sample.validation.valang.custom;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.sample.domain.LineItem;
import org.easymock.MockControl;
import org.springmodules.validation.valang.functions.Function;
import junit.framework.TestCase;
public class ValidateDiscountsFunctionTests extends TestCase {
private ValidateDiscountsFunction function;
private MockControl argumentControl;
private Function argument;
public void setUp() {
argumentControl = MockControl.createControl(Function.class);
argument = (Function) argumentControl.getMock();
//create function
function = new ValidateDiscountsFunction(new Function[] {argument}, 0, 0);
}
public void testDiscountPercentageMin() throws Exception {
//create line item with correct discount percentage and zero discount amount
LineItem item = new LineItem();
item.setDiscountPerc(new BigDecimal(1.0));
item.setDiscountAmount(new BigDecimal(0.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all discount percentages are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with negative percentage
item = new LineItem();
item.setDiscountPerc(new BigDecimal(-1.0));
item.setDiscountAmount(new BigDecimal(0.0));
items.add(item);
//verify result - should be false - second item has invalid discount percentage
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testDiscountPercentageMax() throws Exception {
//create line item with correct discount percentage and zero discount amount
LineItem item = new LineItem();
item.setDiscountPerc(new BigDecimal(99.0));
item.setDiscountAmount(new BigDecimal(0.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all discount percentages are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with discount percentage above 100
item = new LineItem();
item.setDiscountPerc(new BigDecimal(101.0));
item.setDiscountAmount(new BigDecimal(0.0));
items.add(item);
//verify result - should be false - second item has invalid discount percentage
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testDiscountPriceMin() throws Exception {
//create line item with correct discount amount and zero discount percentage
LineItem item = new LineItem();
item.setDiscountPerc(new BigDecimal(0.0));
item.setDiscountAmount(new BigDecimal(10.0));
item.setPrice(new BigDecimal(100.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all discount amounts are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with negative discount amount
item = new LineItem();
item.setDiscountPerc(new BigDecimal(0.0));
item.setDiscountAmount(new BigDecimal(-1.0));
item.setPrice(new BigDecimal(100.0));
items.add(item);
//verify result - should be false - second item has invalid discount amount
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testDiscountPriceMax() throws Exception {
//create line item with correct discount amount and zero discount percentage
LineItem item = new LineItem();
item.setDiscountPerc(new BigDecimal(0.0));
item.setDiscountAmount(new BigDecimal(99.0));
item.setPrice(new BigDecimal(100.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all discount amounts are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with discount amount above item price
item = new LineItem();
item.setDiscountPerc(new BigDecimal(0.0));
item.setDiscountAmount(new BigDecimal(101.0));
item.setPrice(new BigDecimal(100.0));
items.add(item);
//verify result - should be false - second item has invalid discount amount
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testBothDiscountValuesNonZero() throws Exception {
//create line item with non-zero discount amount and non-zero discount percentage
LineItem item = new LineItem();
item.setDiscountPerc(new BigDecimal(10.0));
item.setDiscountAmount(new BigDecimal(99.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items);
argumentControl.replay();
//verify result - should be false - only one of the discount values is empty
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
}

View File

@@ -0,0 +1,81 @@
package org.springframework.batch.sample.validation.valang.custom;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.easymock.MockControl;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.Function;
import junit.framework.TestCase;
public class ValidateHandlingPricesFunctionTests extends TestCase {
private ValidateHandlingPricesFunction function;
private MockControl argumentControl;
private Function argument;
public void setUp() {
argumentControl = MockControl.createControl(Function.class);
argument = (Function) argumentControl.getMock();
//create function
function = new ValidateHandlingPricesFunction(new Function[] {argument}, 0, 0);
}
public void testHandlingPriceMin() throws Exception {
//create line item with correct handling price
LineItem item = new LineItem();
item.setHandlingPrice(new BigDecimal(1.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all handling prices are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with negative handling price
item = new LineItem();
item.setHandlingPrice(new BigDecimal(-1.0));
items.add(item);
//verify result - should be false - second item has invalid handling price
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testHandlingPriceMax() throws Exception {
//create line item with correct handling price
LineItem item = new LineItem();
item.setHandlingPrice(new BigDecimal(99999999.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all handling prices are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with handling price above allowed max
item = new LineItem();
item.setHandlingPrice(new BigDecimal(100000000.0));
items.add(item);
//verify result - should be false - second item has invalid handling price
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
}

View File

@@ -0,0 +1,80 @@
package org.springframework.batch.sample.validation.valang.custom;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.Function;
public class ValidateIdsFunctionTests extends TestCase {
private ValidateIdsFunction function;
private MockControl argumentControl;
private Function argument;
public void setUp() {
argumentControl = MockControl.createControl(Function.class);
argument = (Function) argumentControl.getMock();
//create function
function = new ValidateIdsFunction(new Function[] {argument}, 0, 0);
}
public void testIdMin() throws Exception {
//create line item with correct item id
LineItem item = new LineItem();
item.setItemId(1);
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all ids are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with negative id
item = new LineItem();
item.setItemId(-1);
items.add(item);
//verify result - should be false - second item has invalid id
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testIdMax() throws Exception {
//create line item with correct item id
LineItem item = new LineItem();
item.setItemId(9999999999L);
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all item ids are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with item id above allowed max
item = new LineItem();
item.setItemId(10000000000L);
items.add(item);
//verify result - should be false - second item has invalid item id
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
}

View File

@@ -0,0 +1,82 @@
package org.springframework.batch.sample.validation.valang.custom;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.easymock.MockControl;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.Function;
import junit.framework.TestCase;
public class ValidatePricesFunctionTests extends TestCase {
private ValidatePricesFunction function;
private MockControl argumentControl;
private Function argument;
public void setUp() {
argumentControl = MockControl.createControl(Function.class);
argument = (Function) argumentControl.getMock();
//create function
function = new ValidatePricesFunction(new Function[] {argument}, 0, 0);
}
public void testItemPriceMin() throws Exception {
//create line item with correct item price
LineItem item = new LineItem();
item.setPrice(new BigDecimal(1.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all item prices are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with negative item price
item = new LineItem();
item.setPrice(new BigDecimal(-1.0));
items.add(item);
//verify result - should be false - second item has invalid item price
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testItemPriceMax() throws Exception {
//create line item with correct item price
LineItem item = new LineItem();
item.setPrice(new BigDecimal(99999999.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all item prices are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with item price above allowed max
item = new LineItem();
item.setPrice(new BigDecimal(100000000.0));
items.add(item);
//verify result - should be false - second item has invalid item price
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
}

View File

@@ -0,0 +1,80 @@
package org.springframework.batch.sample.validation.valang.custom;
import java.util.ArrayList;
import java.util.List;
import org.easymock.MockControl;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.Function;
import junit.framework.TestCase;
public class ValidateQuantitiesFunctionTests extends TestCase {
private ValidateQuantitiesFunction function;
private MockControl argumentControl;
private Function argument;
public void setUp() {
argumentControl = MockControl.createControl(Function.class);
argument = (Function) argumentControl.getMock();
//create function
function = new ValidateQuantitiesFunction(new Function[] {argument}, 0, 0);
}
public void testQuantityMin() throws Exception {
//create line item with correct item quantity
LineItem item = new LineItem();
item.setQuantity(1);
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all quantities are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with negative quantity
item = new LineItem();
item.setQuantity(-1);
items.add(item);
//verify result - should be false - second item has invalid quantity
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testQuantityMax() throws Exception {
//create line item with correct item quantity
LineItem item = new LineItem();
item.setQuantity(9999);
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all item quantities are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with item quantity above allowed max
item = new LineItem();
item.setQuantity(10000);
items.add(item);
//verify result - should be false - second item has invalid item quantity
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
}

View File

@@ -0,0 +1,81 @@
package org.springframework.batch.sample.validation.valang.custom;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.easymock.MockControl;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.Function;
import junit.framework.TestCase;
public class ValidateShippingPricesFunctionTests extends TestCase {
private ValidateShippingPricesFunction function;
private MockControl argumentControl;
private Function argument;
public void setUp() {
argumentControl = MockControl.createControl(Function.class);
argument = (Function) argumentControl.getMock();
//create function
function = new ValidateShippingPricesFunction(new Function[] {argument}, 0, 0);
}
public void testShippingPriceMin() throws Exception {
//create line item with correct shipping price
LineItem item = new LineItem();
item.setShippingPrice(new BigDecimal(1.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all shipping prices are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with negative shipping price
item = new LineItem();
item.setShippingPrice(new BigDecimal(-1.0));
items.add(item);
//verify result - should be false - second item has invalid shipping price
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testShippingPriceMax() throws Exception {
//create line item with correct shipping price
LineItem item = new LineItem();
item.setShippingPrice(new BigDecimal(99999999.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all shipping prices are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with shipping price above allowed max
item = new LineItem();
item.setShippingPrice(new BigDecimal(100000000.0));
items.add(item);
//verify result - should be false - second item has invalid shipping price
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
}

View File

@@ -0,0 +1,133 @@
package org.springframework.batch.sample.validation.valang.custom;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.easymock.MockControl;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.Function;
import junit.framework.TestCase;
public class ValidateTotalPricesFunctionTests extends TestCase {
private ValidateTotalPricesFunction function;
private MockControl argumentControl;
private Function argument;
public void setUp() {
argumentControl = MockControl.createControl(Function.class);
argument = (Function) argumentControl.getMock();
//create function
function = new ValidateTotalPricesFunction(new Function[] {argument}, 0, 0);
}
public void testTotalPriceMin() throws Exception {
//create line item with correct total price
LineItem item = new LineItem();
item.setDiscountAmount(new BigDecimal(0.0));
item.setDiscountPerc(new BigDecimal(0.0));
item.setHandlingPrice(new BigDecimal(0.0));
item.setShippingPrice(new BigDecimal(0.0));
item.setPrice(new BigDecimal(1.0));
item.setQuantity(1);
item.setTotalPrice(new BigDecimal(1.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all total prices are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with negative item price
item = new LineItem();
item.setTotalPrice(new BigDecimal(-1.0));
items.add(item);
//verify result - should be false - second item has invalid total price
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testTotalPriceMax() throws Exception {
//create line item with correct total price
LineItem item = new LineItem();
item.setDiscountAmount(new BigDecimal(0.0));
item.setDiscountPerc(new BigDecimal(0.0));
item.setHandlingPrice(new BigDecimal(0.0));
item.setShippingPrice(new BigDecimal(0.0));
item.setPrice(new BigDecimal(99999999.0));
item.setQuantity(1);
item.setTotalPrice(new BigDecimal(99999999.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all total prices are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with total price above allowed max
item = new LineItem();
item.setTotalPrice(new BigDecimal(100000000.0));
items.add(item);
//verify result - should be false - second item has invalid total price
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
public void testTotalPriceCalculation() throws Exception {
//create line item
LineItem item = new LineItem();
item.setDiscountAmount(new BigDecimal(5.0));
item.setDiscountPerc(new BigDecimal(0.0));
item.setHandlingPrice(new BigDecimal(1.0));
item.setShippingPrice(new BigDecimal(2.0));
item.setPrice(new BigDecimal(250.0));
item.setQuantity(1);
item.setTotalPrice(new BigDecimal(248.0));
//add it to line items list
List items = new ArrayList();
items.add(item);
//set return value for mock argument
argument.getResult(null);
argumentControl.setReturnValue(items,2);
argumentControl.replay();
//verify result - should be true - all total prices are correct
assertTrue(((Boolean)function.doGetResult(null)).booleanValue());
//now add line item with incorrect total price
item = new LineItem();
item.setDiscountAmount(new BigDecimal(5.0));
item.setDiscountPerc(new BigDecimal(0.0));
item.setHandlingPrice(new BigDecimal(1.0));
item.setShippingPrice(new BigDecimal(2.0));
item.setPrice(new BigDecimal(250.0));
item.setQuantity(1);
item.setTotalPrice(new BigDecimal(253.0));
items.add(item);
//verify result - should be false - second item has incorrect total price
assertFalse(((Boolean)function.doGetResult(null)).booleanValue());
}
}

View File

@@ -0,0 +1,156 @@
/*
* Copyright 2006-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 test.jdbc.datasource;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
public class InitializingDataSourceFactoryBean extends AbstractFactoryBean {
private Resource[] initScripts;
private Resource destroyScript;
DataSource dataSource;
private static boolean initialized = false;
/**
* @throws Throwable
* @see java.lang.Object#finalize()
*/
protected void finalize() throws Throwable {
super.finalize();
initialized = false;
logger.debug("finalize called");
}
protected void destroyInstance(Object instance) throws Exception {
try {
doExecuteScript(destroyScript);
}
catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.warn("Could not execute destroy script [" + destroyScript + "]", e);
}
else {
logger.warn("Could not execute destroy script [" + destroyScript + "]");
}
}
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(dataSource);
super.afterPropertiesSet();
}
protected Object createInstance() throws Exception {
Assert.notNull(dataSource);
if (!initialized) {
try {
doExecuteScript(destroyScript);
}
catch (Exception e) {
logger.debug("Could not execute destroy script [" + destroyScript + "]", e);
}
if (initScripts != null) {
for (int i = 0; i < initScripts.length; i++) {
Resource initScript = initScripts[i];
doExecuteScript(initScript);
}
}
initialized = true;
}
return dataSource;
}
private void doExecuteScript(final Resource scriptResource) {
if (scriptResource == null || !scriptResource.exists())
return;
TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String[] scripts;
try {
scripts = StringUtils.delimitedListToStringArray(stripComments(IOUtils.readLines(scriptResource
.getInputStream())), ";");
}
catch (IOException e) {
throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
}
for (int i = 0; i < scripts.length; i++) {
String script = scripts[i].trim();
if (StringUtils.hasText(script)) {
jdbcTemplate.execute(script);
}
}
return null;
}
});
}
private String stripComments(List list) {
StringBuffer buffer = new StringBuffer();
for (Iterator iter = list.iterator(); iter.hasNext();) {
String line = (String) iter.next();
if (!line.startsWith("//") && !line.startsWith("--")) {
buffer.append(line + "\n");
}
}
return buffer.toString();
}
public Class getObjectType() {
return DataSource.class;
}
public void setInitScript(Resource initScript) {
this.initScripts = new Resource[] { initScript };
}
public void setInitScripts(Resource[] initScripts) {
this.initScripts = initScripts;
}
public void setDestroyScript(Resource destroyScript) {
this.destroyScript = destroyScript;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}