Change svn:eol-style to LF

This commit is contained in:
dsyer
2008-03-06 21:59:13 +00:00
parent ee5746a860
commit f5e85d5f63
372 changed files with 33472 additions and 33470 deletions

View File

@@ -1,63 +1,63 @@
package org.springframework.batch.io.cursor;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.springframework.batch.io.support.AbstractDataSourceItemReaderIntegrationTests;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
/**
* Tests for {@link HibernateCursorItemReader} using {@link StatelessSession}.
*
* @author Robert Kasanicky
*/
public class HibernateCursorItemReaderIntegrationTests extends AbstractDataSourceItemReaderIntegrationTests {
protected ItemReader createItemReader() throws Exception {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(super.getJdbcTemplate().getDataSource());
factoryBean.setMappingLocations(new Resource[] { new ClassPathResource("Foo.hbm.xml", getClass()) });
factoryBean.afterPropertiesSet();
SessionFactory sessionFactory = (SessionFactory) factoryBean.getObject();
String hsqlQuery = "from Foo";
HibernateCursorItemReader inputSource = new HibernateCursorItemReader();
inputSource.setQueryString(hsqlQuery);
inputSource.setSessionFactory(sessionFactory);
inputSource.setUseStatelessSession(isUseStatelessSession());
inputSource.afterPropertiesSet();
inputSource.setSaveState(true);
return inputSource;
}
protected boolean isUseStatelessSession() {
return true;
}
/**
* Exception scenario.
*
* {@link HibernateCursorItemReader#setUseStatelessSession(boolean)} can be
* called only in uninitialized state.
*/
public void testSetUseStatelessSession() {
HibernateCursorItemReader inputSource = ((HibernateCursorItemReader) reader);
// initialize and call setter => error
inputSource.open(new ExecutionContext());
try {
inputSource.setUseStatelessSession(false);
fail();
}
catch (IllegalStateException e) {
// expected
}
}
}
package org.springframework.batch.io.cursor;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.springframework.batch.io.support.AbstractDataSourceItemReaderIntegrationTests;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
/**
* Tests for {@link HibernateCursorItemReader} using {@link StatelessSession}.
*
* @author Robert Kasanicky
*/
public class HibernateCursorItemReaderIntegrationTests extends AbstractDataSourceItemReaderIntegrationTests {
protected ItemReader createItemReader() throws Exception {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(super.getJdbcTemplate().getDataSource());
factoryBean.setMappingLocations(new Resource[] { new ClassPathResource("Foo.hbm.xml", getClass()) });
factoryBean.afterPropertiesSet();
SessionFactory sessionFactory = (SessionFactory) factoryBean.getObject();
String hsqlQuery = "from Foo";
HibernateCursorItemReader inputSource = new HibernateCursorItemReader();
inputSource.setQueryString(hsqlQuery);
inputSource.setSessionFactory(sessionFactory);
inputSource.setUseStatelessSession(isUseStatelessSession());
inputSource.afterPropertiesSet();
inputSource.setSaveState(true);
return inputSource;
}
protected boolean isUseStatelessSession() {
return true;
}
/**
* Exception scenario.
*
* {@link HibernateCursorItemReader#setUseStatelessSession(boolean)} can be
* called only in uninitialized state.
*/
public void testSetUseStatelessSession() {
HibernateCursorItemReader inputSource = ((HibernateCursorItemReader) reader);
// initialize and call setter => error
inputSource.open(new ExecutionContext());
try {
inputSource.setUseStatelessSession(false);
fail();
}
catch (IllegalStateException e) {
// expected
}
}
}

View File

@@ -1,16 +1,16 @@
package org.springframework.batch.io.cursor;
import org.hibernate.Session;
/**
* Tests for {@link HibernateCursorItemReader} using standard hibernate {@link Session}.
*
* @author Robert Kasanicky
*/
public class HibernateCursorItemReaderStatefulIntegrationTests extends HibernateCursorItemReaderIntegrationTests {
protected boolean isUseStatelessSession() {
return false;
}
}
package org.springframework.batch.io.cursor;
import org.hibernate.Session;
/**
* Tests for {@link HibernateCursorItemReader} using standard hibernate {@link Session}.
*
* @author Robert Kasanicky
*/
public class HibernateCursorItemReaderStatefulIntegrationTests extends HibernateCursorItemReaderIntegrationTests {
protected boolean isUseStatelessSession() {
return false;
}
}

View File

@@ -1,30 +1,30 @@
package org.springframework.batch.io.cursor;
import org.springframework.batch.io.driving.FooRowMapper;
import org.springframework.batch.io.support.AbstractDataSourceItemReaderIntegrationTests;
import org.springframework.batch.item.ItemReader;
/**
* Tests for {@link JdbcCursorItemReader}
*
* @author Robert Kasanicky
*/
public class JdbcCursorItemReaderIntegrationTests extends AbstractDataSourceItemReaderIntegrationTests {
protected ItemReader createItemReader() throws Exception {
JdbcCursorItemReader result = new JdbcCursorItemReader();
result.setDataSource(super.getJdbcTemplate().getDataSource());
result.setSql("select ID, NAME, VALUE from T_FOOS");
result.setIgnoreWarnings(true);
result.setVerifyCursorPosition(true);
result.setMapper(new FooRowMapper());
result.setFetchSize(10);
result.setMaxRows(100);
result.setQueryTimeout(1000);
result.setSaveState(true);
return result;
}
}
package org.springframework.batch.io.cursor;
import org.springframework.batch.io.driving.FooRowMapper;
import org.springframework.batch.io.support.AbstractDataSourceItemReaderIntegrationTests;
import org.springframework.batch.item.ItemReader;
/**
* Tests for {@link JdbcCursorItemReader}
*
* @author Robert Kasanicky
*/
public class JdbcCursorItemReaderIntegrationTests extends AbstractDataSourceItemReaderIntegrationTests {
protected ItemReader createItemReader() throws Exception {
JdbcCursorItemReader result = new JdbcCursorItemReader();
result.setDataSource(super.getJdbcTemplate().getDataSource());
result.setSql("select ID, NAME, VALUE from T_FOOS");
result.setIgnoreWarnings(true);
result.setVerifyCursorPosition(true);
result.setMapper(new FooRowMapper());
result.setFetchSize(10);
result.setMaxRows(100);
result.setQueryTimeout(1000);
result.setSaveState(true);
return result;
}
}

View File

@@ -1,58 +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.io.driving;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
* @author Lucas Ward
*
*/
public class CompositeKeyFooDao extends JdbcDaoSupport implements FooDao {
public CompositeKeyFooDao(JdbcTemplate jdbcTemplate) {
this.setJdbcTemplate(jdbcTemplate);
}
/* (non-Javadoc)
* @see org.springframework.batch.io.sql.scratch.FooDao#getFoo(java.lang.Object)
*/
public Foo getFoo(Object key) {
Map keys = (Map)key;
Object[] args = keys.values().toArray();
RowMapper fooMapper = new RowMapper(){
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Foo foo = new Foo();
foo.setId(rs.getInt(1));
foo.setName(rs.getString(2));
foo.setValue(rs.getInt(3));
return foo;
}
};
return (Foo)getJdbcTemplate().query("SELECT ID, NAME, VALUE from T_FOOS where ID = ? and VALUE = ?",
args, fooMapper).get(0);
}
}
/*
* 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.io.driving;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
* @author Lucas Ward
*
*/
public class CompositeKeyFooDao extends JdbcDaoSupport implements FooDao {
public CompositeKeyFooDao(JdbcTemplate jdbcTemplate) {
this.setJdbcTemplate(jdbcTemplate);
}
/* (non-Javadoc)
* @see org.springframework.batch.io.sql.scratch.FooDao#getFoo(java.lang.Object)
*/
public Foo getFoo(Object key) {
Map keys = (Map)key;
Object[] args = keys.values().toArray();
RowMapper fooMapper = new RowMapper(){
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Foo foo = new Foo();
foo.setId(rs.getInt(1));
foo.setName(rs.getString(2));
foo.setValue(rs.getInt(3));
return foo;
}
};
return (Foo)getJdbcTemplate().query("SELECT ID, NAME, VALUE from T_FOOS where ID = ? and VALUE = ?",
args, fooMapper).get(0);
}
}

View File

@@ -1,30 +1,30 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.io.driving;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* @author Lucas Ward
*
*/
public interface FooDao {
Foo getFoo(Object key);
void setJdbcTemplate(JdbcTemplate jdbcTemplate);
}
/*
* 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.io.driving;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* @author Lucas Ward
*
*/
public interface FooDao {
Foo getFoo(Object key);
void setJdbcTemplate(JdbcTemplate jdbcTemplate);
}

View File

@@ -1,68 +1,68 @@
package org.springframework.batch.io.driving;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
class FooItemReader implements ItemStream, ItemReader, DisposableBean, InitializingBean {
DrivingQueryItemReader inputSource;
FooDao fooDao = new SingleKeyFooDao();
public FooItemReader(DrivingQueryItemReader inputSource, JdbcTemplate jdbcTemplate) {
this.inputSource = inputSource;
fooDao.setJdbcTemplate(jdbcTemplate);
}
public Object read() {
Object key = inputSource.read();
if (key != null) {
return fooDao.getFoo(key);
}
else {
return null;
}
}
public void update(ExecutionContext executionContext) {
inputSource.update(executionContext);
}
public void destroy() throws Exception {
inputSource.close(null);
}
public void setFooDao(FooDao fooDao) {
this.fooDao = fooDao;
}
public void afterPropertiesSet() throws Exception {
}
public void open(ExecutionContext executionContext) {
inputSource.open(executionContext);
};
public void close(ExecutionContext executionContext) {
}
/*
* (non-Javadoc)
* @see org.springframework.batch.item.ItemStream#mark(org.springframework.batch.item.StreamContext)
*/
public void mark() {
inputSource.mark();
}
/*
* (non-Javadoc)
* @see org.springframework.batch.item.ItemStream#reset(org.springframework.batch.item.StreamContext)
*/
public void reset() {
inputSource.reset();
};
}
package org.springframework.batch.io.driving;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
class FooItemReader implements ItemStream, ItemReader, DisposableBean, InitializingBean {
DrivingQueryItemReader inputSource;
FooDao fooDao = new SingleKeyFooDao();
public FooItemReader(DrivingQueryItemReader inputSource, JdbcTemplate jdbcTemplate) {
this.inputSource = inputSource;
fooDao.setJdbcTemplate(jdbcTemplate);
}
public Object read() {
Object key = inputSource.read();
if (key != null) {
return fooDao.getFoo(key);
}
else {
return null;
}
}
public void update(ExecutionContext executionContext) {
inputSource.update(executionContext);
}
public void destroy() throws Exception {
inputSource.close(null);
}
public void setFooDao(FooDao fooDao) {
this.fooDao = fooDao;
}
public void afterPropertiesSet() throws Exception {
}
public void open(ExecutionContext executionContext) {
inputSource.open(executionContext);
};
public void close(ExecutionContext executionContext) {
}
/*
* (non-Javadoc)
* @see org.springframework.batch.item.ItemStream#mark(org.springframework.batch.item.StreamContext)
*/
public void mark() {
inputSource.mark();
}
/*
* (non-Javadoc)
* @see org.springframework.batch.item.ItemStream#reset(org.springframework.batch.item.StreamContext)
*/
public void reset() {
inputSource.reset();
};
}

View File

@@ -1,21 +1,21 @@
package org.springframework.batch.io.driving;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.jdbc.core.RowMapper;
public class FooRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Foo foo = new Foo();
foo.setId(rs.getInt(1));
foo.setName(rs.getString(2));
foo.setValue(rs.getInt(3));
return foo;
}
}
package org.springframework.batch.io.driving;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.jdbc.core.RowMapper;
public class FooRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Foo foo = new Foo();
foo.setId(rs.getInt(1));
foo.setName(rs.getString(2));
foo.setValue(rs.getInt(3));
return foo;
}
}

View File

@@ -1,40 +1,40 @@
package org.springframework.batch.io.driving;
import org.springframework.batch.io.driving.support.IbatisKeyGenerator;
import org.springframework.batch.io.support.AbstractDataSourceItemReaderIntegrationTests;
import org.springframework.batch.item.ItemReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.orm.ibatis.SqlMapClientFactoryBean;
import com.ibatis.sqlmap.client.SqlMapClient;
/**
* Tests for {@link IbatisDrivingQueryItemReader}
*
* @author Robert Kasanicky
*/
public class IbatisItemReaderIntegrationTests extends AbstractDataSourceItemReaderIntegrationTests {
protected ItemReader createItemReader() throws Exception {
SqlMapClientFactoryBean factory = new SqlMapClientFactoryBean();
factory.setConfigLocation(new ClassPathResource("ibatis-config.xml", getClass()));
factory.setDataSource(super.getJdbcTemplate().getDataSource());
factory.afterPropertiesSet();
SqlMapClient sqlMapClient = (SqlMapClient) factory.getObject();
IbatisDrivingQueryItemReader inputSource = new IbatisDrivingQueryItemReader();
IbatisKeyGenerator keyGenerator = new IbatisKeyGenerator();
keyGenerator.setDrivingQueryId("getAllFooIds");
inputSource.setDetailsQueryId("getFooById");
keyGenerator.setRestartQueryId("getAllFooIdsRestart");
keyGenerator.setSqlMapClient(sqlMapClient);
inputSource.setSqlMapClient(sqlMapClient);
inputSource.setKeyGenerator(keyGenerator);
inputSource.setSaveState(true);
return inputSource;
}
}
package org.springframework.batch.io.driving;
import org.springframework.batch.io.driving.support.IbatisKeyGenerator;
import org.springframework.batch.io.support.AbstractDataSourceItemReaderIntegrationTests;
import org.springframework.batch.item.ItemReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.orm.ibatis.SqlMapClientFactoryBean;
import com.ibatis.sqlmap.client.SqlMapClient;
/**
* Tests for {@link IbatisDrivingQueryItemReader}
*
* @author Robert Kasanicky
*/
public class IbatisItemReaderIntegrationTests extends AbstractDataSourceItemReaderIntegrationTests {
protected ItemReader createItemReader() throws Exception {
SqlMapClientFactoryBean factory = new SqlMapClientFactoryBean();
factory.setConfigLocation(new ClassPathResource("ibatis-config.xml", getClass()));
factory.setDataSource(super.getJdbcTemplate().getDataSource());
factory.afterPropertiesSet();
SqlMapClient sqlMapClient = (SqlMapClient) factory.getObject();
IbatisDrivingQueryItemReader inputSource = new IbatisDrivingQueryItemReader();
IbatisKeyGenerator keyGenerator = new IbatisKeyGenerator();
keyGenerator.setDrivingQueryId("getAllFooIds");
inputSource.setDetailsQueryId("getFooById");
keyGenerator.setRestartQueryId("getAllFooIdsRestart");
keyGenerator.setSqlMapClient(sqlMapClient);
inputSource.setSqlMapClient(sqlMapClient);
inputSource.setKeyGenerator(keyGenerator);
inputSource.setSaveState(true);
return inputSource;
}
}

View File

@@ -1,44 +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.io.driving;
import org.springframework.batch.io.driving.support.MultipleColumnJdbcKeyGenerator;
import org.springframework.batch.io.sql.AbstractJdbcItemReaderIntegrationTests;
import org.springframework.batch.item.ItemReader;
/**
* @author Lucas Ward
*
*/
public class MultipleColumnJdbcDrivingQueryItemReaderIntegrationTests extends
AbstractJdbcItemReaderIntegrationTests {
protected ItemReader createItemReader() throws Exception {
MultipleColumnJdbcKeyGenerator keyGenerator =
new MultipleColumnJdbcKeyGenerator(getJdbcTemplate(),
"SELECT ID, VALUE from T_FOOS order by ID, VALUE");
keyGenerator.setRestartSql("SELECT ID, VALUE from T_FOOS where ID > ? and VALUE > ? order by ID");
DrivingQueryItemReader inputSource = new DrivingQueryItemReader();
inputSource.setSaveState(true);
inputSource.setKeyGenerator(keyGenerator);
FooItemReader fooItemReader = new FooItemReader(inputSource, getJdbcTemplate());
fooItemReader.setFooDao(new CompositeKeyFooDao(getJdbcTemplate()));
return fooItemReader;
}
}
/*
* 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.io.driving;
import org.springframework.batch.io.driving.support.MultipleColumnJdbcKeyGenerator;
import org.springframework.batch.io.sql.AbstractJdbcItemReaderIntegrationTests;
import org.springframework.batch.item.ItemReader;
/**
* @author Lucas Ward
*
*/
public class MultipleColumnJdbcDrivingQueryItemReaderIntegrationTests extends
AbstractJdbcItemReaderIntegrationTests {
protected ItemReader createItemReader() throws Exception {
MultipleColumnJdbcKeyGenerator keyGenerator =
new MultipleColumnJdbcKeyGenerator(getJdbcTemplate(),
"SELECT ID, VALUE from T_FOOS order by ID, VALUE");
keyGenerator.setRestartSql("SELECT ID, VALUE from T_FOOS where ID > ? and VALUE > ? order by ID");
DrivingQueryItemReader inputSource = new DrivingQueryItemReader();
inputSource.setSaveState(true);
inputSource.setKeyGenerator(keyGenerator);
FooItemReader fooItemReader = new FooItemReader(inputSource, getJdbcTemplate());
fooItemReader.setFooDao(new CompositeKeyFooDao(getJdbcTemplate()));
return fooItemReader;
}
}

View File

@@ -1,26 +1,26 @@
package org.springframework.batch.io.driving;
import org.springframework.batch.io.driving.support.SingleColumnJdbcKeyGenerator;
import org.springframework.batch.io.sql.AbstractJdbcItemReaderIntegrationTests;
import org.springframework.batch.item.ItemReader;
public class SingleColumnJdbcDrivingQueryItemReaderIntegrationTests extends AbstractJdbcItemReaderIntegrationTests {
protected ItemReader source;
/**
* @return input source with all necessary dependencies set
*/
protected ItemReader createItemReader() throws Exception {
SingleColumnJdbcKeyGenerator keyStrategy = new SingleColumnJdbcKeyGenerator(getJdbcTemplate(),
"SELECT ID from T_FOOS order by ID");
keyStrategy.setRestartSql("SELECT ID from T_FOOS where ID > ? order by ID");
DrivingQueryItemReader inputSource = new DrivingQueryItemReader();
inputSource.setKeyGenerator(keyStrategy);
inputSource.setSaveState(true);
return new FooItemReader(inputSource, getJdbcTemplate());
}
}
package org.springframework.batch.io.driving;
import org.springframework.batch.io.driving.support.SingleColumnJdbcKeyGenerator;
import org.springframework.batch.io.sql.AbstractJdbcItemReaderIntegrationTests;
import org.springframework.batch.item.ItemReader;
public class SingleColumnJdbcDrivingQueryItemReaderIntegrationTests extends AbstractJdbcItemReaderIntegrationTests {
protected ItemReader source;
/**
* @return input source with all necessary dependencies set
*/
protected ItemReader createItemReader() throws Exception {
SingleColumnJdbcKeyGenerator keyStrategy = new SingleColumnJdbcKeyGenerator(getJdbcTemplate(),
"SELECT ID from T_FOOS order by ID");
keyStrategy.setRestartSql("SELECT ID from T_FOOS where ID > ? order by ID");
DrivingQueryItemReader inputSource = new DrivingQueryItemReader();
inputSource.setKeyGenerator(keyStrategy);
inputSource.setSaveState(true);
return new FooItemReader(inputSource, getJdbcTemplate());
}
}

View File

@@ -1,28 +1,28 @@
package org.springframework.batch.io.driving;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class SingleKeyFooDao extends JdbcDaoSupport implements FooDao {
public Foo getFoo(Object key){
RowMapper fooMapper = new RowMapper(){
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Foo foo = new Foo();
foo.setId(rs.getInt(1));
foo.setName(rs.getString(2));
foo.setValue(rs.getInt(3));
return foo;
}
};
return (Foo)getJdbcTemplate().query("SELECT ID, NAME, VALUE from T_FOOS where ID = ?",
new Object[] {key}, fooMapper).get(0);
}
}
package org.springframework.batch.io.driving;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class SingleKeyFooDao extends JdbcDaoSupport implements FooDao {
public Foo getFoo(Object key){
RowMapper fooMapper = new RowMapper(){
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Foo foo = new Foo();
foo.setId(rs.getInt(1));
foo.setName(rs.getString(2));
foo.setValue(rs.getInt(3));
return foo;
}
};
return (Foo)getJdbcTemplate().query("SELECT ID, NAME, VALUE from T_FOOS where ID = ?",
new Object[] {key}, fooMapper).get(0);
}
}

View File

@@ -1,453 +1,453 @@
/*
* 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.io.file;
import java.math.BigDecimal;
import java.text.ParseException;
import junit.framework.TestCase;
import org.springframework.batch.io.file.mapping.DefaultFieldSet;
import org.springframework.batch.io.file.mapping.FieldSet;
public class FieldSetTests extends TestCase {
FieldSet fieldSet;
String[] tokens;
String[] names;
protected void setUp() throws Exception {
super.setUp();
tokens = new String[] { "TestString", "true", "C", "10", "-472", "354224", "543", "124.3", "424.3", "324",
null, "2007-10-12", "12-10-2007", "" };
names = new String[] { "String", "Boolean", "Char", "Byte", "Short", "Integer", "Long", "Float", "Double",
"BigDecimal", "Null", "Date", "DatePattern", "BlankInput" };
fieldSet = new DefaultFieldSet(tokens, names);
assertEquals(14, fieldSet.getFieldCount());
}
public void testNames() throws Exception {
assertEquals(fieldSet.getFieldCount(), fieldSet.getNames().length);
}
public void testNamesNotKnown() throws Exception {
fieldSet = new DefaultFieldSet(new String[]{"foo"});
try {
fieldSet.getNames();
fail("Expected IllegalStateException");
} catch (IllegalStateException e) {
// expected
}
}
public void testReadString() throws ParseException {
assertEquals(fieldSet.readString(0), "TestString");
assertEquals(fieldSet.readString("String"), "TestString");
}
public void testReadChar() throws Exception {
assertTrue(fieldSet.readChar(2) == 'C');
assertTrue(fieldSet.readChar("Char") == 'C');
}
public void testReadBooleanTrue() throws Exception {
assertTrue(fieldSet.readBoolean(1));
assertTrue(fieldSet.readBoolean("Boolean"));
}
public void testReadByte() throws Exception {
assertTrue(fieldSet.readByte(3) == 10);
assertTrue(fieldSet.readByte("Byte") == 10);
}
public void testReadShort() throws Exception {
assertTrue(fieldSet.readShort(4) == -472);
assertTrue(fieldSet.readShort("Short") == -472);
}
public void testReadFloat() throws Exception {
assertTrue(fieldSet.readFloat(7) == 124.3F);
assertTrue(fieldSet.readFloat("Float") == 124.3F);
}
public void testReadDouble() throws Exception {
assertTrue(fieldSet.readDouble(8) == 424.3);
assertTrue(fieldSet.readDouble("Double") == 424.3);
}
public void testReadBigDecimal() throws Exception {
BigDecimal bd = new BigDecimal(324);
assertEquals(fieldSet.readBigDecimal(9), bd);
assertEquals(fieldSet.readBigDecimal("BigDecimal"), bd);
}
public void testReadBigDecimalWithDefaultvalue() throws Exception {
BigDecimal bd = new BigDecimal(324);
assertEquals(bd, fieldSet.readBigDecimal(10, bd));
assertEquals(bd, fieldSet.readBigDecimal("Null", bd));
}
public void testReadNonExistentField() throws Exception {
try {
fieldSet.readString("something");
fail("field set returns value even value was never put in!");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("something") > 0);
}
}
public void testReadIndexOutOfRange() throws Exception {
try {
fieldSet.readShort(-1);
fail("field set returns value even index is out of range!");
}
catch (IndexOutOfBoundsException e) {
assertTrue(true);
}
try {
fieldSet.readShort(99);
fail("field set returns value even index is out of range!");
}
catch (Exception e) {
assertTrue(true);
}
}
public void testReadBooleanWithTrueValue() {
assertTrue(fieldSet.readBoolean(1, "true"));
assertFalse(fieldSet.readBoolean(1, "incorrect trueValue"));
assertTrue(fieldSet.readBoolean("Boolean", "true"));
assertFalse(fieldSet.readBoolean("Boolean", "incorrect trueValue"));
}
public void testReadBooleanFalse() {
fieldSet = new DefaultFieldSet(new String[] { "false" });
assertFalse(fieldSet.readBoolean(0));
}
public void testReadCharException() {
try {
fieldSet.readChar(1);
fail("the value read was not a character, exception expected");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
fieldSet.readChar("Boolean");
fail("the value read was not a character, exception expected");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testReadInt() throws Exception {
assertEquals(354224, fieldSet.readInt(5));
assertEquals(354224, fieldSet.readInt("Integer"));
}
public void testReadBlankInt(){
//Trying to parse a blank field as an integer, but without a default
//value should throw a NumberFormatException
try{
fieldSet.readInt(13);
fail();
}
catch(NumberFormatException ex){
//expected
}
try{
fieldSet.readInt("BlankInput");
fail();
}
catch(NumberFormatException ex){
//expected
}
}
public void testReadLong() throws Exception {
assertEquals(543, fieldSet.readLong(6));
assertEquals(543, fieldSet.readLong("Long"));
}
public void testReadLongWithPadding() throws Exception {
fieldSet = new DefaultFieldSet(new String[] {"000009"});
assertEquals(9, fieldSet.readLong(0));
}
public void testReadIntWithNullValue() {
assertEquals(5, fieldSet.readInt(10, 5));
assertEquals(5, fieldSet.readInt("Null", 5));
}
public void testReadIntWithDefaultAndNotNull() throws Exception {
assertEquals(354224, fieldSet.readInt(5, 5));
assertEquals(354224, fieldSet.readInt("Integer", 5));
}
public void testReadLongWithNullValue() {
int defaultValue = 5;
int indexOfNull = 10;
int indexNotNull = 6;
String nameNull = "Null";
String nameNotNull = "Long";
long longValueAtIndex = 543;
assertEquals(fieldSet.readLong(indexOfNull, defaultValue), defaultValue);
assertEquals(fieldSet.readLong(indexNotNull, defaultValue), longValueAtIndex);
assertEquals(fieldSet.readLong(nameNull, defaultValue), defaultValue);
assertEquals(fieldSet.readLong(nameNotNull, defaultValue), longValueAtIndex);
}
public void testReadBigDecimalInvalid() {
int index = 0;
try {
fieldSet.readBigDecimal(index);
fail("field value is not a number, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("TestString") > 0);
}
}
public void testReadBigDecimalByNameInvalid() throws Exception {
try {
fieldSet.readBigDecimal("String");
fail("field value is not a number, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("TestString") > 0);
assertTrue(e.getMessage().indexOf("name: [String]") > 0);
}
}
public void testReadDate() throws Exception {
assertNotNull(fieldSet.readDate(11));
assertNotNull(fieldSet.readDate("Date"));
}
public void testReadDateInvalid() throws Exception {
try {
fieldSet.readDate(0);
fail("field value is not a date, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("TestString") > 0);
}
}
public void testReadDateInvalidByName() throws Exception {
try {
fieldSet.readDate("String");
fail("field value is not a date, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("name: [String]") > 0);
}
}
public void testReadDateInvalidWithPattern() throws Exception {
try {
fieldSet.readDate(0, "dd-MM-yyyy");
fail("field value is not a date, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("dd-MM-yyyy") > 0);
}
}
public void testReadDateByNameInvalidWithPattern() throws Exception {
try {
fieldSet.readDate("String", "dd-MM-yyyy");
fail("field value is not a date, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("dd-MM-yyyy") > 0);
assertTrue(e.getMessage().indexOf("String") > 0);
}
}
public void testEquals() {
assertEquals(fieldSet, fieldSet);
assertEquals(fieldSet, new DefaultFieldSet(tokens));
String[] tokens1 = new String[] { "token1" };
String[] tokens2 = new String[] { "token1" };
FieldSet fs1 = new DefaultFieldSet(tokens1);
FieldSet fs2 = new DefaultFieldSet(tokens2);
assertEquals(fs1, fs2);
}
public void testNullField() {
assertEquals(null, fieldSet.readString(10));
}
public void testEqualsNull() {
assertFalse(fieldSet.equals(null));
}
public void testEqualsNullTokens() {
assertFalse(new DefaultFieldSet(null).equals(fieldSet));
}
public void testEqualsNotEqual() throws Exception {
String[] tokens1 = new String[] { "token1" };
String[] tokens2 = new String[] { "token1", "token2" };
FieldSet fs1 = new DefaultFieldSet(tokens1);
FieldSet fs2 = new DefaultFieldSet(tokens2);
assertFalse(fs1.equals(fs2));
}
public void testHashCode() throws Exception {
assertEquals(fieldSet.hashCode(), new DefaultFieldSet(tokens).hashCode());
}
public void testHashCodeWithNullTokens() throws Exception {
assertEquals(0, new DefaultFieldSet(null).hashCode());
}
public void testConstructor() throws Exception {
try {
new DefaultFieldSet(new String[] { "1", "2" }, new String[] { "a" });
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
public void testToStringWithNames() throws Exception {
fieldSet = new DefaultFieldSet(new String[] { "foo", "bar" }, new String[] { "Foo", "Bar" });
assertTrue(fieldSet.toString().indexOf("Foo=foo") >= 0);
}
public void testToStringWithoutNames() throws Exception {
fieldSet = new DefaultFieldSet(new String[] { "foo", "bar" });
assertTrue(fieldSet.toString().indexOf("foo") >= 0);
}
public void testToStringNullTokens() throws Exception {
fieldSet = new DefaultFieldSet(null);
assertEquals("", fieldSet.toString());
}
public void testProperties() throws Exception {
assertEquals("foo", new DefaultFieldSet(new String[] { "foo", "bar" }, new String[] { "Foo", "Bar" }).getProperties()
.getProperty("Foo"));
}
public void testPropertiesWithNoNames() throws Exception {
try {
new DefaultFieldSet(new String[] { "foo", "bar" }).getProperties();
fail("Expected IllegalStateException");
}
catch (IllegalStateException e) {
// expected
}
}
public void testPropertiesWithWhiteSpace() throws Exception{
assertEquals("bar", new DefaultFieldSet(new String[] { "foo", "bar " }, new String[] { "Foo", "Bar"}).getProperties().getProperty("Bar"));
}
public void testPropertiesWithNullValues() throws Exception{
fieldSet = new DefaultFieldSet(new String[] { null, "bar" }, new String[] { "Foo", "Bar"});
assertEquals("bar", fieldSet.getProperties().getProperty("Bar"));
assertEquals(null, fieldSet.getProperties().getProperty("Foo"));
}
public void testAccessByNameWhenNamesMissing() throws Exception {
try {
new DefaultFieldSet(new String[] { "1", "2" }).readInt("a");
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
public void testGetValues() {
String[] values = fieldSet.getValues();
assertEquals(tokens.length, values.length);
for (int i = 0; i < tokens.length; i++) {
assertEquals(tokens[i], values[i]);
}
}
public void testPaddedLong(){
FieldSet fs = new DefaultFieldSet(new String[]{"00000009"});
long value = fs.readLong(0);
assertEquals(value, 9);
}
public void testReadRawString() {
String name = "fieldName";
String value = " string with trailing whitespace ";
FieldSet fs = new DefaultFieldSet(new String[] { value }, new String[]{ name });
assertEquals(value, fs.readRawString(0));
assertEquals(value, fs.readRawString(name));
}
}
/*
* 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.io.file;
import java.math.BigDecimal;
import java.text.ParseException;
import junit.framework.TestCase;
import org.springframework.batch.io.file.mapping.DefaultFieldSet;
import org.springframework.batch.io.file.mapping.FieldSet;
public class FieldSetTests extends TestCase {
FieldSet fieldSet;
String[] tokens;
String[] names;
protected void setUp() throws Exception {
super.setUp();
tokens = new String[] { "TestString", "true", "C", "10", "-472", "354224", "543", "124.3", "424.3", "324",
null, "2007-10-12", "12-10-2007", "" };
names = new String[] { "String", "Boolean", "Char", "Byte", "Short", "Integer", "Long", "Float", "Double",
"BigDecimal", "Null", "Date", "DatePattern", "BlankInput" };
fieldSet = new DefaultFieldSet(tokens, names);
assertEquals(14, fieldSet.getFieldCount());
}
public void testNames() throws Exception {
assertEquals(fieldSet.getFieldCount(), fieldSet.getNames().length);
}
public void testNamesNotKnown() throws Exception {
fieldSet = new DefaultFieldSet(new String[]{"foo"});
try {
fieldSet.getNames();
fail("Expected IllegalStateException");
} catch (IllegalStateException e) {
// expected
}
}
public void testReadString() throws ParseException {
assertEquals(fieldSet.readString(0), "TestString");
assertEquals(fieldSet.readString("String"), "TestString");
}
public void testReadChar() throws Exception {
assertTrue(fieldSet.readChar(2) == 'C');
assertTrue(fieldSet.readChar("Char") == 'C');
}
public void testReadBooleanTrue() throws Exception {
assertTrue(fieldSet.readBoolean(1));
assertTrue(fieldSet.readBoolean("Boolean"));
}
public void testReadByte() throws Exception {
assertTrue(fieldSet.readByte(3) == 10);
assertTrue(fieldSet.readByte("Byte") == 10);
}
public void testReadShort() throws Exception {
assertTrue(fieldSet.readShort(4) == -472);
assertTrue(fieldSet.readShort("Short") == -472);
}
public void testReadFloat() throws Exception {
assertTrue(fieldSet.readFloat(7) == 124.3F);
assertTrue(fieldSet.readFloat("Float") == 124.3F);
}
public void testReadDouble() throws Exception {
assertTrue(fieldSet.readDouble(8) == 424.3);
assertTrue(fieldSet.readDouble("Double") == 424.3);
}
public void testReadBigDecimal() throws Exception {
BigDecimal bd = new BigDecimal(324);
assertEquals(fieldSet.readBigDecimal(9), bd);
assertEquals(fieldSet.readBigDecimal("BigDecimal"), bd);
}
public void testReadBigDecimalWithDefaultvalue() throws Exception {
BigDecimal bd = new BigDecimal(324);
assertEquals(bd, fieldSet.readBigDecimal(10, bd));
assertEquals(bd, fieldSet.readBigDecimal("Null", bd));
}
public void testReadNonExistentField() throws Exception {
try {
fieldSet.readString("something");
fail("field set returns value even value was never put in!");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("something") > 0);
}
}
public void testReadIndexOutOfRange() throws Exception {
try {
fieldSet.readShort(-1);
fail("field set returns value even index is out of range!");
}
catch (IndexOutOfBoundsException e) {
assertTrue(true);
}
try {
fieldSet.readShort(99);
fail("field set returns value even index is out of range!");
}
catch (Exception e) {
assertTrue(true);
}
}
public void testReadBooleanWithTrueValue() {
assertTrue(fieldSet.readBoolean(1, "true"));
assertFalse(fieldSet.readBoolean(1, "incorrect trueValue"));
assertTrue(fieldSet.readBoolean("Boolean", "true"));
assertFalse(fieldSet.readBoolean("Boolean", "incorrect trueValue"));
}
public void testReadBooleanFalse() {
fieldSet = new DefaultFieldSet(new String[] { "false" });
assertFalse(fieldSet.readBoolean(0));
}
public void testReadCharException() {
try {
fieldSet.readChar(1);
fail("the value read was not a character, exception expected");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
fieldSet.readChar("Boolean");
fail("the value read was not a character, exception expected");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testReadInt() throws Exception {
assertEquals(354224, fieldSet.readInt(5));
assertEquals(354224, fieldSet.readInt("Integer"));
}
public void testReadBlankInt(){
//Trying to parse a blank field as an integer, but without a default
//value should throw a NumberFormatException
try{
fieldSet.readInt(13);
fail();
}
catch(NumberFormatException ex){
//expected
}
try{
fieldSet.readInt("BlankInput");
fail();
}
catch(NumberFormatException ex){
//expected
}
}
public void testReadLong() throws Exception {
assertEquals(543, fieldSet.readLong(6));
assertEquals(543, fieldSet.readLong("Long"));
}
public void testReadLongWithPadding() throws Exception {
fieldSet = new DefaultFieldSet(new String[] {"000009"});
assertEquals(9, fieldSet.readLong(0));
}
public void testReadIntWithNullValue() {
assertEquals(5, fieldSet.readInt(10, 5));
assertEquals(5, fieldSet.readInt("Null", 5));
}
public void testReadIntWithDefaultAndNotNull() throws Exception {
assertEquals(354224, fieldSet.readInt(5, 5));
assertEquals(354224, fieldSet.readInt("Integer", 5));
}
public void testReadLongWithNullValue() {
int defaultValue = 5;
int indexOfNull = 10;
int indexNotNull = 6;
String nameNull = "Null";
String nameNotNull = "Long";
long longValueAtIndex = 543;
assertEquals(fieldSet.readLong(indexOfNull, defaultValue), defaultValue);
assertEquals(fieldSet.readLong(indexNotNull, defaultValue), longValueAtIndex);
assertEquals(fieldSet.readLong(nameNull, defaultValue), defaultValue);
assertEquals(fieldSet.readLong(nameNotNull, defaultValue), longValueAtIndex);
}
public void testReadBigDecimalInvalid() {
int index = 0;
try {
fieldSet.readBigDecimal(index);
fail("field value is not a number, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("TestString") > 0);
}
}
public void testReadBigDecimalByNameInvalid() throws Exception {
try {
fieldSet.readBigDecimal("String");
fail("field value is not a number, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("TestString") > 0);
assertTrue(e.getMessage().indexOf("name: [String]") > 0);
}
}
public void testReadDate() throws Exception {
assertNotNull(fieldSet.readDate(11));
assertNotNull(fieldSet.readDate("Date"));
}
public void testReadDateInvalid() throws Exception {
try {
fieldSet.readDate(0);
fail("field value is not a date, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("TestString") > 0);
}
}
public void testReadDateInvalidByName() throws Exception {
try {
fieldSet.readDate("String");
fail("field value is not a date, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("name: [String]") > 0);
}
}
public void testReadDateInvalidWithPattern() throws Exception {
try {
fieldSet.readDate(0, "dd-MM-yyyy");
fail("field value is not a date, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("dd-MM-yyyy") > 0);
}
}
public void testReadDateByNameInvalidWithPattern() throws Exception {
try {
fieldSet.readDate("String", "dd-MM-yyyy");
fail("field value is not a date, exception expected");
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().indexOf("dd-MM-yyyy") > 0);
assertTrue(e.getMessage().indexOf("String") > 0);
}
}
public void testEquals() {
assertEquals(fieldSet, fieldSet);
assertEquals(fieldSet, new DefaultFieldSet(tokens));
String[] tokens1 = new String[] { "token1" };
String[] tokens2 = new String[] { "token1" };
FieldSet fs1 = new DefaultFieldSet(tokens1);
FieldSet fs2 = new DefaultFieldSet(tokens2);
assertEquals(fs1, fs2);
}
public void testNullField() {
assertEquals(null, fieldSet.readString(10));
}
public void testEqualsNull() {
assertFalse(fieldSet.equals(null));
}
public void testEqualsNullTokens() {
assertFalse(new DefaultFieldSet(null).equals(fieldSet));
}
public void testEqualsNotEqual() throws Exception {
String[] tokens1 = new String[] { "token1" };
String[] tokens2 = new String[] { "token1", "token2" };
FieldSet fs1 = new DefaultFieldSet(tokens1);
FieldSet fs2 = new DefaultFieldSet(tokens2);
assertFalse(fs1.equals(fs2));
}
public void testHashCode() throws Exception {
assertEquals(fieldSet.hashCode(), new DefaultFieldSet(tokens).hashCode());
}
public void testHashCodeWithNullTokens() throws Exception {
assertEquals(0, new DefaultFieldSet(null).hashCode());
}
public void testConstructor() throws Exception {
try {
new DefaultFieldSet(new String[] { "1", "2" }, new String[] { "a" });
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
public void testToStringWithNames() throws Exception {
fieldSet = new DefaultFieldSet(new String[] { "foo", "bar" }, new String[] { "Foo", "Bar" });
assertTrue(fieldSet.toString().indexOf("Foo=foo") >= 0);
}
public void testToStringWithoutNames() throws Exception {
fieldSet = new DefaultFieldSet(new String[] { "foo", "bar" });
assertTrue(fieldSet.toString().indexOf("foo") >= 0);
}
public void testToStringNullTokens() throws Exception {
fieldSet = new DefaultFieldSet(null);
assertEquals("", fieldSet.toString());
}
public void testProperties() throws Exception {
assertEquals("foo", new DefaultFieldSet(new String[] { "foo", "bar" }, new String[] { "Foo", "Bar" }).getProperties()
.getProperty("Foo"));
}
public void testPropertiesWithNoNames() throws Exception {
try {
new DefaultFieldSet(new String[] { "foo", "bar" }).getProperties();
fail("Expected IllegalStateException");
}
catch (IllegalStateException e) {
// expected
}
}
public void testPropertiesWithWhiteSpace() throws Exception{
assertEquals("bar", new DefaultFieldSet(new String[] { "foo", "bar " }, new String[] { "Foo", "Bar"}).getProperties().getProperty("Bar"));
}
public void testPropertiesWithNullValues() throws Exception{
fieldSet = new DefaultFieldSet(new String[] { null, "bar" }, new String[] { "Foo", "Bar"});
assertEquals("bar", fieldSet.getProperties().getProperty("Bar"));
assertEquals(null, fieldSet.getProperties().getProperty("Foo"));
}
public void testAccessByNameWhenNamesMissing() throws Exception {
try {
new DefaultFieldSet(new String[] { "1", "2" }).readInt("a");
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
public void testGetValues() {
String[] values = fieldSet.getValues();
assertEquals(tokens.length, values.length);
for (int i = 0; i < tokens.length; i++) {
assertEquals(tokens[i], values[i]);
}
}
public void testPaddedLong(){
FieldSet fs = new DefaultFieldSet(new String[]{"00000009"});
long value = fs.readLong(0);
assertEquals(value, 9);
}
public void testReadRawString() {
String name = "fieldName";
String value = " string with trailing whitespace ";
FieldSet fs = new DefaultFieldSet(new String[] { value }, new String[]{ name });
assertEquals(value, fs.readRawString(0));
assertEquals(value, fs.readRawString(name));
}
}

View File

@@ -1,339 +1,339 @@
/*
* 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.io.file;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
import org.springframework.batch.io.exception.FlatFileParsingException;
import org.springframework.batch.io.file.mapping.DefaultFieldSet;
import org.springframework.batch.io.file.mapping.FieldSet;
import org.springframework.batch.io.file.mapping.FieldSetMapper;
import org.springframework.batch.io.file.separator.DefaultRecordSeparatorPolicy;
import org.springframework.batch.io.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.io.file.transform.LineTokenizer;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.exception.StreamException;
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
/**
* Tests for {@link FlatFileItemReader} - the fundamental item reading functionality.
*
* @see FlatFileItemReaderAdvancedTests
* @author Dave Syer
*/
public class FlatFileItemReaderBasicTests extends TestCase {
// object under test
private FlatFileItemReader itemReader = new FlatFileItemReader();
// common value used for writing to a file
private String TEST_STRING = "FlatFileInputTemplate-TestData";
private String TEST_OUTPUT = "[FlatFileInputTemplate-TestData]";
private ExecutionContext executionContext;
// simple stub instead of a realistic tokenizer
private LineTokenizer tokenizer = new LineTokenizer() {
public FieldSet tokenize(String line) {
return new DefaultFieldSet(new String[] { line });
}
};
private FieldSetMapper fieldSetMapper = new FieldSetMapper(){
public Object mapLine(FieldSet fs) {
return fs;
}
};
/**
* Create inputFile, inject mock/stub dependencies for tested object,
* initialize the tested object
*/
protected void setUp() throws Exception {
itemReader.setResource(getInputResource(TEST_STRING));
itemReader.setLineTokenizer(tokenizer);
itemReader.setFieldSetMapper(fieldSetMapper);
itemReader.afterPropertiesSet();
executionContext = new ExecutionContext();
}
/**
* Release resources.
*/
protected void tearDown() throws Exception {
itemReader.close(null);
}
private Resource getInputResource(String input) {
return new ByteArrayResource(input.getBytes());
}
/**
* Regular usage of <code>read</code> method
*/
public void testRead() throws Exception {
itemReader.open(executionContext);
assertEquals("[FlatFileInputTemplate-TestData]", itemReader.read().toString());
}
/**
* Regular usage of <code>read</code> method
*/
public void testReadExhausted() throws Exception {
itemReader.open(executionContext);
assertEquals("[FlatFileInputTemplate-TestData]", itemReader.read().toString());
assertEquals(null, itemReader.read());
}
/**
* Regular usage of <code>read</code> method
*/
public void testReadWithTokenizerError() throws Exception {
itemReader.setLineTokenizer(new LineTokenizer() {
public FieldSet tokenize(String line) {
throw new RuntimeException("foo");
}
});
try {
itemReader.open(executionContext);
itemReader.read();
fail("Expected ParsingException");
} catch (FlatFileParsingException e) {
assertEquals(e.getInput(), TEST_STRING);
assertEquals(e.getLineNumber(), 1);
}
}
public void testReadWithMapperError() throws Exception {
itemReader.setFieldSetMapper(new FieldSetMapper(){
public Object mapLine(FieldSet fs) {
throw new RuntimeException("foo");
}
});
try {
itemReader.open(executionContext);
itemReader.read();
fail("Expected ParsingException");
} catch (FlatFileParsingException e) {
assertEquals(e.getInput(), TEST_STRING);
assertEquals(e.getLineNumber(), 1);
}
}
public void testReadBeforeOpen() throws Exception {
itemReader = new FlatFileItemReader();
itemReader.setResource(getInputResource(TEST_STRING));
itemReader.setFieldSetMapper(fieldSetMapper);
try {
itemReader.read();
fail("Expected StreamException");
} catch (StreamException e) {
assertTrue(e.getMessage().contains("open"));
}
}
public void testCloseBeforeOpen() throws Exception {
itemReader = new FlatFileItemReader();
itemReader.setResource(getInputResource(TEST_STRING));
itemReader.setFieldSetMapper(fieldSetMapper);
itemReader.close(null);
// The open does not happen automatically on a read...
itemReader.open(executionContext);
assertEquals("[FlatFileInputTemplate-TestData]", itemReader.read().toString());
}
public void testInitializationWithNullResource() throws Exception {
itemReader = new FlatFileItemReader();
try {
itemReader.afterPropertiesSet();
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
public void testOpenTwiceHasNoEffect() throws Exception {
itemReader.open(executionContext);
testRead();
}
public void testSetValidEncoding() throws Exception {
itemReader = new FlatFileItemReader();
itemReader.setEncoding("UTF-8");
itemReader.setResource(getInputResource(TEST_STRING));
itemReader.setFieldSetMapper(fieldSetMapper);
itemReader.open(executionContext);
testRead();
}
public void testSetNullEncoding() throws Exception {
itemReader = new FlatFileItemReader();
itemReader.setEncoding(null);
itemReader.setResource(getInputResource(TEST_STRING));
try {
itemReader.open(executionContext);
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
public void testSetInvalidEncoding() throws Exception {
itemReader = new FlatFileItemReader();
itemReader.setEncoding("foo");
itemReader.setResource(getInputResource(TEST_STRING));
try {
itemReader.open(executionContext);
fail("Expected BatchEnvironmentException");
}
catch (StreamException e) {
// expected
assertEquals("foo", e.getCause().getMessage());
}
}
public void testEncoding() throws Exception {
itemReader.setEncoding("UTF-8");
testRead();
}
public void testRecordSeparator() throws Exception {
itemReader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
testRead();
}
public void testComments() throws Exception {
itemReader.setResource(getInputResource("% Comment\n"+TEST_STRING));
itemReader.setComments(new String[] {"%"});
testRead();
}
/**
* Header line is skipped and used to setup fieldSet column names.
*/
public void testColumnNamesInHeader() throws Exception {
final String INPUT = "name1|name2\nvalue1|value2\nvalue3|value4";
itemReader = new FlatFileItemReader();
itemReader.setResource(getInputResource(INPUT));
itemReader.setLineTokenizer(new DelimitedLineTokenizer('|'));
itemReader.setFieldSetMapper(fieldSetMapper);
itemReader.setFirstLineIsHeader(true);
itemReader.afterPropertiesSet();
itemReader.open(executionContext);
FieldSet fs = (FieldSet) itemReader.read();
assertEquals("value1", fs.readString("name1"));
assertEquals("value2", fs.readString("name2"));
fs = (FieldSet) itemReader.read();
assertEquals("value3", fs.readString("name1"));
assertEquals("value4", fs.readString("name2"));
}
/**
* Header line is skipped and used to setup fieldSet column names.
*/
public void testLinesToSkip() throws Exception {
final String INPUT = "foo bar spam\none two\nthree four";
itemReader = new FlatFileItemReader();
itemReader.setResource(getInputResource(INPUT));
itemReader.setLineTokenizer(new DelimitedLineTokenizer(' '));
itemReader.setFieldSetMapper(fieldSetMapper);
itemReader.setLinesToSkip(1);
itemReader.afterPropertiesSet();
itemReader.open(executionContext);
FieldSet fs = (FieldSet) itemReader.read();
assertEquals("one", fs.readString(0));
assertEquals("two", fs.readString(1));
fs = (FieldSet) itemReader.read();
assertEquals("three", fs.readString(0));
assertEquals("four", fs.readString(1));
}
public void testNonExistantResource() throws Exception{
Resource resource = new NonExistentResource();
FlatFileItemReader testReader = new FlatFileItemReader();
testReader.setResource(resource);
testReader.setLineTokenizer(tokenizer);
testReader.setFieldSetMapper(fieldSetMapper);
testReader.setResource(resource);
//afterPropertiesSet should only throw an exception if the Resource is null
testReader.afterPropertiesSet();
try{
testReader.open(executionContext);
fail();
}catch(IllegalStateException ex){
//expected
}
}
public void testRuntimeFileCreation() throws Exception{
Resource resource = new NonExistentResource();
FlatFileItemReader testReader = new FlatFileItemReader();
testReader.setResource(resource);
testReader.setLineTokenizer(tokenizer);
testReader.setFieldSetMapper(fieldSetMapper);
testReader.setResource(resource);
//afterPropertiesSet should only throw an exception if the Resource is null
testReader.afterPropertiesSet();
//replace the resource to simulate runtime resource creation
testReader.setResource(getInputResource(TEST_STRING));
testReader.open(executionContext);
assertEquals(TEST_OUTPUT, testReader.read().toString());
}
private class NonExistentResource extends AbstractResource{
public NonExistentResource() {
}
public boolean exists() {
return false;
}
public String getDescription() {
return "NonExistantResource";
}
public InputStream getInputStream() throws IOException {
return null;
}
}
}
/*
* 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.io.file;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
import org.springframework.batch.io.exception.FlatFileParsingException;
import org.springframework.batch.io.file.mapping.DefaultFieldSet;
import org.springframework.batch.io.file.mapping.FieldSet;
import org.springframework.batch.io.file.mapping.FieldSetMapper;
import org.springframework.batch.io.file.separator.DefaultRecordSeparatorPolicy;
import org.springframework.batch.io.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.io.file.transform.LineTokenizer;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.exception.StreamException;
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
/**
* Tests for {@link FlatFileItemReader} - the fundamental item reading functionality.
*
* @see FlatFileItemReaderAdvancedTests
* @author Dave Syer
*/
public class FlatFileItemReaderBasicTests extends TestCase {
// object under test
private FlatFileItemReader itemReader = new FlatFileItemReader();
// common value used for writing to a file
private String TEST_STRING = "FlatFileInputTemplate-TestData";
private String TEST_OUTPUT = "[FlatFileInputTemplate-TestData]";
private ExecutionContext executionContext;
// simple stub instead of a realistic tokenizer
private LineTokenizer tokenizer = new LineTokenizer() {
public FieldSet tokenize(String line) {
return new DefaultFieldSet(new String[] { line });
}
};
private FieldSetMapper fieldSetMapper = new FieldSetMapper(){
public Object mapLine(FieldSet fs) {
return fs;
}
};
/**
* Create inputFile, inject mock/stub dependencies for tested object,
* initialize the tested object
*/
protected void setUp() throws Exception {
itemReader.setResource(getInputResource(TEST_STRING));
itemReader.setLineTokenizer(tokenizer);
itemReader.setFieldSetMapper(fieldSetMapper);
itemReader.afterPropertiesSet();
executionContext = new ExecutionContext();
}
/**
* Release resources.
*/
protected void tearDown() throws Exception {
itemReader.close(null);
}
private Resource getInputResource(String input) {
return new ByteArrayResource(input.getBytes());
}
/**
* Regular usage of <code>read</code> method
*/
public void testRead() throws Exception {
itemReader.open(executionContext);
assertEquals("[FlatFileInputTemplate-TestData]", itemReader.read().toString());
}
/**
* Regular usage of <code>read</code> method
*/
public void testReadExhausted() throws Exception {
itemReader.open(executionContext);
assertEquals("[FlatFileInputTemplate-TestData]", itemReader.read().toString());
assertEquals(null, itemReader.read());
}
/**
* Regular usage of <code>read</code> method
*/
public void testReadWithTokenizerError() throws Exception {
itemReader.setLineTokenizer(new LineTokenizer() {
public FieldSet tokenize(String line) {
throw new RuntimeException("foo");
}
});
try {
itemReader.open(executionContext);
itemReader.read();
fail("Expected ParsingException");
} catch (FlatFileParsingException e) {
assertEquals(e.getInput(), TEST_STRING);
assertEquals(e.getLineNumber(), 1);
}
}
public void testReadWithMapperError() throws Exception {
itemReader.setFieldSetMapper(new FieldSetMapper(){
public Object mapLine(FieldSet fs) {
throw new RuntimeException("foo");
}
});
try {
itemReader.open(executionContext);
itemReader.read();
fail("Expected ParsingException");
} catch (FlatFileParsingException e) {
assertEquals(e.getInput(), TEST_STRING);
assertEquals(e.getLineNumber(), 1);
}
}
public void testReadBeforeOpen() throws Exception {
itemReader = new FlatFileItemReader();
itemReader.setResource(getInputResource(TEST_STRING));
itemReader.setFieldSetMapper(fieldSetMapper);
try {
itemReader.read();
fail("Expected StreamException");
} catch (StreamException e) {
assertTrue(e.getMessage().contains("open"));
}
}
public void testCloseBeforeOpen() throws Exception {
itemReader = new FlatFileItemReader();
itemReader.setResource(getInputResource(TEST_STRING));
itemReader.setFieldSetMapper(fieldSetMapper);
itemReader.close(null);
// The open does not happen automatically on a read...
itemReader.open(executionContext);
assertEquals("[FlatFileInputTemplate-TestData]", itemReader.read().toString());
}
public void testInitializationWithNullResource() throws Exception {
itemReader = new FlatFileItemReader();
try {
itemReader.afterPropertiesSet();
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
public void testOpenTwiceHasNoEffect() throws Exception {
itemReader.open(executionContext);
testRead();
}
public void testSetValidEncoding() throws Exception {
itemReader = new FlatFileItemReader();
itemReader.setEncoding("UTF-8");
itemReader.setResource(getInputResource(TEST_STRING));
itemReader.setFieldSetMapper(fieldSetMapper);
itemReader.open(executionContext);
testRead();
}
public void testSetNullEncoding() throws Exception {
itemReader = new FlatFileItemReader();
itemReader.setEncoding(null);
itemReader.setResource(getInputResource(TEST_STRING));
try {
itemReader.open(executionContext);
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
public void testSetInvalidEncoding() throws Exception {
itemReader = new FlatFileItemReader();
itemReader.setEncoding("foo");
itemReader.setResource(getInputResource(TEST_STRING));
try {
itemReader.open(executionContext);
fail("Expected BatchEnvironmentException");
}
catch (StreamException e) {
// expected
assertEquals("foo", e.getCause().getMessage());
}
}
public void testEncoding() throws Exception {
itemReader.setEncoding("UTF-8");
testRead();
}
public void testRecordSeparator() throws Exception {
itemReader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
testRead();
}
public void testComments() throws Exception {
itemReader.setResource(getInputResource("% Comment\n"+TEST_STRING));
itemReader.setComments(new String[] {"%"});
testRead();
}
/**
* Header line is skipped and used to setup fieldSet column names.
*/
public void testColumnNamesInHeader() throws Exception {
final String INPUT = "name1|name2\nvalue1|value2\nvalue3|value4";
itemReader = new FlatFileItemReader();
itemReader.setResource(getInputResource(INPUT));
itemReader.setLineTokenizer(new DelimitedLineTokenizer('|'));
itemReader.setFieldSetMapper(fieldSetMapper);
itemReader.setFirstLineIsHeader(true);
itemReader.afterPropertiesSet();
itemReader.open(executionContext);
FieldSet fs = (FieldSet) itemReader.read();
assertEquals("value1", fs.readString("name1"));
assertEquals("value2", fs.readString("name2"));
fs = (FieldSet) itemReader.read();
assertEquals("value3", fs.readString("name1"));
assertEquals("value4", fs.readString("name2"));
}
/**
* Header line is skipped and used to setup fieldSet column names.
*/
public void testLinesToSkip() throws Exception {
final String INPUT = "foo bar spam\none two\nthree four";
itemReader = new FlatFileItemReader();
itemReader.setResource(getInputResource(INPUT));
itemReader.setLineTokenizer(new DelimitedLineTokenizer(' '));
itemReader.setFieldSetMapper(fieldSetMapper);
itemReader.setLinesToSkip(1);
itemReader.afterPropertiesSet();
itemReader.open(executionContext);
FieldSet fs = (FieldSet) itemReader.read();
assertEquals("one", fs.readString(0));
assertEquals("two", fs.readString(1));
fs = (FieldSet) itemReader.read();
assertEquals("three", fs.readString(0));
assertEquals("four", fs.readString(1));
}
public void testNonExistantResource() throws Exception{
Resource resource = new NonExistentResource();
FlatFileItemReader testReader = new FlatFileItemReader();
testReader.setResource(resource);
testReader.setLineTokenizer(tokenizer);
testReader.setFieldSetMapper(fieldSetMapper);
testReader.setResource(resource);
//afterPropertiesSet should only throw an exception if the Resource is null
testReader.afterPropertiesSet();
try{
testReader.open(executionContext);
fail();
}catch(IllegalStateException ex){
//expected
}
}
public void testRuntimeFileCreation() throws Exception{
Resource resource = new NonExistentResource();
FlatFileItemReader testReader = new FlatFileItemReader();
testReader.setResource(resource);
testReader.setLineTokenizer(tokenizer);
testReader.setFieldSetMapper(fieldSetMapper);
testReader.setResource(resource);
//afterPropertiesSet should only throw an exception if the Resource is null
testReader.afterPropertiesSet();
//replace the resource to simulate runtime resource creation
testReader.setResource(getInputResource(TEST_STRING));
testReader.open(executionContext);
assertEquals(TEST_OUTPUT, testReader.read().toString());
}
private class NonExistentResource extends AbstractResource{
public NonExistentResource() {
}
public boolean exists() {
return false;
}
public String getDescription() {
return "NonExistantResource";
}
public InputStream getInputStream() throws IOException {
return null;
}
}
}

View File

@@ -1,196 +1,196 @@
/*
* 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.io.file;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
import org.springframework.batch.io.file.separator.ResourceLineReader;
import org.springframework.batch.io.file.separator.SuffixRecordSeparatorPolicy;
import org.springframework.batch.item.exception.StreamException;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
/**
* @author Rob Harrop
*/
public class ResourceLineReaderTests extends TestCase {
public void testBadResource() throws Exception {
ResourceLineReader reader = new ResourceLineReader(new InputStreamResource(new InputStream() {
public int read() throws IOException {
throw new IOException("Foo");
}
}));
try {
reader.read();
fail("Expected InputException");
}
catch (StreamException e) {
// expected
assertTrue(e.getMessage().startsWith("Unable to read"));
}
}
public void testRead() throws Exception {
Resource resource = new ByteArrayResource("a,b,c\n1,2,3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
int count = 0;
String line;
while ((line = (String) reader.read()) != null) {
count++;
assertNotNull(line);
}
assertEquals(2, count);
}
public void testCloseTwice() throws Exception {
Resource resource = new ByteArrayResource("a,b,c\n1,2,3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.open();
reader.close(null);
try {
reader.close(null); // just closing a BufferedReader twice should be fine
} catch (Exception e) {
fail("Unexpected Exception "+e);
}
assertEquals("a,b,c", reader.read());
}
public void testEncoding() throws Exception {
Resource resource = new ByteArrayResource("a,b,c\n1,2,3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource, "UTF-8");
int count = 0;
String line;
while ((line = (String) reader.read()) != null) {
count++;
assertNotNull(line);
}
assertEquals(2, count);
}
public void testLineCount() throws Exception {
Resource resource = new ByteArrayResource("1,2,\"3\n4\"\n5,6,7".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
assertEquals(2, reader.getPosition());
}
public void testLineContent() throws Exception {
Resource resource = new ByteArrayResource("1,2,3\n4\n5,6,7".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
assertEquals("1,2,3", reader.read());
assertEquals("4", reader.read());
assertEquals("5,6,7", reader.read());
}
public void testLineContentWhenLineContainsQuotedNewline() throws Exception {
Resource resource = new ByteArrayResource("1,2,\"3\n4\"\n5,6,7".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
assertEquals("1,2,\"3\n4\"", reader.read());
assertEquals("5,6,7", reader.read());
}
public void testLineEndings() throws Exception {
Resource resource = new ByteArrayResource("1\n2\r\n3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
String line = (String) reader.read();
assertEquals("2", line);
assertEquals(2, reader.getPosition());
line = (String) reader.read();
assertEquals("3", line);
assertEquals(3, reader.getPosition());
}
public void testDefaultComments() throws Exception {
Resource resource = new ByteArrayResource("1\n# 2\n3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
String line = (String) reader.read();
assertEquals("3", line);
}
public void testComments() throws Exception {
Resource resource = new ByteArrayResource("1\n-- 2\n3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.setComments(new String[] {"//", "--"});
reader.read();
String line = (String) reader.read();
assertEquals("3", line);
}
public void testCommentOnTheLastLine() throws Exception {
Resource resource = new ByteArrayResource("1\n#last line".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
String line = (String) reader.read();
assertNull(line);
}
public void testResetNewReader() throws Exception {
Resource resource = new ByteArrayResource("1\n4\n5".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.reset();
assertEquals(0, reader.getPosition());
}
public void testMarkReset() throws Exception {
Resource resource = new ByteArrayResource("1\n4\n5".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
assertEquals(1, reader.getPosition());
reader.mark();
reader.read();
assertEquals(2, reader.getPosition());
reader.reset();
reader.read();
assertEquals(2, reader.getPosition());
}
public void testMarkOnFirstRead() throws Exception {
Resource resource = new ByteArrayResource("1\n# 2\n3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
// The first read should do a mark() so the reset goes back to the beginning.
reader.reset();
String line = (String) reader.read();
assertEquals("1", line);
}
public void testMarkAfterClose() throws Exception {
Resource resource = new ByteArrayResource("1\n# 2\n3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
reader.close(null);
reader.mark();
}
public void testNonDefaultRecordSeparatorPolicy() throws Exception {
Resource resource = new ByteArrayResource("1\n\"4\n5\"; \n6".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.setRecordSeparatorPolicy(new SuffixRecordSeparatorPolicy());
assertEquals(0, reader.getPosition());
String line = (String) reader.read();
assertEquals("1\"4\n5\"", line);
}
}
/*
* 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.io.file;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
import org.springframework.batch.io.file.separator.ResourceLineReader;
import org.springframework.batch.io.file.separator.SuffixRecordSeparatorPolicy;
import org.springframework.batch.item.exception.StreamException;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
/**
* @author Rob Harrop
*/
public class ResourceLineReaderTests extends TestCase {
public void testBadResource() throws Exception {
ResourceLineReader reader = new ResourceLineReader(new InputStreamResource(new InputStream() {
public int read() throws IOException {
throw new IOException("Foo");
}
}));
try {
reader.read();
fail("Expected InputException");
}
catch (StreamException e) {
// expected
assertTrue(e.getMessage().startsWith("Unable to read"));
}
}
public void testRead() throws Exception {
Resource resource = new ByteArrayResource("a,b,c\n1,2,3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
int count = 0;
String line;
while ((line = (String) reader.read()) != null) {
count++;
assertNotNull(line);
}
assertEquals(2, count);
}
public void testCloseTwice() throws Exception {
Resource resource = new ByteArrayResource("a,b,c\n1,2,3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.open();
reader.close(null);
try {
reader.close(null); // just closing a BufferedReader twice should be fine
} catch (Exception e) {
fail("Unexpected Exception "+e);
}
assertEquals("a,b,c", reader.read());
}
public void testEncoding() throws Exception {
Resource resource = new ByteArrayResource("a,b,c\n1,2,3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource, "UTF-8");
int count = 0;
String line;
while ((line = (String) reader.read()) != null) {
count++;
assertNotNull(line);
}
assertEquals(2, count);
}
public void testLineCount() throws Exception {
Resource resource = new ByteArrayResource("1,2,\"3\n4\"\n5,6,7".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
assertEquals(2, reader.getPosition());
}
public void testLineContent() throws Exception {
Resource resource = new ByteArrayResource("1,2,3\n4\n5,6,7".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
assertEquals("1,2,3", reader.read());
assertEquals("4", reader.read());
assertEquals("5,6,7", reader.read());
}
public void testLineContentWhenLineContainsQuotedNewline() throws Exception {
Resource resource = new ByteArrayResource("1,2,\"3\n4\"\n5,6,7".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
assertEquals("1,2,\"3\n4\"", reader.read());
assertEquals("5,6,7", reader.read());
}
public void testLineEndings() throws Exception {
Resource resource = new ByteArrayResource("1\n2\r\n3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
String line = (String) reader.read();
assertEquals("2", line);
assertEquals(2, reader.getPosition());
line = (String) reader.read();
assertEquals("3", line);
assertEquals(3, reader.getPosition());
}
public void testDefaultComments() throws Exception {
Resource resource = new ByteArrayResource("1\n# 2\n3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
String line = (String) reader.read();
assertEquals("3", line);
}
public void testComments() throws Exception {
Resource resource = new ByteArrayResource("1\n-- 2\n3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.setComments(new String[] {"//", "--"});
reader.read();
String line = (String) reader.read();
assertEquals("3", line);
}
public void testCommentOnTheLastLine() throws Exception {
Resource resource = new ByteArrayResource("1\n#last line".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
String line = (String) reader.read();
assertNull(line);
}
public void testResetNewReader() throws Exception {
Resource resource = new ByteArrayResource("1\n4\n5".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.reset();
assertEquals(0, reader.getPosition());
}
public void testMarkReset() throws Exception {
Resource resource = new ByteArrayResource("1\n4\n5".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
assertEquals(1, reader.getPosition());
reader.mark();
reader.read();
assertEquals(2, reader.getPosition());
reader.reset();
reader.read();
assertEquals(2, reader.getPosition());
}
public void testMarkOnFirstRead() throws Exception {
Resource resource = new ByteArrayResource("1\n# 2\n3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
// The first read should do a mark() so the reset goes back to the beginning.
reader.reset();
String line = (String) reader.read();
assertEquals("1", line);
}
public void testMarkAfterClose() throws Exception {
Resource resource = new ByteArrayResource("1\n# 2\n3".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.read();
reader.close(null);
reader.mark();
}
public void testNonDefaultRecordSeparatorPolicy() throws Exception {
Resource resource = new ByteArrayResource("1\n\"4\n5\"; \n6".getBytes());
ResourceLineReader reader = new ResourceLineReader(resource);
reader.setRecordSeparatorPolicy(new SuffixRecordSeparatorPolicy());
assertEquals(0, reader.getPosition());
String line = (String) reader.read();
assertEquals("1\"4\n5\"", line);
}
}

View File

@@ -1,135 +1,135 @@
/*
* 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.io.file.mapping;
import java.math.BigDecimal;
import java.util.Date;
public class TestObject {
String varString;
boolean varBoolean;
char varChar;
byte varByte;
short varShort;
int varInt;
long varLong;
float varFloat;
double varDouble;
BigDecimal varBigDecimal;
Date varDate;
public Date getVarDate() {
return (Date)varDate.clone();
}
public void setVarDate(Date varDate) {
this.varDate = varDate == null ? null : (Date)varDate.clone();
}
public TestObject() {
}
public BigDecimal getVarBigDecimal() {
return varBigDecimal;
}
public void setVarBigDecimal(BigDecimal varBigDecimal) {
this.varBigDecimal = varBigDecimal;
}
public boolean isVarBoolean() {
return varBoolean;
}
public void setVarBoolean(boolean varBoolean) {
this.varBoolean = varBoolean;
}
public byte getVarByte() {
return varByte;
}
public void setVarByte(byte varByte) {
this.varByte = varByte;
}
public char getVarChar() {
return varChar;
}
public void setVarChar(char varChar) {
this.varChar = varChar;
}
public double getVarDouble() {
return varDouble;
}
public void setVarDouble(double varDouble) {
this.varDouble = varDouble;
}
public float getVarFloat() {
return varFloat;
}
public void setVarFloat(float varFloat) {
this.varFloat = varFloat;
}
public long getVarLong() {
return varLong;
}
public void setVarLong(long varLong) {
this.varLong = varLong;
}
public short getVarShort() {
return varShort;
}
public void setVarShort(short varShort) {
this.varShort = varShort;
}
public String getVarString() {
return varString;
}
public void setVarString(String varString) {
this.varString = varString;
}
public int getVarInt() {
return varInt;
}
public void setVarInt(int varInt) {
this.varInt = varInt;
}
}
/*
* 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.io.file.mapping;
import java.math.BigDecimal;
import java.util.Date;
public class TestObject {
String varString;
boolean varBoolean;
char varChar;
byte varByte;
short varShort;
int varInt;
long varLong;
float varFloat;
double varDouble;
BigDecimal varBigDecimal;
Date varDate;
public Date getVarDate() {
return (Date)varDate.clone();
}
public void setVarDate(Date varDate) {
this.varDate = varDate == null ? null : (Date)varDate.clone();
}
public TestObject() {
}
public BigDecimal getVarBigDecimal() {
return varBigDecimal;
}
public void setVarBigDecimal(BigDecimal varBigDecimal) {
this.varBigDecimal = varBigDecimal;
}
public boolean isVarBoolean() {
return varBoolean;
}
public void setVarBoolean(boolean varBoolean) {
this.varBoolean = varBoolean;
}
public byte getVarByte() {
return varByte;
}
public void setVarByte(byte varByte) {
this.varByte = varByte;
}
public char getVarChar() {
return varChar;
}
public void setVarChar(char varChar) {
this.varChar = varChar;
}
public double getVarDouble() {
return varDouble;
}
public void setVarDouble(double varDouble) {
this.varDouble = varDouble;
}
public float getVarFloat() {
return varFloat;
}
public void setVarFloat(float varFloat) {
this.varFloat = varFloat;
}
public long getVarLong() {
return varLong;
}
public void setVarLong(long varLong) {
this.varLong = varLong;
}
public short getVarShort() {
return varShort;
}
public void setVarShort(short varShort) {
this.varShort = varShort;
}
public String getVarString() {
return varString;
}
public void setVarString(String varString) {
this.varString = varString;
}
public int getVarInt() {
return varInt;
}
public void setVarInt(int varInt) {
this.varInt = varInt;
}
}

View File

@@ -1,39 +1,39 @@
package org.springframework.batch.io.file.transform;
import java.util.List;
import org.springframework.batch.io.file.transform.AbstractLineTokenizer;
import junit.framework.TestCase;
/**
* Tests for {@link AbstractLineTokenizer}.
*
* @author Robert Kasanicky
* @author Dave Syer
*/
public class CommonLineTokenizerTests extends TestCase {
/**
* Columns names are considered to be specified if they are not <code>null</code> or empty.
*/
public void testHasNames() {
AbstractLineTokenizer tokenizer = new AbstractLineTokenizer() {
protected List doTokenize(String line) {
return null;
}
};
assertFalse(tokenizer.hasNames());
tokenizer.setNames(null);
assertFalse(tokenizer.hasNames());
tokenizer.setNames(new String[0]);
assertFalse(tokenizer.hasNames());
tokenizer.setNames(new String[]{"name1", "name2"});
assertTrue(tokenizer.hasNames());
}
}
package org.springframework.batch.io.file.transform;
import java.util.List;
import org.springframework.batch.io.file.transform.AbstractLineTokenizer;
import junit.framework.TestCase;
/**
* Tests for {@link AbstractLineTokenizer}.
*
* @author Robert Kasanicky
* @author Dave Syer
*/
public class CommonLineTokenizerTests extends TestCase {
/**
* Columns names are considered to be specified if they are not <code>null</code> or empty.
*/
public void testHasNames() {
AbstractLineTokenizer tokenizer = new AbstractLineTokenizer() {
protected List doTokenize(String line) {
return null;
}
};
assertFalse(tokenizer.hasNames());
tokenizer.setNames(null);
assertFalse(tokenizer.hasNames());
tokenizer.setNames(new String[0]);
assertFalse(tokenizer.hasNames());
tokenizer.setNames(new String[]{"name1", "name2"});
assertTrue(tokenizer.hasNames());
}
}

View File

@@ -1,185 +1,185 @@
/*
* 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.io.file.transform;
import junit.framework.TestCase;
import org.springframework.batch.io.file.mapping.FieldSet;
import org.springframework.batch.io.file.transform.AbstractLineTokenizer;
import org.springframework.batch.io.file.transform.DelimitedLineTokenizer;
public class DelimitedLineTokenizerTests extends TestCase {
private static final String TOKEN_MATCHES = "token equals the expected string";
private DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
public void testTokenizeRegularUse() {
FieldSet tokens = tokenizer.tokenize("sfd,\"Well,I have no idea what to do in the afternoon\",sFj, asdf,,as\n");
assertEquals(6, tokens.getFieldCount());
assertTrue(TOKEN_MATCHES, tokens.readString(0).equals("sfd"));
assertTrue(TOKEN_MATCHES, tokens.readString(1).equals("Well,I have no idea what to do in the afternoon"));
assertTrue(TOKEN_MATCHES, tokens.readString(2).equals("sFj"));
assertTrue(TOKEN_MATCHES, tokens.readString(3).equals("asdf"));
assertTrue(TOKEN_MATCHES, tokens.readString(4).equals(""));
assertTrue(TOKEN_MATCHES, tokens.readString(5).equals("as"));
tokens = tokenizer.tokenize("First string,");
assertEquals(2, tokens.getFieldCount());
assertTrue(TOKEN_MATCHES, tokens.readString(0).equals("First string"));
assertTrue(TOKEN_MATCHES, tokens.readString(1).equals(""));
}
public void testInvalidConstructorArgument() {
try {
new DelimitedLineTokenizer(DelimitedLineTokenizer.DEFAULT_QUOTE_CHARACTER);
fail("Quote character can't be used as delimiter for delimited line tokenizer!");
}
catch (Exception e) {
assertTrue(true);
}
}
public void testDelimitedLineTokenizer() {
FieldSet line = tokenizer.tokenize("a,b,c");
assertEquals(3, line.getFieldCount());
}
public void testNames() {
tokenizer.setNames(new String[] {"A", "B", "C"});
FieldSet line = tokenizer.tokenize("a,b,c");
assertEquals(3, line.getFieldCount());
assertEquals("a", line.readString("A"));
}
public void testTooFewNames() {
tokenizer.setNames(new String[] {"A", "B"});
try {
tokenizer.tokenize("a,b,c");
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
public void testTooManyNames() {
tokenizer.setNames(new String[] {"A", "B", "C", "D"});
FieldSet line = tokenizer.tokenize("a,b,c");
assertEquals(4, line.getFieldCount());
assertEquals("c", line.readString("C"));
assertEquals(null, line.readString("D"));
}
public void testDelimitedLineTokenizerChar() {
AbstractLineTokenizer tokenizer = new DelimitedLineTokenizer(' ');
FieldSet line = tokenizer.tokenize("a b c");
assertEquals(3, line.getFieldCount());
}
public void testTokenizeWithQuotes() {
FieldSet line = tokenizer.tokenize("a,b,\"c\"");
assertEquals(3, line.getFieldCount());
assertEquals("c", line.readString(2));
}
public void testTokenizeWithNotDefaultQuotes() {
tokenizer.setQuoteCharacter('\'');
FieldSet line = tokenizer.tokenize("a,b,'c'");
assertEquals(3, line.getFieldCount());
assertEquals("c", line.readString(2));
}
public void testTokenizeWithEscapedQuotes() {
FieldSet line = tokenizer.tokenize("a,\"\"b,\"\"\"c\"");
assertEquals(3, line.getFieldCount());
assertEquals("\"\"b", line.readString(1));
assertEquals("\"c", line.readString(2));
}
public void testTokenizeWithUnclosedQuotes() {
tokenizer.setQuoteCharacter('\'');
FieldSet line = tokenizer.tokenize("a,\"b,c");
assertEquals(3, line.getFieldCount());
assertEquals("\"b", line.readString(1));
assertEquals("c", line.readString(2));
}
public void testTokenizeWithSpaceAtEnd() {
FieldSet line = tokenizer.tokenize("a,b,c ");
assertEquals(3, line.getFieldCount());
assertEquals("c", line.readString(2));
}
public void testTokenizeWithQuoteAndSpaceAtEnd() {
FieldSet line = tokenizer.tokenize("a,b,\"c\" ");
assertEquals(3, line.getFieldCount());
assertEquals("c", line.readString(2));
}
public void testTokenizeWithQuoteAndSpaceBeforeDelimiter() {
FieldSet line = tokenizer.tokenize("a,\"b\" ,c");
assertEquals(3, line.getFieldCount());
assertEquals("b", line.readString(1));
}
public void testTokenizeWithDelimiterAtEnd() {
FieldSet line = tokenizer.tokenize("a,b,c,");
assertEquals(4, line.getFieldCount());
assertEquals("c", line.readString(2));
assertEquals("", line.readString(3));
}
public void testEmptyLine() throws Exception {
FieldSet line = tokenizer.tokenize("");
assertEquals(0, line.getFieldCount());
}
public void testWhitespaceLine() throws Exception {
FieldSet line = tokenizer.tokenize(" ");
// whitespace counts as text
assertEquals(1, line.getFieldCount());
}
public void testNullLine() throws Exception {
FieldSet line = tokenizer.tokenize(null);
// null doesn't...
assertEquals(0, line.getFieldCount());
}
public void testMultiLineField() throws Exception {
FieldSet line = tokenizer.tokenize("a,b,c\nrap");
assertEquals(3, line.getFieldCount());
assertEquals("c\nrap", line.readString(2));
}
public void testMultiLineFieldWithQuotes() throws Exception {
FieldSet line = tokenizer.tokenize("a,b,\"c\nrap\"");
assertEquals(3, line.getFieldCount());
assertEquals("c\nrap", line.readString(2));
}
public void testTokenizeWithQuotesEmptyValue() {
FieldSet line = tokenizer.tokenize("\"a\",\"b\",\"\",\"d\"");
assertEquals(4, line.getFieldCount());
assertEquals("", line.readString(2));
}
}
/*
* 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.io.file.transform;
import junit.framework.TestCase;
import org.springframework.batch.io.file.mapping.FieldSet;
import org.springframework.batch.io.file.transform.AbstractLineTokenizer;
import org.springframework.batch.io.file.transform.DelimitedLineTokenizer;
public class DelimitedLineTokenizerTests extends TestCase {
private static final String TOKEN_MATCHES = "token equals the expected string";
private DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
public void testTokenizeRegularUse() {
FieldSet tokens = tokenizer.tokenize("sfd,\"Well,I have no idea what to do in the afternoon\",sFj, asdf,,as\n");
assertEquals(6, tokens.getFieldCount());
assertTrue(TOKEN_MATCHES, tokens.readString(0).equals("sfd"));
assertTrue(TOKEN_MATCHES, tokens.readString(1).equals("Well,I have no idea what to do in the afternoon"));
assertTrue(TOKEN_MATCHES, tokens.readString(2).equals("sFj"));
assertTrue(TOKEN_MATCHES, tokens.readString(3).equals("asdf"));
assertTrue(TOKEN_MATCHES, tokens.readString(4).equals(""));
assertTrue(TOKEN_MATCHES, tokens.readString(5).equals("as"));
tokens = tokenizer.tokenize("First string,");
assertEquals(2, tokens.getFieldCount());
assertTrue(TOKEN_MATCHES, tokens.readString(0).equals("First string"));
assertTrue(TOKEN_MATCHES, tokens.readString(1).equals(""));
}
public void testInvalidConstructorArgument() {
try {
new DelimitedLineTokenizer(DelimitedLineTokenizer.DEFAULT_QUOTE_CHARACTER);
fail("Quote character can't be used as delimiter for delimited line tokenizer!");
}
catch (Exception e) {
assertTrue(true);
}
}
public void testDelimitedLineTokenizer() {
FieldSet line = tokenizer.tokenize("a,b,c");
assertEquals(3, line.getFieldCount());
}
public void testNames() {
tokenizer.setNames(new String[] {"A", "B", "C"});
FieldSet line = tokenizer.tokenize("a,b,c");
assertEquals(3, line.getFieldCount());
assertEquals("a", line.readString("A"));
}
public void testTooFewNames() {
tokenizer.setNames(new String[] {"A", "B"});
try {
tokenizer.tokenize("a,b,c");
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
public void testTooManyNames() {
tokenizer.setNames(new String[] {"A", "B", "C", "D"});
FieldSet line = tokenizer.tokenize("a,b,c");
assertEquals(4, line.getFieldCount());
assertEquals("c", line.readString("C"));
assertEquals(null, line.readString("D"));
}
public void testDelimitedLineTokenizerChar() {
AbstractLineTokenizer tokenizer = new DelimitedLineTokenizer(' ');
FieldSet line = tokenizer.tokenize("a b c");
assertEquals(3, line.getFieldCount());
}
public void testTokenizeWithQuotes() {
FieldSet line = tokenizer.tokenize("a,b,\"c\"");
assertEquals(3, line.getFieldCount());
assertEquals("c", line.readString(2));
}
public void testTokenizeWithNotDefaultQuotes() {
tokenizer.setQuoteCharacter('\'');
FieldSet line = tokenizer.tokenize("a,b,'c'");
assertEquals(3, line.getFieldCount());
assertEquals("c", line.readString(2));
}
public void testTokenizeWithEscapedQuotes() {
FieldSet line = tokenizer.tokenize("a,\"\"b,\"\"\"c\"");
assertEquals(3, line.getFieldCount());
assertEquals("\"\"b", line.readString(1));
assertEquals("\"c", line.readString(2));
}
public void testTokenizeWithUnclosedQuotes() {
tokenizer.setQuoteCharacter('\'');
FieldSet line = tokenizer.tokenize("a,\"b,c");
assertEquals(3, line.getFieldCount());
assertEquals("\"b", line.readString(1));
assertEquals("c", line.readString(2));
}
public void testTokenizeWithSpaceAtEnd() {
FieldSet line = tokenizer.tokenize("a,b,c ");
assertEquals(3, line.getFieldCount());
assertEquals("c", line.readString(2));
}
public void testTokenizeWithQuoteAndSpaceAtEnd() {
FieldSet line = tokenizer.tokenize("a,b,\"c\" ");
assertEquals(3, line.getFieldCount());
assertEquals("c", line.readString(2));
}
public void testTokenizeWithQuoteAndSpaceBeforeDelimiter() {
FieldSet line = tokenizer.tokenize("a,\"b\" ,c");
assertEquals(3, line.getFieldCount());
assertEquals("b", line.readString(1));
}
public void testTokenizeWithDelimiterAtEnd() {
FieldSet line = tokenizer.tokenize("a,b,c,");
assertEquals(4, line.getFieldCount());
assertEquals("c", line.readString(2));
assertEquals("", line.readString(3));
}
public void testEmptyLine() throws Exception {
FieldSet line = tokenizer.tokenize("");
assertEquals(0, line.getFieldCount());
}
public void testWhitespaceLine() throws Exception {
FieldSet line = tokenizer.tokenize(" ");
// whitespace counts as text
assertEquals(1, line.getFieldCount());
}
public void testNullLine() throws Exception {
FieldSet line = tokenizer.tokenize(null);
// null doesn't...
assertEquals(0, line.getFieldCount());
}
public void testMultiLineField() throws Exception {
FieldSet line = tokenizer.tokenize("a,b,c\nrap");
assertEquals(3, line.getFieldCount());
assertEquals("c\nrap", line.readString(2));
}
public void testMultiLineFieldWithQuotes() throws Exception {
FieldSet line = tokenizer.tokenize("a,b,\"c\nrap\"");
assertEquals(3, line.getFieldCount());
assertEquals("c\nrap", line.readString(2));
}
public void testTokenizeWithQuotesEmptyValue() {
FieldSet line = tokenizer.tokenize("\"a\",\"b\",\"\",\"d\"");
assertEquals(4, line.getFieldCount());
assertEquals("", line.readString(2));
}
}

View File

@@ -1,172 +1,172 @@
/*
* 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.io.file.transform;
import org.springframework.batch.io.file.mapping.DefaultFieldSet;
import org.springframework.batch.io.file.transform.FixedLengthLineAggregator;
import org.springframework.batch.io.file.transform.Range;
import junit.framework.TestCase;
/**
* Unit tests for {@link FixedLengthLineAggregator}
*
* @author robert.kasanicky
* @author peter.zozom
*/
public class FixedLengthLineAggregatorTests extends TestCase {
// object under test
private FixedLengthLineAggregator aggregator = new FixedLengthLineAggregator();
/**
* If no ranges are specified, IllegalArgumentException is thrown
*/
public void testAggregateNullRecordDescriptor() {
String[] args = { "does not matter what is here" };
try {
aggregator.aggregate(new DefaultFieldSet(args));
fail("should not work with no ranges specified");
}
catch (IllegalArgumentException expected) {
// expected
}
}
/**
* Count of aggregated strings does not match the number of columns
*/
public void testAggregateWrongArgumentCount() {
String[] string = { "only one test string" };
aggregator.setColumns(new Range[0]);
try {
aggregator.aggregate(new DefaultFieldSet(string));
fail("Exception expected: count of aggregated strings"
+ " does not match the number of columns");
}
catch (IllegalArgumentException expected) {
// expected
}
}
/**
* Text length exceeds the length of the column.
*/
public void testAggregateInvalidInputLength() {
String[] args = { "Oversize" };
aggregator.setColumns(new Range[] {new Range(1,args[0].length()-1)});
try {
aggregator.aggregate(new DefaultFieldSet(args));
fail("Invalid text length, exception should have been thrown");
}
catch (IllegalArgumentException expected) {
// expected
}
}
/**
* Test aggregation
*/
public void testAggregate() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setColumns(new Range[] {new Range(1,9), new Range(10,18)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals("MatchsizeSmallsize", result);
}
/**
* Test aggregation with last range unbound
*/
public void testAggregateWithLastRangeUnbound() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setColumns(new Range[] {new Range(1,12), new Range(13)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals("Matchsize Smallsize", result);
}
/**
* Test aggregation with right alignment
*/
public void testAggregateFormattedRight() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setAlignment("right");
aggregator.setColumns(new Range[] {new Range(1,13), new Range(14,23)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals(23,result.length());
assertEquals(result, " Matchsize Smallsize");
}
/**
* Test aggregation with center alignment
*/
public void testAggregateFormattedCenter() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setAlignment("center");
aggregator.setColumns(new Range[] {new Range(1,13), new Range(14,25)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals(result, " Matchsize Smallsize ");
}
/**
* Test aggregation with left alignment
*/
public void testAggregateWithCustomPadding() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setPadding('.');
aggregator.setAlignment("left");
aggregator.setColumns(new Range[] {new Range(1,13), new Range(14,24)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals(result, "Matchsize....Smallsize..");
}
/**
* Test aggregation with left alignment
*/
public void testAggregateFormattedLeft() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setAlignment("left");
aggregator.setColumns(new Range[] {new Range(1,13), new Range(14,24)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals(result, "Matchsize Smallsize ");
}
/**
* Try set ivalid alignment
*/
public void testInvalidAlignment() {
try {
aggregator.setAlignment("foo");
fail("Exception was expected: invalid alignment value");
} catch (IllegalArgumentException iae) {
// expected
}
}
/**
* If one of the passed arguments is null, string filled with spaces should
* be returned
*/
public void testAggregateNullArgument() {
String[] args = { null };
aggregator.setColumns(new Range[] {new Range(1,3)});
assertEquals(" ", aggregator.aggregate(new DefaultFieldSet(args)));
}
}
/*
* 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.io.file.transform;
import org.springframework.batch.io.file.mapping.DefaultFieldSet;
import org.springframework.batch.io.file.transform.FixedLengthLineAggregator;
import org.springframework.batch.io.file.transform.Range;
import junit.framework.TestCase;
/**
* Unit tests for {@link FixedLengthLineAggregator}
*
* @author robert.kasanicky
* @author peter.zozom
*/
public class FixedLengthLineAggregatorTests extends TestCase {
// object under test
private FixedLengthLineAggregator aggregator = new FixedLengthLineAggregator();
/**
* If no ranges are specified, IllegalArgumentException is thrown
*/
public void testAggregateNullRecordDescriptor() {
String[] args = { "does not matter what is here" };
try {
aggregator.aggregate(new DefaultFieldSet(args));
fail("should not work with no ranges specified");
}
catch (IllegalArgumentException expected) {
// expected
}
}
/**
* Count of aggregated strings does not match the number of columns
*/
public void testAggregateWrongArgumentCount() {
String[] string = { "only one test string" };
aggregator.setColumns(new Range[0]);
try {
aggregator.aggregate(new DefaultFieldSet(string));
fail("Exception expected: count of aggregated strings"
+ " does not match the number of columns");
}
catch (IllegalArgumentException expected) {
// expected
}
}
/**
* Text length exceeds the length of the column.
*/
public void testAggregateInvalidInputLength() {
String[] args = { "Oversize" };
aggregator.setColumns(new Range[] {new Range(1,args[0].length()-1)});
try {
aggregator.aggregate(new DefaultFieldSet(args));
fail("Invalid text length, exception should have been thrown");
}
catch (IllegalArgumentException expected) {
// expected
}
}
/**
* Test aggregation
*/
public void testAggregate() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setColumns(new Range[] {new Range(1,9), new Range(10,18)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals("MatchsizeSmallsize", result);
}
/**
* Test aggregation with last range unbound
*/
public void testAggregateWithLastRangeUnbound() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setColumns(new Range[] {new Range(1,12), new Range(13)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals("Matchsize Smallsize", result);
}
/**
* Test aggregation with right alignment
*/
public void testAggregateFormattedRight() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setAlignment("right");
aggregator.setColumns(new Range[] {new Range(1,13), new Range(14,23)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals(23,result.length());
assertEquals(result, " Matchsize Smallsize");
}
/**
* Test aggregation with center alignment
*/
public void testAggregateFormattedCenter() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setAlignment("center");
aggregator.setColumns(new Range[] {new Range(1,13), new Range(14,25)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals(result, " Matchsize Smallsize ");
}
/**
* Test aggregation with left alignment
*/
public void testAggregateWithCustomPadding() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setPadding('.');
aggregator.setAlignment("left");
aggregator.setColumns(new Range[] {new Range(1,13), new Range(14,24)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals(result, "Matchsize....Smallsize..");
}
/**
* Test aggregation with left alignment
*/
public void testAggregateFormattedLeft() {
String[] args = { "Matchsize", "Smallsize" };
aggregator.setAlignment("left");
aggregator.setColumns(new Range[] {new Range(1,13), new Range(14,24)});
String result = aggregator.aggregate(new DefaultFieldSet(args));
assertEquals(result, "Matchsize Smallsize ");
}
/**
* Try set ivalid alignment
*/
public void testInvalidAlignment() {
try {
aggregator.setAlignment("foo");
fail("Exception was expected: invalid alignment value");
} catch (IllegalArgumentException iae) {
// expected
}
}
/**
* If one of the passed arguments is null, string filled with spaces should
* be returned
*/
public void testAggregateNullArgument() {
String[] args = { null };
aggregator.setColumns(new Range[] {new Range(1,3)});
assertEquals(" ", aggregator.aggregate(new DefaultFieldSet(args)));
}
}

View File

@@ -1,128 +1,128 @@
/*
* 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.io.file.transform;
import junit.framework.TestCase;
import org.springframework.batch.io.file.mapping.FieldSet;
import org.springframework.batch.io.file.transform.FixedLengthTokenizer;
import org.springframework.batch.io.file.transform.Range;
public class FixedLengthTokenizerTests extends TestCase {
private FixedLengthTokenizer tokenizer = new FixedLengthTokenizer();
private String line = null;
/**
* if null or empty string is tokenized, tokenizer returns empty fieldset
* (with no tokens).
*/
public void testTokenizeEmptyString() {
tokenizer.setColumns(new Range[] {new Range(1,5),new Range(6,10),new Range(11,15)});
FieldSet tokens = tokenizer.tokenize("");
assertEquals(0, tokens.getFieldCount());
}
public void testTokenizeNullString() {
tokenizer.setColumns(new Range[] {new Range(1,5),new Range(6,10),new Range(11,15)});
FieldSet tokens = tokenizer.tokenize(null);
assertEquals(0, tokens.getFieldCount());
}
public void testTokenizeRegularUse() {
tokenizer.setColumns(new Range[] {new Range(1,2),new Range(3,7),new Range(8,12)});
// test shorter line as defined by record descriptor
line = "H1";
FieldSet tokens = tokenizer.tokenize(line);
assertEquals(3, tokens.getFieldCount());
assertEquals("H1", tokens.readString(0));
assertEquals("", tokens.readString(1));
assertEquals("", tokens.readString(2));
}
public void testNormalLength() throws Exception {
tokenizer.setColumns(new Range[] {new Range(1,10),new Range(11,25),new Range(26,30)});
// test shorter line as defined by record descriptor
line = "H1";
FieldSet tokens = tokenizer.tokenize(line);
// test normal length
line = "H1 12345678 12345";
tokens = tokenizer.tokenize(line);
assertEquals(3, tokens.getFieldCount());
assertEquals(line.substring(0, 10).trim(), tokens.readString(0));
assertEquals(line.substring(10, 25).trim(), tokens.readString(1));
assertEquals(line.substring(25).trim(), tokens.readString(2));
}
public void testLongerLinesRestIgnored() throws Exception {
tokenizer.setColumns(new Range[] {new Range(1,10),new Range(11,25),new Range(26,30)});
// test shorter line as defined by record descriptor
line = "H1";
FieldSet tokens = tokenizer.tokenize(line);
// test longer lines => rest will be ignored
line = "H1 12345678 1234567890";
tokens = tokenizer.tokenize(line);
assertEquals(3, tokens.getFieldCount());
assertEquals(line.substring(0, 10).trim(), tokens.readString(0));
assertEquals(line.substring(10, 25).trim(), tokens.readString(1));
assertEquals(line.substring(25, 30).trim(), tokens.readString(2));
}
public void testNonAdjacentRangesUnsorted() throws Exception {
tokenizer.setColumns(new Range[] {new Range(14,28), new Range(34,38), new Range(1,10)});
// test shorter line as defined by record descriptor
line = "H1";
FieldSet tokens = tokenizer.tokenize(line);
// test normal length
line = "H1 +++12345678 +++++12345+++";
tokens = tokenizer.tokenize(line);
assertEquals(3, tokens.getFieldCount());
assertEquals(line.substring(0, 10).trim(), tokens.readString(2));
assertEquals(line.substring(13, 28).trim(), tokens.readString(0));
assertEquals(line.substring(33, 38).trim(), tokens.readString(1));
}
public void testAnotherTypeOfRecord() throws Exception {
tokenizer.setColumns(new Range[] {new Range(1,5),new Range(6,15),new Range(16,25),new Range(26,27)});
// test shorter line as defined by record descriptor
line = "H1";
FieldSet tokens = tokenizer.tokenize(line);
// test another type of record
line = "H2 123456 12345 12";
tokens = tokenizer.tokenize(line);
assertEquals(4, tokens.getFieldCount());
assertEquals(line.substring(0, 5).trim(), tokens.readString(0));
assertEquals(line.substring(5, 15).trim(), tokens.readString(1));
assertEquals(line.substring(15, 25).trim(), tokens.readString(2));
assertEquals(line.substring(25).trim(), tokens.readString(3));
}
public void testTokenizerInvalidSetup() {
tokenizer.setNames(new String[] {"a", "b"});
tokenizer.setColumns(new Range[] {new Range(1,5),new Range(6,15),new Range(16,25),new Range(26,27)});
try {
tokenizer.tokenize("Test tokenize");
fail("Exception was expected: too few names provided");
}
catch (Exception e) {
assertTrue(true);
}
}
}
/*
* 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.io.file.transform;
import junit.framework.TestCase;
import org.springframework.batch.io.file.mapping.FieldSet;
import org.springframework.batch.io.file.transform.FixedLengthTokenizer;
import org.springframework.batch.io.file.transform.Range;
public class FixedLengthTokenizerTests extends TestCase {
private FixedLengthTokenizer tokenizer = new FixedLengthTokenizer();
private String line = null;
/**
* if null or empty string is tokenized, tokenizer returns empty fieldset
* (with no tokens).
*/
public void testTokenizeEmptyString() {
tokenizer.setColumns(new Range[] {new Range(1,5),new Range(6,10),new Range(11,15)});
FieldSet tokens = tokenizer.tokenize("");
assertEquals(0, tokens.getFieldCount());
}
public void testTokenizeNullString() {
tokenizer.setColumns(new Range[] {new Range(1,5),new Range(6,10),new Range(11,15)});
FieldSet tokens = tokenizer.tokenize(null);
assertEquals(0, tokens.getFieldCount());
}
public void testTokenizeRegularUse() {
tokenizer.setColumns(new Range[] {new Range(1,2),new Range(3,7),new Range(8,12)});
// test shorter line as defined by record descriptor
line = "H1";
FieldSet tokens = tokenizer.tokenize(line);
assertEquals(3, tokens.getFieldCount());
assertEquals("H1", tokens.readString(0));
assertEquals("", tokens.readString(1));
assertEquals("", tokens.readString(2));
}
public void testNormalLength() throws Exception {
tokenizer.setColumns(new Range[] {new Range(1,10),new Range(11,25),new Range(26,30)});
// test shorter line as defined by record descriptor
line = "H1";
FieldSet tokens = tokenizer.tokenize(line);
// test normal length
line = "H1 12345678 12345";
tokens = tokenizer.tokenize(line);
assertEquals(3, tokens.getFieldCount());
assertEquals(line.substring(0, 10).trim(), tokens.readString(0));
assertEquals(line.substring(10, 25).trim(), tokens.readString(1));
assertEquals(line.substring(25).trim(), tokens.readString(2));
}
public void testLongerLinesRestIgnored() throws Exception {
tokenizer.setColumns(new Range[] {new Range(1,10),new Range(11,25),new Range(26,30)});
// test shorter line as defined by record descriptor
line = "H1";
FieldSet tokens = tokenizer.tokenize(line);
// test longer lines => rest will be ignored
line = "H1 12345678 1234567890";
tokens = tokenizer.tokenize(line);
assertEquals(3, tokens.getFieldCount());
assertEquals(line.substring(0, 10).trim(), tokens.readString(0));
assertEquals(line.substring(10, 25).trim(), tokens.readString(1));
assertEquals(line.substring(25, 30).trim(), tokens.readString(2));
}
public void testNonAdjacentRangesUnsorted() throws Exception {
tokenizer.setColumns(new Range[] {new Range(14,28), new Range(34,38), new Range(1,10)});
// test shorter line as defined by record descriptor
line = "H1";
FieldSet tokens = tokenizer.tokenize(line);
// test normal length
line = "H1 +++12345678 +++++12345+++";
tokens = tokenizer.tokenize(line);
assertEquals(3, tokens.getFieldCount());
assertEquals(line.substring(0, 10).trim(), tokens.readString(2));
assertEquals(line.substring(13, 28).trim(), tokens.readString(0));
assertEquals(line.substring(33, 38).trim(), tokens.readString(1));
}
public void testAnotherTypeOfRecord() throws Exception {
tokenizer.setColumns(new Range[] {new Range(1,5),new Range(6,15),new Range(16,25),new Range(26,27)});
// test shorter line as defined by record descriptor
line = "H1";
FieldSet tokens = tokenizer.tokenize(line);
// test another type of record
line = "H2 123456 12345 12";
tokens = tokenizer.tokenize(line);
assertEquals(4, tokens.getFieldCount());
assertEquals(line.substring(0, 5).trim(), tokens.readString(0));
assertEquals(line.substring(5, 15).trim(), tokens.readString(1));
assertEquals(line.substring(15, 25).trim(), tokens.readString(2));
assertEquals(line.substring(25).trim(), tokens.readString(3));
}
public void testTokenizerInvalidSetup() {
tokenizer.setNames(new String[] {"a", "b"});
tokenizer.setColumns(new Range[] {new Range(1,5),new Range(6,15),new Range(16,25),new Range(26,27)});
try {
tokenizer.tokenize("Test tokenize");
fail("Exception was expected: too few names provided");
}
catch (Exception e) {
assertTrue(true);
}
}
}

View File

@@ -1,109 +1,109 @@
package org.springframework.batch.io.file.transform;
import org.springframework.batch.io.file.transform.Range;
import org.springframework.batch.io.file.transform.RangeArrayPropertyEditor;
import junit.framework.TestCase;
public class RangeArrayPropertyEditorTests extends TestCase {
private Range[] ranges;
private RangeArrayPropertyEditor pe;
public void setUp() {
ranges = null;
pe = new RangeArrayPropertyEditor() {
public void setValue(Object value) {
ranges = (Range[]) value;
}
public Object getValue() {
return ranges;
}
};
}
public void testSetAsText() {
pe.setAsText("15, 32, 1-10, 33");
// result should be 15-31, 32-32, 1-10, 33-unbound
assertEquals(4, ranges.length);
assertEquals(15, ranges[0].getMin());
assertEquals(31, ranges[0].getMax());
assertEquals(32, ranges[1].getMin());
assertEquals(32, ranges[1].getMax());
assertEquals(1, ranges[2].getMin());
assertEquals(10, ranges[2].getMax());
assertEquals(33, ranges[3].getMin());
assertFalse(ranges[3].hasMaxValue());
}
public void testSetAsTextWithNoSpaces() {
pe.setAsText("15,32");
// result should be 15-31, 32-unbound
assertEquals(2, ranges.length);
assertEquals(15, ranges[0].getMin());
assertEquals(31, ranges[0].getMax());
assertEquals(32, ranges[1].getMin());
assertFalse(ranges[1].hasMaxValue());
}
public void testGetAsText() {
ranges = new Range[] { new Range(20), new Range(6, 15), new Range(2),
new Range(26, 95) };
assertEquals("20, 6-15, 2, 26-95", pe.getAsText());
}
public void testValidDisjointRanges() {
pe.setForceDisjointRanges(true);
// test disjoint ranges
pe.setAsText("1-5,11-15");
assertEquals(2, ranges.length);
assertEquals(1, ranges[0].getMin());
assertEquals(5, ranges[0].getMax());
assertEquals(11, ranges[1].getMin());
assertEquals(15, ranges[1].getMax());
}
public void testInvalidOverlappingRanges() {
pe.setForceDisjointRanges(true);
// test joint ranges
try {
pe.setAsText("1-10, 5-15");
fail("Exception expected: ranges are not disjoint");
} catch (IllegalArgumentException iae) {
// expected
}
}
public void testValidOverlappingRanges() {
// test joint ranges
pe.setAsText("1-10, 5-15");
assertEquals(2, ranges.length);
assertEquals(1, ranges[0].getMin());
assertEquals(10, ranges[0].getMax());
assertEquals(5, ranges[1].getMin());
assertEquals(15, ranges[1].getMax());
}
public void testInvalidInput() {
try {
pe.setAsText("1-5, b");
fail("Exception expected: 2nd range is invalid");
} catch (IllegalArgumentException iae) {
// expected
}
}
}
package org.springframework.batch.io.file.transform;
import org.springframework.batch.io.file.transform.Range;
import org.springframework.batch.io.file.transform.RangeArrayPropertyEditor;
import junit.framework.TestCase;
public class RangeArrayPropertyEditorTests extends TestCase {
private Range[] ranges;
private RangeArrayPropertyEditor pe;
public void setUp() {
ranges = null;
pe = new RangeArrayPropertyEditor() {
public void setValue(Object value) {
ranges = (Range[]) value;
}
public Object getValue() {
return ranges;
}
};
}
public void testSetAsText() {
pe.setAsText("15, 32, 1-10, 33");
// result should be 15-31, 32-32, 1-10, 33-unbound
assertEquals(4, ranges.length);
assertEquals(15, ranges[0].getMin());
assertEquals(31, ranges[0].getMax());
assertEquals(32, ranges[1].getMin());
assertEquals(32, ranges[1].getMax());
assertEquals(1, ranges[2].getMin());
assertEquals(10, ranges[2].getMax());
assertEquals(33, ranges[3].getMin());
assertFalse(ranges[3].hasMaxValue());
}
public void testSetAsTextWithNoSpaces() {
pe.setAsText("15,32");
// result should be 15-31, 32-unbound
assertEquals(2, ranges.length);
assertEquals(15, ranges[0].getMin());
assertEquals(31, ranges[0].getMax());
assertEquals(32, ranges[1].getMin());
assertFalse(ranges[1].hasMaxValue());
}
public void testGetAsText() {
ranges = new Range[] { new Range(20), new Range(6, 15), new Range(2),
new Range(26, 95) };
assertEquals("20, 6-15, 2, 26-95", pe.getAsText());
}
public void testValidDisjointRanges() {
pe.setForceDisjointRanges(true);
// test disjoint ranges
pe.setAsText("1-5,11-15");
assertEquals(2, ranges.length);
assertEquals(1, ranges[0].getMin());
assertEquals(5, ranges[0].getMax());
assertEquals(11, ranges[1].getMin());
assertEquals(15, ranges[1].getMax());
}
public void testInvalidOverlappingRanges() {
pe.setForceDisjointRanges(true);
// test joint ranges
try {
pe.setAsText("1-10, 5-15");
fail("Exception expected: ranges are not disjoint");
} catch (IllegalArgumentException iae) {
// expected
}
}
public void testValidOverlappingRanges() {
// test joint ranges
pe.setAsText("1-10, 5-15");
assertEquals(2, ranges.length);
assertEquals(1, ranges[0].getMin());
assertEquals(10, ranges[0].getMax());
assertEquals(5, ranges[1].getMin());
assertEquals(15, ranges[1].getMax());
}
public void testInvalidInput() {
try {
pe.setAsText("1-5, b");
fail("Exception expected: 2nd range is invalid");
} catch (IllegalArgumentException iae) {
// expected
}
}
}

View File

@@ -1,54 +1,54 @@
package org.springframework.batch.io.sample.domain;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Simple domain object for testing purposes.
*/
public class Foo {
private int id;
private String name;
private int value;
public Foo(){}
public Foo(int id, String name, int value) {
this.id = id;
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return "Foo[id=" +id +",name=" + name + ",value=" + value + "]";
}
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
package org.springframework.batch.io.sample.domain;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Simple domain object for testing purposes.
*/
public class Foo {
private int id;
private String name;
private int value;
public Foo(){}
public Foo(int id, String name, int value) {
this.id = id;
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return "Foo[id=" +id +",name=" + name + ",value=" + value + "]";
}
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}

View File

@@ -1,53 +1,53 @@
package org.springframework.batch.io.sample.domain;
import java.util.ArrayList;
import java.util.List;
/**
* Custom class that contains the logic of providing and processing {@link Foo}
* objects. It serves the purpose to show how providing/processing logic contained in a
* custom class can be reused by the framework.
*
* @author Robert Kasanicky
*/
public class FooService {
public static final int GENERATION_LIMIT = 10;
private int counter = 0;
private List generatedFoos = new ArrayList(GENERATION_LIMIT);
private List processedFoos = new ArrayList(GENERATION_LIMIT);
private List processedFooNameValuePairs = new ArrayList(GENERATION_LIMIT);
public Foo generateFoo() {
if (counter++ >= GENERATION_LIMIT) return null;
Foo foo = new Foo(counter, "foo" + counter, counter);
generatedFoos.add(foo);
return foo;
}
public void processFoo(Foo foo) {
processedFoos.add(foo);
}
public void processNameValuePair(String name, int value) {
processedFooNameValuePairs.add(new Foo(0, name, value));
}
public List getGeneratedFoos() {
return generatedFoos;
}
public List getProcessedFoos() {
return processedFoos;
}
public List getProcessedFooNameValuePairs() {
return processedFooNameValuePairs;
}
}
package org.springframework.batch.io.sample.domain;
import java.util.ArrayList;
import java.util.List;
/**
* Custom class that contains the logic of providing and processing {@link Foo}
* objects. It serves the purpose to show how providing/processing logic contained in a
* custom class can be reused by the framework.
*
* @author Robert Kasanicky
*/
public class FooService {
public static final int GENERATION_LIMIT = 10;
private int counter = 0;
private List generatedFoos = new ArrayList(GENERATION_LIMIT);
private List processedFoos = new ArrayList(GENERATION_LIMIT);
private List processedFooNameValuePairs = new ArrayList(GENERATION_LIMIT);
public Foo generateFoo() {
if (counter++ >= GENERATION_LIMIT) return null;
Foo foo = new Foo(counter, "foo" + counter, counter);
generatedFoos.add(foo);
return foo;
}
public void processFoo(Foo foo) {
processedFoos.add(foo);
}
public void processNameValuePair(String name, int value) {
processedFooNameValuePairs.add(new Foo(0, name, value));
}
public List getGeneratedFoos() {
return generatedFoos;
}
public List getProcessedFoos() {
return processedFoos;
}
public List getProcessedFooNameValuePairs() {
return processedFooNameValuePairs;
}
}

View File

@@ -1,83 +1,83 @@
/*
* 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.io.sample.domain;
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;
/**
* 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)date.clone();
}
public void setDate(Date date) {
this.date = date == null ? null : (Date)date.clone();
}
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 boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(obj, this);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
/*
* 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.io.sample.domain;
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;
/**
* 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)date.clone();
}
public void setDate(Date date) {
this.date = date == null ? null : (Date)date.clone();
}
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 boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(obj, this);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}

View File

@@ -1,173 +1,173 @@
package org.springframework.batch.io.sql;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
import org.springframework.util.Assert;
/**
* Common scenarios for testing {@link ItemReader} implementations which read data from database.
*
* @author Lucas Ward
* @author Robert Kasanicky
*/
public abstract class AbstractJdbcItemReaderIntegrationTests extends AbstractTransactionalDataSourceSpringContextTests {
protected ItemReader itemReader;
protected ExecutionContext executionContext;
/**
* @return input source with all necessary dependencies set
*/
protected abstract ItemReader createItemReader() throws Exception;
protected String[] getConfigLocations(){
return new String[] { "org/springframework/batch/io/sql/data-source-context.xml"};
}
protected void onSetUp()throws Exception{
super.onSetUp();
itemReader = createItemReader();
getAsInitializingBean(itemReader).afterPropertiesSet();
executionContext = new ExecutionContext();
}
protected void onTearDown()throws Exception {
getAsDisposableBean(itemReader).destroy();
super.onTearDown();
}
/**
* Regular scenario - read all rows and eventually return null.
*/
public void testNormalProcessing() throws Exception {
getAsInitializingBean(itemReader).afterPropertiesSet();
getAsItemStream(itemReader).open(executionContext);
Foo foo1 = (Foo) itemReader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) itemReader.read();
assertEquals(2, foo2.getValue());
Foo foo3 = (Foo) itemReader.read();
assertEquals(3, foo3.getValue());
Foo foo4 = (Foo) itemReader.read();
assertEquals(4, foo4.getValue());
Foo foo5 = (Foo) itemReader.read();
assertEquals(5, foo5.getValue());
assertNull(itemReader.read());
}
/**
* Restart scenario.
* @throws Exception
*/
public void testRestart() throws Exception {
getAsItemStream(itemReader).open(executionContext);
Foo foo1 = (Foo) itemReader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) itemReader.read();
assertEquals(2, foo2.getValue());
getAsItemStream(itemReader).update(executionContext);
// create new input source
itemReader = createItemReader();
getAsItemStream(itemReader).open(executionContext);
Foo fooAfterRestart = (Foo) itemReader.read();
assertEquals(3, fooAfterRestart.getValue());
}
/**
* Reading from an input source and then trying to restore causes an error.
*/
public void testInvalidRestore() throws Exception {
getAsItemStream(itemReader).open(executionContext);
Foo foo1 = (Foo) itemReader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) itemReader.read();
assertEquals(2, foo2.getValue());
getAsItemStream(itemReader).update(executionContext);
// create new input source
itemReader = createItemReader();
Foo foo = (Foo) itemReader.read();
assertEquals(1, foo.getValue());
try {
getAsItemStream(itemReader).open(executionContext);
fail();
}
catch (IllegalStateException ex) {
// expected
}
}
/**
* Empty restart data should be handled gracefully.
* @throws Exception
*/
public void testRestoreFromEmptyData() throws Exception {
ExecutionContext streamContext = new ExecutionContext();
getAsItemStream(itemReader).open(streamContext);
Foo foo = (Foo) itemReader.read();
assertEquals(1, foo.getValue());
}
/**
* Rollback scenario.
* @throws Exception
*/
public void testRollback() throws Exception {
Foo foo1 = (Foo) itemReader.read();
commit();
Foo foo2 = (Foo) itemReader.read();
Assert.state(!foo2.equals(foo1));
Foo foo3 = (Foo) itemReader.read();
Assert.state(!foo2.equals(foo3));
rollback();
assertEquals(foo2, itemReader.read());
}
private void commit() {
itemReader.mark();
}
private void rollback() {
itemReader.reset();
}
private ItemStream getAsItemStream(ItemReader source) {
return (ItemStream) source;
}
private InitializingBean getAsInitializingBean(ItemReader source) {
return (InitializingBean) source;
}
private DisposableBean getAsDisposableBean(ItemReader source) {
return (DisposableBean) source;
}
}
package org.springframework.batch.io.sql;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
import org.springframework.util.Assert;
/**
* Common scenarios for testing {@link ItemReader} implementations which read data from database.
*
* @author Lucas Ward
* @author Robert Kasanicky
*/
public abstract class AbstractJdbcItemReaderIntegrationTests extends AbstractTransactionalDataSourceSpringContextTests {
protected ItemReader itemReader;
protected ExecutionContext executionContext;
/**
* @return input source with all necessary dependencies set
*/
protected abstract ItemReader createItemReader() throws Exception;
protected String[] getConfigLocations(){
return new String[] { "org/springframework/batch/io/sql/data-source-context.xml"};
}
protected void onSetUp()throws Exception{
super.onSetUp();
itemReader = createItemReader();
getAsInitializingBean(itemReader).afterPropertiesSet();
executionContext = new ExecutionContext();
}
protected void onTearDown()throws Exception {
getAsDisposableBean(itemReader).destroy();
super.onTearDown();
}
/**
* Regular scenario - read all rows and eventually return null.
*/
public void testNormalProcessing() throws Exception {
getAsInitializingBean(itemReader).afterPropertiesSet();
getAsItemStream(itemReader).open(executionContext);
Foo foo1 = (Foo) itemReader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) itemReader.read();
assertEquals(2, foo2.getValue());
Foo foo3 = (Foo) itemReader.read();
assertEquals(3, foo3.getValue());
Foo foo4 = (Foo) itemReader.read();
assertEquals(4, foo4.getValue());
Foo foo5 = (Foo) itemReader.read();
assertEquals(5, foo5.getValue());
assertNull(itemReader.read());
}
/**
* Restart scenario.
* @throws Exception
*/
public void testRestart() throws Exception {
getAsItemStream(itemReader).open(executionContext);
Foo foo1 = (Foo) itemReader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) itemReader.read();
assertEquals(2, foo2.getValue());
getAsItemStream(itemReader).update(executionContext);
// create new input source
itemReader = createItemReader();
getAsItemStream(itemReader).open(executionContext);
Foo fooAfterRestart = (Foo) itemReader.read();
assertEquals(3, fooAfterRestart.getValue());
}
/**
* Reading from an input source and then trying to restore causes an error.
*/
public void testInvalidRestore() throws Exception {
getAsItemStream(itemReader).open(executionContext);
Foo foo1 = (Foo) itemReader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) itemReader.read();
assertEquals(2, foo2.getValue());
getAsItemStream(itemReader).update(executionContext);
// create new input source
itemReader = createItemReader();
Foo foo = (Foo) itemReader.read();
assertEquals(1, foo.getValue());
try {
getAsItemStream(itemReader).open(executionContext);
fail();
}
catch (IllegalStateException ex) {
// expected
}
}
/**
* Empty restart data should be handled gracefully.
* @throws Exception
*/
public void testRestoreFromEmptyData() throws Exception {
ExecutionContext streamContext = new ExecutionContext();
getAsItemStream(itemReader).open(streamContext);
Foo foo = (Foo) itemReader.read();
assertEquals(1, foo.getValue());
}
/**
* Rollback scenario.
* @throws Exception
*/
public void testRollback() throws Exception {
Foo foo1 = (Foo) itemReader.read();
commit();
Foo foo2 = (Foo) itemReader.read();
Assert.state(!foo2.equals(foo1));
Foo foo3 = (Foo) itemReader.read();
Assert.state(!foo2.equals(foo3));
rollback();
assertEquals(foo2, itemReader.read());
}
private void commit() {
itemReader.mark();
}
private void rollback() {
itemReader.reset();
}
private ItemStream getAsItemStream(ItemReader source) {
return (ItemStream) source;
}
private InitializingBean getAsInitializingBean(ItemReader source) {
return (InitializingBean) source;
}
private DisposableBean getAsDisposableBean(ItemReader source) {
return (DisposableBean) source;
}
}

View File

@@ -1,253 +1,253 @@
package org.springframework.batch.io.support;
import org.springframework.batch.io.Skippable;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
import org.springframework.util.Assert;
/**
* Common scenarios for testing {@link ItemReader} implementations which read
* data from database.
*
* @author Lucas Ward
* @author Robert Kasanicky
*/
public abstract class AbstractDataSourceItemReaderIntegrationTests extends
AbstractTransactionalDataSourceSpringContextTests {
protected ItemReader reader;
protected ExecutionContext executionContext;
/**
* @return configured input source ready for use
*/
protected abstract ItemReader createItemReader() throws Exception;
protected String[] getConfigLocations() {
return new String[] { "org/springframework/batch/io/sql/data-source-context.xml" };
}
/*
* (non-Javadoc)
* @see org.springframework.test.AbstractTransactionalSpringContextTests#onSetUpInTransaction()
*/
protected void onSetUpInTransaction() throws Exception {
super.onSetUpInTransaction();
reader = createItemReader();
executionContext = new ExecutionContext();
}
/*
* (non-Javadoc)
* @see org.springframework.test.AbstractTransactionalSpringContextTests#onTearDownAfterTransaction()
*/
protected void onTearDownAfterTransaction() throws Exception {
getAsItemStream(reader).close(null);
super.onTearDownAfterTransaction();
}
/**
* Regular scenario - read all rows and eventually return null.
*/
public void testNormalProcessing() throws Exception {
getAsInitializingBean(reader).afterPropertiesSet();
Foo foo1 = (Foo) reader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) reader.read();
assertEquals(2, foo2.getValue());
Foo foo3 = (Foo) reader.read();
assertEquals(3, foo3.getValue());
Foo foo4 = (Foo) reader.read();
assertEquals(4, foo4.getValue());
Foo foo5 = (Foo) reader.read();
assertEquals(5, foo5.getValue());
assertNull(reader.read());
}
/**
* Restart scenario - read records, save restart data, create new input
* source and restore from restart data - the new input source should
* continue where the old one finished.
*/
public void testRestart() throws Exception {
getAsItemStream(reader).open(executionContext);
Foo foo1 = (Foo) reader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) reader.read();
assertEquals(2, foo2.getValue());
getAsItemStream(reader).update(executionContext);
// create new input source
reader = createItemReader();
getAsItemStream(reader).open(executionContext);
Foo fooAfterRestart = (Foo) reader.read();
assertEquals(3, fooAfterRestart.getValue());
}
/**
* Reading from an input source and then trying to restore causes an error.
*/
public void testInvalidRestore() throws Exception {
getAsItemStream(reader).open(executionContext);
Foo foo1 = (Foo) reader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) reader.read();
assertEquals(2, foo2.getValue());
getAsItemStream(reader).update(executionContext);
// create new input source
reader = createItemReader();
Foo foo = (Foo) reader.read();
assertEquals(1, foo.getValue());
try {
getAsItemStream(reader).open(executionContext);
fail();
}
catch (IllegalStateException ex) {
// expected
}
}
/**
* Empty restart data should be handled gracefully.
* @throws Exception
*/
public void testRestoreFromEmptyData() throws Exception {
getAsItemStream(reader).update(executionContext);
Foo foo = (Foo) reader.read();
assertEquals(1, foo.getValue());
}
/**
* Rollback scenario - input source rollbacks to last commit point.
* @throws Exception
*/
public void testRollback() throws Exception {
Foo foo1 = (Foo) reader.read();
commit();
Foo foo2 = (Foo) reader.read();
Assert.state(!foo2.equals(foo1));
Foo foo3 = (Foo) reader.read();
Assert.state(!foo2.equals(foo3));
rollback();
assertEquals(foo2, reader.read());
}
/**
* Rollback scenario with skip - input source rollbacks to last commit
* point.
* @throws Exception
*/
public void testRollbackAndSkip() throws Exception {
if (!(reader instanceof Skippable)) {
return;
}
Foo foo1 = (Foo) reader.read();
commit();
Foo foo2 = (Foo) reader.read();
Assert.state(!foo2.equals(foo1));
Foo foo3 = (Foo) reader.read();
Assert.state(!foo2.equals(foo3));
getAsSkippable(reader).skip();
rollback();
assertEquals(foo2, reader.read());
Foo foo4 = (Foo) reader.read();
assertEquals(4, foo4.getValue());
}
/**
* Rollback scenario with skip and restart - input source rollbacks to last
* commit point.
* @throws Exception
*/
public void testRollbackSkipAndRestart() throws Exception {
if (!(reader instanceof Skippable)) {
return;
}
getAsItemStream(reader).open(executionContext);
Foo foo1 = (Foo) reader.read();
commit();
Foo foo2 = (Foo) reader.read();
Assert.state(!foo2.equals(foo1));
Foo foo3 = (Foo) reader.read();
Assert.state(!foo2.equals(foo3));
getAsSkippable(reader).skip();
rollback();
getAsItemStream(reader).update(executionContext);
// create new input source
reader = createItemReader();
getAsItemStream(reader).open(executionContext);
assertEquals(foo2, reader.read());
Foo foo4 = (Foo) reader.read();
assertEquals(4, foo4.getValue());
}
private void commit() {
reader.mark();
}
private void rollback() {
reader.reset();
}
private Skippable getAsSkippable(ItemReader source) {
return (Skippable) source;
}
private ItemStream getAsItemStream(ItemReader source) {
return (ItemStream) source;
}
private InitializingBean getAsInitializingBean(ItemReader source) {
return (InitializingBean) source;
}
}
package org.springframework.batch.io.support;
import org.springframework.batch.io.Skippable;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
import org.springframework.util.Assert;
/**
* Common scenarios for testing {@link ItemReader} implementations which read
* data from database.
*
* @author Lucas Ward
* @author Robert Kasanicky
*/
public abstract class AbstractDataSourceItemReaderIntegrationTests extends
AbstractTransactionalDataSourceSpringContextTests {
protected ItemReader reader;
protected ExecutionContext executionContext;
/**
* @return configured input source ready for use
*/
protected abstract ItemReader createItemReader() throws Exception;
protected String[] getConfigLocations() {
return new String[] { "org/springframework/batch/io/sql/data-source-context.xml" };
}
/*
* (non-Javadoc)
* @see org.springframework.test.AbstractTransactionalSpringContextTests#onSetUpInTransaction()
*/
protected void onSetUpInTransaction() throws Exception {
super.onSetUpInTransaction();
reader = createItemReader();
executionContext = new ExecutionContext();
}
/*
* (non-Javadoc)
* @see org.springframework.test.AbstractTransactionalSpringContextTests#onTearDownAfterTransaction()
*/
protected void onTearDownAfterTransaction() throws Exception {
getAsItemStream(reader).close(null);
super.onTearDownAfterTransaction();
}
/**
* Regular scenario - read all rows and eventually return null.
*/
public void testNormalProcessing() throws Exception {
getAsInitializingBean(reader).afterPropertiesSet();
Foo foo1 = (Foo) reader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) reader.read();
assertEquals(2, foo2.getValue());
Foo foo3 = (Foo) reader.read();
assertEquals(3, foo3.getValue());
Foo foo4 = (Foo) reader.read();
assertEquals(4, foo4.getValue());
Foo foo5 = (Foo) reader.read();
assertEquals(5, foo5.getValue());
assertNull(reader.read());
}
/**
* Restart scenario - read records, save restart data, create new input
* source and restore from restart data - the new input source should
* continue where the old one finished.
*/
public void testRestart() throws Exception {
getAsItemStream(reader).open(executionContext);
Foo foo1 = (Foo) reader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) reader.read();
assertEquals(2, foo2.getValue());
getAsItemStream(reader).update(executionContext);
// create new input source
reader = createItemReader();
getAsItemStream(reader).open(executionContext);
Foo fooAfterRestart = (Foo) reader.read();
assertEquals(3, fooAfterRestart.getValue());
}
/**
* Reading from an input source and then trying to restore causes an error.
*/
public void testInvalidRestore() throws Exception {
getAsItemStream(reader).open(executionContext);
Foo foo1 = (Foo) reader.read();
assertEquals(1, foo1.getValue());
Foo foo2 = (Foo) reader.read();
assertEquals(2, foo2.getValue());
getAsItemStream(reader).update(executionContext);
// create new input source
reader = createItemReader();
Foo foo = (Foo) reader.read();
assertEquals(1, foo.getValue());
try {
getAsItemStream(reader).open(executionContext);
fail();
}
catch (IllegalStateException ex) {
// expected
}
}
/**
* Empty restart data should be handled gracefully.
* @throws Exception
*/
public void testRestoreFromEmptyData() throws Exception {
getAsItemStream(reader).update(executionContext);
Foo foo = (Foo) reader.read();
assertEquals(1, foo.getValue());
}
/**
* Rollback scenario - input source rollbacks to last commit point.
* @throws Exception
*/
public void testRollback() throws Exception {
Foo foo1 = (Foo) reader.read();
commit();
Foo foo2 = (Foo) reader.read();
Assert.state(!foo2.equals(foo1));
Foo foo3 = (Foo) reader.read();
Assert.state(!foo2.equals(foo3));
rollback();
assertEquals(foo2, reader.read());
}
/**
* Rollback scenario with skip - input source rollbacks to last commit
* point.
* @throws Exception
*/
public void testRollbackAndSkip() throws Exception {
if (!(reader instanceof Skippable)) {
return;
}
Foo foo1 = (Foo) reader.read();
commit();
Foo foo2 = (Foo) reader.read();
Assert.state(!foo2.equals(foo1));
Foo foo3 = (Foo) reader.read();
Assert.state(!foo2.equals(foo3));
getAsSkippable(reader).skip();
rollback();
assertEquals(foo2, reader.read());
Foo foo4 = (Foo) reader.read();
assertEquals(4, foo4.getValue());
}
/**
* Rollback scenario with skip and restart - input source rollbacks to last
* commit point.
* @throws Exception
*/
public void testRollbackSkipAndRestart() throws Exception {
if (!(reader instanceof Skippable)) {
return;
}
getAsItemStream(reader).open(executionContext);
Foo foo1 = (Foo) reader.read();
commit();
Foo foo2 = (Foo) reader.read();
Assert.state(!foo2.equals(foo1));
Foo foo3 = (Foo) reader.read();
Assert.state(!foo2.equals(foo3));
getAsSkippable(reader).skip();
rollback();
getAsItemStream(reader).update(executionContext);
// create new input source
reader = createItemReader();
getAsItemStream(reader).open(executionContext);
assertEquals(foo2, reader.read());
Foo foo4 = (Foo) reader.read();
assertEquals(4, foo4.getValue());
}
private void commit() {
reader.mark();
}
private void rollback() {
reader.reset();
}
private Skippable getAsSkippable(ItemReader source) {
return (Skippable) source;
}
private ItemStream getAsItemStream(ItemReader source) {
return (ItemStream) source;
}
private InitializingBean getAsInitializingBean(ItemReader source) {
return (InitializingBean) source;
}
}

View File

@@ -1,132 +1,132 @@
package org.springframework.batch.io.support;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.util.Assert;
import junit.framework.TestCase;
/**
* Tests for {@link FileUtils}
*
* @author Robert Kasanicky
*/
public class FileUtilsTests extends TestCase {
private File file = new File("FileUtilsTests.tmp");
/**
* No restart + file should not be overwritten => file is created if it does
* not exist, exception is thrown if it already exists
*/
public void testNoRestart() throws Exception {
FileUtils.setUpOutputFile(file, false, false);
assertTrue(file.exists());
try {
FileUtils.setUpOutputFile(file, false, false);
fail();
}
catch (Exception e) {
// expected
}
file.delete();
Assert.state(!file.exists());
FileUtils.setUpOutputFile(file, false, true);
assertTrue(file.exists());
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("testString");
writer.close();
long size = file.length();
Assert.state(size > 0);
FileUtils.setUpOutputFile(file, false, true);
long newSize = file.length();
assertTrue(size != newSize);
assertEquals(0, newSize);
}
/**
* In case of restart, the file is supposed to exist and exception is thrown
* if it does not.
*/
public void testRestart() throws Exception {
try {
FileUtils.setUpOutputFile(file, true, false);
fail();
}
catch (DataAccessResourceFailureException e) {
// expected
}
try {
FileUtils.setUpOutputFile(file, true, true);
fail();
}
catch (DataAccessResourceFailureException e) {
// expected
}
file.createNewFile();
assertTrue(file.exists());
// with existing file there should be no trouble
FileUtils.setUpOutputFile(file, true, false);
FileUtils.setUpOutputFile(file, true, true);
}
/**
* If the directories on the file path do not exist, they should be created
*/
public void testCreateDirectoryStructure() {
File file = new File("testDirectory/testDirectory2/testFile.tmp");
File dir1 = new File("testDirectory");
File dir2 = new File("testDirectory/testDirectory2");
try {
FileUtils.setUpOutputFile(file, false, false);
assertTrue(file.exists());
assertTrue(dir1.exists());
assertTrue(dir2.exists());
}
finally {
file.delete();
dir2.delete();
dir1.delete();
}
}
public void testBadFile(){
File file = new File("new file"){
public boolean createNewFile() throws IOException {
throw new IOException();
}
};
try{
FileUtils.setUpOutputFile(file, false, false);
fail();
}catch(DataAccessResourceFailureException ex){
assertTrue(ex.getCause() instanceof IOException);
}finally{
file.delete();
}
}
protected void setUp() throws Exception {
Assert.state(!file.exists());
}
protected void tearDown() throws Exception {
file.delete();
}
}
package org.springframework.batch.io.support;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.util.Assert;
import junit.framework.TestCase;
/**
* Tests for {@link FileUtils}
*
* @author Robert Kasanicky
*/
public class FileUtilsTests extends TestCase {
private File file = new File("FileUtilsTests.tmp");
/**
* No restart + file should not be overwritten => file is created if it does
* not exist, exception is thrown if it already exists
*/
public void testNoRestart() throws Exception {
FileUtils.setUpOutputFile(file, false, false);
assertTrue(file.exists());
try {
FileUtils.setUpOutputFile(file, false, false);
fail();
}
catch (Exception e) {
// expected
}
file.delete();
Assert.state(!file.exists());
FileUtils.setUpOutputFile(file, false, true);
assertTrue(file.exists());
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("testString");
writer.close();
long size = file.length();
Assert.state(size > 0);
FileUtils.setUpOutputFile(file, false, true);
long newSize = file.length();
assertTrue(size != newSize);
assertEquals(0, newSize);
}
/**
* In case of restart, the file is supposed to exist and exception is thrown
* if it does not.
*/
public void testRestart() throws Exception {
try {
FileUtils.setUpOutputFile(file, true, false);
fail();
}
catch (DataAccessResourceFailureException e) {
// expected
}
try {
FileUtils.setUpOutputFile(file, true, true);
fail();
}
catch (DataAccessResourceFailureException e) {
// expected
}
file.createNewFile();
assertTrue(file.exists());
// with existing file there should be no trouble
FileUtils.setUpOutputFile(file, true, false);
FileUtils.setUpOutputFile(file, true, true);
}
/**
* If the directories on the file path do not exist, they should be created
*/
public void testCreateDirectoryStructure() {
File file = new File("testDirectory/testDirectory2/testFile.tmp");
File dir1 = new File("testDirectory");
File dir2 = new File("testDirectory/testDirectory2");
try {
FileUtils.setUpOutputFile(file, false, false);
assertTrue(file.exists());
assertTrue(dir1.exists());
assertTrue(dir2.exists());
}
finally {
file.delete();
dir2.delete();
dir1.delete();
}
}
public void testBadFile(){
File file = new File("new file"){
public boolean createNewFile() throws IOException {
throw new IOException();
}
};
try{
FileUtils.setUpOutputFile(file, false, false);
fail();
}catch(DataAccessResourceFailureException ex){
assertTrue(ex.getCause() instanceof IOException);
}finally{
file.delete();
}
}
protected void setUp() throws Exception {
Assert.state(!file.exists());
}
protected void tearDown() throws Exception {
file.delete();
}
}

View File

@@ -1,206 +1,206 @@
/*
* 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.io.support;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.exception.ClearFailedException;
import org.springframework.batch.item.exception.FlushFailedException;
import org.springframework.batch.repeat.context.RepeatContextSupport;
import org.springframework.batch.repeat.synch.RepeatSynchronizationManager;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* @author Dave Syer
*
*/
public class HibernateAwareItemWriterTests extends TestCase {
private class HibernateTemplateWrapper extends HibernateTemplate {
public void flush() throws DataAccessException {
list.add("flush");
}
public void clear() {
list.add("clear");
};
}
private class StubItemWriter implements ItemWriter {
public void write(Object item) {
list.add(item);
}
public void clear() throws ClearFailedException {
list.add("delegateClear");
}
public void flush() throws FlushFailedException {
list.add("delegateFlush");
}
}
HibernateAwareItemWriter writer = new HibernateAwareItemWriter();
final List list = new ArrayList();
private RepeatContextSupport context;
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
writer.setDelegate(new StubItemWriter());
context = new RepeatContextSupport(null);
RepeatSynchronizationManager.register(context);
writer.setHibernateTemplate(new HibernateTemplateWrapper());
list.clear();
}
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
Map map = TransactionSynchronizationManager.getResourceMap();
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
TransactionSynchronizationManager.unbindResource(key);
}
RepeatSynchronizationManager.clear();
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#initDao()}.
*
* @throws Exception
*/
public void testAfterPropertiesSet() throws Exception {
writer = new HibernateAwareItemWriter();
try {
writer.afterPropertiesSet();
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
assertTrue("Wrong message for exception: " + e.getMessage(), e
.getMessage().indexOf("delegate") >= 0);
}
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#initDao()}.
*
* @throws Exception
*/
public void testAfterPropertiesSetWithDelegate() throws Exception {
writer.afterPropertiesSet();
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#write(java.lang.Object)}.
* @throws Exception
*/
public void testWrite() throws Exception {
writer.write("foo");
assertEquals(1, list.size());
assertTrue(list.contains("foo"));
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#write(java.lang.Object)}.
*/
public void testFlushWithFailure() throws Exception{
final RuntimeException ex = new RuntimeException("bar");
writer.setHibernateTemplate(new HibernateTemplate() {
public void flush() throws DataAccessException {
throw ex;
}
});
try {
writer.flush();
fail("Expected RuntimeException");
} catch (RuntimeException e) {
assertEquals("bar", e.getMessage());
}
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#write(java.lang.Object)}.
* @throws Exception
*/
public void testWriteAndFlushWithFailure() throws Exception {
final RuntimeException ex = new RuntimeException("bar");
writer.setHibernateTemplate(new HibernateTemplateWrapper() {
public void flush() throws DataAccessException {
throw ex;
}
});
writer.write("foo");
try {
writer.flush();
fail("Expected RuntimeException");
} catch (RuntimeException e) {
assertEquals("bar", e.getMessage());
}
assertEquals(1, list.size());
writer.setHibernateTemplate(new HibernateTemplateWrapper() {
public void flush() throws DataAccessException {
list.add("flush");
}
});
writer.write("foo");
assertEquals(4, list.size());
assertTrue(list.contains("flush"));
assertTrue(list.contains("clear"));
assertTrue(context.isCompleteOnly());
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#close(org.springframework.batch.repeat.RepeatContext)}.
*/
public void testFlush() throws Exception{
writer.flush();
assertEquals(3, list.size());
assertTrue(list.contains("flush"));
assertTrue(list.contains("clear"));
assertTrue(list.contains("delegateFlush"));
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#close(org.springframework.batch.repeat.RepeatContext)}.
*/
public void testClear() throws Exception{
writer.clear();
assertEquals(2, list.size());
assertTrue(list.contains("clear"));
assertTrue(list.contains("delegateClear"));
}
}
/*
* 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.io.support;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.exception.ClearFailedException;
import org.springframework.batch.item.exception.FlushFailedException;
import org.springframework.batch.repeat.context.RepeatContextSupport;
import org.springframework.batch.repeat.synch.RepeatSynchronizationManager;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* @author Dave Syer
*
*/
public class HibernateAwareItemWriterTests extends TestCase {
private class HibernateTemplateWrapper extends HibernateTemplate {
public void flush() throws DataAccessException {
list.add("flush");
}
public void clear() {
list.add("clear");
};
}
private class StubItemWriter implements ItemWriter {
public void write(Object item) {
list.add(item);
}
public void clear() throws ClearFailedException {
list.add("delegateClear");
}
public void flush() throws FlushFailedException {
list.add("delegateFlush");
}
}
HibernateAwareItemWriter writer = new HibernateAwareItemWriter();
final List list = new ArrayList();
private RepeatContextSupport context;
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
writer.setDelegate(new StubItemWriter());
context = new RepeatContextSupport(null);
RepeatSynchronizationManager.register(context);
writer.setHibernateTemplate(new HibernateTemplateWrapper());
list.clear();
}
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
Map map = TransactionSynchronizationManager.getResourceMap();
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
TransactionSynchronizationManager.unbindResource(key);
}
RepeatSynchronizationManager.clear();
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#initDao()}.
*
* @throws Exception
*/
public void testAfterPropertiesSet() throws Exception {
writer = new HibernateAwareItemWriter();
try {
writer.afterPropertiesSet();
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
assertTrue("Wrong message for exception: " + e.getMessage(), e
.getMessage().indexOf("delegate") >= 0);
}
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#initDao()}.
*
* @throws Exception
*/
public void testAfterPropertiesSetWithDelegate() throws Exception {
writer.afterPropertiesSet();
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#write(java.lang.Object)}.
* @throws Exception
*/
public void testWrite() throws Exception {
writer.write("foo");
assertEquals(1, list.size());
assertTrue(list.contains("foo"));
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#write(java.lang.Object)}.
*/
public void testFlushWithFailure() throws Exception{
final RuntimeException ex = new RuntimeException("bar");
writer.setHibernateTemplate(new HibernateTemplate() {
public void flush() throws DataAccessException {
throw ex;
}
});
try {
writer.flush();
fail("Expected RuntimeException");
} catch (RuntimeException e) {
assertEquals("bar", e.getMessage());
}
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#write(java.lang.Object)}.
* @throws Exception
*/
public void testWriteAndFlushWithFailure() throws Exception {
final RuntimeException ex = new RuntimeException("bar");
writer.setHibernateTemplate(new HibernateTemplateWrapper() {
public void flush() throws DataAccessException {
throw ex;
}
});
writer.write("foo");
try {
writer.flush();
fail("Expected RuntimeException");
} catch (RuntimeException e) {
assertEquals("bar", e.getMessage());
}
assertEquals(1, list.size());
writer.setHibernateTemplate(new HibernateTemplateWrapper() {
public void flush() throws DataAccessException {
list.add("flush");
}
});
writer.write("foo");
assertEquals(4, list.size());
assertTrue(list.contains("flush"));
assertTrue(list.contains("clear"));
assertTrue(context.isCompleteOnly());
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#close(org.springframework.batch.repeat.RepeatContext)}.
*/
public void testFlush() throws Exception{
writer.flush();
assertEquals(3, list.size());
assertTrue(list.contains("flush"));
assertTrue(list.contains("clear"));
assertTrue(list.contains("delegateFlush"));
}
/**
* Test method for
* {@link org.springframework.batch.io.support.HibernateAwareItemWriter#close(org.springframework.batch.repeat.RepeatContext)}.
*/
public void testClear() throws Exception{
writer.clear();
assertEquals(2, list.size());
assertTrue(list.contains("clear"));
assertTrue(list.contains("delegateClear"));
}
}

View File

@@ -1,30 +1,30 @@
package org.springframework.batch.io.xml;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
/**
* Helper methods for working with XML Events.
*
* @author Robert Kasanicky
*/
public class EventHelper {
//utility class
private EventHelper() {}
/**
* @return element name assuming the event is instance of StartElement
*/
public static String startElementName(XMLEvent event) {
return ((StartElement) event).getName().getLocalPart();
}
/**
* @return element name assuming the event is instance of EndElement
*/
public static String endElementName(XMLEvent event) {
return ((EndElement) event).getName().getLocalPart();
}
}
package org.springframework.batch.io.xml;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
/**
* Helper methods for working with XML Events.
*
* @author Robert Kasanicky
*/
public class EventHelper {
//utility class
private EventHelper() {}
/**
* @return element name assuming the event is instance of StartElement
*/
public static String startElementName(XMLEvent event) {
return ((StartElement) event).getName().getLocalPart();
}
/**
* @return element name assuming the event is instance of EndElement
*/
public static String endElementName(XMLEvent event) {
return ((EndElement) event).getName().getLocalPart();
}
}

View File

@@ -1,424 +1,424 @@
package org.springframework.batch.io.xml;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.exception.StreamException;
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataAccessResourceFailureException;
/**
* Tests for {@link StaxEventItemReader}.
*
* @author Robert Kasanicky
*/
public class StaxEventItemReaderTests extends TestCase {
// object under test
private StaxEventItemReader source;
// test xml input
private String xml = "<root> <fragment> <misc1/> </fragment> <misc2/> <fragment> testString </fragment> </root>";
private EventReaderDeserializer deserializer = new MockFragmentDeserializer();
private static final String FRAGMENT_ROOT_ELEMENT = "fragment";
private ExecutionContext executionContext;
protected void setUp() throws Exception {
this.executionContext = new ExecutionContext();
source = createNewInputSouce();
}
public void testAfterPropertiesSet() throws Exception {
source.afterPropertiesSet();
}
public void testAfterPropertesSetException() throws Exception {
source.setResource(null);
try {
source.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected;
}
source = createNewInputSouce();
source.setFragmentRootElementName("");
try {
source.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
source = createNewInputSouce();
source.setFragmentDeserializer(null);
try {
source.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
}
/**
* Regular usage scenario. ItemReader should pass XML fragments to
* deserializer wrapped with StartDocument and EndDocument events.
*/
public void testFragmentWrapping() throws Exception {
source.afterPropertiesSet();
source.open(executionContext);
// see asserts in the mock deserializer
assertNotNull(source.read());
assertNotNull(source.read());
assertNull(source.read()); // there are only two fragments
source.close(executionContext);
}
/**
* Cursor is moved before beginning of next fragment.
*/
public void testMoveCursorToNextFragment() throws XMLStreamException, FactoryConfigurationError, IOException {
Resource resource = new ByteArrayResource(xml.getBytes());
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(resource.getInputStream());
final int EXPECTED_NUMBER_OF_FRAGMENTS = 2;
for (int i = 0; i < EXPECTED_NUMBER_OF_FRAGMENTS; i++) {
assertTrue(source.moveCursorToNextFragment(reader));
assertTrue(EventHelper.startElementName(reader.peek()).equals("fragment"));
reader.nextEvent(); // move away from beginning of fragment
}
assertFalse(source.moveCursorToNextFragment(reader));
}
/**
* Save restart data and restore from it.
*/
public void testRestart() {
source.open(executionContext);
source.read();
source.update(executionContext);
System.out.println(executionContext);
assertEquals(1, executionContext.getLong(StaxEventItemReader.class.getSimpleName() + ".read.count"));
List expectedAfterRestart = (List) source.read();
source = createNewInputSouce();
source.open(executionContext);
List afterRestart = (List) source.read();
assertEquals(expectedAfterRestart.size(), afterRestart.size());
}
/**
* Restore point must not exceed end of file, input source must not be
* already initialised when restoring.
*/
public void testInvalidRestore() {
ExecutionContext context = new ExecutionContext();
context.putLong(StaxEventItemReader.class.getSimpleName() + ".read.count", 100000);
try {
source.open(context);
fail("Expected StreamException");
}
catch (StreamException e) {
// expected
String message = e.getMessage();
assertTrue("Wrong message: "+message, message.contains("must be before"));
}
}
public void testRestoreWorksFromClosedStream() throws Exception {
source.close(executionContext);
source.update(executionContext);
}
/**
* Skipping marked records after rollback.
*/
public void testSkip() {
source.open(executionContext);
List first = (List) source.read();
source.skip();
List second = (List) source.read();
assertFalse(first.equals(second));
source.reset();
assertEquals(second, source.read());
}
/**
* Rollback to last commited record.
*/
public void testRollback() {
source.open(executionContext);
// rollback between deserializing records
List first = (List) source.read();
source.mark();
List second = (List) source.read();
assertFalse(first.equals(second));
source.reset();
assertEquals(second, source.read());
// rollback while deserializing record
source.reset();
source.setFragmentDeserializer(new ExceptionFragmentDeserializer());
try {
source.read();
}
catch (Exception expected) {
source.reset();
}
source.setFragmentDeserializer(deserializer);
assertEquals(second, source.read());
}
/**
* Statistics return the current record count. Calling read after end of
* input does not increase the counter.
*/
public void testExecutionContext() {
final int NUMBER_OF_RECORDS = 2;
source.open(executionContext);
source.update(executionContext);
for (int i = 0; i < NUMBER_OF_RECORDS; i++) {
long recordCount = extractRecordCount();
assertEquals(i, recordCount);
source.read();
source.update(executionContext);
}
assertEquals(NUMBER_OF_RECORDS, extractRecordCount());
source.read();
assertEquals(NUMBER_OF_RECORDS, extractRecordCount());
}
private long extractRecordCount() {
return executionContext.getLong(StaxEventItemReader.class.getSimpleName() + ".read.count");
}
public void testCloseWithoutOpen() throws Exception {
source.close(null);
// No error!
}
public void testClose() throws Exception {
MockStaxEventItemReader newSource = new MockStaxEventItemReader();
Resource resource = new ByteArrayResource(xml.getBytes());
newSource.setResource(resource);
newSource.setFragmentRootElementName(FRAGMENT_ROOT_ELEMENT);
newSource.setFragmentDeserializer(deserializer);
newSource.open(executionContext);
Object item = newSource.read();
assertNotNull(item);
assertTrue(newSource.isOpenCalled());
newSource.close(null);
newSource.setOpenCalled(false);
// calling read again should require re-initialization because of close
try {
item = newSource.read();
fail("Expected StreamException");
}
catch (StreamException e) {
// expected
}
}
public void testOpenBadIOInput() {
source.setResource(new AbstractResource() {
public String getDescription() {
return null;
}
public InputStream getInputStream() throws IOException {
throw new IOException();
}
public boolean exists() {
return true;
}
});
try {
source.open(executionContext);
}
catch (DataAccessResourceFailureException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
}
public void testNonExistentResource() throws Exception {
source.setResource(new NonExistentResource());
source.afterPropertiesSet();
try {
source.open(executionContext);
fail();
}
catch (IllegalStateException ex) {
// expected
}
}
public void testRuntimeFileCreation() throws Exception {
source.setResource(new NonExistentResource());
source.afterPropertiesSet();
source.setResource(new ByteArrayResource(xml.getBytes()));
source.open(executionContext);
source.read();
}
private StaxEventItemReader createNewInputSouce() {
Resource resource = new ByteArrayResource(xml.getBytes());
StaxEventItemReader newSource = new StaxEventItemReader();
newSource.setResource(resource);
newSource.setFragmentRootElementName(FRAGMENT_ROOT_ELEMENT);
newSource.setFragmentDeserializer(deserializer);
newSource.setSaveState(true);
return newSource;
}
/**
* A simple XMLEvent deserializer mock - check for the start and end
* document events for the fragment root & end tags + skips the fragment
* contents.
*/
private static class MockFragmentDeserializer implements EventReaderDeserializer {
/**
* A simple mapFragment implementation checking the
* StaxEventReaderItemReader basic read functionality.
* @param eventReader
* @return list of the events from fragment body
*/
public Object deserializeFragment(XMLEventReader eventReader) {
List fragmentContent;
try {
// first event should be StartDocument
XMLEvent event1 = eventReader.nextEvent();
assertTrue(event1.isStartDocument());
// second should be StartElement of the fragment
XMLEvent event2 = eventReader.nextEvent();
assertTrue(event2.isStartElement());
assertTrue(EventHelper.startElementName(event2).equals(FRAGMENT_ROOT_ELEMENT));
// jump before the end of fragment
fragmentContent = readRecordsInsideFragment(eventReader);
// end of fragment
XMLEvent event3 = eventReader.nextEvent();
assertTrue(event3.isEndElement());
assertTrue(EventHelper.endElementName(event3).equals(FRAGMENT_ROOT_ELEMENT));
// EndDocument should follow the end of fragment
XMLEvent event4 = eventReader.nextEvent();
assertTrue(event4.isEndDocument());
}
catch (XMLStreamException e) {
throw new RuntimeException("Error occured in FragmentDeserializer", e);
}
return fragmentContent;
}
/**
* Skips the XML fragment contents.
*/
private List readRecordsInsideFragment(XMLEventReader eventReader) throws XMLStreamException {
XMLEvent eventInsideFragment;
List events = new ArrayList();
do {
eventInsideFragment = eventReader.peek();
if (eventInsideFragment instanceof EndElement
&& ((EndElement) eventInsideFragment).getName().getLocalPart().equals(FRAGMENT_ROOT_ELEMENT)) {
break;
}
events.add(eventReader.nextEvent());
} while (eventInsideFragment != null);
return events;
}
}
/**
* Moves cursor inside the fragment body and causes rollback.
*/
private static class ExceptionFragmentDeserializer implements EventReaderDeserializer {
public Object deserializeFragment(XMLEventReader eventReader) {
eventReader.next();
throw new RuntimeException();
}
}
private static class MockStaxEventItemReader extends StaxEventItemReader {
private boolean openCalled = false;
public void open(ExecutionContext executionContext) {
super.open(executionContext);
openCalled = true;
}
public boolean isOpenCalled() {
return openCalled;
}
public void setOpenCalled(boolean openCalled) {
this.openCalled = openCalled;
}
}
private class NonExistentResource extends AbstractResource {
public NonExistentResource() {
}
public boolean exists() {
return false;
}
public String getDescription() {
return "NonExistantResource";
}
public InputStream getInputStream() throws IOException {
return null;
}
}
}
package org.springframework.batch.io.xml;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.exception.StreamException;
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataAccessResourceFailureException;
/**
* Tests for {@link StaxEventItemReader}.
*
* @author Robert Kasanicky
*/
public class StaxEventItemReaderTests extends TestCase {
// object under test
private StaxEventItemReader source;
// test xml input
private String xml = "<root> <fragment> <misc1/> </fragment> <misc2/> <fragment> testString </fragment> </root>";
private EventReaderDeserializer deserializer = new MockFragmentDeserializer();
private static final String FRAGMENT_ROOT_ELEMENT = "fragment";
private ExecutionContext executionContext;
protected void setUp() throws Exception {
this.executionContext = new ExecutionContext();
source = createNewInputSouce();
}
public void testAfterPropertiesSet() throws Exception {
source.afterPropertiesSet();
}
public void testAfterPropertesSetException() throws Exception {
source.setResource(null);
try {
source.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected;
}
source = createNewInputSouce();
source.setFragmentRootElementName("");
try {
source.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
source = createNewInputSouce();
source.setFragmentDeserializer(null);
try {
source.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
}
/**
* Regular usage scenario. ItemReader should pass XML fragments to
* deserializer wrapped with StartDocument and EndDocument events.
*/
public void testFragmentWrapping() throws Exception {
source.afterPropertiesSet();
source.open(executionContext);
// see asserts in the mock deserializer
assertNotNull(source.read());
assertNotNull(source.read());
assertNull(source.read()); // there are only two fragments
source.close(executionContext);
}
/**
* Cursor is moved before beginning of next fragment.
*/
public void testMoveCursorToNextFragment() throws XMLStreamException, FactoryConfigurationError, IOException {
Resource resource = new ByteArrayResource(xml.getBytes());
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(resource.getInputStream());
final int EXPECTED_NUMBER_OF_FRAGMENTS = 2;
for (int i = 0; i < EXPECTED_NUMBER_OF_FRAGMENTS; i++) {
assertTrue(source.moveCursorToNextFragment(reader));
assertTrue(EventHelper.startElementName(reader.peek()).equals("fragment"));
reader.nextEvent(); // move away from beginning of fragment
}
assertFalse(source.moveCursorToNextFragment(reader));
}
/**
* Save restart data and restore from it.
*/
public void testRestart() {
source.open(executionContext);
source.read();
source.update(executionContext);
System.out.println(executionContext);
assertEquals(1, executionContext.getLong(StaxEventItemReader.class.getSimpleName() + ".read.count"));
List expectedAfterRestart = (List) source.read();
source = createNewInputSouce();
source.open(executionContext);
List afterRestart = (List) source.read();
assertEquals(expectedAfterRestart.size(), afterRestart.size());
}
/**
* Restore point must not exceed end of file, input source must not be
* already initialised when restoring.
*/
public void testInvalidRestore() {
ExecutionContext context = new ExecutionContext();
context.putLong(StaxEventItemReader.class.getSimpleName() + ".read.count", 100000);
try {
source.open(context);
fail("Expected StreamException");
}
catch (StreamException e) {
// expected
String message = e.getMessage();
assertTrue("Wrong message: "+message, message.contains("must be before"));
}
}
public void testRestoreWorksFromClosedStream() throws Exception {
source.close(executionContext);
source.update(executionContext);
}
/**
* Skipping marked records after rollback.
*/
public void testSkip() {
source.open(executionContext);
List first = (List) source.read();
source.skip();
List second = (List) source.read();
assertFalse(first.equals(second));
source.reset();
assertEquals(second, source.read());
}
/**
* Rollback to last commited record.
*/
public void testRollback() {
source.open(executionContext);
// rollback between deserializing records
List first = (List) source.read();
source.mark();
List second = (List) source.read();
assertFalse(first.equals(second));
source.reset();
assertEquals(second, source.read());
// rollback while deserializing record
source.reset();
source.setFragmentDeserializer(new ExceptionFragmentDeserializer());
try {
source.read();
}
catch (Exception expected) {
source.reset();
}
source.setFragmentDeserializer(deserializer);
assertEquals(second, source.read());
}
/**
* Statistics return the current record count. Calling read after end of
* input does not increase the counter.
*/
public void testExecutionContext() {
final int NUMBER_OF_RECORDS = 2;
source.open(executionContext);
source.update(executionContext);
for (int i = 0; i < NUMBER_OF_RECORDS; i++) {
long recordCount = extractRecordCount();
assertEquals(i, recordCount);
source.read();
source.update(executionContext);
}
assertEquals(NUMBER_OF_RECORDS, extractRecordCount());
source.read();
assertEquals(NUMBER_OF_RECORDS, extractRecordCount());
}
private long extractRecordCount() {
return executionContext.getLong(StaxEventItemReader.class.getSimpleName() + ".read.count");
}
public void testCloseWithoutOpen() throws Exception {
source.close(null);
// No error!
}
public void testClose() throws Exception {
MockStaxEventItemReader newSource = new MockStaxEventItemReader();
Resource resource = new ByteArrayResource(xml.getBytes());
newSource.setResource(resource);
newSource.setFragmentRootElementName(FRAGMENT_ROOT_ELEMENT);
newSource.setFragmentDeserializer(deserializer);
newSource.open(executionContext);
Object item = newSource.read();
assertNotNull(item);
assertTrue(newSource.isOpenCalled());
newSource.close(null);
newSource.setOpenCalled(false);
// calling read again should require re-initialization because of close
try {
item = newSource.read();
fail("Expected StreamException");
}
catch (StreamException e) {
// expected
}
}
public void testOpenBadIOInput() {
source.setResource(new AbstractResource() {
public String getDescription() {
return null;
}
public InputStream getInputStream() throws IOException {
throw new IOException();
}
public boolean exists() {
return true;
}
});
try {
source.open(executionContext);
}
catch (DataAccessResourceFailureException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
}
public void testNonExistentResource() throws Exception {
source.setResource(new NonExistentResource());
source.afterPropertiesSet();
try {
source.open(executionContext);
fail();
}
catch (IllegalStateException ex) {
// expected
}
}
public void testRuntimeFileCreation() throws Exception {
source.setResource(new NonExistentResource());
source.afterPropertiesSet();
source.setResource(new ByteArrayResource(xml.getBytes()));
source.open(executionContext);
source.read();
}
private StaxEventItemReader createNewInputSouce() {
Resource resource = new ByteArrayResource(xml.getBytes());
StaxEventItemReader newSource = new StaxEventItemReader();
newSource.setResource(resource);
newSource.setFragmentRootElementName(FRAGMENT_ROOT_ELEMENT);
newSource.setFragmentDeserializer(deserializer);
newSource.setSaveState(true);
return newSource;
}
/**
* A simple XMLEvent deserializer mock - check for the start and end
* document events for the fragment root & end tags + skips the fragment
* contents.
*/
private static class MockFragmentDeserializer implements EventReaderDeserializer {
/**
* A simple mapFragment implementation checking the
* StaxEventReaderItemReader basic read functionality.
* @param eventReader
* @return list of the events from fragment body
*/
public Object deserializeFragment(XMLEventReader eventReader) {
List fragmentContent;
try {
// first event should be StartDocument
XMLEvent event1 = eventReader.nextEvent();
assertTrue(event1.isStartDocument());
// second should be StartElement of the fragment
XMLEvent event2 = eventReader.nextEvent();
assertTrue(event2.isStartElement());
assertTrue(EventHelper.startElementName(event2).equals(FRAGMENT_ROOT_ELEMENT));
// jump before the end of fragment
fragmentContent = readRecordsInsideFragment(eventReader);
// end of fragment
XMLEvent event3 = eventReader.nextEvent();
assertTrue(event3.isEndElement());
assertTrue(EventHelper.endElementName(event3).equals(FRAGMENT_ROOT_ELEMENT));
// EndDocument should follow the end of fragment
XMLEvent event4 = eventReader.nextEvent();
assertTrue(event4.isEndDocument());
}
catch (XMLStreamException e) {
throw new RuntimeException("Error occured in FragmentDeserializer", e);
}
return fragmentContent;
}
/**
* Skips the XML fragment contents.
*/
private List readRecordsInsideFragment(XMLEventReader eventReader) throws XMLStreamException {
XMLEvent eventInsideFragment;
List events = new ArrayList();
do {
eventInsideFragment = eventReader.peek();
if (eventInsideFragment instanceof EndElement
&& ((EndElement) eventInsideFragment).getName().getLocalPart().equals(FRAGMENT_ROOT_ELEMENT)) {
break;
}
events.add(eventReader.nextEvent());
} while (eventInsideFragment != null);
return events;
}
}
/**
* Moves cursor inside the fragment body and causes rollback.
*/
private static class ExceptionFragmentDeserializer implements EventReaderDeserializer {
public Object deserializeFragment(XMLEventReader eventReader) {
eventReader.next();
throw new RuntimeException();
}
}
private static class MockStaxEventItemReader extends StaxEventItemReader {
private boolean openCalled = false;
public void open(ExecutionContext executionContext) {
super.open(executionContext);
openCalled = true;
}
public boolean isOpenCalled() {
return openCalled;
}
public void setOpenCalled(boolean openCalled) {
this.openCalled = openCalled;
}
}
private class NonExistentResource extends AbstractResource {
public NonExistentResource() {
}
public boolean exists() {
return false;
}
public String getDescription() {
return "NonExistantResource";
}
public InputStream getInputStream() throws IOException {
return null;
}
}
}

View File

@@ -1,234 +1,234 @@
package org.springframework.batch.io.xml;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Result;
import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
import org.springframework.batch.io.xml.oxm.MarshallingEventWriterSerializer;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.util.Assert;
import org.springframework.xml.transform.StaxResult;
/**
* Tests for {@link StaxEventItemWriter}.
*/
public class StaxEventItemWriterTests extends TestCase {
// object under test
private StaxEventItemWriter writer;
// output file
private Resource resource;
private ExecutionContext executionContext;
// test item for writing to output
private Object item = new Object() {
public String toString() {
return TEST_STRING;
}
};
private static final String TEST_STRING = StaxEventItemWriter.class.getSimpleName() + "-testString";
private static final int NOT_FOUND = -1;
protected void setUp() throws Exception {
resource = new FileSystemResource(File.createTempFile("StaxEventWriterOutputSourceTests", "xml"));
writer = createItemWriter();
executionContext = new ExecutionContext();
}
/**
* Flush should pass buffered items to Serializer.
*/
public void testFlush() throws Exception {
writer.open(executionContext);
InputCheckMarshaller marshaller = new InputCheckMarshaller();
MarshallingEventWriterSerializer serializer = new MarshallingEventWriterSerializer(marshaller);
writer.setSerializer(serializer);
// see asserts in the marshaller
writer.write(item);
assertFalse(marshaller.wasCalled);
writer.flush();
assertTrue(marshaller.wasCalled);
}
public void testClear() throws Exception {
writer.open(executionContext);
writer.write(item);
writer.write(item);
writer.clear();
//writer.write(item);
writer.flush();
assertFalse(outputFileContent().contains(TEST_STRING));
}
/**
* Rolled back records should not be written to output file.
*/
public void testRollback() throws Exception {
writer.open(executionContext);
writer.write(item);
// rollback
writer.clear();
assertEquals("", outputFileContent());
}
/**
* Item is written to the output file only after flush.
*/
public void testWriteAndFlush() throws Exception {
writer.open(executionContext);
writer.write(item);
assertEquals("", outputFileContent());
writer.flush();
assertTrue(outputFileContent().contains(TEST_STRING));
}
/**
* Restart scenario - content is appended to the output file after restart.
*/
public void testRestart() throws Exception {
writer.open(executionContext);
// write item
writer.write(item);
writer.flush();
writer.update(executionContext);
writer.close(executionContext);
// create new writer from saved restart data and continue writing
writer = createItemWriter();
writer.open(executionContext);
writer.write(item);
writer.close(executionContext);
// check the output is concatenation of 'before restart' and 'after
// restart' writes.
String outputFile = outputFileContent();
int firstRecord = outputFile.indexOf(TEST_STRING);
int secondRecord = outputFile.indexOf(TEST_STRING, firstRecord + TEST_STRING.length());
int thirdRecord = outputFile.indexOf(TEST_STRING, secondRecord + TEST_STRING.length());
// (two records should be written)
assertTrue(firstRecord != NOT_FOUND);
assertTrue(secondRecord != NOT_FOUND);
assertEquals(NOT_FOUND, thirdRecord);
}
/**
* Count of 'records written so far' is returned as statistics.
*/
public void testStreamContext() throws Exception {
writer.open(executionContext);
final int NUMBER_OF_RECORDS = 10;
for (int i = 1; i <= NUMBER_OF_RECORDS; i++) {
writer.write(item);
writer.update(executionContext);
long writeStatistics = executionContext.getLong(StaxEventItemWriter.class.getSimpleName() + ".record.count");
assertEquals(i, writeStatistics);
}
}
/**
* Open method writes the root tag, close method adds corresponding end tag.
*/
public void testOpenAndClose() throws Exception {
writer.setRootTagName("testroot");
writer.setRootElementAttributes(new HashMap() {
{
put("attribute", "value");
}
});
writer.open(executionContext);
writer.flush();
assertTrue(outputFileContent().indexOf("<testroot attribute=\"value\"") != NOT_FOUND);
writer.close(null);
assertTrue(outputFileContent().endsWith("</testroot>"));
}
/**
* Checks the received parameters.
*/
private class InputCheckMarshaller implements Marshaller {
boolean wasCalled = false;
public void marshal(Object graph, Result result) {
wasCalled = true;
assertTrue(result instanceof StaxResult);
assertSame(item, graph);
}
public boolean supports(Class clazz) {
return true;
}
}
/**
* Writes object's toString representation as XML comment.
*/
private static class SimpleMarshaller implements Marshaller {
public void marshal(Object graph, Result result) throws XmlMappingException, IOException {
Assert.isInstanceOf(StaxResult.class, result);
StaxResult staxResult = (StaxResult) result;
try {
staxResult.getXMLEventWriter().add(XMLEventFactory.newInstance().createComment(graph.toString()));
}
catch (XMLStreamException e) {
throw new RuntimeException("Exception while writing to output file", e);
}
}
public boolean supports(Class clazz) {
return true;
}
}
/**
* @return output file content as String
*/
private String outputFileContent() throws IOException {
return FileUtils.readFileToString(resource.getFile(), null);
}
/**
* @return new instance of fully configured writer
*/
private StaxEventItemWriter createItemWriter() throws Exception {
StaxEventItemWriter source = new StaxEventItemWriter();
source.setResource(resource);
Marshaller marshaller = new SimpleMarshaller();
MarshallingEventWriterSerializer serializer = new MarshallingEventWriterSerializer(marshaller);
source.setSerializer(serializer);
source.setEncoding("UTF-8");
source.setRootTagName("root");
source.setVersion("1.0");
source.setOverwriteOutput(true);
source.setSaveState(true);
source.afterPropertiesSet();
return source;
}
}
package org.springframework.batch.io.xml;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Result;
import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
import org.springframework.batch.io.xml.oxm.MarshallingEventWriterSerializer;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.util.Assert;
import org.springframework.xml.transform.StaxResult;
/**
* Tests for {@link StaxEventItemWriter}.
*/
public class StaxEventItemWriterTests extends TestCase {
// object under test
private StaxEventItemWriter writer;
// output file
private Resource resource;
private ExecutionContext executionContext;
// test item for writing to output
private Object item = new Object() {
public String toString() {
return TEST_STRING;
}
};
private static final String TEST_STRING = StaxEventItemWriter.class.getSimpleName() + "-testString";
private static final int NOT_FOUND = -1;
protected void setUp() throws Exception {
resource = new FileSystemResource(File.createTempFile("StaxEventWriterOutputSourceTests", "xml"));
writer = createItemWriter();
executionContext = new ExecutionContext();
}
/**
* Flush should pass buffered items to Serializer.
*/
public void testFlush() throws Exception {
writer.open(executionContext);
InputCheckMarshaller marshaller = new InputCheckMarshaller();
MarshallingEventWriterSerializer serializer = new MarshallingEventWriterSerializer(marshaller);
writer.setSerializer(serializer);
// see asserts in the marshaller
writer.write(item);
assertFalse(marshaller.wasCalled);
writer.flush();
assertTrue(marshaller.wasCalled);
}
public void testClear() throws Exception {
writer.open(executionContext);
writer.write(item);
writer.write(item);
writer.clear();
//writer.write(item);
writer.flush();
assertFalse(outputFileContent().contains(TEST_STRING));
}
/**
* Rolled back records should not be written to output file.
*/
public void testRollback() throws Exception {
writer.open(executionContext);
writer.write(item);
// rollback
writer.clear();
assertEquals("", outputFileContent());
}
/**
* Item is written to the output file only after flush.
*/
public void testWriteAndFlush() throws Exception {
writer.open(executionContext);
writer.write(item);
assertEquals("", outputFileContent());
writer.flush();
assertTrue(outputFileContent().contains(TEST_STRING));
}
/**
* Restart scenario - content is appended to the output file after restart.
*/
public void testRestart() throws Exception {
writer.open(executionContext);
// write item
writer.write(item);
writer.flush();
writer.update(executionContext);
writer.close(executionContext);
// create new writer from saved restart data and continue writing
writer = createItemWriter();
writer.open(executionContext);
writer.write(item);
writer.close(executionContext);
// check the output is concatenation of 'before restart' and 'after
// restart' writes.
String outputFile = outputFileContent();
int firstRecord = outputFile.indexOf(TEST_STRING);
int secondRecord = outputFile.indexOf(TEST_STRING, firstRecord + TEST_STRING.length());
int thirdRecord = outputFile.indexOf(TEST_STRING, secondRecord + TEST_STRING.length());
// (two records should be written)
assertTrue(firstRecord != NOT_FOUND);
assertTrue(secondRecord != NOT_FOUND);
assertEquals(NOT_FOUND, thirdRecord);
}
/**
* Count of 'records written so far' is returned as statistics.
*/
public void testStreamContext() throws Exception {
writer.open(executionContext);
final int NUMBER_OF_RECORDS = 10;
for (int i = 1; i <= NUMBER_OF_RECORDS; i++) {
writer.write(item);
writer.update(executionContext);
long writeStatistics = executionContext.getLong(StaxEventItemWriter.class.getSimpleName() + ".record.count");
assertEquals(i, writeStatistics);
}
}
/**
* Open method writes the root tag, close method adds corresponding end tag.
*/
public void testOpenAndClose() throws Exception {
writer.setRootTagName("testroot");
writer.setRootElementAttributes(new HashMap() {
{
put("attribute", "value");
}
});
writer.open(executionContext);
writer.flush();
assertTrue(outputFileContent().indexOf("<testroot attribute=\"value\"") != NOT_FOUND);
writer.close(null);
assertTrue(outputFileContent().endsWith("</testroot>"));
}
/**
* Checks the received parameters.
*/
private class InputCheckMarshaller implements Marshaller {
boolean wasCalled = false;
public void marshal(Object graph, Result result) {
wasCalled = true;
assertTrue(result instanceof StaxResult);
assertSame(item, graph);
}
public boolean supports(Class clazz) {
return true;
}
}
/**
* Writes object's toString representation as XML comment.
*/
private static class SimpleMarshaller implements Marshaller {
public void marshal(Object graph, Result result) throws XmlMappingException, IOException {
Assert.isInstanceOf(StaxResult.class, result);
StaxResult staxResult = (StaxResult) result;
try {
staxResult.getXMLEventWriter().add(XMLEventFactory.newInstance().createComment(graph.toString()));
}
catch (XMLStreamException e) {
throw new RuntimeException("Exception while writing to output file", e);
}
}
public boolean supports(Class clazz) {
return true;
}
}
/**
* @return output file content as String
*/
private String outputFileContent() throws IOException {
return FileUtils.readFileToString(resource.getFile(), null);
}
/**
* @return new instance of fully configured writer
*/
private StaxEventItemWriter createItemWriter() throws Exception {
StaxEventItemWriter source = new StaxEventItemWriter();
source.setResource(resource);
Marshaller marshaller = new SimpleMarshaller();
MarshallingEventWriterSerializer serializer = new MarshallingEventWriterSerializer(marshaller);
source.setSerializer(serializer);
source.setEncoding("UTF-8");
source.setRootTagName("root");
source.setVersion("1.0");
source.setOverwriteOutput(true);
source.setSaveState(true);
source.afterPropertiesSet();
return source;
}
}

View File

@@ -1,132 +1,132 @@
/*
* 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.io.xml.oxm;
import java.io.IOException;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.Result;
import junit.framework.TestCase;
import org.springframework.batch.io.xml.oxm.MarshallingEventWriterSerializer;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;
/**
*
*
* @author Lucas Ward
*
*/
public class MarshallingObjectToXmlSerializerTests extends TestCase {
MarshallingEventWriterSerializer xmlSerializer;
MockMarshaller mockMarshaller = new MockMarshaller();
private StubXmlEventWriter writer;
protected void setUp() throws Exception {
super.setUp();
xmlSerializer = new MarshallingEventWriterSerializer(mockMarshaller);
writer = new StubXmlEventWriter();
}
public void testSuccessfulWrite(){
Object objectToOutput = new Object();
xmlSerializer.serializeObject(writer, objectToOutput);
assertEquals(objectToOutput, mockMarshaller.getMarshalledObject());
}
public void testUnsucessfulWrite(){
mockMarshaller.setThrowException(true);
try{
xmlSerializer.serializeObject(writer, new Object());
fail("Exception expected");
}catch(DataAccessResourceFailureException ex){
//expected
}
}
private static class MockMarshaller implements Marshaller{
private Object marshalledObject;
private boolean throwException = false;
public void marshal(Object arg0, Result arg1)
throws XmlMappingException, IOException {
if(throwException){
throw new IOException();
}
marshalledObject = arg0;
}
public boolean supports(Class arg0) {
return false;
}
public Object getMarshalledObject() {
return marshalledObject;
}
public void setThrowException(boolean throwException) {
this.throwException = throwException;
}
}
private static class StubXmlEventWriter implements XMLEventWriter{
public void add(XMLEvent arg0) throws XMLStreamException { }
public void add(XMLEventReader arg0) throws XMLStreamException { }
public void close() throws XMLStreamException {
}
public void flush() throws XMLStreamException {
}
public NamespaceContext getNamespaceContext() {
return null;
}
public String getPrefix(String arg0) throws XMLStreamException {
return null;
}
public void setDefaultNamespace(String arg0) throws XMLStreamException {
}
public void setNamespaceContext(NamespaceContext arg0)
throws XMLStreamException {
}
public void setPrefix(String arg0, String arg1)
throws XMLStreamException {
}
}
}
/*
* 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.io.xml.oxm;
import java.io.IOException;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.Result;
import junit.framework.TestCase;
import org.springframework.batch.io.xml.oxm.MarshallingEventWriterSerializer;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;
/**
*
*
* @author Lucas Ward
*
*/
public class MarshallingObjectToXmlSerializerTests extends TestCase {
MarshallingEventWriterSerializer xmlSerializer;
MockMarshaller mockMarshaller = new MockMarshaller();
private StubXmlEventWriter writer;
protected void setUp() throws Exception {
super.setUp();
xmlSerializer = new MarshallingEventWriterSerializer(mockMarshaller);
writer = new StubXmlEventWriter();
}
public void testSuccessfulWrite(){
Object objectToOutput = new Object();
xmlSerializer.serializeObject(writer, objectToOutput);
assertEquals(objectToOutput, mockMarshaller.getMarshalledObject());
}
public void testUnsucessfulWrite(){
mockMarshaller.setThrowException(true);
try{
xmlSerializer.serializeObject(writer, new Object());
fail("Exception expected");
}catch(DataAccessResourceFailureException ex){
//expected
}
}
private static class MockMarshaller implements Marshaller{
private Object marshalledObject;
private boolean throwException = false;
public void marshal(Object arg0, Result arg1)
throws XmlMappingException, IOException {
if(throwException){
throw new IOException();
}
marshalledObject = arg0;
}
public boolean supports(Class arg0) {
return false;
}
public Object getMarshalledObject() {
return marshalledObject;
}
public void setThrowException(boolean throwException) {
this.throwException = throwException;
}
}
private static class StubXmlEventWriter implements XMLEventWriter{
public void add(XMLEvent arg0) throws XMLStreamException { }
public void add(XMLEventReader arg0) throws XMLStreamException { }
public void close() throws XMLStreamException {
}
public void flush() throws XMLStreamException {
}
public NamespaceContext getNamespaceContext() {
return null;
}
public String getPrefix(String arg0) throws XMLStreamException {
return null;
}
public void setDefaultNamespace(String arg0) throws XMLStreamException {
}
public void setNamespaceContext(NamespaceContext arg0)
throws XMLStreamException {
}
public void setPrefix(String arg0, String arg1)
throws XMLStreamException {
}
}
}

View File

@@ -1,92 +1,92 @@
package org.springframework.batch.io.xml.oxm;
import java.io.IOException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.xml.oxm.UnmarshallingEventReaderDeserializer;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataAccessException;
import org.springframework.oxm.Unmarshaller;
/**
* Tests for {@link UnmarshallingEventReaderDeserializer}
*
* @author Robert Kasanicky
*/
public class UnmarshallingFragmentDeserializerTests extends TestCase {
// object under test
private UnmarshallingEventReaderDeserializer deserializer;
private XMLEventReader eventReader;
private String xml = "<root> </root>";
private Unmarshaller unmarshaller;
private MockControl unmarshallerControl = MockControl.createStrictControl(Unmarshaller.class);
protected void setUp() throws Exception {
Resource input = new ByteArrayResource(xml.getBytes());
eventReader = XMLInputFactory.newInstance().createXMLEventReader(input.getInputStream());
unmarshaller = (Unmarshaller) unmarshallerControl.getMock();
unmarshallerControl.setDefaultMatcher(MockControl.ALWAYS_MATCHER);
deserializer = new UnmarshallingEventReaderDeserializer(unmarshaller);
}
/**
* Regular scenario when deserializer returns the object provided by Unmarshaller
*/
public void testSuccessfulDeserialization() throws Exception {
Object expectedResult = new Object();
unmarshaller.unmarshal(null);
unmarshallerControl.setReturnValue(expectedResult);
unmarshallerControl.replay();
Object result = deserializer.deserializeFragment(eventReader);
assertEquals(expectedResult, result);
unmarshallerControl.verify();
}
/**
* Appropriate exception rethrown in case of failure.
*/
public void testFailedDeserialization() throws Exception {
unmarshaller.unmarshal(null);
unmarshallerControl.setThrowable(new IOException());
unmarshallerControl.replay();
try {
deserializer.deserializeFragment(eventReader);
fail("Exception expected");
}
catch (DataAccessException e) {
// expected
}
unmarshallerControl.verify();
}
/**
* It makes no sense to create UnmarshallingFragmentDeserializer with null Unmarshaller,
* therefore it should cause exception.
*/
public void testExceptionOnNullUnmarshaller() {
try {
deserializer = new UnmarshallingEventReaderDeserializer(null);
fail("Exception expected");
}
catch (IllegalArgumentException e) {
// expected
}
}
}
package org.springframework.batch.io.xml.oxm;
import java.io.IOException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.xml.oxm.UnmarshallingEventReaderDeserializer;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataAccessException;
import org.springframework.oxm.Unmarshaller;
/**
* Tests for {@link UnmarshallingEventReaderDeserializer}
*
* @author Robert Kasanicky
*/
public class UnmarshallingFragmentDeserializerTests extends TestCase {
// object under test
private UnmarshallingEventReaderDeserializer deserializer;
private XMLEventReader eventReader;
private String xml = "<root> </root>";
private Unmarshaller unmarshaller;
private MockControl unmarshallerControl = MockControl.createStrictControl(Unmarshaller.class);
protected void setUp() throws Exception {
Resource input = new ByteArrayResource(xml.getBytes());
eventReader = XMLInputFactory.newInstance().createXMLEventReader(input.getInputStream());
unmarshaller = (Unmarshaller) unmarshallerControl.getMock();
unmarshallerControl.setDefaultMatcher(MockControl.ALWAYS_MATCHER);
deserializer = new UnmarshallingEventReaderDeserializer(unmarshaller);
}
/**
* Regular scenario when deserializer returns the object provided by Unmarshaller
*/
public void testSuccessfulDeserialization() throws Exception {
Object expectedResult = new Object();
unmarshaller.unmarshal(null);
unmarshallerControl.setReturnValue(expectedResult);
unmarshallerControl.replay();
Object result = deserializer.deserializeFragment(eventReader);
assertEquals(expectedResult, result);
unmarshallerControl.verify();
}
/**
* Appropriate exception rethrown in case of failure.
*/
public void testFailedDeserialization() throws Exception {
unmarshaller.unmarshal(null);
unmarshallerControl.setThrowable(new IOException());
unmarshallerControl.replay();
try {
deserializer.deserializeFragment(eventReader);
fail("Exception expected");
}
catch (DataAccessException e) {
// expected
}
unmarshallerControl.verify();
}
/**
* It makes no sense to create UnmarshallingFragmentDeserializer with null Unmarshaller,
* therefore it should cause exception.
*/
public void testExceptionOnNullUnmarshaller() {
try {
deserializer = new UnmarshallingEventReaderDeserializer(null);
fail("Exception expected");
}
catch (IllegalArgumentException e) {
// expected
}
}
}

View File

@@ -1,135 +1,135 @@
/*
* 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.io.xml.stax;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.xml.stax.AbstractEventReaderWrapper;
import com.bea.xml.stream.events.StartDocumentEvent;
/**
* @author Lucas Ward
*
*/
public class AbstractEventReaderWrapperTests extends TestCase {
AbstractEventReaderWrapper eventReaderWrapper;
MockControl mockEventReaderControl = MockControl.createControl(XMLEventReader.class);
XMLEventReader xmlEventReader;
protected void setUp() throws Exception {
super.setUp();
xmlEventReader = (XMLEventReader)mockEventReaderControl.getMock();
eventReaderWrapper = new StubEventReader(xmlEventReader);
}
public void testClose() throws XMLStreamException {
xmlEventReader.close();
mockEventReaderControl.replay();
eventReaderWrapper.close();
mockEventReaderControl.verify();
}
public void testGetElementText() throws XMLStreamException {
String text = "text";
xmlEventReader.getElementText();
mockEventReaderControl.setReturnValue(text);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.getElementText(), text);
mockEventReaderControl.verify();
}
public void testGetProperty() throws IllegalArgumentException {
String text = "text";
xmlEventReader.getProperty("name");
mockEventReaderControl.setReturnValue(text);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.getProperty("name"), text);
mockEventReaderControl.verify();
}
public void testHasNext() {
xmlEventReader.hasNext();
mockEventReaderControl.setReturnValue(true);
mockEventReaderControl.replay();
assertTrue(eventReaderWrapper.hasNext());
mockEventReaderControl.verify();
}
public void testNext() {
String text = "text";
xmlEventReader.next();
mockEventReaderControl.setReturnValue(text);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.next(), text);
mockEventReaderControl.verify();
}
public void testNextEvent() throws XMLStreamException {
XMLEvent event = new StartDocumentEvent();
xmlEventReader.nextEvent();
mockEventReaderControl.setReturnValue(event);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.nextEvent(), event);
mockEventReaderControl.verify();
}
public void testNextTag() throws XMLStreamException {
XMLEvent event = new StartDocumentEvent();
xmlEventReader.nextTag();
mockEventReaderControl.setReturnValue(event);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.nextTag(), event);
mockEventReaderControl.verify();
}
public void testPeek() throws XMLStreamException {
XMLEvent event = new StartDocumentEvent();
xmlEventReader.peek();
mockEventReaderControl.setReturnValue(event);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.peek(), event);
mockEventReaderControl.verify();
}
public void testRemove() {
xmlEventReader.remove();
mockEventReaderControl.replay();
eventReaderWrapper.remove();
mockEventReaderControl.verify();
}
private static class StubEventReader extends AbstractEventReaderWrapper{
public StubEventReader(XMLEventReader wrappedEventReader) {
super(wrappedEventReader);
}
}
}
/*
* 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.io.xml.stax;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.xml.stax.AbstractEventReaderWrapper;
import com.bea.xml.stream.events.StartDocumentEvent;
/**
* @author Lucas Ward
*
*/
public class AbstractEventReaderWrapperTests extends TestCase {
AbstractEventReaderWrapper eventReaderWrapper;
MockControl mockEventReaderControl = MockControl.createControl(XMLEventReader.class);
XMLEventReader xmlEventReader;
protected void setUp() throws Exception {
super.setUp();
xmlEventReader = (XMLEventReader)mockEventReaderControl.getMock();
eventReaderWrapper = new StubEventReader(xmlEventReader);
}
public void testClose() throws XMLStreamException {
xmlEventReader.close();
mockEventReaderControl.replay();
eventReaderWrapper.close();
mockEventReaderControl.verify();
}
public void testGetElementText() throws XMLStreamException {
String text = "text";
xmlEventReader.getElementText();
mockEventReaderControl.setReturnValue(text);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.getElementText(), text);
mockEventReaderControl.verify();
}
public void testGetProperty() throws IllegalArgumentException {
String text = "text";
xmlEventReader.getProperty("name");
mockEventReaderControl.setReturnValue(text);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.getProperty("name"), text);
mockEventReaderControl.verify();
}
public void testHasNext() {
xmlEventReader.hasNext();
mockEventReaderControl.setReturnValue(true);
mockEventReaderControl.replay();
assertTrue(eventReaderWrapper.hasNext());
mockEventReaderControl.verify();
}
public void testNext() {
String text = "text";
xmlEventReader.next();
mockEventReaderControl.setReturnValue(text);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.next(), text);
mockEventReaderControl.verify();
}
public void testNextEvent() throws XMLStreamException {
XMLEvent event = new StartDocumentEvent();
xmlEventReader.nextEvent();
mockEventReaderControl.setReturnValue(event);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.nextEvent(), event);
mockEventReaderControl.verify();
}
public void testNextTag() throws XMLStreamException {
XMLEvent event = new StartDocumentEvent();
xmlEventReader.nextTag();
mockEventReaderControl.setReturnValue(event);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.nextTag(), event);
mockEventReaderControl.verify();
}
public void testPeek() throws XMLStreamException {
XMLEvent event = new StartDocumentEvent();
xmlEventReader.peek();
mockEventReaderControl.setReturnValue(event);
mockEventReaderControl.replay();
assertEquals(eventReaderWrapper.peek(), event);
mockEventReaderControl.verify();
}
public void testRemove() {
xmlEventReader.remove();
mockEventReaderControl.replay();
eventReaderWrapper.remove();
mockEventReaderControl.verify();
}
private static class StubEventReader extends AbstractEventReaderWrapper{
public StubEventReader(XMLEventReader wrappedEventReader) {
super(wrappedEventReader);
}
}
}

View File

@@ -1,135 +1,135 @@
/*
* 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.io.xml.stax;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.xml.stax.AbstractEventWriterWrapper;
import com.bea.xml.stream.events.StartDocumentEvent;
import com.bea.xml.stream.util.NamespaceContextImpl;
/**
* @author Lucas Ward
*
*/
public class AbstractEventWriterWrapperTests extends TestCase {
AbstractEventWriterWrapper eventWriterWrapper;
MockControl mockEventWriterControl = MockControl.createControl(XMLEventWriter.class);
XMLEventWriter xmlEventWriter;
protected void setUp() throws Exception {
super.setUp();
xmlEventWriter = (XMLEventWriter)mockEventWriterControl.getMock();
eventWriterWrapper = new StubEventWriter(xmlEventWriter);
}
public void testAdd() throws XMLStreamException {
XMLEvent event = new StartDocumentEvent();
xmlEventWriter.add(event);
mockEventWriterControl.replay();
eventWriterWrapper.add(event);
mockEventWriterControl.verify();
}
public void testAddReader() throws XMLStreamException {
MockControl readerControl = MockControl.createControl(XMLEventReader.class);
XMLEventReader reader = (XMLEventReader)readerControl.getMock();
xmlEventWriter.add(reader);
mockEventWriterControl.replay();
eventWriterWrapper.add(reader);
mockEventWriterControl.verify();
}
public void testClose() throws XMLStreamException {
xmlEventWriter.close();
mockEventWriterControl.replay();
eventWriterWrapper.close();
mockEventWriterControl.verify();
}
public void testFlush() throws XMLStreamException {
xmlEventWriter.flush();
mockEventWriterControl.replay();
eventWriterWrapper.flush();
mockEventWriterControl.verify();
}
public void testGetNamespaceContext() {
NamespaceContext context = new NamespaceContextImpl();
xmlEventWriter.getNamespaceContext();
mockEventWriterControl.setReturnValue(context);
mockEventWriterControl.replay();
assertEquals(eventWriterWrapper.getNamespaceContext(), context);
mockEventWriterControl.verify();
}
public void testGetPrefix() throws XMLStreamException {
String uri = "uri";
xmlEventWriter.getPrefix(uri);
mockEventWriterControl.setReturnValue(uri);
mockEventWriterControl.replay();
assertEquals(eventWriterWrapper.getPrefix(uri), uri);
mockEventWriterControl.verify();
}
public void testSetDefaultNamespace() throws XMLStreamException {
String uri = "uri";
xmlEventWriter.setDefaultNamespace(uri);
mockEventWriterControl.replay();
eventWriterWrapper.setDefaultNamespace(uri);
mockEventWriterControl.verify();
}
public void testSetNamespaceContext()
throws XMLStreamException {
NamespaceContext context = new NamespaceContextImpl();
xmlEventWriter.setNamespaceContext(context);
mockEventWriterControl.replay();
eventWriterWrapper.setNamespaceContext(context);
mockEventWriterControl.verify();
}
public void testSetPrefix() throws XMLStreamException {
String uri = "uri";
String prefix = "prefix";
xmlEventWriter.setPrefix(prefix, uri);
mockEventWriterControl.replay();
eventWriterWrapper.setPrefix(prefix, uri);
mockEventWriterControl.verify();
}
private static class StubEventWriter extends AbstractEventWriterWrapper{
public StubEventWriter(XMLEventWriter wrappedEventWriter) {
super(wrappedEventWriter);
}
}
}
/*
* 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.io.xml.stax;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.xml.stax.AbstractEventWriterWrapper;
import com.bea.xml.stream.events.StartDocumentEvent;
import com.bea.xml.stream.util.NamespaceContextImpl;
/**
* @author Lucas Ward
*
*/
public class AbstractEventWriterWrapperTests extends TestCase {
AbstractEventWriterWrapper eventWriterWrapper;
MockControl mockEventWriterControl = MockControl.createControl(XMLEventWriter.class);
XMLEventWriter xmlEventWriter;
protected void setUp() throws Exception {
super.setUp();
xmlEventWriter = (XMLEventWriter)mockEventWriterControl.getMock();
eventWriterWrapper = new StubEventWriter(xmlEventWriter);
}
public void testAdd() throws XMLStreamException {
XMLEvent event = new StartDocumentEvent();
xmlEventWriter.add(event);
mockEventWriterControl.replay();
eventWriterWrapper.add(event);
mockEventWriterControl.verify();
}
public void testAddReader() throws XMLStreamException {
MockControl readerControl = MockControl.createControl(XMLEventReader.class);
XMLEventReader reader = (XMLEventReader)readerControl.getMock();
xmlEventWriter.add(reader);
mockEventWriterControl.replay();
eventWriterWrapper.add(reader);
mockEventWriterControl.verify();
}
public void testClose() throws XMLStreamException {
xmlEventWriter.close();
mockEventWriterControl.replay();
eventWriterWrapper.close();
mockEventWriterControl.verify();
}
public void testFlush() throws XMLStreamException {
xmlEventWriter.flush();
mockEventWriterControl.replay();
eventWriterWrapper.flush();
mockEventWriterControl.verify();
}
public void testGetNamespaceContext() {
NamespaceContext context = new NamespaceContextImpl();
xmlEventWriter.getNamespaceContext();
mockEventWriterControl.setReturnValue(context);
mockEventWriterControl.replay();
assertEquals(eventWriterWrapper.getNamespaceContext(), context);
mockEventWriterControl.verify();
}
public void testGetPrefix() throws XMLStreamException {
String uri = "uri";
xmlEventWriter.getPrefix(uri);
mockEventWriterControl.setReturnValue(uri);
mockEventWriterControl.replay();
assertEquals(eventWriterWrapper.getPrefix(uri), uri);
mockEventWriterControl.verify();
}
public void testSetDefaultNamespace() throws XMLStreamException {
String uri = "uri";
xmlEventWriter.setDefaultNamespace(uri);
mockEventWriterControl.replay();
eventWriterWrapper.setDefaultNamespace(uri);
mockEventWriterControl.verify();
}
public void testSetNamespaceContext()
throws XMLStreamException {
NamespaceContext context = new NamespaceContextImpl();
xmlEventWriter.setNamespaceContext(context);
mockEventWriterControl.replay();
eventWriterWrapper.setNamespaceContext(context);
mockEventWriterControl.verify();
}
public void testSetPrefix() throws XMLStreamException {
String uri = "uri";
String prefix = "prefix";
xmlEventWriter.setPrefix(prefix, uri);
mockEventWriterControl.replay();
eventWriterWrapper.setPrefix(prefix, uri);
mockEventWriterControl.verify();
}
private static class StubEventWriter extends AbstractEventWriterWrapper{
public StubEventWriter(XMLEventWriter wrappedEventWriter) {
super(wrappedEventWriter);
}
}
}

View File

@@ -1,144 +1,144 @@
package org.springframework.batch.io.xml.stax;
import java.util.NoSuchElementException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import org.springframework.batch.io.xml.EventHelper;
import org.springframework.batch.io.xml.stax.DefaultFragmentEventReader;
import org.springframework.batch.io.xml.stax.DefaultTransactionalEventReader;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
/**
* Tests for {@link DefaultFragmentEventReader}.
*
* @author Robert Kasanicky
*/
public class DefaultFragmentEventReaderTests extends TestCase {
// object under test
private FragmentEventReader fragmentReader;
// wrapped event fragmentReader
private XMLEventReader eventReader;
// test xml input
private String xml = "<root> <fragment> <misc1/> </fragment> <misc2/> <fragment> </fragment> </root>";
/**
* Setup the fragmentReader to read the test input.
*/
protected void setUp() throws Exception {
Resource input = new ByteArrayResource(xml.getBytes());
eventReader = new DefaultTransactionalEventReader(XMLInputFactory.newInstance().createXMLEventReader(
input.getInputStream()));
fragmentReader = new DefaultFragmentEventReader(eventReader);
}
/**
* Marked element should be wrapped with StartDocument and EndDocument
* events.
* Test uses redundant peek() calls before nextEvent() in important moments to assure
* peek() has no side effects on the inner state of reader.
*/
public void testFragmentWrapping() throws XMLStreamException {
assertTrue(fragmentReader.hasNext());
moveCursorBeforeFragmentStart();
fragmentReader.markStartFragment(); // mark the fragment
assertTrue(EventHelper.startElementName(eventReader.peek()).equals("fragment"));
// StartDocument inserted before StartElement
assertTrue(fragmentReader.peek().isStartDocument());
assertTrue(fragmentReader.nextEvent().isStartDocument());
// StartElement follows in the next step
assertTrue(EventHelper.startElementName(fragmentReader.nextEvent()).equals("fragment"));
moveCursorToNextElementEvent(); // misc1 start
fragmentReader.nextEvent(); // skip it
moveCursorToNextElementEvent(); // misc1 end
fragmentReader.nextEvent(); // skip it
moveCursorToNextElementEvent(); // move to end of fragment
// expected EndElement, peek first which should have no side effect
assertTrue(EventHelper.endElementName(fragmentReader.nextEvent()).equals("fragment"));
// inserted EndDocument
assertTrue(fragmentReader.peek().isEndDocument());
assertTrue(fragmentReader.nextEvent().isEndDocument());
// now the reader should behave like the document has finished
assertTrue(fragmentReader.peek() == null);
assertFalse(fragmentReader.hasNext());
try{
fragmentReader.nextEvent();
fail("nextEvent should simulate behavior as if document ended");
}
catch (NoSuchElementException expected) {
//expected
}
}
/**
* When fragment is marked as processed the cursor is moved after the end of
* the fragment.
*/
public void testMarkFragmentProcessed() throws XMLStreamException {
moveCursorBeforeFragmentStart();
fragmentReader.markStartFragment(); // mark the fragment start
// read only one event to move inside the fragment
XMLEvent startFragment = fragmentReader.nextEvent();
assertTrue(startFragment.isStartDocument());
fragmentReader.markFragmentProcessed(); // mark fragment as processed
fragmentReader.nextEvent(); // skip whitespace
// the next element after fragment end is <misc2/>
XMLEvent misc2 = fragmentReader.nextEvent();
assertTrue(EventHelper.startElementName(misc2).equals("misc2"));
}
/**
* Cursor is moved to the end of the fragment as usually even
* if nothing was read from the event reader after beginning
* of fragment was marked.
*/
public void testMarkFragmentProcessedImmediatelyAfterMarkFragmentStart() throws Exception {
moveCursorBeforeFragmentStart();
fragmentReader.markStartFragment();
fragmentReader.markFragmentProcessed();
fragmentReader.nextEvent(); // skip whitespace
// the next element after fragment end is <misc2/>
XMLEvent misc2 = fragmentReader.nextEvent();
assertTrue(EventHelper.startElementName(misc2).equals("misc2"));
}
private void moveCursorToNextElementEvent() throws XMLStreamException {
XMLEvent event = eventReader.peek();
while (!event.isStartElement() && !event.isEndElement()) {
eventReader.nextEvent();
event = eventReader.peek();
}
}
private void moveCursorBeforeFragmentStart() throws XMLStreamException {
XMLEvent event = eventReader.peek();
while (!event.isStartElement() || !EventHelper.startElementName(event).equals("fragment")) {
eventReader.nextEvent();
event = eventReader.peek();
}
}
}
package org.springframework.batch.io.xml.stax;
import java.util.NoSuchElementException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import org.springframework.batch.io.xml.EventHelper;
import org.springframework.batch.io.xml.stax.DefaultFragmentEventReader;
import org.springframework.batch.io.xml.stax.DefaultTransactionalEventReader;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
/**
* Tests for {@link DefaultFragmentEventReader}.
*
* @author Robert Kasanicky
*/
public class DefaultFragmentEventReaderTests extends TestCase {
// object under test
private FragmentEventReader fragmentReader;
// wrapped event fragmentReader
private XMLEventReader eventReader;
// test xml input
private String xml = "<root> <fragment> <misc1/> </fragment> <misc2/> <fragment> </fragment> </root>";
/**
* Setup the fragmentReader to read the test input.
*/
protected void setUp() throws Exception {
Resource input = new ByteArrayResource(xml.getBytes());
eventReader = new DefaultTransactionalEventReader(XMLInputFactory.newInstance().createXMLEventReader(
input.getInputStream()));
fragmentReader = new DefaultFragmentEventReader(eventReader);
}
/**
* Marked element should be wrapped with StartDocument and EndDocument
* events.
* Test uses redundant peek() calls before nextEvent() in important moments to assure
* peek() has no side effects on the inner state of reader.
*/
public void testFragmentWrapping() throws XMLStreamException {
assertTrue(fragmentReader.hasNext());
moveCursorBeforeFragmentStart();
fragmentReader.markStartFragment(); // mark the fragment
assertTrue(EventHelper.startElementName(eventReader.peek()).equals("fragment"));
// StartDocument inserted before StartElement
assertTrue(fragmentReader.peek().isStartDocument());
assertTrue(fragmentReader.nextEvent().isStartDocument());
// StartElement follows in the next step
assertTrue(EventHelper.startElementName(fragmentReader.nextEvent()).equals("fragment"));
moveCursorToNextElementEvent(); // misc1 start
fragmentReader.nextEvent(); // skip it
moveCursorToNextElementEvent(); // misc1 end
fragmentReader.nextEvent(); // skip it
moveCursorToNextElementEvent(); // move to end of fragment
// expected EndElement, peek first which should have no side effect
assertTrue(EventHelper.endElementName(fragmentReader.nextEvent()).equals("fragment"));
// inserted EndDocument
assertTrue(fragmentReader.peek().isEndDocument());
assertTrue(fragmentReader.nextEvent().isEndDocument());
// now the reader should behave like the document has finished
assertTrue(fragmentReader.peek() == null);
assertFalse(fragmentReader.hasNext());
try{
fragmentReader.nextEvent();
fail("nextEvent should simulate behavior as if document ended");
}
catch (NoSuchElementException expected) {
//expected
}
}
/**
* When fragment is marked as processed the cursor is moved after the end of
* the fragment.
*/
public void testMarkFragmentProcessed() throws XMLStreamException {
moveCursorBeforeFragmentStart();
fragmentReader.markStartFragment(); // mark the fragment start
// read only one event to move inside the fragment
XMLEvent startFragment = fragmentReader.nextEvent();
assertTrue(startFragment.isStartDocument());
fragmentReader.markFragmentProcessed(); // mark fragment as processed
fragmentReader.nextEvent(); // skip whitespace
// the next element after fragment end is <misc2/>
XMLEvent misc2 = fragmentReader.nextEvent();
assertTrue(EventHelper.startElementName(misc2).equals("misc2"));
}
/**
* Cursor is moved to the end of the fragment as usually even
* if nothing was read from the event reader after beginning
* of fragment was marked.
*/
public void testMarkFragmentProcessedImmediatelyAfterMarkFragmentStart() throws Exception {
moveCursorBeforeFragmentStart();
fragmentReader.markStartFragment();
fragmentReader.markFragmentProcessed();
fragmentReader.nextEvent(); // skip whitespace
// the next element after fragment end is <misc2/>
XMLEvent misc2 = fragmentReader.nextEvent();
assertTrue(EventHelper.startElementName(misc2).equals("misc2"));
}
private void moveCursorToNextElementEvent() throws XMLStreamException {
XMLEvent event = eventReader.peek();
while (!event.isStartElement() && !event.isEndElement()) {
eventReader.nextEvent();
event = eventReader.peek();
}
}
private void moveCursorBeforeFragmentStart() throws XMLStreamException {
XMLEvent event = eventReader.peek();
while (!event.isStartElement() || !EventHelper.startElementName(event).equals("fragment")) {
eventReader.nextEvent();
event = eventReader.peek();
}
}
}

View File

@@ -1,68 +1,68 @@
package org.springframework.batch.io.xml.stax;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import junit.framework.TestCase;
import org.springframework.batch.io.xml.EventHelper;
import org.springframework.batch.io.xml.stax.DefaultTransactionalEventReader;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
/**
* Tests for {@link DefaultTransactionalEventReader}.
*
* @author Robert Kasanicky
*/
public class DefaultTransactionalEventReaderTests extends TestCase {
// object under test
private TransactionalEventReader reader;
// test xml input
private String xml = "<root> <fragment> <misc1/> </fragment> <misc2/> <fragment> </fragment> </root>";
protected void setUp() throws Exception {
Resource resource = new ByteArrayResource(xml.getBytes());
XMLEventReader wrappedReader = XMLInputFactory.newInstance().createXMLEventReader(resource.getInputStream());
reader = new DefaultTransactionalEventReader(wrappedReader);
}
/**
* Rollback scenario.
*/
public void testRollback() throws Exception {
assertTrue(reader.hasNext());
reader.nextEvent(); //start document
reader.nextEvent(); //start root element
reader.nextEvent(); //whitespace
reader.onCommit(); // commit point
assertTrue(EventHelper.startElementName(reader.nextEvent()).equals("fragment"));
reader.nextEvent(); //whitespace
assertTrue(EventHelper.startElementName(reader.nextEvent()).equals("misc1"));
assertTrue(EventHelper.endElementName(reader.peek()).equals("misc1"));
reader.onRollback(); // now we should be at the last commit point
assertTrue(reader.hasNext());
assertTrue(EventHelper.startElementName(reader.nextEvent()).equals("fragment"));
reader.nextEvent();
assertTrue(EventHelper.startElementName(reader.nextEvent()).equals("misc1"));
}
/**
* Remove operation is not supported
*/
public void testRemove() {
try {
reader.remove();
fail("UnsupportedOperationException expected on calling remove()");
}
catch (UnsupportedOperationException e) {
// expected
}
}
}
package org.springframework.batch.io.xml.stax;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import junit.framework.TestCase;
import org.springframework.batch.io.xml.EventHelper;
import org.springframework.batch.io.xml.stax.DefaultTransactionalEventReader;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
/**
* Tests for {@link DefaultTransactionalEventReader}.
*
* @author Robert Kasanicky
*/
public class DefaultTransactionalEventReaderTests extends TestCase {
// object under test
private TransactionalEventReader reader;
// test xml input
private String xml = "<root> <fragment> <misc1/> </fragment> <misc2/> <fragment> </fragment> </root>";
protected void setUp() throws Exception {
Resource resource = new ByteArrayResource(xml.getBytes());
XMLEventReader wrappedReader = XMLInputFactory.newInstance().createXMLEventReader(resource.getInputStream());
reader = new DefaultTransactionalEventReader(wrappedReader);
}
/**
* Rollback scenario.
*/
public void testRollback() throws Exception {
assertTrue(reader.hasNext());
reader.nextEvent(); //start document
reader.nextEvent(); //start root element
reader.nextEvent(); //whitespace
reader.onCommit(); // commit point
assertTrue(EventHelper.startElementName(reader.nextEvent()).equals("fragment"));
reader.nextEvent(); //whitespace
assertTrue(EventHelper.startElementName(reader.nextEvent()).equals("misc1"));
assertTrue(EventHelper.endElementName(reader.peek()).equals("misc1"));
reader.onRollback(); // now we should be at the last commit point
assertTrue(reader.hasNext());
assertTrue(EventHelper.startElementName(reader.nextEvent()).equals("fragment"));
reader.nextEvent();
assertTrue(EventHelper.startElementName(reader.nextEvent()).equals("misc1"));
}
/**
* Remove operation is not supported
*/
public void testRemove() {
try {
reader.remove();
fail("UnsupportedOperationException expected on calling remove()");
}
catch (UnsupportedOperationException e) {
// expected
}
}
}

View File

@@ -1,39 +1,39 @@
package org.springframework.batch.io.xml.stax;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.events.XMLEvent;
import org.springframework.batch.io.xml.stax.EventSequence;
import junit.framework.TestCase;
/**
* Tests for {@link EventSequence}
*
* @author Robert Kasanicky
*/
public class EventSequenceTests extends TestCase {
// object under test
private EventSequence seq = new EventSequence();
private XMLEventFactory factory = XMLEventFactory.newInstance();
/**
* Common usage scenario.
*/
public void testCommonUse() {
XMLEvent event1 = factory.createComment("testString1");
XMLEvent event2 = factory.createCData("testString2");
seq.addEvent(event1);
seq.addEvent(event2);
assertTrue(seq.hasNext());
assertSame(event1, seq.nextEvent());
assertTrue(seq.hasNext());
assertSame(event2, seq.nextEvent());
assertFalse(seq.hasNext());
assertNull(seq.nextEvent());
}
}
package org.springframework.batch.io.xml.stax;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.events.XMLEvent;
import org.springframework.batch.io.xml.stax.EventSequence;
import junit.framework.TestCase;
/**
* Tests for {@link EventSequence}
*
* @author Robert Kasanicky
*/
public class EventSequenceTests extends TestCase {
// object under test
private EventSequence seq = new EventSequence();
private XMLEventFactory factory = XMLEventFactory.newInstance();
/**
* Common usage scenario.
*/
public void testCommonUse() {
XMLEvent event1 = factory.createComment("testString1");
XMLEvent event2 = factory.createCData("testString2");
seq.addEvent(event1);
seq.addEvent(event2);
assertTrue(seq.hasNext());
assertSame(event1, seq.nextEvent());
assertTrue(seq.hasNext());
assertSame(event2, seq.nextEvent());
assertFalse(seq.hasNext());
assertNull(seq.nextEvent());
}
}

View File

@@ -1,51 +1,51 @@
package org.springframework.batch.io.xml.stax;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.xml.stax.NoStartEndDocumentStreamWriter;
/**
* Tests for {@link NoStartEndDocumentStreamWriter}
*
* @author Robert Kasanicky
*/
public class NoStartEndDocumentWriterTests extends TestCase {
// object under test
private NoStartEndDocumentStreamWriter writer;
private XMLEventWriter wrappedWriter;
private MockControl wrappedWriterControl = MockControl.createStrictControl(XMLEventWriter.class);
private XMLEventFactory eventFactory = XMLEventFactory.newInstance();
protected void setUp() throws Exception {
wrappedWriter = (XMLEventWriter) wrappedWriterControl.getMock();
writer = new NoStartEndDocumentStreamWriter(wrappedWriter);
}
/**
* StartDocument and EndDocument events are not passed to the wrapped writer.
*/
public void testNoStartEnd() throws Exception {
XMLEvent event = eventFactory.createComment("testEvent");
//mock expects only a single event
wrappedWriter.add(event);
wrappedWriterControl.setVoidCallable();
wrappedWriterControl.replay();
writer.add(eventFactory.createStartDocument());
writer.add(event);
writer.add(eventFactory.createEndDocument());
wrappedWriterControl.verify();
}
}
package org.springframework.batch.io.xml.stax;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.xml.stax.NoStartEndDocumentStreamWriter;
/**
* Tests for {@link NoStartEndDocumentStreamWriter}
*
* @author Robert Kasanicky
*/
public class NoStartEndDocumentWriterTests extends TestCase {
// object under test
private NoStartEndDocumentStreamWriter writer;
private XMLEventWriter wrappedWriter;
private MockControl wrappedWriterControl = MockControl.createStrictControl(XMLEventWriter.class);
private XMLEventFactory eventFactory = XMLEventFactory.newInstance();
protected void setUp() throws Exception {
wrappedWriter = (XMLEventWriter) wrappedWriterControl.getMock();
writer = new NoStartEndDocumentStreamWriter(wrappedWriter);
}
/**
* StartDocument and EndDocument events are not passed to the wrapped writer.
*/
public void testNoStartEnd() throws Exception {
XMLEvent event = eventFactory.createComment("testEvent");
//mock expects only a single event
wrappedWriter.add(event);
wrappedWriterControl.setVoidCallable();
wrappedWriterControl.replay();
writer.add(eventFactory.createStartDocument());
writer.add(event);
writer.add(eventFactory.createEndDocument());
wrappedWriterControl.verify();
}
}

View File

@@ -1,34 +1,34 @@
package org.springframework.batch.item;
import junit.framework.TestCase;
/**
* Tests for {@link ExecutionContextUserSupport}.
*/
public class ExecutionContextUserSupportTests extends TestCase {
ExecutionContextUserSupport tested = new ExecutionContextUserSupport();
/**
* Regular usage scenario - prepends the name (supposed to be unique) to
* argument.
*/
public void testGetKey() {
tested.setName("uniqueName");
assertEquals("uniqueName.key", tested.getKey("key"));
}
/**
* Exception scenario - name must not be empty.
*/
public void testGetKeyWithNoNameSet() {
tested.setName("");
try {
tested.getKey("arbitrary string");
fail();
}
catch (IllegalArgumentException e) {
// expected
}
}
}
package org.springframework.batch.item;
import junit.framework.TestCase;
/**
* Tests for {@link ExecutionContextUserSupport}.
*/
public class ExecutionContextUserSupportTests extends TestCase {
ExecutionContextUserSupport tested = new ExecutionContextUserSupport();
/**
* Regular usage scenario - prepends the name (supposed to be unique) to
* argument.
*/
public void testGetKey() {
tested.setName("uniqueName");
assertEquals("uniqueName.key", tested.getKey("key"));
}
/**
* Exception scenario - name must not be empty.
*/
public void testGetKeyWithNoNameSet() {
tested.setName("");
try {
tested.getKey("arbitrary string");
fail();
}
catch (IllegalArgumentException e) {
// expected
}
}
}

View File

@@ -1,60 +1,60 @@
package org.springframework.batch.item.reader;
import java.util.Collection;
import java.util.Iterator;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.reader.AggregateItemReader;
public class AggregateItemReaderTests extends TestCase {
private MockControl inputControl;
private ItemReader input;
private AggregateItemReader provider;
public void setUp() {
//create mock for input
inputControl = MockControl.createControl(ItemReader.class);
input = (ItemReader) inputControl.getMock();
//create provider
provider = new AggregateItemReader();
provider.setItemReader(input);
}
public void testNext() throws Exception {
//set-up mock input
input.read();
inputControl.setReturnValue(AggregateItemReader.BEGIN_RECORD);
input.read();
inputControl.setReturnValue("line",3);
input.read();
inputControl.setReturnValue(AggregateItemReader.END_RECORD);
input.read();
inputControl.setReturnValue(null);
inputControl.replay();
//read object
Object result = provider.read();
//it should be collection of 3 strings "line"
assertTrue(result instanceof Collection);
Collection lines = (Collection)result;
assertEquals(3, lines.size());
for (Iterator i = lines.iterator(); i.hasNext();) {
assertEquals("line", i.next());
}
//read object again - it should return null
assertNull(provider.read());
//verify method calls
inputControl.verify();
}
}
package org.springframework.batch.item.reader;
import java.util.Collection;
import java.util.Iterator;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.reader.AggregateItemReader;
public class AggregateItemReaderTests extends TestCase {
private MockControl inputControl;
private ItemReader input;
private AggregateItemReader provider;
public void setUp() {
//create mock for input
inputControl = MockControl.createControl(ItemReader.class);
input = (ItemReader) inputControl.getMock();
//create provider
provider = new AggregateItemReader();
provider.setItemReader(input);
}
public void testNext() throws Exception {
//set-up mock input
input.read();
inputControl.setReturnValue(AggregateItemReader.BEGIN_RECORD);
input.read();
inputControl.setReturnValue("line",3);
input.read();
inputControl.setReturnValue(AggregateItemReader.END_RECORD);
input.read();
inputControl.setReturnValue(null);
inputControl.replay();
//read object
Object result = provider.read();
//it should be collection of 3 strings "line"
assertTrue(result instanceof Collection);
Collection lines = (Collection)result;
assertEquals(3, lines.size());
for (Iterator i = lines.iterator(); i.hasNext();) {
assertEquals("line", i.next());
}
//read object again - it should return null
assertNull(provider.read());
//verify method calls
inputControl.verify();
}
}

View File

@@ -1,52 +1,52 @@
package org.springframework.batch.item.reader;
import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.io.sample.domain.FooService;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Tests for {@link ItemReaderAdapter}.
*
* @author Robert Kasanicky
*/
public class DelegatingItemReaderIntegrationTests extends AbstractDependencyInjectionSpringContextTests {
private ItemReaderAdapter provider;
private FooService fooService;
protected String getConfigPath() {
return "delegating-item-provider.xml";
}
/**
* Regular usage scenario - items are retrieved from the service injected
* invoker points to.
*/
public void testNext() throws Exception {
List returnedItems = new ArrayList();
Object item;
while ((item = provider.read()) != null) {
returnedItems.add(item);
}
List input = fooService.getGeneratedFoos();
assertEquals(input.size(), returnedItems.size());
assertFalse(returnedItems.isEmpty());
for (int i = 0; i < input.size(); i++) {
assertSame(input.get(i), returnedItems.get(i));
}
}
public void setProvider(ItemReaderAdapter provider) {
this.provider = provider;
}
public void setFooService(FooService fooService) {
this.fooService = fooService;
}
}
package org.springframework.batch.item.reader;
import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.io.sample.domain.FooService;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Tests for {@link ItemReaderAdapter}.
*
* @author Robert Kasanicky
*/
public class DelegatingItemReaderIntegrationTests extends AbstractDependencyInjectionSpringContextTests {
private ItemReaderAdapter provider;
private FooService fooService;
protected String getConfigPath() {
return "delegating-item-provider.xml";
}
/**
* Regular usage scenario - items are retrieved from the service injected
* invoker points to.
*/
public void testNext() throws Exception {
List returnedItems = new ArrayList();
Object item;
while ((item = provider.read()) != null) {
returnedItems.add(item);
}
List input = fooService.getGeneratedFoos();
assertEquals(input.size(), returnedItems.size());
assertFalse(returnedItems.isEmpty());
for (int i = 0; i < input.size(); i++) {
assertSame(input.get(i), returnedItems.get(i));
}
}
public void setProvider(ItemReaderAdapter provider) {
this.provider = provider;
}
public void setFooService(FooService fooService) {
this.fooService = fooService;
}
}

View File

@@ -1,111 +1,111 @@
/*
* 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.item.reader;
import junit.framework.TestCase;
import org.springframework.batch.io.Skippable;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
/**
* Unit test for {@link DelegatingItemReader}
*
* @author Robert Kasanicky
*/
public class DelegatingItemReaderTests extends TestCase {
// object under test
private DelegatingItemReader itemProvider = new DelegatingItemReader();
private ItemReader source;
private ExecutionContext executionContext;
// create input template and inject it to data provider
protected void setUp() throws Exception {
executionContext = new ExecutionContext();
source = new MockItemReader(this, executionContext);
itemProvider.setItemReader(source);
}
public void testAfterPropertiesSet() throws Exception {
// shouldn't throw an exception since the input source is set
itemProvider.afterPropertiesSet();
}
public void testNullItemReader() {
try {
itemProvider.setItemReader(null);
itemProvider.afterPropertiesSet();
fail();
}
catch (Exception ex) {
assertTrue(ex instanceof IllegalArgumentException);
}
}
/**
* Uses input template to provide the domain object.
* @throws Exception
*/
public void testNext() throws Exception {
Object result = itemProvider.read();
assertSame("domain object is provided by the input template", this, result);
}
public void testSkip() throws Exception {
itemProvider.skip();
assertEquals("after skip", itemProvider.read());
}
private static class MockItemReader extends AbstractItemReader implements ItemReader, ItemStream, Skippable {
private Object value;
public void update(ExecutionContext executionContext) {
executionContext.putString("value", "foo");
}
public MockItemReader(Object value, ExecutionContext executionContext) {
this.value = value;
}
public Object read() {
return value;
}
public void close(ExecutionContext executionContext) {
}
public void open(ExecutionContext executionContext) {
}
public void skip() {
value = "after skip";
}
public void mark() {
}
public void reset() {
}
}
}
/*
* 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.item.reader;
import junit.framework.TestCase;
import org.springframework.batch.io.Skippable;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
/**
* Unit test for {@link DelegatingItemReader}
*
* @author Robert Kasanicky
*/
public class DelegatingItemReaderTests extends TestCase {
// object under test
private DelegatingItemReader itemProvider = new DelegatingItemReader();
private ItemReader source;
private ExecutionContext executionContext;
// create input template and inject it to data provider
protected void setUp() throws Exception {
executionContext = new ExecutionContext();
source = new MockItemReader(this, executionContext);
itemProvider.setItemReader(source);
}
public void testAfterPropertiesSet() throws Exception {
// shouldn't throw an exception since the input source is set
itemProvider.afterPropertiesSet();
}
public void testNullItemReader() {
try {
itemProvider.setItemReader(null);
itemProvider.afterPropertiesSet();
fail();
}
catch (Exception ex) {
assertTrue(ex instanceof IllegalArgumentException);
}
}
/**
* Uses input template to provide the domain object.
* @throws Exception
*/
public void testNext() throws Exception {
Object result = itemProvider.read();
assertSame("domain object is provided by the input template", this, result);
}
public void testSkip() throws Exception {
itemProvider.skip();
assertEquals("after skip", itemProvider.read());
}
private static class MockItemReader extends AbstractItemReader implements ItemReader, ItemStream, Skippable {
private Object value;
public void update(ExecutionContext executionContext) {
executionContext.putString("value", "foo");
}
public MockItemReader(Object value, ExecutionContext executionContext) {
this.value = value;
}
public Object read() {
return value;
}
public void close(ExecutionContext executionContext) {
}
public void open(ExecutionContext executionContext) {
}
public void skip() {
value = "after skip";
}
public void mark() {
}
public void reset() {
}
}
}

View File

@@ -1,116 +1,116 @@
/*
* 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.item.reader;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.exception.ValidationException;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.reader.AbstractItemReader;
import org.springframework.batch.item.reader.ValidatingItemReader;
import org.springframework.batch.item.validator.Validator;
/**
* @author Lucas Ward
*
*/
public class ValidatingItemReaderTests extends TestCase {
ItemReader inputSource;
ValidatingItemReader itemProvider;
Validator validator;
MockControl validatorControl = MockControl.createControl(Validator.class);
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
inputSource = new MockItemReader(this);
validator = (Validator)validatorControl.getMock();
itemProvider = new ValidatingItemReader();
itemProvider.setItemReader(inputSource);
itemProvider.setValidator(validator);
}
/*
* Super class' afterPropertieSet should be called to
* ensure ItemReader is set.
*/
public void testItemReaderPropertiesSet(){
try{
itemProvider.setItemReader(null);
itemProvider.afterPropertiesSet();
fail();
}catch(Exception ex){
assertTrue(ex instanceof IllegalArgumentException);
}
}
public void testValidatorPropertesSet(){
try{
itemProvider.setValidator(null);
itemProvider.afterPropertiesSet();
fail();
}catch(Exception ex){
assertTrue(ex instanceof IllegalArgumentException);
}
}
public void testValidation() throws Exception{
validator.validate(this);
validatorControl.replay();
assertEquals(itemProvider.read(), this);
validatorControl.verify();
}
public void testValidationException() throws Exception{
validator.validate(this);
validatorControl.setThrowable(new ValidationException(""));
validatorControl.replay();
try{
itemProvider.read();
fail();
}catch(ValidationException ex){
//expected
}
}
public void testNullInput() throws Exception{
validatorControl.replay();
itemProvider.setItemReader(new MockItemReader(null));
assertNull(itemProvider.read());
//assert validator wasn't called.
validatorControl.verify();
}
private static class MockItemReader extends AbstractItemReader {
Object value;
public MockItemReader(Object value){
this.value = value;
}
public Object read() {
return value;
}
}
}
/*
* 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.item.reader;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.io.exception.ValidationException;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.reader.AbstractItemReader;
import org.springframework.batch.item.reader.ValidatingItemReader;
import org.springframework.batch.item.validator.Validator;
/**
* @author Lucas Ward
*
*/
public class ValidatingItemReaderTests extends TestCase {
ItemReader inputSource;
ValidatingItemReader itemProvider;
Validator validator;
MockControl validatorControl = MockControl.createControl(Validator.class);
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
inputSource = new MockItemReader(this);
validator = (Validator)validatorControl.getMock();
itemProvider = new ValidatingItemReader();
itemProvider.setItemReader(inputSource);
itemProvider.setValidator(validator);
}
/*
* Super class' afterPropertieSet should be called to
* ensure ItemReader is set.
*/
public void testItemReaderPropertiesSet(){
try{
itemProvider.setItemReader(null);
itemProvider.afterPropertiesSet();
fail();
}catch(Exception ex){
assertTrue(ex instanceof IllegalArgumentException);
}
}
public void testValidatorPropertesSet(){
try{
itemProvider.setValidator(null);
itemProvider.afterPropertiesSet();
fail();
}catch(Exception ex){
assertTrue(ex instanceof IllegalArgumentException);
}
}
public void testValidation() throws Exception{
validator.validate(this);
validatorControl.replay();
assertEquals(itemProvider.read(), this);
validatorControl.verify();
}
public void testValidationException() throws Exception{
validator.validate(this);
validatorControl.setThrowable(new ValidationException(""));
validatorControl.replay();
try{
itemProvider.read();
fail();
}catch(ValidationException ex){
//expected
}
}
public void testNullInput() throws Exception{
validatorControl.replay();
itemProvider.setItemReader(new MockItemReader(null));
assertNull(itemProvider.read());
//assert validator wasn't called.
validatorControl.verify();
}
private static class MockItemReader extends AbstractItemReader {
Object value;
public MockItemReader(Object value){
this.value = value;
}
public Object read() {
return value;
}
}
}

View File

@@ -1,97 +1,97 @@
package org.springframework.batch.item.writer;
import java.util.ArrayList;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.item.writer.CompositeItemTransformer;
import org.springframework.batch.item.writer.ItemTransformer;
/**
* Tests for {@link CompositeItemTransformer}.
*
* @author Robert Kasanicky
*/
public class CompositeItemTransformerTests extends TestCase {
private CompositeItemTransformer composite = new CompositeItemTransformer();
private ItemTransformer transformer1;
private ItemTransformer transformer2;
private MockControl tControl1 = MockControl.createControl(ItemTransformer.class);
private MockControl tControl2 = MockControl.createControl(ItemTransformer.class);
protected void setUp() throws Exception {
transformer1 = (ItemTransformer) tControl1.getMock();
transformer2 = (ItemTransformer) tControl2 .getMock();
composite.setItemTransformers(new ArrayList() {{
add(transformer1); add(transformer2);
}});
composite.afterPropertiesSet();
}
/**
* Regular usage scenario - item is passed through the processing chain,
* return value of the of the last transformation is returned by the composite.
*/
public void testTransform() throws Exception {
Object item = new Object();
Object itemAfterFirstTransfromation = new Object();
Object itemAfterSecondTransformation = new Object();
transformer1.transform(item);
tControl1.setReturnValue(itemAfterFirstTransfromation);
transformer2.transform(itemAfterFirstTransfromation);
tControl2.setReturnValue(itemAfterSecondTransformation);
tControl1.replay();
tControl2.replay();
assertSame(itemAfterSecondTransformation, composite.transform(item));
tControl1.verify();
tControl2.verify();
}
/**
* The list of transformers must not be null or empty and
* can contain only instances of {@link ItemTransformer}.
*/
public void testAfterPropertiesSet() throws Exception {
// value not set
composite.setItemTransformers(null);
try {
composite.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
// empty list
composite.setItemTransformers(new ArrayList());
try {
composite.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
// invalid list member
composite.setItemTransformers(new ArrayList() {{ add(new Object()); }});
try {
composite.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
}
}
package org.springframework.batch.item.writer;
import java.util.ArrayList;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.item.writer.CompositeItemTransformer;
import org.springframework.batch.item.writer.ItemTransformer;
/**
* Tests for {@link CompositeItemTransformer}.
*
* @author Robert Kasanicky
*/
public class CompositeItemTransformerTests extends TestCase {
private CompositeItemTransformer composite = new CompositeItemTransformer();
private ItemTransformer transformer1;
private ItemTransformer transformer2;
private MockControl tControl1 = MockControl.createControl(ItemTransformer.class);
private MockControl tControl2 = MockControl.createControl(ItemTransformer.class);
protected void setUp() throws Exception {
transformer1 = (ItemTransformer) tControl1.getMock();
transformer2 = (ItemTransformer) tControl2 .getMock();
composite.setItemTransformers(new ArrayList() {{
add(transformer1); add(transformer2);
}});
composite.afterPropertiesSet();
}
/**
* Regular usage scenario - item is passed through the processing chain,
* return value of the of the last transformation is returned by the composite.
*/
public void testTransform() throws Exception {
Object item = new Object();
Object itemAfterFirstTransfromation = new Object();
Object itemAfterSecondTransformation = new Object();
transformer1.transform(item);
tControl1.setReturnValue(itemAfterFirstTransfromation);
transformer2.transform(itemAfterFirstTransfromation);
tControl2.setReturnValue(itemAfterSecondTransformation);
tControl1.replay();
tControl2.replay();
assertSame(itemAfterSecondTransformation, composite.transform(item));
tControl1.verify();
tControl2.verify();
}
/**
* The list of transformers must not be null or empty and
* can contain only instances of {@link ItemTransformer}.
*/
public void testAfterPropertiesSet() throws Exception {
// value not set
composite.setItemTransformers(null);
try {
composite.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
// empty list
composite.setItemTransformers(new ArrayList());
try {
composite.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
// invalid list member
composite.setItemTransformers(new ArrayList() {{ add(new Object()); }});
try {
composite.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
}
}

View File

@@ -1,55 +1,55 @@
package org.springframework.batch.item.writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.item.ItemWriter;
/**
* Tests for {@link CompositeItemWriter}
*
* @author Robert Kasanicky
*/
public class CompositeItemWriterTests extends TestCase {
// object under test
private CompositeItemWriter itemProcessor = new CompositeItemWriter();
/**
* Regular usage scenario.
* All injected processors should be called.
*/
public void testProcess() throws Exception {
final int NUMBER_OF_PROCESSORS = 10;
Object data = new Object();
List controls = new ArrayList(NUMBER_OF_PROCESSORS);
List processors = new ArrayList(NUMBER_OF_PROCESSORS);
for (int i = 0; i < NUMBER_OF_PROCESSORS; i++) {
MockControl control = MockControl.createStrictControl(ItemWriter.class);
ItemWriter processor = (ItemWriter) control.getMock();
processor.write(data);
control.setVoidCallable();
control.replay();
processors.add(processor);
controls.add(control);
}
itemProcessor.setDelegates(processors);
itemProcessor.write(data);
for (Iterator iterator = controls.iterator(); iterator.hasNext();) {
MockControl control = (MockControl) iterator.next();
control.verify();
}
}
}
package org.springframework.batch.item.writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.item.ItemWriter;
/**
* Tests for {@link CompositeItemWriter}
*
* @author Robert Kasanicky
*/
public class CompositeItemWriterTests extends TestCase {
// object under test
private CompositeItemWriter itemProcessor = new CompositeItemWriter();
/**
* Regular usage scenario.
* All injected processors should be called.
*/
public void testProcess() throws Exception {
final int NUMBER_OF_PROCESSORS = 10;
Object data = new Object();
List controls = new ArrayList(NUMBER_OF_PROCESSORS);
List processors = new ArrayList(NUMBER_OF_PROCESSORS);
for (int i = 0; i < NUMBER_OF_PROCESSORS; i++) {
MockControl control = MockControl.createStrictControl(ItemWriter.class);
ItemWriter processor = (ItemWriter) control.getMock();
processor.write(data);
control.setVoidCallable();
control.replay();
processors.add(processor);
controls.add(control);
}
itemProcessor.setDelegates(processors);
itemProcessor.write(data);
for (Iterator iterator = controls.iterator(); iterator.hasNext();) {
MockControl control = (MockControl) iterator.next();
control.verify();
}
}
}

View File

@@ -1,72 +1,72 @@
package org.springframework.batch.item.writer;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.writer.ItemTransformer;
import org.springframework.batch.item.writer.ItemTransformerItemWriter;
/**
* Tests for {@link ItemTransformerItemWriter}.
*
* @author Robert Kasanicky
*/
public class ItemTransformerItemWriterTests extends TestCase {
private ItemTransformerItemWriter processor = new ItemTransformerItemWriter();
private ItemTransformer transformer;
private ItemWriter itemWriter;
private MockControl tControl = MockControl.createControl(ItemTransformer.class);
private MockControl outControl = MockControl.createControl(ItemWriter.class);
protected void setUp() throws Exception {
transformer = (ItemTransformer) tControl.getMock();
itemWriter = (ItemWriter) outControl.getMock();
processor.setItemTransformer(transformer);
processor.setDelegate(itemWriter);
processor.afterPropertiesSet();
}
/**
* Regular usage scenario - item is passed to transformer
* and the result of transformation is passed to output source.
*/
public void testProcess() throws Exception {
Object item = new Object();
Object itemAfterTransformation = new Object();
transformer.transform(item);
tControl.setReturnValue(itemAfterTransformation);
itemWriter.write(itemAfterTransformation);
outControl.setVoidCallable();
tControl.replay();
outControl.replay();
processor.write(item);
tControl.verify();
outControl.verify();
}
/**
* Item transformer must be set.
*/
public void testAfterPropertiesSet() throws Exception {
// value not set
processor.setItemTransformer(null);
try {
processor.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
}
}
package org.springframework.batch.item.writer;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.writer.ItemTransformer;
import org.springframework.batch.item.writer.ItemTransformerItemWriter;
/**
* Tests for {@link ItemTransformerItemWriter}.
*
* @author Robert Kasanicky
*/
public class ItemTransformerItemWriterTests extends TestCase {
private ItemTransformerItemWriter processor = new ItemTransformerItemWriter();
private ItemTransformer transformer;
private ItemWriter itemWriter;
private MockControl tControl = MockControl.createControl(ItemTransformer.class);
private MockControl outControl = MockControl.createControl(ItemWriter.class);
protected void setUp() throws Exception {
transformer = (ItemTransformer) tControl.getMock();
itemWriter = (ItemWriter) outControl.getMock();
processor.setItemTransformer(transformer);
processor.setDelegate(itemWriter);
processor.afterPropertiesSet();
}
/**
* Regular usage scenario - item is passed to transformer
* and the result of transformation is passed to output source.
*/
public void testProcess() throws Exception {
Object item = new Object();
Object itemAfterTransformation = new Object();
transformer.transform(item);
tControl.setReturnValue(itemAfterTransformation);
itemWriter.write(itemAfterTransformation);
outControl.setVoidCallable();
tControl.replay();
outControl.replay();
processor.write(item);
tControl.verify();
outControl.verify();
}
/**
* Item transformer must be set.
*/
public void testAfterPropertiesSet() throws Exception {
// value not set
processor.setItemTransformer(null);
try {
processor.afterPropertiesSet();
fail();
}
catch (IllegalArgumentException e) {
// expected
}
}
}

View File

@@ -1,56 +1,56 @@
package org.springframework.batch.item.writer;
import java.util.List;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.batch.io.sample.domain.FooService;
import org.springframework.batch.item.ItemWriter;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Tests for {@link ItemWriterAdapter}.
*
* @author Robert Kasanicky
*/
public class ItemWriterAdapterTests extends AbstractDependencyInjectionSpringContextTests {
private ItemWriter processor;
private FooService fooService;
protected String getConfigPath() {
return "delegating-item-writer.xml";
}
/**
* Regular usage scenario - input object should be passed to
* the service the injected invoker points to.
*/
public void testProcess() throws Exception {
Foo foo;
while ((foo = fooService.generateFoo()) != null) {
processor.write(foo);
}
List input = fooService.getGeneratedFoos();
List processed = fooService.getProcessedFoos();
assertEquals(input.size(), processed.size());
assertFalse(fooService.getProcessedFoos().isEmpty());
for (int i = 0; i < input.size(); i++) {
assertSame(input.get(i), processed.get(i));
}
}
//setter for auto-injection
public void setProcessor(ItemWriter processor) {
this.processor = processor;
}
//setter for auto-injection
public void setFooService(FooService fooService) {
this.fooService = fooService;
}
}
package org.springframework.batch.item.writer;
import java.util.List;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.batch.io.sample.domain.FooService;
import org.springframework.batch.item.ItemWriter;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Tests for {@link ItemWriterAdapter}.
*
* @author Robert Kasanicky
*/
public class ItemWriterAdapterTests extends AbstractDependencyInjectionSpringContextTests {
private ItemWriter processor;
private FooService fooService;
protected String getConfigPath() {
return "delegating-item-writer.xml";
}
/**
* Regular usage scenario - input object should be passed to
* the service the injected invoker points to.
*/
public void testProcess() throws Exception {
Foo foo;
while ((foo = fooService.generateFoo()) != null) {
processor.write(foo);
}
List input = fooService.getGeneratedFoos();
List processed = fooService.getProcessedFoos();
assertEquals(input.size(), processed.size());
assertFalse(fooService.getProcessedFoos().isEmpty());
for (int i = 0; i < input.size(); i++) {
assertSame(input.get(i), processed.get(i));
}
}
//setter for auto-injection
public void setProcessor(ItemWriter processor) {
this.processor = processor;
}
//setter for auto-injection
public void setFooService(FooService fooService) {
this.fooService = fooService;
}
}

View File

@@ -1,59 +1,59 @@
package org.springframework.batch.item.writer;
import java.util.List;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.batch.io.sample.domain.FooService;
import org.springframework.batch.item.writer.PropertyExtractingDelegatingItemWriter;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Tests for {@link PropertyExtractingDelegatingItemWriter}
*
* @author Robert Kasanicky
*/
public class PropertyExtractingDelegatingItemProccessorIntegrationTests
extends AbstractDependencyInjectionSpringContextTests {
private PropertyExtractingDelegatingItemWriter processor;
private FooService fooService;
protected String getConfigPath() {
return "pe-delegating-item-writer.xml";
}
/**
* Regular usage scenario - input object should be passed to
* the service the injected invoker points to.
*/
public void testProcess() throws Exception {
Foo foo;
while ((foo = fooService.generateFoo()) != null) {
processor.write(foo);
}
List input = fooService.getGeneratedFoos();
List processed = fooService.getProcessedFooNameValuePairs();
assertEquals(input.size(), processed.size());
assertFalse(fooService.getProcessedFooNameValuePairs().isEmpty());
for (int i = 0; i < input.size(); i++) {
Foo inputFoo = (Foo) input.get(i);
Foo outputFoo = (Foo) processed.get(i);
assertEquals(inputFoo.getName(), outputFoo.getName());
assertEquals(inputFoo.getValue(), outputFoo.getValue());
assertEquals(0, outputFoo.getId());
}
}
public void setProcessor(PropertyExtractingDelegatingItemWriter processor) {
this.processor = processor;
}
public void setFooService(FooService fooService) {
this.fooService = fooService;
}
}
package org.springframework.batch.item.writer;
import java.util.List;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.batch.io.sample.domain.FooService;
import org.springframework.batch.item.writer.PropertyExtractingDelegatingItemWriter;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Tests for {@link PropertyExtractingDelegatingItemWriter}
*
* @author Robert Kasanicky
*/
public class PropertyExtractingDelegatingItemProccessorIntegrationTests
extends AbstractDependencyInjectionSpringContextTests {
private PropertyExtractingDelegatingItemWriter processor;
private FooService fooService;
protected String getConfigPath() {
return "pe-delegating-item-writer.xml";
}
/**
* Regular usage scenario - input object should be passed to
* the service the injected invoker points to.
*/
public void testProcess() throws Exception {
Foo foo;
while ((foo = fooService.generateFoo()) != null) {
processor.write(foo);
}
List input = fooService.getGeneratedFoos();
List processed = fooService.getProcessedFooNameValuePairs();
assertEquals(input.size(), processed.size());
assertFalse(fooService.getProcessedFooNameValuePairs().isEmpty());
for (int i = 0; i < input.size(); i++) {
Foo inputFoo = (Foo) input.get(i);
Foo outputFoo = (Foo) processed.get(i);
assertEquals(inputFoo.getName(), outputFoo.getName());
assertEquals(inputFoo.getValue(), outputFoo.getValue());
assertEquals(0, outputFoo.getId());
}
}
public void setProcessor(PropertyExtractingDelegatingItemWriter processor) {
this.processor = processor;
}
public void setFooService(FooService fooService) {
this.fooService = fooService;
}
}

View File

@@ -1,210 +1,210 @@
/*
* 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.repeat;
import org.apache.commons.lang.SerializationUtils;
import junit.framework.TestCase;
/**
* @author Dave Syer
*
*/
public class ExitStatusTests extends TestCase {
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#ExitStatus(boolean, int)}.
*/
public void testExitStatusBooleanInt() {
ExitStatus status = new ExitStatus(true, "10");
assertTrue(status.isContinuable());
assertEquals("10", status.getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#ExitStatus(boolean, int)}.
*/
public void testExitStatusConstantsContinuable() {
ExitStatus status = ExitStatus.CONTINUABLE;
assertTrue(status.isContinuable());
assertEquals("CONTINUABLE", status.getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#ExitStatus(boolean, int)}.
*/
public void testExitStatusConstantsFinished() {
ExitStatus status = ExitStatus.FINISHED;
assertFalse(status.isContinuable());
assertEquals("COMPLETED", status.getExitCode());
}
/**
* Test equality of exit statuses.
*
* @throws Exception
*/
public void testEqualsWithSameProperties() throws Exception {
assertEquals(ExitStatus.CONTINUABLE, new ExitStatus(true, "CONTINUABLE"));
}
public void testEqualsSelf() {
ExitStatus status = new ExitStatus(true, "test");
assertEquals(status, status);
}
public void testEquals() {
assertEquals(new ExitStatus(true, "test"), new ExitStatus(true, "test"));
}
/**
* Test equality of exit statuses.
*
* @throws Exception
*/
public void testEqualsWithNull() throws Exception {
assertFalse(ExitStatus.CONTINUABLE.equals(null));
}
/**
* Test equality of exit statuses.
*
* @throws Exception
*/
public void testHashcode() throws Exception {
assertEquals(ExitStatus.CONTINUABLE.toString().hashCode(), ExitStatus.CONTINUABLE.hashCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(boolean)}.
*/
public void testAndBoolean() {
assertTrue(ExitStatus.CONTINUABLE.and(true).isContinuable());
assertFalse(ExitStatus.CONTINUABLE.and(false).isContinuable());
ExitStatus status = new ExitStatus(false, "CUSTOM_CODE", "CUSTOM_DESCRIPTION");
assertTrue(status.and(true).getExitCode() == "CUSTOM_CODE");
assertTrue(status.and(true).getExitDescription() == "CUSTOM_DESCRIPTION");
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(org.springframework.batch.repeat.ExitStatus)}.
*/
public void testAndExitStatusStillContinuable() {
assertTrue(ExitStatus.CONTINUABLE.and(ExitStatus.CONTINUABLE).isContinuable());
assertFalse(ExitStatus.CONTINUABLE.and(ExitStatus.FINISHED).isContinuable());
assertTrue(ExitStatus.CONTINUABLE.and(ExitStatus.CONTINUABLE).getExitCode() == ExitStatus.CONTINUABLE
.getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(org.springframework.batch.repeat.ExitStatus)}.
*/
public void testAndExitStatusWhenFinishedAddedToContinuable() {
assertEquals(ExitStatus.FINISHED.getExitCode(), ExitStatus.CONTINUABLE.and(ExitStatus.FINISHED).getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(org.springframework.batch.repeat.ExitStatus)}.
*/
public void testAndExitStatusWhenContinuableAddedToFinished() {
assertEquals(ExitStatus.FINISHED.getExitCode(), ExitStatus.FINISHED.and(ExitStatus.CONTINUABLE).getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(org.springframework.batch.repeat.ExitStatus)}.
*/
public void testAndExitStatusWhenCustomContinuableAddedToContinuable() {
assertEquals("CUSTOM", ExitStatus.CONTINUABLE.and(ExitStatus.CONTINUABLE.replaceExitCode("CUSTOM"))
.getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(org.springframework.batch.repeat.ExitStatus)}.
*/
public void testAndExitStatusWhenCustomContinuableAddedToFinished() {
assertEquals(ExitStatus.FINISHED.getExitCode(), ExitStatus.FINISHED.and(ExitStatus.CONTINUABLE.replaceExitCode("CUSTOM"))
.getExitCode());
}
public void testAddExitCode() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.replaceExitCode("FOO");
assertTrue(ExitStatus.CONTINUABLE != status);
assertTrue(status.isContinuable());
assertEquals("FOO", status.getExitCode());
}
public void testAddExitCodeToExistingStatus() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.replaceExitCode("FOO").replaceExitCode("BAR");
assertTrue(ExitStatus.CONTINUABLE != status);
assertTrue(status.isContinuable());
assertEquals("BAR", status.getExitCode());
}
public void testAddExitCodeToSameStatus() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.replaceExitCode(ExitStatus.CONTINUABLE.getExitCode());
assertTrue(ExitStatus.CONTINUABLE != status);
assertTrue(status.isContinuable());
assertEquals(ExitStatus.CONTINUABLE.getExitCode(), status.getExitCode());
}
public void testAddExitDescription() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.addExitDescription("Foo");
assertTrue(ExitStatus.CONTINUABLE != status);
assertTrue(status.isContinuable());
assertEquals("Foo", status.getExitDescription());
}
public void testAddExitDescriptionToSameStatus() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.addExitDescription("Foo").addExitDescription("Foo");
assertTrue(ExitStatus.CONTINUABLE != status);
assertTrue(status.isContinuable());
assertEquals("Foo", status.getExitDescription());
}
public void testAddExitCodeWithDescription() throws Exception {
ExitStatus status = new ExitStatus(true, "BAR", "Bar").replaceExitCode("FOO");
assertEquals("FOO", status.getExitCode());
assertEquals("Bar", status.getExitDescription());
}
public void testRunningIsRunning() throws Exception {
assertTrue(ExitStatus.RUNNING.isRunning());
assertTrue(new ExitStatus(true, "RUNNING").isRunning());
}
public void testUnkownIsRunning() throws Exception {
assertTrue(ExitStatus.UNKNOWN.isRunning());
}
public void testSerializable() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.replaceExitCode("FOO");
byte[] bytes = SerializationUtils.serialize(status);
Object object = SerializationUtils.deserialize(bytes);
assertTrue(object instanceof ExitStatus);
ExitStatus restored = (ExitStatus) object;
assertTrue(restored.isContinuable());
assertEquals(status.getExitCode(), restored.getExitCode());
}
}
/*
* 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.repeat;
import org.apache.commons.lang.SerializationUtils;
import junit.framework.TestCase;
/**
* @author Dave Syer
*
*/
public class ExitStatusTests extends TestCase {
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#ExitStatus(boolean, int)}.
*/
public void testExitStatusBooleanInt() {
ExitStatus status = new ExitStatus(true, "10");
assertTrue(status.isContinuable());
assertEquals("10", status.getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#ExitStatus(boolean, int)}.
*/
public void testExitStatusConstantsContinuable() {
ExitStatus status = ExitStatus.CONTINUABLE;
assertTrue(status.isContinuable());
assertEquals("CONTINUABLE", status.getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#ExitStatus(boolean, int)}.
*/
public void testExitStatusConstantsFinished() {
ExitStatus status = ExitStatus.FINISHED;
assertFalse(status.isContinuable());
assertEquals("COMPLETED", status.getExitCode());
}
/**
* Test equality of exit statuses.
*
* @throws Exception
*/
public void testEqualsWithSameProperties() throws Exception {
assertEquals(ExitStatus.CONTINUABLE, new ExitStatus(true, "CONTINUABLE"));
}
public void testEqualsSelf() {
ExitStatus status = new ExitStatus(true, "test");
assertEquals(status, status);
}
public void testEquals() {
assertEquals(new ExitStatus(true, "test"), new ExitStatus(true, "test"));
}
/**
* Test equality of exit statuses.
*
* @throws Exception
*/
public void testEqualsWithNull() throws Exception {
assertFalse(ExitStatus.CONTINUABLE.equals(null));
}
/**
* Test equality of exit statuses.
*
* @throws Exception
*/
public void testHashcode() throws Exception {
assertEquals(ExitStatus.CONTINUABLE.toString().hashCode(), ExitStatus.CONTINUABLE.hashCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(boolean)}.
*/
public void testAndBoolean() {
assertTrue(ExitStatus.CONTINUABLE.and(true).isContinuable());
assertFalse(ExitStatus.CONTINUABLE.and(false).isContinuable());
ExitStatus status = new ExitStatus(false, "CUSTOM_CODE", "CUSTOM_DESCRIPTION");
assertTrue(status.and(true).getExitCode() == "CUSTOM_CODE");
assertTrue(status.and(true).getExitDescription() == "CUSTOM_DESCRIPTION");
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(org.springframework.batch.repeat.ExitStatus)}.
*/
public void testAndExitStatusStillContinuable() {
assertTrue(ExitStatus.CONTINUABLE.and(ExitStatus.CONTINUABLE).isContinuable());
assertFalse(ExitStatus.CONTINUABLE.and(ExitStatus.FINISHED).isContinuable());
assertTrue(ExitStatus.CONTINUABLE.and(ExitStatus.CONTINUABLE).getExitCode() == ExitStatus.CONTINUABLE
.getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(org.springframework.batch.repeat.ExitStatus)}.
*/
public void testAndExitStatusWhenFinishedAddedToContinuable() {
assertEquals(ExitStatus.FINISHED.getExitCode(), ExitStatus.CONTINUABLE.and(ExitStatus.FINISHED).getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(org.springframework.batch.repeat.ExitStatus)}.
*/
public void testAndExitStatusWhenContinuableAddedToFinished() {
assertEquals(ExitStatus.FINISHED.getExitCode(), ExitStatus.FINISHED.and(ExitStatus.CONTINUABLE).getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(org.springframework.batch.repeat.ExitStatus)}.
*/
public void testAndExitStatusWhenCustomContinuableAddedToContinuable() {
assertEquals("CUSTOM", ExitStatus.CONTINUABLE.and(ExitStatus.CONTINUABLE.replaceExitCode("CUSTOM"))
.getExitCode());
}
/**
* Test method for
* {@link org.springframework.batch.repeat.ExitStatus#and(org.springframework.batch.repeat.ExitStatus)}.
*/
public void testAndExitStatusWhenCustomContinuableAddedToFinished() {
assertEquals(ExitStatus.FINISHED.getExitCode(), ExitStatus.FINISHED.and(ExitStatus.CONTINUABLE.replaceExitCode("CUSTOM"))
.getExitCode());
}
public void testAddExitCode() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.replaceExitCode("FOO");
assertTrue(ExitStatus.CONTINUABLE != status);
assertTrue(status.isContinuable());
assertEquals("FOO", status.getExitCode());
}
public void testAddExitCodeToExistingStatus() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.replaceExitCode("FOO").replaceExitCode("BAR");
assertTrue(ExitStatus.CONTINUABLE != status);
assertTrue(status.isContinuable());
assertEquals("BAR", status.getExitCode());
}
public void testAddExitCodeToSameStatus() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.replaceExitCode(ExitStatus.CONTINUABLE.getExitCode());
assertTrue(ExitStatus.CONTINUABLE != status);
assertTrue(status.isContinuable());
assertEquals(ExitStatus.CONTINUABLE.getExitCode(), status.getExitCode());
}
public void testAddExitDescription() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.addExitDescription("Foo");
assertTrue(ExitStatus.CONTINUABLE != status);
assertTrue(status.isContinuable());
assertEquals("Foo", status.getExitDescription());
}
public void testAddExitDescriptionToSameStatus() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.addExitDescription("Foo").addExitDescription("Foo");
assertTrue(ExitStatus.CONTINUABLE != status);
assertTrue(status.isContinuable());
assertEquals("Foo", status.getExitDescription());
}
public void testAddExitCodeWithDescription() throws Exception {
ExitStatus status = new ExitStatus(true, "BAR", "Bar").replaceExitCode("FOO");
assertEquals("FOO", status.getExitCode());
assertEquals("Bar", status.getExitDescription());
}
public void testRunningIsRunning() throws Exception {
assertTrue(ExitStatus.RUNNING.isRunning());
assertTrue(new ExitStatus(true, "RUNNING").isRunning());
}
public void testUnkownIsRunning() throws Exception {
assertTrue(ExitStatus.UNKNOWN.isRunning());
}
public void testSerializable() throws Exception {
ExitStatus status = ExitStatus.CONTINUABLE.replaceExitCode("FOO");
byte[] bytes = SerializationUtils.serialize(status);
Object object = SerializationUtils.deserialize(bytes);
assertTrue(object instanceof ExitStatus);
ExitStatus restored = (ExitStatus) object;
assertTrue(restored.isContinuable());
assertEquals(status.getExitCode(), restored.getExitCode());
}
}

View File

@@ -1,93 +1,93 @@
/*
* 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.repeat.context;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
/**
* @author dsyer
*
*/
public class RepeatContextSupportTests extends TestCase {
private List list = new ArrayList();
/**
* Test method for {@link org.springframework.batch.repeat.context.RepeatContextSupport#registerDestructionCallback(java.lang.String, java.lang.Runnable)}.
*/
public void testDestructionCallbackSunnyDay() throws Exception {
RepeatContextSupport context = new RepeatContextSupport(null);
context.setAttribute("foo", "FOO");
context.registerDestructionCallback("foo", new Runnable() {
public void run() {
list.add("bar");
}
});
context.close();
assertEquals(1, list.size());
assertEquals("bar", list.get(0));
}
/**
* Test method for {@link org.springframework.batch.repeat.context.RepeatContextSupport#registerDestructionCallback(java.lang.String, java.lang.Runnable)}.
*/
public void testDestructionCallbackMissingAttribute() throws Exception {
RepeatContextSupport context = new RepeatContextSupport(null);
context.registerDestructionCallback("foo", new Runnable() {
public void run() {
list.add("bar");
}
});
context.close();
// No check for the attribute before executing callback
assertEquals(1, list.size());
}
/**
* Test method for {@link org.springframework.batch.repeat.context.RepeatContextSupport#registerDestructionCallback(java.lang.String, java.lang.Runnable)}.
*/
public void testDestructionCallbackWithException() throws Exception {
RepeatContextSupport context = new RepeatContextSupport(null);
context.setAttribute("foo", "FOO");
context.setAttribute("bar", "BAR");
context.registerDestructionCallback("bar", new Runnable() {
public void run() {
list.add("spam");
throw new RuntimeException("fail!");
}
});
context.registerDestructionCallback("foo", new Runnable() {
public void run() {
list.add("bar");
throw new RuntimeException("fail!");
}
});
try {
context.close();
fail("Expected RuntimeException");
} catch (RuntimeException e) {
// We don't care which one was thrown...
assertEquals("fail!", e.getMessage());
}
// ...but we do care that both were executed:
assertEquals(2, list.size());
assertTrue(list.contains("bar"));
assertTrue(list.contains("spam"));
}
}
/*
* 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.repeat.context;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
/**
* @author dsyer
*
*/
public class RepeatContextSupportTests extends TestCase {
private List list = new ArrayList();
/**
* Test method for {@link org.springframework.batch.repeat.context.RepeatContextSupport#registerDestructionCallback(java.lang.String, java.lang.Runnable)}.
*/
public void testDestructionCallbackSunnyDay() throws Exception {
RepeatContextSupport context = new RepeatContextSupport(null);
context.setAttribute("foo", "FOO");
context.registerDestructionCallback("foo", new Runnable() {
public void run() {
list.add("bar");
}
});
context.close();
assertEquals(1, list.size());
assertEquals("bar", list.get(0));
}
/**
* Test method for {@link org.springframework.batch.repeat.context.RepeatContextSupport#registerDestructionCallback(java.lang.String, java.lang.Runnable)}.
*/
public void testDestructionCallbackMissingAttribute() throws Exception {
RepeatContextSupport context = new RepeatContextSupport(null);
context.registerDestructionCallback("foo", new Runnable() {
public void run() {
list.add("bar");
}
});
context.close();
// No check for the attribute before executing callback
assertEquals(1, list.size());
}
/**
* Test method for {@link org.springframework.batch.repeat.context.RepeatContextSupport#registerDestructionCallback(java.lang.String, java.lang.Runnable)}.
*/
public void testDestructionCallbackWithException() throws Exception {
RepeatContextSupport context = new RepeatContextSupport(null);
context.setAttribute("foo", "FOO");
context.setAttribute("bar", "BAR");
context.registerDestructionCallback("bar", new Runnable() {
public void run() {
list.add("spam");
throw new RuntimeException("fail!");
}
});
context.registerDestructionCallback("foo", new Runnable() {
public void run() {
list.add("bar");
throw new RuntimeException("fail!");
}
});
try {
context.close();
fail("Expected RuntimeException");
} catch (RuntimeException e) {
// We don't care which one was thrown...
assertEquals("fail!", e.getMessage());
}
// ...but we do care that both were executed:
assertEquals(2, list.size());
assertTrue(list.contains("bar"));
assertTrue(list.contains("spam"));
}
}

View File

@@ -1,172 +1,172 @@
package org.springframework.batch.support;
import junit.framework.TestCase;
import org.springframework.batch.io.exception.DynamicMethodInvocationException;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.batch.io.sample.domain.FooService;
import org.springframework.util.Assert;
/**
* Tests for {@link AbstractMethodInvokingDelegator}
*
* @author Robert Kasanicky
*/
public class AbstractDelegatorTests extends TestCase {
private static class ConcreteDelegator extends AbstractMethodInvokingDelegator {
}
private AbstractMethodInvokingDelegator delegator = new ConcreteDelegator();
private Foo foo = new Foo(0, "foo", 1);
protected void setUp() throws Exception {
delegator.setTargetObject(foo);
delegator.setArguments(null);
}
/**
* Regular use - calling methods directly and via delegator leads to same
* results
*/
public void testDelegation() throws Exception {
delegator.setTargetMethod("getName");
delegator.afterPropertiesSet();
assertEquals(foo.getName(), delegator.invokeDelegateMethod());
}
/**
* Regular use - calling methods directly and via delegator leads to same
* results
*/
public void testDelegationWithArgument() throws Exception {
delegator.setTargetMethod("setName");
final String NEW_FOO_NAME = "newFooName";
delegator.afterPropertiesSet();
delegator.invokeDelegateMethodWithArgument(NEW_FOO_NAME);
assertEquals(NEW_FOO_NAME, foo.getName());
// using the arguments setter should work equally well
foo.setName("foo");
Assert.state(!foo.getName().equals(NEW_FOO_NAME));
delegator.setArguments(new Object[] { NEW_FOO_NAME });
delegator.afterPropertiesSet();
delegator.invokeDelegateMethod();
assertEquals(NEW_FOO_NAME, foo.getName());
}
/**
* Regular use - calling methods directly and via delegator leads to same
* results
*/
public void testDelegationWithMultipleArguments() throws Exception {
FooService fooService = new FooService();
delegator.setTargetObject(fooService);
delegator.setTargetMethod("processNameValuePair");
delegator.afterPropertiesSet();
final String FOO_NAME = "fooName";
final int FOO_VALUE = 12345;
delegator.invokeDelegateMethodWithArguments(new Object[]{FOO_NAME, new Integer(FOO_VALUE)});
Foo foo = (Foo) fooService.getProcessedFooNameValuePairs().get(0);
assertEquals(FOO_NAME, foo.getName());
assertEquals(FOO_VALUE, foo.getValue());
}
/**
* Exception scenario - target method is not declared by target object.
*/
public void testInvalidMethodName() throws Exception {
delegator.setTargetMethod("not-existing-method-name");
try {
delegator.afterPropertiesSet();
fail();
}
catch (IllegalStateException e) {
// expected
}
try {
delegator.invokeDelegateMethod();
fail();
}
catch (DynamicMethodInvocationException e) {
// expected
}
}
/**
* Exception scenario - target method is called with invalid arguments.
*/
public void testInvalidArgumentsForExistingMethod() throws Exception {
delegator.setTargetMethod("setName");
delegator.afterPropertiesSet();
try {
delegator.invokeDelegateMethodWithArgument(new Object());
fail();
}
catch (DynamicMethodInvocationException e) {
// expected
}
}
/**
* Exception scenario - target method is called with incorrect number of
* arguments.
*/
public void testIncorrectArgumentCount() throws Exception {
delegator.setTargetMethod("setName");
delegator.afterPropertiesSet();
try {
// single argument expected but none provided
delegator.invokeDelegateMethod();
fail();
}
catch (DynamicMethodInvocationException e) {
// expected
}
try {
// single argument expected but two provided
delegator.invokeDelegateMethodWithArguments(new Object[]{"name", "anotherName"});
fail();
}
catch (DynamicMethodInvocationException e) {
// expected
}
}
/**
* Exception scenario - incorrect static arguments set.
*/
public void testIncorrectNumberOfStaticArguments() throws Exception {
delegator.setTargetMethod("setName");
// incorrect argument count
delegator.setArguments(new Object[]{"first", "second"});
try {
delegator.afterPropertiesSet();
fail();
}
catch (IllegalStateException e) {
// expected
}
// correct argument count, but invalid argument type
delegator.setArguments(new Object[]{new Object()});
try {
delegator.afterPropertiesSet();
fail();
}
catch (IllegalStateException e) {
// expected
}
}
}
package org.springframework.batch.support;
import junit.framework.TestCase;
import org.springframework.batch.io.exception.DynamicMethodInvocationException;
import org.springframework.batch.io.sample.domain.Foo;
import org.springframework.batch.io.sample.domain.FooService;
import org.springframework.util.Assert;
/**
* Tests for {@link AbstractMethodInvokingDelegator}
*
* @author Robert Kasanicky
*/
public class AbstractDelegatorTests extends TestCase {
private static class ConcreteDelegator extends AbstractMethodInvokingDelegator {
}
private AbstractMethodInvokingDelegator delegator = new ConcreteDelegator();
private Foo foo = new Foo(0, "foo", 1);
protected void setUp() throws Exception {
delegator.setTargetObject(foo);
delegator.setArguments(null);
}
/**
* Regular use - calling methods directly and via delegator leads to same
* results
*/
public void testDelegation() throws Exception {
delegator.setTargetMethod("getName");
delegator.afterPropertiesSet();
assertEquals(foo.getName(), delegator.invokeDelegateMethod());
}
/**
* Regular use - calling methods directly and via delegator leads to same
* results
*/
public void testDelegationWithArgument() throws Exception {
delegator.setTargetMethod("setName");
final String NEW_FOO_NAME = "newFooName";
delegator.afterPropertiesSet();
delegator.invokeDelegateMethodWithArgument(NEW_FOO_NAME);
assertEquals(NEW_FOO_NAME, foo.getName());
// using the arguments setter should work equally well
foo.setName("foo");
Assert.state(!foo.getName().equals(NEW_FOO_NAME));
delegator.setArguments(new Object[] { NEW_FOO_NAME });
delegator.afterPropertiesSet();
delegator.invokeDelegateMethod();
assertEquals(NEW_FOO_NAME, foo.getName());
}
/**
* Regular use - calling methods directly and via delegator leads to same
* results
*/
public void testDelegationWithMultipleArguments() throws Exception {
FooService fooService = new FooService();
delegator.setTargetObject(fooService);
delegator.setTargetMethod("processNameValuePair");
delegator.afterPropertiesSet();
final String FOO_NAME = "fooName";
final int FOO_VALUE = 12345;
delegator.invokeDelegateMethodWithArguments(new Object[]{FOO_NAME, new Integer(FOO_VALUE)});
Foo foo = (Foo) fooService.getProcessedFooNameValuePairs().get(0);
assertEquals(FOO_NAME, foo.getName());
assertEquals(FOO_VALUE, foo.getValue());
}
/**
* Exception scenario - target method is not declared by target object.
*/
public void testInvalidMethodName() throws Exception {
delegator.setTargetMethod("not-existing-method-name");
try {
delegator.afterPropertiesSet();
fail();
}
catch (IllegalStateException e) {
// expected
}
try {
delegator.invokeDelegateMethod();
fail();
}
catch (DynamicMethodInvocationException e) {
// expected
}
}
/**
* Exception scenario - target method is called with invalid arguments.
*/
public void testInvalidArgumentsForExistingMethod() throws Exception {
delegator.setTargetMethod("setName");
delegator.afterPropertiesSet();
try {
delegator.invokeDelegateMethodWithArgument(new Object());
fail();
}
catch (DynamicMethodInvocationException e) {
// expected
}
}
/**
* Exception scenario - target method is called with incorrect number of
* arguments.
*/
public void testIncorrectArgumentCount() throws Exception {
delegator.setTargetMethod("setName");
delegator.afterPropertiesSet();
try {
// single argument expected but none provided
delegator.invokeDelegateMethod();
fail();
}
catch (DynamicMethodInvocationException e) {
// expected
}
try {
// single argument expected but two provided
delegator.invokeDelegateMethodWithArguments(new Object[]{"name", "anotherName"});
fail();
}
catch (DynamicMethodInvocationException e) {
// expected
}
}
/**
* Exception scenario - incorrect static arguments set.
*/
public void testIncorrectNumberOfStaticArguments() throws Exception {
delegator.setTargetMethod("setName");
// incorrect argument count
delegator.setArguments(new Object[]{"first", "second"});
try {
delegator.afterPropertiesSet();
fail();
}
catch (IllegalStateException e) {
// expected
}
// correct argument count, but invalid argument type
delegator.setArguments(new Object[]{new Object()});
try {
delegator.afterPropertiesSet();
fail();
}
catch (IllegalStateException e) {
// expected
}
}
}