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,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.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.io.file.FieldSet;
/**
* ResultSetExtractor implementation that returns list of FieldSets
* for given ResultSet.
*
* @author peter.zozom
*
*/
public final class FieldSetResultSetExtractor {
// utility class not meant for instantiation
private FieldSetResultSetExtractor(){}
/**
* Processes single row in ResultSet and returns its FieldSet representation.
* @param rs ResultSet ResultSet to extract data from.
* @return FieldSet representation of current row in ResultSet
* @throws SQLException
*/
public static FieldSet getFieldSet(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
FieldSet fs = null;
List tokens = new ArrayList();
List names = new ArrayList();
for (int i = 1; i <= columnCount; i++) {
tokens.add(rs.getString(i));
names.add(metaData.getColumnName(i));
}
fs = new FieldSet((String[])tokens.toArray(new String[0]), (String[])names.toArray(new String[0]));
return fs;
}
}

View File

@@ -0,0 +1,42 @@
/*
* 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.advice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
/**
* Wraps calls for 'Processing' methods which output a single Object to write
* the string representation of the object to the log.
*
* @author Lucas Ward
*/
public class MethodExecutionLogAdvice {
private static Log log = LogFactory.getLog(MethodExecutionLogAdvice.class);
/**
* Wraps original method and adds logging both before and after method
*/
public void doBasicLogging(JoinPoint jp) throws Throwable {
log.info("Processed method "+jp);
}
}

View File

@@ -0,0 +1,52 @@
/*
* 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.advice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
/**
* Wraps calls for 'Processing' methods which output a single Object to write
* the string representation of the object to the log.
*
* @author Lucas Ward
*/
public class ProcessorLogAdvice {
private static Log log = LogFactory.getLog(ProcessorLogAdvice.class);
/**
* Wraps original method and adds logging both before and after method
*/
public void doBasicLogging(JoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
StringBuffer output = new StringBuffer();
for(int i = 0; i < args.length; i++){
output.append(args[i] + " ");
}
log.info("Processed: " + output.toString());
}
public void doStronglyTypedLogging(Object item){
log.info("Processed: " + item);
}
}

View File

@@ -0,0 +1,43 @@
/*
* 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.advice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.springframework.batch.sample.domain.Trade;
/**
* Wraps calls for 'Processing' methods which output a single Object to write
* the string representation of the object to the log.
*
* @author Lucas Ward
*/
public class TradeWriterLogAdvice {
private static Log log = LogFactory.getLog(TradeWriterLogAdvice.class);
/**
* Wraps original method and adds logging both before and after method
*/
public void doBasicLogging(JoinPoint pjp, Trade trade) throws Throwable {
log.info("Processed: " + trade.toString());
}
}

View File

@@ -0,0 +1,31 @@
/*
* 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.io.ItemWriter;
import org.springframework.batch.sample.domain.CustomerCredit;
/**
* Interface for writing customer's credit information to output.
*
* @author Robert Kasanicky
*/
public interface CustomerCreditWriter extends ItemWriter {
void writeCredit(CustomerCredit customerCredit);
}

View File

@@ -0,0 +1,24 @@
/*
* 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.CustomerDebit;
public interface CustomerDebitWriter {
void write(CustomerDebit customerDebit);
}

View File

@@ -0,0 +1,84 @@
/*
* 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.io.ItemWriter;
import org.springframework.batch.item.ResourceLifecycle;
import org.springframework.batch.sample.domain.CustomerCredit;
import org.springframework.beans.factory.DisposableBean;
/**
* Writes customer's credit information in a file.
*
* @see CustomerCreditWriter
* @author Robert Kasanicky
*/
public class FlatFileCustomerCreditWriter implements CustomerCreditWriter,
DisposableBean {
private ItemWriter outputSource;
private String separator = "\t";
private volatile boolean opened = false;
public void writeCredit(CustomerCredit customerCredit) {
if (!opened) {
open();
}
String line = "" + customerCredit.getName() + separator
+ customerCredit.getCredit();
outputSource.write(line);
}
public void setSeparator(String separator) {
this.separator = separator;
}
public void setOutputSource(ItemWriter outputSource) {
this.outputSource = outputSource;
}
public void open() {
if (outputSource instanceof ResourceLifecycle) {
((ResourceLifecycle) outputSource).open();
}
opened = true;
}
public void close() {
if (outputSource instanceof ResourceLifecycle) {
((ResourceLifecycle) outputSource).close();
}
}
/*
* (non-Javadoc)
*
* @see org.springframework.beans.factory.DisposableBean#destroy()
*/
public void destroy() throws Exception {
close();
}
public void write(Object output) {
writeCredit((CustomerCredit)output);
}
}

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 org.springframework.batch.io.ItemWriter;
import org.springframework.batch.io.file.support.transform.Converter;
import org.springframework.batch.sample.domain.Order;
/**
* Writes <code>Order</code> objects to a file.
*
* @see OrderWriter
*
* @author Dave Syer
*/
public class FlatFileOrderWriter implements OrderWriter {
/**
* Takes care of writing to a file
*/
private ItemWriter outputSource;
/**
* Converter for order
*/
private Converter converter = new OrderConverter();
/**
* Public setter for the converter.
*
* @param converter the converter to set
*/
public void setConverter(Converter converter) {
this.converter = converter;
}
/**
* Writes information from an Order object to a file
*/
public void write(Order data) {
outputSource.write(converter.convert(data));
}
public void setOutputSource(ItemWriter outputSource) {
this.outputSource = outputSource;
}
}

View File

@@ -0,0 +1,112 @@
/*
* 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.util.ArrayList;
import java.util.List;
import org.springframework.batch.repeat.ExitStatus;
import org.springframework.batch.repeat.RepeatContext;
import org.springframework.batch.repeat.RepeatInterceptor;
import org.springframework.batch.sample.domain.CustomerCredit;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/**
* @author Lucas Ward
* @author Dave Syer
*
*/
public class HibernateCreditWriter extends HibernateDaoSupport implements
CustomerCreditWriter, RepeatInterceptor {
private int failOnFlush = -1;
private List errors = new ArrayList();
/**
* Public accessor for the errors property.
*
* @return the errors - a list of Throwable instances
*/
public List getErrors() {
return errors;
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.sample.dao.CustomerCreditWriter#write(org.springframework.batch.sample.domain.CustomerCredit)
*/
public void writeCredit(CustomerCredit customerCredit) {
if (customerCredit.getId() == failOnFlush) {
// try to insert one with a duplicate ID
CustomerCredit newCredit = new CustomerCredit();
newCredit.setId(customerCredit.getId());
newCredit.setName(customerCredit.getName());
newCredit.setCredit(customerCredit.getCredit());
getHibernateTemplate().save(newCredit);
} else {
getHibernateTemplate().update(customerCredit);
}
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.io.OutputSource#write(java.lang.Object)
*/
public void write(Object output) {
writeCredit((CustomerCredit) output);
}
/**
* Public setter for the failOnFlush property.
*
* @param failOnFlush
* the ID of the record you want to fail on flush (for testing)
*/
public void setFailOnFlush(int failOnFlush) {
this.failOnFlush = failOnFlush;
}
public void onError(RepeatContext context, Throwable e) {
errors.add(e);
}
/* (non-Javadoc)
* @see org.springframework.batch.repeat.RepeatInterceptor#after(org.springframework.batch.repeat.RepeatContext, org.springframework.batch.repeat.ExitStatus)
*/
public void after(RepeatContext context, ExitStatus result) {
}
/* (non-Javadoc)
* @see org.springframework.batch.repeat.RepeatInterceptor#before(org.springframework.batch.repeat.RepeatContext)
*/
public void before(RepeatContext context) {
}
/* (non-Javadoc)
* @see org.springframework.batch.repeat.RepeatInterceptor#close(org.springframework.batch.repeat.RepeatContext)
*/
public void close(RepeatContext context) {
}
/* (non-Javadoc)
* @see org.springframework.batch.repeat.RepeatInterceptor#open(org.springframework.batch.repeat.RepeatContext)
*/
public void open(RepeatContext context) {
}
}

View File

@@ -0,0 +1,63 @@
/*
* 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.io.ItemWriter;
import org.springframework.batch.sample.domain.CustomerCredit;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
/**
* @author Lucas Ward
*
*/
public class IbatisCustomerCreditWriter extends SqlMapClientDaoSupport
implements CustomerCreditWriter, ItemWriter {
String statementId;
/* (non-Javadoc)
* @see org.springframework.batch.sample.dao.CustomerCreditWriter#write(org.springframework.batch.sample.domain.CustomerCredit)
*/
public void writeCredit(CustomerCredit customerCredit) {
getSqlMapClientTemplate().update(statementId, customerCredit);
}
/* (non-Javadoc)
* @see org.springframework.batch.item.ResourceLifecycle#close()
*/
public void close() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.springframework.batch.item.ResourceLifecycle#open()
*/
public void open() {
// TODO Auto-generated method stub
}
public void setStatementId(String statementId) {
this.statementId = statementId;
}
public void write(Object output) {
writeCredit((CustomerCredit)output);
}
}

View File

@@ -0,0 +1,43 @@
/*
* 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.CustomerDebit;
import org.springframework.jdbc.core.JdbcOperations;
/**
* Reduces customer's credit by the provided amount.
*
* @author Robert Kasanicky
*/
public class JdbcCustomerDebitWriter implements CustomerDebitWriter {
private static final String UPDATE_CREDIT = "UPDATE customer SET credit= credit-? WHERE name=?";
private JdbcOperations jdbcTemplate;
public void write(CustomerDebit customerDebit) {
jdbcTemplate.update(UPDATE_CREDIT,
new Object[] { customerDebit.getDebit(), customerDebit.getName() });
}
public void setJdbcTemplate(JdbcOperations jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}

View File

@@ -0,0 +1,73 @@
/*
* 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.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
/**
* Writes a Trade object to a database
*
* @author Robert Kasanicky
*/
public class JdbcTradeWriter implements TradeWriter {
private Log log = LogFactory.getLog(JdbcTradeWriter.class);
/**
* template for inserting a row
*/
private static final String INSERT_TRADE_RECORD = "INSERT INTO trade (id, isin, quantity, price, customer) VALUES (?, ?, ? ,?, ?)";
/**
* handles the processing of sql query
*/
private JdbcOperations jdbcTemplate;
/**
* database is not expected to be setup for autoincrementation
*/
private DataFieldMaxValueIncrementer incrementer;
/**
* @see TradeWriter
*/
public void writeTrade(Trade trade) {
Long id = new Long(incrementer.nextLongValue());
log.debug("Processing: " + trade);
jdbcTemplate.update(INSERT_TRADE_RECORD,
new Object[] {
id, trade.getIsin(), new Long(trade.getQuantity()), trade.getPrice(),
trade.getCustomer()
});
}
public void setJdbcTemplate(JdbcOperations jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void setIncrementer(DataFieldMaxValueIncrementer incrementer) {
this.incrementer = incrementer;
}
public void write(Object output) {
this.writeTrade((Trade)output);
}
}

View File

@@ -0,0 +1,117 @@
/*
* 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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.batch.io.file.support.transform.Converter;
import org.springframework.batch.io.file.support.transform.LineAggregator;
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;
/**
* Converts <code>Order</code> object to a String.
* @author Dave Syer
*/
public class OrderConverter implements Converter {
/**
* Aggregators for all types of lines in the output file
*/
private Map aggregators;
/**
* Converts information from an Order object to a collection of Strings for output.
*/
public Object convert(Object data) {
Order order = (Order) data;
List result = new ArrayList();
result.add(getAggregator("header").aggregate(OrderFormatterUtils.headerArgs(order)));
result.add(getAggregator("customer").aggregate(OrderFormatterUtils.customerArgs(order)));
result.add(getAggregator("address").aggregate(OrderFormatterUtils.billingAddressArgs(order)));
result.add(getAggregator("billing").aggregate(OrderFormatterUtils.billingInfoArgs(order)));
List items = order.getLineItems();
LineItem item;
for (int i = 0; i < items.size(); i++) {
item = (LineItem) items.get(i);
result.add(getAggregator("item").aggregate(OrderFormatterUtils.lineItemArgs(item)));
}
result.add(getAggregator("footer").aggregate(OrderFormatterUtils.footerArgs(order)));
return result;
}
public void setAggregators(Map aggregators) {
this.aggregators = aggregators;
}
private LineAggregator getAggregator(String name) {
return (LineAggregator) aggregators.get(name);
}
/**
* Utility class encapsulating formatting of <code>Order</code> and its nested objects.
*/
private static class OrderFormatterUtils {
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
static String[] headerArgs(Order order) {
return new String[] { "BEGIN_ORDER:", String.valueOf(order.getOrderId()), dateFormat.format(order.getOrderDate()) };
}
static String[] footerArgs(Order order) {
return new String[] { "END_ORDER:", order.getTotalPrice().toString() };
}
static String[] customerArgs(Order order) {
Customer customer = order.getCustomer();
return new String[] { "CUSTOMER:", String.valueOf(customer.getRegistrationId()), customer.getFirstName(),
customer.getMiddleName(), customer.getLastName() };
}
static String[] lineItemArgs(LineItem item) {
return new String[] { "ITEM:", String.valueOf(item.getItemId()), item.getPrice().toString() };
}
static String[] billingAddressArgs(Order order) {
Address address = order.getBillingAddress();
return new String[] { "ADDRESS:", address.getAddrLine1(), address.getCity(), address.getZipCode() };
}
static String[] billingInfoArgs(Order order) {
BillingInfo billingInfo = order.getBilling();
return new String[] { "BILLING:", billingInfo.getPaymentId(), billingInfo.getPaymentDesc() };
}
}
}

View File

@@ -0,0 +1,28 @@
/*
* 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.Order;
/**
* Interface for writing <code>Order</code> objects.
*/
public interface OrderWriter {
public void write(Order order);
}

View File

@@ -0,0 +1,8 @@
package org.springframework.batch.sample.dao;
import org.springframework.batch.sample.domain.Player;
public interface PlayerDao {
void savePlayer(Player player);
}

View File

@@ -0,0 +1,37 @@
package org.springframework.batch.sample.dao;
import org.springframework.batch.io.ItemWriter;
import org.springframework.batch.sample.domain.Game;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.util.Assert;
public class SqlGameDao extends JdbcDaoSupport implements ItemWriter {
private static final String INSERT_GAME = "INSERT into GAMES(player_id,year,team,week,opponent,"
+ "completes,attempts,passing_yards,passing_td,interceptions,rushes,rush_yards,"
+ "receptions,receptions_yards,total_td) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
public void write(Object output) {
Assert.isTrue(output instanceof Game,
"Only Game objects can be written out" + "using this Dao");
Game game = (Game) output;
Object[] args = new Object[] { game.getId(),
new Integer(game.getYear()), game.getTeam(),
new Integer(game.getWeek()), game.getOpponent(),
new Integer(game.getCompletes()),
new Integer(game.getAttempts()),
new Integer(game.getPassingYards()),
new Integer(game.getPassingTd()),
new Integer(game.getInterceptions()),
new Integer(game.getRushes()),
new Integer(game.getRushYards()),
new Integer(game.getReceptions()),
new Integer(game.getReceptionYards()),
new Integer(game.getTotalTd()) };
this.getJdbcTemplate().update(INSERT_GAME, args);
}
}

View File

@@ -0,0 +1,27 @@
/**
*
*/
package org.springframework.batch.sample.dao;
import org.springframework.batch.sample.domain.Player;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
* @author Lucas Ward
*
*/
public class SqlPlayerDao extends JdbcDaoSupport implements PlayerDao {
public static final String INSERT_PLAYER = "INSERT into players(player_id, " +
"last_name, first_name, pos, year_of_birth, year_drafted)" +
" values (?,?,?,?,?,?)";
public void savePlayer(Player player) {
getJdbcTemplate().update(INSERT_PLAYER,
new Object[]{player.getID(),player.getLastName(),
player.getFirstName(), player.getPosition(),
new Integer(player.getBirthYear()),
new Integer(player.getDebutYear())});
}
}

View File

@@ -0,0 +1,31 @@
package org.springframework.batch.sample.dao;
import org.springframework.batch.io.ItemWriter;
import org.springframework.batch.sample.domain.PlayerSummary;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.util.Assert;
public class SqlPlayerSummaryDao extends JdbcDaoSupport implements ItemWriter {
private static final String INSERT_SUMMARY = "INSERT into PLAYER_SUMMARY(ID,YEAR,COMPLETES,ATTEMPTS," +
"PASSING_YARDS,PASSING_TD,INTERCEPTIONS,RUSHES,RUSH_YARDS,RECEPTIONS,RECEPTIONS_YARDS," +
"TOTAL_TD) values(?,?,?,?,?,?,?,?,?,?,?,?)";
public void write(Object output) {
Assert.isInstanceOf(PlayerSummary.class, output, SqlPlayerSummaryDao.class.getName() + " only " +
"supports outputing " + PlayerSummary.class.getName() + " instances.");
PlayerSummary summary = (PlayerSummary)output;
Object[] args = new Object[]{summary.getId(), Integer.valueOf(summary.getYear()),
Integer.valueOf(summary.getCompletes()), Integer.valueOf(summary.getAttempts()),
Integer.valueOf(summary.getPassingYards()), Integer.valueOf(summary.getPassingTd()),
Integer.valueOf(summary.getInterceptions()), Integer.valueOf(summary.getRushes()),
Integer.valueOf(summary.getRushYards()), Integer.valueOf(summary.getReceptions()),
Integer.valueOf(summary.getReceptionYards()), Integer.valueOf(summary.getTotalTd()) };
getJdbcTemplate().update(INSERT_SUMMARY, args);
}
}

View File

@@ -0,0 +1,36 @@
/*
* 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.io.ItemWriter;
import org.springframework.batch.sample.domain.Trade;
/**
* Simple interface for writing a Trade object
* to an arbitraty output
*
* @author Robert Kasanicky
*/
public interface TradeWriter extends ItemWriter{
/**
* Write a trade object to some kind of output,
* different implementations can write to file, database etc.
*/
void writeTrade(Trade trade);
}

View File

@@ -0,0 +1,103 @@
/*
* 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.domain;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
public class Address {
public static final String LINE_ID_BILLING_ADDR = "BAD";
public static final String LINE_ID_SHIPPING_ADDR = "SAD";
private String addressee;
private String addrLine1;
private String addrLine2;
private String city;
private String zipCode;
private String state;
private String country;
public String getAddrLine1() {
return addrLine1;
}
public void setAddrLine1(String addrLine1) {
this.addrLine1 = addrLine1;
}
public String getAddrLine2() {
return addrLine2;
}
public void setAddrLine2(String addrLine2) {
this.addrLine2 = addrLine2;
}
public String getAddressee() {
return addressee;
}
public void setAddressee(String addressee) {
this.addressee = addressee;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

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.domain;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
public class BillingInfo {
public static final String LINE_ID_BILLING_INFO = "BIN";
private String paymentId;
private String paymentDesc;
public String getPaymentDesc() {
return paymentDesc;
}
public void setPaymentDesc(String paymentDesc) {
this.paymentDesc = paymentDesc;
}
public String getPaymentId() {
return paymentId;
}
public void setPaymentId(String paymentId) {
this.paymentId = paymentId;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

View File

@@ -0,0 +1,47 @@
/*
* 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.domain;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
public class Child {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

View File

@@ -0,0 +1,115 @@
/*
* 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.domain;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
public class Customer {
public static final String LINE_ID_BUSINESS_CUST = "BCU";
public static final String LINE_ID_NON_BUSINESS_CUST = "NCU";
private boolean businessCustomer;
private boolean registered;
private long registrationId;
//non-business customer
private String firstName;
private String lastName;
private String middleName;
private boolean vip;
//business customer
private String companyName;
public boolean isBusinessCustomer() {
return businessCustomer;
}
public void setBusinessCustomer(boolean bussinessCustomer) {
this.businessCustomer = bussinessCustomer;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public boolean isRegistered() {
return registered;
}
public void setRegistered(boolean registered) {
this.registered = registered;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public long getRegistrationId() {
return registrationId;
}
public void setRegistrationId(long registrationId) {
this.registrationId = registrationId;
}
public boolean isVip() {
return vip;
}
public void setVip(boolean vip) {
this.vip = vip;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

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.domain;
import java.math.BigDecimal;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class CustomerCredit {
private int id;
private String name;
private BigDecimal credit;
public String toString() {
return "CustomerCredit [id=" + id +",name=" + name + ", credit=" + credit + "]";
}
public BigDecimal getCredit() {
return credit;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setCredit(BigDecimal credit) {
this.credit = credit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void increaseCreditBy(BigDecimal sum) {
this.credit = this.credit.add(sum);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

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.domain;
import java.math.BigDecimal;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class CustomerDebit {
private String name;
private BigDecimal debit;
public CustomerDebit() {
}
CustomerDebit(String name, BigDecimal debit) {
this.name = name;
this.debit = debit;
}
public BigDecimal getDebit() {
return debit;
}
public void setDebit(BigDecimal debit) {
this.debit = debit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "CustomerDebit [name=" + name + ", debit=" + debit + "]";
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

View File

@@ -0,0 +1,213 @@
package org.springframework.batch.sample.domain;
import org.apache.commons.lang.builder.EqualsBuilder;
public class Game {
private String id;
private int year;
private String team;
private int week;
private String opponent;
private int completes;
private int attempts;
private int passingYards;
private int passingTd;
private int interceptions;
private int rushes;
private int rushYards;
private int receptions;
private int receptionYards;
private int totalTd;
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @return the year
*/
public int getYear() {
return year;
}
/**
* @return the team
*/
public String getTeam() {
return team;
}
/**
* @return the week
*/
public int getWeek() {
return week;
}
/**
* @return the opponent
*/
public String getOpponent() {
return opponent;
}
/**
* @return the completes
*/
public int getCompletes() {
return completes;
}
/**
* @return the attempts
*/
public int getAttempts() {
return attempts;
}
/**
* @return the passingYards
*/
public int getPassingYards() {
return passingYards;
}
/**
* @return the passingTd
*/
public int getPassingTd() {
return passingTd;
}
/**
* @return the interceptions
*/
public int getInterceptions() {
return interceptions;
}
/**
* @return the rushes
*/
public int getRushes() {
return rushes;
}
/**
* @return the rushYards
*/
public int getRushYards() {
return rushYards;
}
/**
* @return the receptions
*/
public int getReceptions() {
return receptions;
}
/**
* @return the receptionYards
*/
public int getReceptionYards() {
return receptionYards;
}
/**
* @return the totalTd
*/
public int getTotalTd() {
return totalTd;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @param year the year to set
*/
public void setYear(int year) {
this.year = year;
}
/**
* @param team the team to set
*/
public void setTeam(String team) {
this.team = team;
}
/**
* @param week the week to set
*/
public void setWeek(int week) {
this.week = week;
}
/**
* @param opponent the opponent to set
*/
public void setOpponent(String opponent) {
this.opponent = opponent;
}
/**
* @param completes the completes to set
*/
public void setCompletes(int completes) {
this.completes = completes;
}
/**
* @param attempts the attempts to set
*/
public void setAttempts(int attempts) {
this.attempts = attempts;
}
/**
* @param passingYards the passingYards to set
*/
public void setPassingYards(int passingYards) {
this.passingYards = passingYards;
}
/**
* @param passingTd the passingTd to set
*/
public void setPassingTd(int passingTd) {
this.passingTd = passingTd;
}
/**
* @param interceptions the interceptions to set
*/
public void setInterceptions(int interceptions) {
this.interceptions = interceptions;
}
/**
* @param rushes the rushes to set
*/
public void setRushes(int rushes) {
this.rushes = rushes;
}
/**
* @param rushYards the rushYards to set
*/
public void setRushYards(int rushYards) {
this.rushYards = rushYards;
}
/**
* @param receptions the receptions to set
*/
public void setReceptions(int receptions) {
this.receptions = receptions;
}
/**
* @param receptionYards the receptionYards to set
*/
public void setReceptionYards(int receptionYards) {
this.receptionYards = receptionYards;
}
/**
* @param totalTd the totalTd to set
*/
public void setTotalTd(int totalTd) {
this.totalTd = totalTd;
}
public String toString() {
return "Game: ID=" + id + " " + team + " vs. " + opponent +
" - " + year;
}
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
}

View File

@@ -0,0 +1,113 @@
/*
* 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.domain;
import java.math.BigDecimal;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
public class LineItem {
public static final String LINE_ID_ITEM = "LIT";
private long itemId;
private BigDecimal price;
private BigDecimal discountPerc;
private BigDecimal discountAmount;
private BigDecimal shippingPrice;
private BigDecimal handlingPrice;
private int quantity;
private BigDecimal totalPrice;
public BigDecimal getDiscountAmount() {
return discountAmount;
}
public void setDiscountAmount(BigDecimal discountAmount) {
this.discountAmount = discountAmount;
}
public BigDecimal getDiscountPerc() {
return discountPerc;
}
public void setDiscountPerc(BigDecimal discountPerc) {
this.discountPerc = discountPerc;
}
public BigDecimal getHandlingPrice() {
return handlingPrice;
}
public void setHandlingPrice(BigDecimal handlingPrice) {
this.handlingPrice = handlingPrice;
}
public long getItemId() {
return itemId;
}
public void setItemId(long itemId) {
this.itemId = itemId;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public BigDecimal getShippingPrice() {
return shippingPrice;
}
public void setShippingPrice(BigDecimal shippingPrice) {
this.shippingPrice = shippingPrice;
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

View File

@@ -0,0 +1,148 @@
/*
* 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.domain;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
public class Order {
public static final String LINE_ID_HEADER = "HEA";
public static final String LINE_ID_FOOTER = "FOT";
//header
private long orderId;
private Date orderDate;
//footer
private int totalLines;
private int totalItems;
private BigDecimal totalPrice;
private Customer customer;
private Address billingAddress;
private Address shippingAddress;
private BillingInfo billing;
private ShippingInfo shipping;
//order items
private List lineItems;
public BillingInfo getBilling() {
return billing;
}
public void setBilling(BillingInfo billing) {
this.billing = billing;
}
public Address getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(Address billingAddress) {
this.billingAddress = billingAddress;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List getLineItems() {
return lineItems;
}
public void setLineItems(List lineItems) {
this.lineItems = lineItems;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public ShippingInfo getShipping() {
return shipping;
}
public void setShipping(ShippingInfo shipping) {
this.shipping = shipping;
}
public Address getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(Address shippingAddress) {
this.shippingAddress = shippingAddress;
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
public int getTotalItems() {
return totalItems;
}
public void setTotalItems(int totalItems) {
this.totalItems = totalItems;
}
public int getTotalLines() {
return totalLines;
}
public void setTotalLines(int totalLines) {
this.totalLines = totalLines;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

View File

@@ -0,0 +1,126 @@
/*
* 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.domain;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
public class Person {
private String title = "";
private String firstName = "";
private String last_name = "";
private int age = 0;
private Address address = new Address();
private List children = new ArrayList();
public Person(){
children.add(new Child());
children.add(new Child());
}
/**
* @return the address
*/
public Address getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(Address address) {
this.address = address;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the children
*/
public List getChildren() {
return children;
}
/**
* @param children the children to set
*/
public void setChildren(List children) {
this.children = children;
}
/**
* Intentionally non-standard method name for testing purposes
* @return the last_name
*/
public String getLast_name() {
return last_name;
}
/**
* Intentionally non-standard method name for testing purposes
* @param last_name the last_name to set
*/
public void setLast_name(String last_name) {
this.last_name = last_name;
}
/**
* @return the person_title
*/
public String getTitle() {
return title;
}
/**
* @param person_title the person_title to set
*/
public void setTitle(String title) {
this.title = title;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

View File

@@ -0,0 +1,79 @@
/*
* 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.domain;
import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemProvider;
/**
* Custom class that contains logic that would normally be
* be contained in {@link ItemProvider} (<code>getData()</code>) and
* {@link ItemProcessor} (<code>processData(..)</code>).
*
* @author tomas.slanina
* @author Robert Kasanicky
*/
public class PersonService {
private static final int GENERATION_LIMIT = 10;
private int generatedCounter = 0;
private int processedCounter = 0;
public Person getData() {
if (generatedCounter >= GENERATION_LIMIT) return null;
Person person = new Person();
Address address = new Address();
Child child = new Child();
List children = new ArrayList(1);
children.add(child);
person.setFirstName("John" + generatedCounter);
person.setAge(20 + generatedCounter);
address.setCity("Johnsville" + generatedCounter);
child.setName("Little Johny" + generatedCounter);
person.setAddress(address);
person.setChildren(children);
generatedCounter++;
return person;
}
/**
* Badly designed method signature which accepts multiple implicitly related
* arguments instead of a single Person argument.
*/
public void processPerson(String name, String city) {
processedCounter++;
}
public int getReturnedCount() {
return generatedCounter;
}
public int getReceivedCount() {
return processedCounter;
}
}

View File

@@ -0,0 +1,62 @@
package org.springframework.batch.sample.domain;
public class Player {
private String ID;
private String lastName;
private String firstName;
private String position;
private int birthYear;
private int debutYear;
public String toString() {
return "PLAYER:ID=" + ID + ",Last Name=" + lastName +
",First Name=" + firstName + ",Position=" + position +
",Birth Year=" + birthYear + ",DebutYear=" +
debutYear;
}
public String getID() {
return ID;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public String getPosition() {
return position;
}
public int getBirthYear() {
return birthYear;
}
public int getDebutYear() {
return debutYear;
}
public void setID(String id) {
ID = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setPosition(String position) {
this.position = position;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
public void setDebutYear(int debutYear) {
this.debutYear = debutYear;
}
}

View File

@@ -0,0 +1,108 @@
package org.springframework.batch.sample.domain;
import org.apache.commons.lang.builder.EqualsBuilder;
/**
* Domain object representing the summary of a given Player's
* year.
*
* @author Lucas Ward
*
*/
public class PlayerSummary {
private String id;
private int year;
private int completes;
private int attempts;
private int passingYards;
private int passingTd;
private int interceptions;
private int rushes;
private int rushYards;
private int receptions;
private int receptionYards;
private int totalTd;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getCompletes() {
return completes;
}
public void setCompletes(int completes) {
this.completes = completes;
}
public int getAttempts() {
return attempts;
}
public void setAttempts(int attempts) {
this.attempts = attempts;
}
public int getPassingYards() {
return passingYards;
}
public void setPassingYards(int passingYards) {
this.passingYards = passingYards;
}
public int getPassingTd() {
return passingTd;
}
public void setPassingTd(int passingTd) {
this.passingTd = passingTd;
}
public int getInterceptions() {
return interceptions;
}
public void setInterceptions(int interceptions) {
this.interceptions = interceptions;
}
public int getRushes() {
return rushes;
}
public void setRushes(int rushes) {
this.rushes = rushes;
}
public int getRushYards() {
return rushYards;
}
public void setRushYards(int rushYards) {
this.rushYards = rushYards;
}
public int getReceptions() {
return receptions;
}
public void setReceptions(int receptions) {
this.receptions = receptions;
}
public int getReceptionYards() {
return receptionYards;
}
public void setReceptionYards(int receptionYards) {
this.receptionYards = receptionYards;
}
public int getTotalTd() {
return totalTd;
}
public void setTotalTd(int totalTd) {
this.totalTd = totalTd;
}
public String toString() {
return "Player Summary: ID=" + id + " Year=" + year;
}
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
}

View File

@@ -0,0 +1,59 @@
/*
* 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.domain;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class ShippingInfo {
public static final String LINE_ID_SHIPPING_INFO = "SIN";
private String shipperId;
private String shippingTypeId;
private String shippingInfo;
public String getShipperId() {
return shipperId;
}
public void setShipperId(String shipperId) {
this.shipperId = shipperId;
}
public String getShippingInfo() {
return shippingInfo;
}
public void setShippingInfo(String shippingInfo) {
this.shippingInfo = shippingInfo;
}
public String getShippingTypeId() {
return shippingTypeId;
}
public void setShippingTypeId(String shippingTypeId) {
this.shippingTypeId = shippingTypeId;
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

View File

@@ -0,0 +1,90 @@
/*
* 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.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* @author Rob Harrop
* @author Dave Syer
*/
public class Trade implements Serializable {
private String isin = "";
private long quantity = 0;
private BigDecimal price = new BigDecimal(0);
private String customer = "";
public Trade() {
}
public Trade(String isin, long quantity, BigDecimal price, String customer){
this.isin = isin;
this.quantity = quantity;
this.price = price;
this.customer = customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public void setIsin(String isin) {
this.isin = isin;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setQuantity(long quantity) {
this.quantity = quantity;
}
public String getIsin() {
return isin;
}
public BigDecimal getPrice() {
return price;
}
public long getQuantity() {
return quantity;
}
public String getCustomer() {
return customer;
}
public String toString() {
return "Trade: [isin=" + this.isin + ",quantity=" + this.quantity + ",price="
+ this.price + ",customer=" + this.customer + "]";
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

View File

@@ -0,0 +1,77 @@
/*
* 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.domain.xml;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* An XML customer.
*
* This is a complex type.
*/
public class Customer {
private String name;
private String address;
private int age;
private int moo;
private int poo;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMoo() {
return moo;
}
public void setMoo(int moo) {
this.moo = moo;
}
public int getPoo() {
return poo;
}
public void setPoo(int poo) {
this.poo = poo;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}

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.domain.xml;
/**
* An XML line-item.
*
* This is a complex type.
*/
public class LineItem {
private String description;
private double perUnitOunces;
private double price;
private int quantity;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPerUnitOunces() {
return perUnitOunces;
}
public void setPerUnitOunces(double perUnitOunces) {
this.perUnitOunces = perUnitOunces;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}

View File

@@ -0,0 +1,71 @@
/*
* 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.domain.xml;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* An XML order.
*
* This is a complex type.
*/
public class Order {
private Customer customer;
private Date date;
private List lineItems;
private Shipper shipper;
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List getLineItems() {
return lineItems;
}
public void setLineItems(List lineItems) {
this.lineItems = lineItems;
}
public Shipper getShipper() {
return shipper;
}
public void setShipper(Shipper shipper) {
this.shipper = shipper;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}

View File

@@ -0,0 +1,44 @@
/*
* 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.domain.xml;
/**
* An XML shipper.
*
* This is a complex type.
*/
public class Shipper {
private String name;
private double perOunceRate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPerOunceRate() {
return perOunceRate;
}
public void setPerOunceRate(double perOunceRate) {
this.perOunceRate = perOunceRate;
}
}

View File

@@ -0,0 +1,24 @@
package org.springframework.batch.sample.exception.handler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.repeat.RepeatContext;
import org.springframework.batch.repeat.exception.handler.ExceptionHandler;
public class FootballExceptionHandler implements ExceptionHandler {
private static final Log logger = LogFactory
.getLog(FootballExceptionHandler.class);
public void handleException(RepeatContext context, Throwable throwable)
throws RuntimeException {
if (!(throwable instanceof NumberFormatException)) {
throw new RuntimeException(throwable);
} else {
logger.error("Number Format Exception!", throwable);
}
}
}

View File

@@ -0,0 +1,30 @@
package org.springframework.batch.sample.item.processor;
import java.math.BigDecimal;
import org.springframework.batch.io.ItemWriter;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.sample.domain.CustomerCredit;
/**
* Increases customer's credit by fixed amount.
*
* @author Robert Kasanicky
*/
public class CustomerCreditIncreaseProcessor implements ItemProcessor{
public static final BigDecimal FIXED_AMOUNT = new BigDecimal(1000);
private ItemWriter outputSource;
public void process(Object data) throws Exception {
CustomerCredit customerCredit = (CustomerCredit) data;
customerCredit.increaseCreditBy(FIXED_AMOUNT);
outputSource.write(customerCredit);
}
public void setOutputSource(ItemWriter outputSource) {
this.outputSource = outputSource;
}
}

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.item.processor;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.sample.dao.CustomerCreditWriter;
import org.springframework.batch.sample.domain.CustomerCredit;
public class CustomerCreditUpdateProcessor implements ItemProcessor {
private double creditFilter = 800;
private CustomerCreditWriter writer;
public void process(Object data) {
CustomerCredit customerCredit = (CustomerCredit) data;
if (customerCredit.getCredit().doubleValue() > creditFilter) {
writer.writeCredit(customerCredit);
}
}
public void setCreditFilter(double creditFilter) {
this.creditFilter = creditFilter;
}
public void setWriter(CustomerCreditWriter writer) {
this.writer = writer;
}
}

View File

@@ -0,0 +1,50 @@
/*
* 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.item.processor;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.sample.dao.JdbcCustomerDebitWriter;
import org.springframework.batch.sample.domain.CustomerDebit;
import org.springframework.batch.sample.domain.Trade;
/**
* Transforms Trade to a CustomerDebit and asks dao object to write the result.
*
* @author Robert Kasanicky
*/
public class CustomerUpdateProcessor implements ItemProcessor {
private JdbcCustomerDebitWriter dao;
public void process(Object data) {
Trade trade = (Trade) data;
CustomerDebit customerDebit = new CustomerDebit();
customerDebit.setName(trade.getCustomer());
customerDebit.setDebit(trade.getPrice());
dao.write(customerDebit);
}
public void setDao(JdbcCustomerDebitWriter outputSource) {
this.dao = outputSource;
}
public void close() {
}
public void init() {
}
}

View File

@@ -0,0 +1,18 @@
package org.springframework.batch.sample.item.processor;
import org.springframework.batch.io.file.support.FlatFileItemWriter;
import org.springframework.batch.item.ItemProcessor;
public class DefaultFlatFileProcessor implements ItemProcessor{
private FlatFileItemWriter flatFileItemWriter;
public void process(Object data) throws Exception {
flatFileItemWriter.write(""+data);
}
public void setFlatFileOutputSource(FlatFileItemWriter flatFileItemWriter) {
this.flatFileItemWriter = flatFileItemWriter;
}
}

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.item.processor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.item.ItemProcessor;
/**
* Dummy processor useful for development and testing.
*
* @author Robert Kasanicky
*/
public class DummyProcessor implements ItemProcessor {
private static final Log log = LogFactory.getLog(DummyProcessor.class);
public void process(Object object) {
log.debug("PROCESSING: " + object);
}
public void close() {
}
public void init() {
}
}

View File

@@ -0,0 +1,43 @@
/*
* 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.item.processor;
import org.springframework.batch.io.exception.BatchCriticalException;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.sample.dao.OrderWriter;
import org.springframework.batch.sample.domain.Order;
public class OrderProcessor implements ItemProcessor {
private OrderWriter writer;
private Order order;
public void process(Object data) {
if (!(data instanceof Order)) {
throw new BatchCriticalException("OrderProcessor can process only Order objects");
}
order = (Order) data;
writer.write(order);
}
public void setWriter(OrderWriter reportService) {
this.writer = reportService;
}
}

View File

@@ -0,0 +1,44 @@
/*
* 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.item.processor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.sample.domain.Person;
public class PersonProcessor implements ItemProcessor {
private static Log log = LogFactory.getLog(PersonProcessor.class);
public void process(Object data) {
if (!(data instanceof Person)) {
log.warn("PersonProcessor can process only Person objects, skipping record");
return;
}
log.debug("Processing: " + data);
}
public void close() {
}
public void init() {
}
}

View File

@@ -0,0 +1,18 @@
package org.springframework.batch.sample.item.processor;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.sample.dao.PlayerDao;
import org.springframework.batch.sample.domain.Player;
public class PlayerItemProcessor implements ItemProcessor {
PlayerDao playerDao;
public void process(Object data) throws Exception {
playerDao.savePlayer((Player)data);
}
public void setPlayerDao(PlayerDao playerDao) {
this.playerDao = playerDao;
}
}

View File

@@ -0,0 +1,73 @@
/*
* 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.item.processor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.sample.dao.TradeWriter;
import org.springframework.batch.sample.domain.Trade;
public class TradeProcessor implements ItemProcessor {
private static Log log = LogFactory.getLog(TradeProcessor.class);
private TradeWriter writer;
private int failure = -1;
private int index = 0;
/**
* Public setter for the {@link int} property.
*
* @param failure the failure to set
*/
public void setFailure(int failure) {
this.failure = failure;
}
public void process(Object data) {
if (!(data instanceof Trade)) {
log.warn("TradeProcessor can process only Trade objects, skipping record");
return;
}
Trade trade = (Trade) data;
log.debug(data);
//TODO put some processing of the trade object here
writer.writeTrade(trade);
if(index++ == failure) {
throw new RuntimeException("Something unexpected happened!");
}
}
public void setWriter(TradeWriter dao) {
this.writer = dao;
}
public void close() {
}
public void init() {
}
}

View File

@@ -0,0 +1,209 @@
/*
* 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.item.provider;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.configuration.StepConfiguration;
import org.springframework.batch.core.domain.StepExecution;
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.provider.AbstractItemProvider;
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;
/**
* @author peter.zozom
*
*/
public class OrderItemProvider extends AbstractItemProvider {
private static Log log = LogFactory.getLog(OrderItemProvider.class);
private InputSource inputSource;
private Order order;
private boolean recordFinished;
private FieldSetMapper headerMapper;
private FieldSetMapper customerMapper;
private FieldSetMapper addressMapper;
private FieldSetMapper billingMapper;
private FieldSetMapper itemMapper;
private FieldSetMapper shippingMapper;
private Validator validator;
/**
* @see org.springframework.batch.item.ItemProvider#next()
*/
public Object next() {
recordFinished = false;
while (!recordFinished) {
process((FieldSet)inputSource.read());
}
if (order!=null) {
log.info("Mapped: "+order);
validator.validate(order);
}
Object result = order;
order = null;
return result;
}
/**
* @see org.springframework.batch.execution.io.FieldSetCallback#process(StepConfiguration, StepExecution)
*/
private void process(FieldSet fieldSet) {
//finish processing if we hit the end of file
if (fieldSet == null) {
log.debug("FINISHED");
recordFinished = true;
order = null;
return;
}
String lineId = fieldSet.readString(0);
//start a new Order
if (Order.LINE_ID_HEADER.equals(lineId)) {
log.debug("STARTING NEW RECORD");
order = (Order) headerMapper.mapLine(fieldSet);
return;
}
//mark we are finished with current Order
if (Order.LINE_ID_FOOTER.equals(lineId)) {
log.debug("END OF RECORD");
//Do mapping for footer here, because mapper does not allow to pass an Order object as input.
//Mapper always creates new object
order.setTotalPrice(fieldSet.readBigDecimal("TOTAL_PRICE"));
order.setTotalLines(fieldSet.readInt("TOTAL_LINE_ITEMS"));
order.setTotalItems(fieldSet.readInt("TOTAL_ITEMS"));
recordFinished = true;
return;
}
if (Customer.LINE_ID_BUSINESS_CUST.equals(lineId)) {
log.debug("MAPPING CUSTOMER");
if (order.getCustomer() == null) {
order.setCustomer((Customer) customerMapper.mapLine(fieldSet));
order.getCustomer().setBusinessCustomer(true);
}
return;
}
if (Customer.LINE_ID_NON_BUSINESS_CUST.equals(lineId)) {
log.debug("MAPPING CUSTOMER");
if (order.getCustomer() == null) {
order.setCustomer((Customer) customerMapper.mapLine(fieldSet));
order.getCustomer().setBusinessCustomer(false);
}
return;
}
if (Address.LINE_ID_BILLING_ADDR.equals(lineId)) {
log.debug("MAPPING BILLING ADDRESS");
order.setBillingAddress((Address) addressMapper.mapLine(fieldSet));
return;
}
if (Address.LINE_ID_SHIPPING_ADDR.equals(lineId)) {
log.debug("MAPPING SHIPPING ADDRESS");
order.setShippingAddress((Address) addressMapper.mapLine(fieldSet));
return;
}
if (BillingInfo.LINE_ID_BILLING_INFO.equals(lineId)) {
log.debug("MAPPING BILLING INFO");
order.setBilling((BillingInfo) billingMapper.mapLine(fieldSet));
return;
}
if (ShippingInfo.LINE_ID_SHIPPING_INFO.equals(lineId)) {
log.debug("MAPPING SHIPPING INFO");
order.setShipping((ShippingInfo) shippingMapper.mapLine(fieldSet));
return;
}
if (LineItem.LINE_ID_ITEM.equals(lineId)) {
log.debug("MAPPING LINE ITEM");
if (order.getLineItems() == null) {
order.setLineItems(new ArrayList());
}
order.getLineItems().add(itemMapper.mapLine(fieldSet));
return;
}
log.debug("Could not map LINE_ID="+lineId);
}
public void setAddressMapper(FieldSetMapper addressMapper) {
this.addressMapper = addressMapper;
}
public void setBillingMapper(FieldSetMapper billingMapper) {
this.billingMapper = billingMapper;
}
public void setCustomerMapper(FieldSetMapper customerMapper) {
this.customerMapper = customerMapper;
}
public void setHeaderMapper(FieldSetMapper headerMapper) {
this.headerMapper = headerMapper;
}
public void setInputSource(InputSource inputSource) {
this.inputSource = inputSource;
}
public void setItemMapper(FieldSetMapper itemMapper) {
this.itemMapper = itemMapper;
}
public void setShippingMapper(FieldSetMapper shippingMapper) {
this.shippingMapper = shippingMapper;
}
public void setValidator(Validator validator) {
this.validator = validator;
}
}

View File

@@ -0,0 +1,39 @@
/*
* 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.launch;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class QuartzBatchLauncher {
private static Log log = LogFactory.getLog(QuartzBatchLauncher.class);
public static void main(String[] args) throws IOException {
if (args[0] == null) {
log.error("Missing argument: provide a path to configuration file");
System.exit(-1);
}
new ClassPathXmlApplicationContext(args[0] + ".xml");
log.info("Quartz context initialized");
}
}

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.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.Address;
public class AddressFieldSetMapper implements FieldSetMapper {
public static final String ADDRESSEE_COLUMN = "ADDRESSEE";
public static final String ADDRESS_LINE1_COLUMN = "ADDR_LINE1";
public static final String ADDRESS_LINE2_COLUMN = "ADDR_LINE2";
public static final String CITY_COLUMN = "CITY";
public static final String ZIP_CODE_COLUMN = "ZIP_CODE";
public static final String STATE_COLUMN = "STATE";
public static final String COUNTRY_COLUMN = "COUNTRY";
public Object mapLine(FieldSet fieldSet) {
Address address = new Address();
address.setAddressee(fieldSet.readString(ADDRESSEE_COLUMN));
address.setAddrLine1(fieldSet.readString(ADDRESS_LINE1_COLUMN));
address.setAddrLine2(fieldSet.readString(ADDRESS_LINE2_COLUMN));
address.setCity(fieldSet.readString(CITY_COLUMN));
address.setZipCode(fieldSet.readString(ZIP_CODE_COLUMN));
address.setState(fieldSet.readString(STATE_COLUMN));
address.setCountry(fieldSet.readString(COUNTRY_COLUMN));
return address;
}
}

View File

@@ -0,0 +1,38 @@
/*
* 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.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.BillingInfo;
public class BillingFieldSetMapper implements FieldSetMapper {
public static final String PAYMENT_TYPE_ID_COLUMN = "PAYMENT_TYPE_ID";
public static final String PAYMENT_DESC_COLUMN = "PAYMENT_DESC";
public Object mapLine(FieldSet fieldSet) {
BillingInfo info = new BillingInfo();
info.setPaymentId(fieldSet.readString(PAYMENT_TYPE_ID_COLUMN));
info.setPaymentDesc(fieldSet.readString(PAYMENT_DESC_COLUMN));
return info;
}
}

View File

@@ -0,0 +1,23 @@
package org.springframework.batch.sample.mapping;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.sample.domain.CustomerCredit;
import org.springframework.jdbc.core.RowMapper;
public class CustomerCreditRowMapper implements RowMapper {
public static final String NAME_COLUMN = "name";
public static final String CREDIT_COLUMN = "credit";
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
CustomerCredit customerCredit = new CustomerCredit();
customerCredit.setName(rs.getString(NAME_COLUMN));
customerCredit.setCredit(rs.getBigDecimal(CREDIT_COLUMN));
return customerCredit;
}
}

View File

@@ -0,0 +1,58 @@
/*
* 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.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.Customer;
public class CustomerFieldSetMapper implements FieldSetMapper {
public static final String LINE_ID_COLUMN = "LINE_ID";
public static final String COMPANY_NAME_COLUMN = "COMPANY_NAME";
public static final String LAST_NAME_COLUMN = "LAST_NAME";
public static final String FIRST_NAME_COLUMN = "FIRST_NAME";
public static final String MIDDLE_NAME_COLUMN = "MIDDLE_NAME";
public static final String TRUE_SYMBOL = "T";
public static final String REGISTERED_COLUMN = "REGISTERED";
public static final String REG_ID_COLUMN = "REG_ID";
public static final String VIP_COLUMN = "VIP";
public Object mapLine(FieldSet fieldSet) {
Customer customer = new Customer();
if (Customer.LINE_ID_BUSINESS_CUST.equals(fieldSet.readString(LINE_ID_COLUMN))) {
customer.setCompanyName(fieldSet.readString(COMPANY_NAME_COLUMN));
//business customer must be always registered
customer.setRegistered(true);
}
if (Customer.LINE_ID_NON_BUSINESS_CUST.equals(fieldSet.readString(LINE_ID_COLUMN))) {
customer.setLastName(fieldSet.readString(LAST_NAME_COLUMN));
customer.setFirstName(fieldSet.readString(FIRST_NAME_COLUMN));
customer.setMiddleName(fieldSet.readString(MIDDLE_NAME_COLUMN));
customer.setRegistered(TRUE_SYMBOL.equals(fieldSet.readString(REGISTERED_COLUMN)));
}
customer.setRegistrationId(fieldSet.readLong(REG_ID_COLUMN));
customer.setVip(TRUE_SYMBOL.equals(fieldSet.readString(VIP_COLUMN)));
return customer;
}
}

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.mapping;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.sample.domain.CustomerDebit;
import org.springframework.jdbc.core.RowMapper;
public class CustomerUpdateMapper implements RowMapper {
public static final String CUSTOMER_COLUMN = "customer";
public static final String PRICE_COLUMN = "price";
public Object mapRow(ResultSet rs, int ignoredRowNumber)
throws SQLException {
CustomerDebit customerDebit = new CustomerDebit();
customerDebit.setName(rs.getString(CUSTOMER_COLUMN));
customerDebit.setDebit(rs.getBigDecimal(PRICE_COLUMN));
return customerDebit;
}
}

View File

@@ -0,0 +1,35 @@
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.Game;
public class GameMapper implements FieldSetMapper {
public Object mapLine(FieldSet fs) {
if(fs == null){
return null;
}
Game game = new Game();
game.setId(fs.readString("id"));
game.setYear(fs.readInt("year"));
game.setTeam(fs.readString("team"));
game.setWeek(fs.readInt("week"));
game.setOpponent(fs.readString("opponent"));
game.setCompletes(fs.readInt("completes"));
game.setAttempts(fs.readInt("attempts"));
game.setPassingYards(fs.readInt("passingYards"));
game.setPassingTd(fs.readInt("passingTd"));
game.setInterceptions(fs.readInt("interceptions"));
game.setRushes(fs.readInt("rushes"));
game.setRushYards(fs.readInt("rushYards"));
game.setReceptions(fs.readInt("receptions", 0));
game.setReceptionYards(fs.readInt("receptionYards"));
game.setTotalTd(fs.readInt("totalTd"));
return game;
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.Order;
public class HeaderFieldSetMapper implements FieldSetMapper {
public static final String ORDER_ID_COLUMN = "ORDER_ID";
public static final String ORDER_DATE_COLUMN = "ORDER_DATE";
public Object mapLine(FieldSet fieldSet) {
Order order = new Order();
order.setOrderId(fieldSet.readLong(ORDER_ID_COLUMN));
order.setOrderDate(fieldSet.readDate(ORDER_DATE_COLUMN));
return order;
}
}

View File

@@ -0,0 +1,50 @@
/*
* 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.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.LineItem;
public class OrderItemFieldSetMapper implements FieldSetMapper {
public static final String TOTAL_PRICE_COLUMN = "TOTAL_PRICE";
public static final String QUANTITY_COLUMN = "QUANTITY";
public static final String HANDLING_PRICE_COLUMN = "HANDLING_PRICE";
public static final String SHIPPING_PRICE_COLUMN = "SHIPPING_PRICE";
public static final String DISCOUNT_AMOUNT_COLUMN = "DISCOUNT_AMOUNT";
public static final String DISCOUNT_PERC_COLUMN = "DISCOUNT_PERC";
public static final String PRICE_COLUMN = "PRICE";
public static final String ITEM_ID_COLUMN = "ITEM_ID";
public Object mapLine(FieldSet fieldSet) {
LineItem item = new LineItem();
item.setItemId(fieldSet.readLong(ITEM_ID_COLUMN));
item.setPrice(fieldSet.readBigDecimal(PRICE_COLUMN));
item.setDiscountPerc(fieldSet.readBigDecimal(DISCOUNT_PERC_COLUMN));
item.setDiscountAmount(fieldSet.readBigDecimal(DISCOUNT_AMOUNT_COLUMN));
item.setShippingPrice(fieldSet.readBigDecimal(SHIPPING_PRICE_COLUMN));
item.setHandlingPrice(fieldSet.readBigDecimal(HANDLING_PRICE_COLUMN));
item.setQuantity(fieldSet.readInt(QUANTITY_COLUMN));
item.setTotalPrice(fieldSet.readBigDecimal(TOTAL_PRICE_COLUMN));
return item;
}
}

View File

@@ -0,0 +1,38 @@
/*
* 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.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
/**
* Pass through {@link FieldSetMapper} useful for
* passing a fieldset back from a FlatFileInputsource rather
* than a mapped object.
*
* @author Lucas Ward
*
*/
public class PassThroughFieldSetMapper implements FieldSetMapper {
/* (non-Javadoc)
* @see org.springframework.batch.io.file.FieldSetMapper#mapLine(org.springframework.batch.io.file.FieldSet)
*/
public Object mapLine(FieldSet fs) {
return fs;
}
}

View File

@@ -0,0 +1,27 @@
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.Player;
public class PlayerMapper implements FieldSetMapper {
public Object mapLine(FieldSet fs) {
if(fs == null){
return null;
}
Player player = new Player();
player.setID(fs.readString("ID"));
player.setLastName(fs.readString("lastName"));
player.setFirstName(fs.readString("firstName"));
player.setPosition(fs.readString("position"));
player.setDebutYear(fs.readInt("debutYear"));
player.setBirthYear(fs.readInt("birthYear"));
return player;
}
}

View File

@@ -0,0 +1,55 @@
/*
* 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.mapping;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.sample.domain.PlayerSummary;
import org.springframework.jdbc.core.RowMapper;
/**
* RowMapper used to map a ResultSet to a (@link PlayerSummary)
*
* @author Lucas Ward
*
*/
public class PlayerSummaryMapper implements RowMapper {
/* (non-Javadoc)
* @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int)
*/
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
PlayerSummary summary = new PlayerSummary();
summary.setId(rs.getString(1));
summary.setYear(rs.getInt(2));
summary.setCompletes(rs.getInt(3));
summary.setAttempts(rs.getInt(4));
summary.setPassingYards(rs.getInt(5));
summary.setPassingTd(rs.getInt(6));
summary.setInterceptions(rs.getInt(7));
summary.setRushes(rs.getInt(8));
summary.setRushYards(rs.getInt(9));
summary.setReceptions(rs.getInt(10));
summary.setReceptionYards(rs.getInt(11));
summary.setTotalTd(rs.getInt(12));
return summary;
}
}

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.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.ShippingInfo;
public class ShippingFieldSetMapper implements FieldSetMapper {
public static final String ADDITIONAL_SHIPPING_INFO_COLUMN = "ADDITIONAL_SHIPPING_INFO";
public static final String SHIPPING_TYPE_ID_COLUMN = "SHIPPING_TYPE_ID";
public static final String SHIPPER_ID_COLUMN = "SHIPPER_ID";
public Object mapLine(FieldSet fieldSet) {
ShippingInfo info = new ShippingInfo();
info.setShipperId(fieldSet.readString(SHIPPER_ID_COLUMN));
info.setShippingTypeId(fieldSet.readString(SHIPPING_TYPE_ID_COLUMN));
info.setShippingInfo(fieldSet.readString(ADDITIONAL_SHIPPING_INFO_COLUMN));
return info;
}
}

View File

@@ -0,0 +1,50 @@
/*
* 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.mapping;
import org.springframework.batch.io.file.FieldSet;
import org.springframework.batch.io.file.FieldSetMapper;
import org.springframework.batch.sample.domain.Trade;
public class TradeFieldSetMapper implements FieldSetMapper {
public static final int ISIN_COLUMN = 0;
public static final int QUANTITY_COLUMN = 1;
public static final int PRICE_COLUMN = 2;
public static final int CUSTOMER_COLUMN = 3;
public Object mapLine(FieldSet fieldSet) {
if ("BEGIN".equals(fieldSet.readString(0))) {
return FieldSetMapper.BEGIN_RECORD;
}
if ("END".equals(fieldSet.readString(0))) {
return FieldSetMapper.END_RECORD;
}
Trade trade = new Trade();
trade.setIsin(fieldSet.readString(0));
trade.setQuantity(fieldSet.readLong(1));
trade.setPrice(fieldSet.readBigDecimal(2));
trade.setCustomer(fieldSet.readString(3));
return trade;
}
}

View File

@@ -0,0 +1,43 @@
/*
* 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.mapping;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.jdbc.core.RowMapper;
public class TradeRowMapper implements RowMapper {
public static final int ISIN_COLUMN = 1;
public static final int QUANTITY_COLUMN = 2;
public static final int PRICE_COLUMN = 3;
public static final int CUSTOMER_COLUMN = 4;
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Trade trade = new Trade();
trade.setIsin(rs.getString(ISIN_COLUMN));
trade.setQuantity(rs.getLong(QUANTITY_COLUMN));
trade.setPrice(rs.getBigDecimal(PRICE_COLUMN));
trade.setCustomer(rs.getString(CUSTOMER_COLUMN));
return trade;
}
}

View File

@@ -0,0 +1,63 @@
/*
* 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.tasklet;
import org.springframework.batch.core.tasklet.Tasklet;
import org.springframework.batch.execution.tasklet.RestartableItemProviderTasklet;
import org.springframework.batch.io.exception.BatchCriticalException;
import org.springframework.batch.repeat.ExitStatus;
/**
* Hacked {@link Tasklet} that throws exception on a given record number
* (useful for testing restart).
*
* @author Robert Kasanicky
*
*/
public class ExceptionRestartableTasklet extends RestartableItemProviderTasklet {
private int counter = 0;
private int throwExceptionOnRecordNumber = 4;
/* (non-Javadoc)
* @see Tasklet#execute()
*/
public ExitStatus execute() throws Exception {
counter++;
if (counter == throwExceptionOnRecordNumber) {
throw new BatchCriticalException();
}
return super.execute();
}
/**
* @param throwExceptionOnRecordNumber The number of record on which exception should be thrown
*/
public void setThrowExceptionOnRecordNumber(int throwExceptionOnRecordNumber) {
this.throwExceptionOnRecordNumber = throwExceptionOnRecordNumber;
}
public int getThrowExceptionOnRecordNumber() {
return throwExceptionOnRecordNumber;
}
}

View File

@@ -0,0 +1,58 @@
/*
* 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.tasklet;
import java.util.Properties;
import org.springframework.batch.core.tasklet.Tasklet;
import org.springframework.batch.repeat.ExitStatus;
import org.springframework.batch.statistics.StatisticsProvider;
import org.springframework.batch.support.PropertiesConverter;
/**
* Simple module implementation that will always return true to indicate
* that processing should continue. This is useful for testing graceful
* shutdown of jobs.
*
* @author Lucas Ward
*
*/
public class InfiniteLoopTasklet implements Tasklet, StatisticsProvider {
private int count = 0;
/**
*
*/
public InfiniteLoopTasklet() {
super();
}
public ExitStatus execute() throws Exception {
Thread.sleep(500);
count++;
return ExitStatus.CONTINUABLE;
}
/* (non-Javadoc)
* @see org.springframework.batch.statistics.StatisticsProvider#getStatistics()
*/
public Properties getStatistics() {
return PropertiesConverter.stringToProperties("count="+count);
}
}

View File

@@ -0,0 +1,94 @@
/*
* 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.tasklet;
import java.util.Properties;
import org.springframework.batch.core.tasklet.Tasklet;
import org.springframework.batch.execution.tasklet.ItemProviderProcessTasklet;
import org.springframework.batch.io.file.support.DefaultFlatFileInputSource;
import org.springframework.batch.repeat.ExitStatus;
import org.springframework.batch.sample.dao.TradeWriter;
import org.springframework.batch.sample.domain.Trade;
import org.springframework.batch.statistics.StatisticsProvider;
/**
* Simple implementation of a {@link Tasklet}, which illustrates the reading
* and processing of input data. This can be viable in cases, when the input
* reading and processing logic need not to be reused in different contexts. In
* general it is recommended to separate these two concerns using an
* {@link ItemProviderProcessTasklet}.
*
* Note this class is thread-safe, as per the 'standard' module implementations
* provided by the framework.
*
* @author Robert Kasanicky
* @author Lucas Ward
* @author Dave Syer
*/
public class SimpleTradeTasklet implements Tasklet, StatisticsProvider {
/*
* reads the data from input file
*/
private DefaultFlatFileInputSource inputSource;
/*
* writes a Trade object to output
*/
private TradeWriter tradeWriter;
/**
* number of trade objects processed
*/
private int tradeCount = 0;
/**
* The input template is read using the readAndMap method, which accepts a
* FieldSetMapper. This call returns a Trade object, which is then
* processed. Because this is a simple example job, the data is simply
* written out without any processing.
*/
public ExitStatus execute() throws Exception {
Trade trade = (Trade)inputSource.read();
if (trade == null) {
// no Trade object returned, reading input is finished
return ExitStatus.FINISHED;
}
tradeCount++;
tradeWriter.writeTrade(trade);
return ExitStatus.CONTINUABLE;
}
public void setInputSource(DefaultFlatFileInputSource inputTemplate) {
this.inputSource = inputTemplate;
}
public void setTradeDao(TradeWriter tradeWriter) {
this.tradeWriter = tradeWriter;
}
public Properties getStatistics() {
Properties statistics = new Properties();
statistics.setProperty("Trade.Count", String.valueOf(tradeCount));
statistics.putAll(inputSource.getStatistics());
return statistics;
}
}

View File

@@ -0,0 +1,59 @@
/*
* 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.validation.valang.custom;
import java.util.Date;
import org.springmodules.validation.valang.functions.AbstractFunction;
import org.springmodules.validation.valang.functions.Function;
/**
* Returns Boolean.TRUE if given value is future date, else it returns Boolean.FALSE
* @author peter.zozom
*/
public class FutureDateFunction extends AbstractFunction {
/**
* @param arguments
* @param line
* @param column
*/
public FutureDateFunction(Function[] arguments, int line, int column) {
super(arguments, line, column);
definedExactNumberOfArguments(1);
}
/**
* @see org.springmodules.validation.valang.functions.AbstractFunction#doGetResult(java.lang.Object)
*/
protected Object doGetResult(final Object target) throws Exception {
//get argument
final Object value = getArguments()[0].getResult(target);
Boolean result = Boolean.FALSE;
if (value instanceof Date) {
final Date now = new Date(System.currentTimeMillis());
final Date date = (Date) value;
result = (now.compareTo(date) < 0) ? Boolean.TRUE : Boolean.FALSE;
} else {
throw new Exception("No Date value for validation");
}
return result;
}
}

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.validation.valang.custom;
import java.util.Iterator;
import java.util.List;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.AbstractFunction;
import org.springmodules.validation.valang.functions.Function;
/**
* Validates total items count in Order.
*
* @author peter.zozom
*/
public class TotalOrderItemsFunction extends AbstractFunction {
public TotalOrderItemsFunction(Function[] arguments, int line, int column) {
super(arguments, line, column);
definedExactNumberOfArguments(2);
}
/**
* @see org.springmodules.validation.valang.functions.AbstractFunction#doGetResult(java.lang.Object)
*/
protected Object doGetResult(Object target) throws Exception {
//get arguments
int count = ((Integer) getArguments()[0].getResult(target)).intValue();
Object value = getArguments()[1].getResult(target);
Boolean result;
//count items in list of order lines
if (value instanceof List) {
int totalItems = 0;
for (Iterator i = ((List) value).iterator(); i.hasNext();) {
LineItem item = (LineItem) i.next();
totalItems += item.getQuantity();
}
result = (totalItems == count) ? Boolean.TRUE : Boolean.FALSE;
} else {
throw new Exception("No list for validation");
}
return result;
}
}

View File

@@ -0,0 +1,69 @@
/*
* 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.validation.valang.custom;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.AbstractFunction;
import org.springmodules.validation.valang.functions.Function;
/**
* @author peter.zozom
*
*/
public class ValidateDiscountsFunction extends AbstractFunction {
private static final BigDecimal BD_0 = new BigDecimal(0.0);
private static final BigDecimal BD_PERC_MAX = new BigDecimal(100.0);
public ValidateDiscountsFunction(Function[] arguments, int line, int column) {
super(arguments, line, column);
definedExactNumberOfArguments(1);
}
/**
* @see org.springmodules.validation.valang.functions.AbstractFunction#doGetResult(java.lang.Object)
*/
protected Object doGetResult(Object target) throws Exception {
List lineItems = (List) getArguments()[0].getResult(target);
for (Iterator i = lineItems.iterator(); i.hasNext();) {
LineItem item = (LineItem) i.next();
if (BD_0.compareTo(item.getDiscountPerc()) != 0) {
//DiscountPerc must be between 0.0 and 100.0
if ((BD_0.compareTo(item.getDiscountPerc()) > 0)
|| (BD_PERC_MAX.compareTo(item.getDiscountPerc()) < 0)
|| (BD_0.compareTo(item.getDiscountAmount()) != 0)) { //only one of DiscountAmount and DiscountPerc should be non-zero
return Boolean.FALSE;
}
} else {
//DiscountAmount must be between 0.0 and item.price
if ((BD_0.compareTo(item.getDiscountAmount()) > 0)
|| (item.getPrice().compareTo(item.getDiscountAmount()) < 0)) {
return Boolean.FALSE;
}
}
}
return Boolean.TRUE;
}
}

View File

@@ -0,0 +1,58 @@
/*
* 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.validation.valang.custom;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.AbstractFunction;
import org.springmodules.validation.valang.functions.Function;
/**
* @author peter.zozom
*
*/
public class ValidateHandlingPricesFunction extends AbstractFunction {
private static final BigDecimal BD_MIN = new BigDecimal(0.0);
private static final BigDecimal BD_MAX = new BigDecimal(99999999.99);
public ValidateHandlingPricesFunction(Function[] arguments, int line, int column) {
super(arguments, line, column);
definedExactNumberOfArguments(1);
}
/**
* @see org.springmodules.validation.valang.functions.AbstractFunction#doGetResult(java.lang.Object)
*/
protected Object doGetResult(Object target) throws Exception {
List lineItems = (List) getArguments()[0].getResult(target);
for (Iterator i = lineItems.iterator(); i.hasNext();) {
LineItem item = (LineItem) i.next();
if ((BD_MIN.compareTo(item.getHandlingPrice()) > 0)
|| (BD_MAX.compareTo(item.getHandlingPrice()) < 0)) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
}

View File

@@ -0,0 +1,55 @@
/*
* 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.validation.valang.custom;
import java.util.Iterator;
import java.util.List;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.AbstractFunction;
import org.springmodules.validation.valang.functions.Function;
/**
* @author peter.zozom
*
*/
public class ValidateIdsFunction extends AbstractFunction {
private static final long MAX_ID = 9999999999L;
public ValidateIdsFunction(Function[] arguments, int line, int column) {
super(arguments, line, column);
definedExactNumberOfArguments(1);
}
/**
* @see org.springmodules.validation.valang.functions.AbstractFunction#doGetResult(java.lang.Object)
*/
protected Object doGetResult(Object target) throws Exception {
List lineItems = (List) getArguments()[0].getResult(target);
for (Iterator i = lineItems.iterator(); i.hasNext();) {
LineItem item = (LineItem) i.next();
if ((item.getItemId() <= 0) || (item.getItemId() > MAX_ID)) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
}

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.validation.valang.custom;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.AbstractFunction;
import org.springmodules.validation.valang.functions.Function;
/**
* @author peter.zozom
*
*/
public class ValidatePricesFunction extends AbstractFunction {
private static final BigDecimal BD_MIN = new BigDecimal(0.0);
private static final BigDecimal BD_MAX = new BigDecimal(99999999.99);
public ValidatePricesFunction(Function[] arguments, int line, int column) {
super(arguments, line, column);
definedExactNumberOfArguments(1);
}
/**
* @see org.springmodules.validation.valang.functions.AbstractFunction#doGetResult(java.lang.Object)
*/
protected Object doGetResult(Object target) throws Exception {
List lineItems = (List) getArguments()[0].getResult(target);
for (Iterator i = lineItems.iterator(); i.hasNext();) {
LineItem item = (LineItem) i.next();
if ((BD_MIN.compareTo(item.getPrice()) > 0) || (BD_MAX.compareTo(item.getPrice()) < 0)) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
}

View File

@@ -0,0 +1,55 @@
/*
* 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.validation.valang.custom;
import java.util.Iterator;
import java.util.List;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.AbstractFunction;
import org.springmodules.validation.valang.functions.Function;
/**
* @author peter.zozom
*
*/
public class ValidateQuantitiesFunction extends AbstractFunction {
private static final int MAX_QUANTITY = 9999;
public ValidateQuantitiesFunction(Function[] arguments, int line, int column) {
super(arguments, line, column);
definedExactNumberOfArguments(1);
}
/**
* @see org.springmodules.validation.valang.functions.AbstractFunction#doGetResult(java.lang.Object)
*/
protected Object doGetResult(Object target) throws Exception {
List lineItems = (List) getArguments()[0].getResult(target);
for (Iterator i = lineItems.iterator(); i.hasNext();) {
LineItem item = (LineItem) i.next();
if ((item.getQuantity() <= 0) || (item.getQuantity() > MAX_QUANTITY)) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
}

View File

@@ -0,0 +1,58 @@
/*
* 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.validation.valang.custom;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.AbstractFunction;
import org.springmodules.validation.valang.functions.Function;
/**
* @author peter.zozom
*
*/
public class ValidateShippingPricesFunction extends AbstractFunction {
private static final BigDecimal BD_MIN = new BigDecimal(0.0);
private static final BigDecimal BD_MAX = new BigDecimal(99999999.99);
public ValidateShippingPricesFunction(Function[] arguments, int line, int column) {
super(arguments, line, column);
definedExactNumberOfArguments(1);
}
/**
* @see org.springmodules.validation.valang.functions.AbstractFunction#doGetResult(java.lang.Object)
*/
protected Object doGetResult(Object target) throws Exception {
List lineItems = (List) getArguments()[0].getResult(target);
for (Iterator i = lineItems.iterator(); i.hasNext();) {
LineItem item = (LineItem) i.next();
if ((BD_MIN.compareTo(item.getShippingPrice()) > 0)
|| (BD_MAX.compareTo(item.getShippingPrice()) < 0)) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
}

View File

@@ -0,0 +1,84 @@
/*
* 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.validation.valang.custom;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import org.springframework.batch.sample.domain.LineItem;
import org.springmodules.validation.valang.functions.AbstractFunction;
import org.springmodules.validation.valang.functions.Function;
/**
* @author peter.zozom
*
*/
public class ValidateTotalPricesFunction extends AbstractFunction {
private static final BigDecimal BD_MIN = new BigDecimal(0.0);
private static final BigDecimal BD_MAX = new BigDecimal(99999999.99);
private static final BigDecimal BD_100 = new BigDecimal(100.00);
public ValidateTotalPricesFunction(Function[] arguments, int line, int column) {
super(arguments, line, column);
definedExactNumberOfArguments(1);
}
/**
* @see org.springmodules.validation.valang.functions.AbstractFunction#doGetResult(java.lang.Object)
*/
protected Object doGetResult(Object target) throws Exception {
List lineItems = (List) getArguments()[0].getResult(target);
for (Iterator i = lineItems.iterator(); i.hasNext();) {
LineItem item = (LineItem) i.next();
if ((BD_MIN.compareTo(item.getTotalPrice()) > 0)
|| (BD_MAX.compareTo(item.getTotalPrice()) < 0)) {
return Boolean.FALSE;
}
//calculate total price
//discount coeficient = (100.00 - discountPerc) / 100.00
BigDecimal coef = BD_100.subtract(item.getDiscountPerc())
.divide(BD_100, 4, BigDecimal.ROUND_HALF_UP);
//discountedPrice = (price * coef) - discountAmount
//at least one of discountPerc and discountAmount is 0 - this is validated by ValidateDiscountsFunction
BigDecimal discountedPrice = item.getPrice().multiply(coef)
.subtract(item.getDiscountAmount());
//price for single item = discountedPrice + shipping + handling
BigDecimal singleItemPrice = discountedPrice.add(item.getShippingPrice())
.add(item.getHandlingPrice());
//total price = singleItemPrice * quantity
BigDecimal quantity = new BigDecimal(item.getQuantity());
BigDecimal totalPrice = singleItemPrice.multiply(quantity)
.setScale(2, BigDecimal.ROUND_HALF_UP);
//calculatedPrice should equal to item.totalPrice
if (totalPrice.compareTo(item.getTotalPrice()) != 0) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
}