Spring: using of FlatFileItemReader - spring

Could I use FlatFileItemReader not as reader of batch processing? I want to use it for parsing of File.
I have bean of reader:
<bean id="cvsFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="file:${garmin.fs.in.received2}" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="id,sales,qty,staffName,date" />
</bean>
</property>
<property name="fieldSetMapper">
<bean class="my.app.util.ReportFieldSetMapper" />
</property>
</bean>
</property>
</bean>
And I want to use it in my component:
#Component
public class Handler {
#Autowired
private FlatFileItemReader<Report> reader;
public File handleFile() {
try {
Report report = reader.read();
} catch (Exception e) {
e.printStackTrace();
}
return input;
}
}
But in line of code:
Report report = reader.read();
I got exception:
org.springframework.batch.item.ReaderNotOpenException: Reader must
be open before it can be read.
Is it possible to use spring batch reader in the following way?

As the exception implies, you have to call reader.open() before calling read() for the first time.
You should also call reader.close() when you are done.

As #GaryRussell wrote you can call open/close but - IMHO - use a SB component outside of SB domain is not a good approach because you couple your classes with SB classes too tight.
For me a better and more clear mode to operate is to use a CSV parsing library as BeanIO as main component and reuse it in your Handler as well as with BeanIOFlatFileItemReader as reader.

You have to implement ItemStream and override open, close and update method as below-
#Component
public class Handler implements ItemStream {
#Autowired
private FlatFileItemReader<Report> reader;
public File handleFile() {
try {
Report report = reader.read();
} catch (Exception e) {
e.printStackTrace();
}
return input;
}
#Override
public void open(ExecutionContext executionContext) {
reader.open(executionContext);
}
#Override
public void update(ExecutionContext executionContext) {
reader.update(executionContext);
}
#Override
public void close() {
reader.close();
}
}

Related

#Autowired annotation is not working in spring standalone application

I'm new to spring , and I'm trying to use #Autowired annotation in my standalone app, but I couldn't make it.
Here is my main class
MainDemo.java
public class MainDemo {
public static void main(String[] args) {
BeanFactory sf= new XmlBeanFactory(new FileSystemResource("beans.xml"));
SpringIntro a= (SpringIntro)sf.getBean("act");
System.out.println(a.getResults());
}
SpringIntro.java
#Service("act")
public class SpringIntro {
#Autowired
AdminInterface adminDAO;
public String getResults(){
System.out.println("in spring intro");
for( AdminBean ab:adminDAO.getAdminData() ){
System.out.println(ab.getAdministratiorName());
}
return "sree";
}
}
Admininterface.java
public interface AdminInterface {
List<AdminBean> getAdminData();
}
AdminDao.java
public class AdminDao implements AdminInterface{
#Autowired
public JdbcTemplate jdbcTemplate;
#Override
public List<AdminBean> getAdminData() {
// TODO Auto-generated method stub
System.out.println("admin dao autowired is working "+jdbcTemplate);
String sql = "select * from administrator";
List<AdminBean> resultList = jdbcTemplate.query(sql,
new AdminMapping());
return resultList;
}
}
Beans.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/dbschool" />
<property name="username" value="root" />
<property name="password" value="spinsci" />
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
when I run app through main method i'm getting null pointer, If add beans for adminDao in beans.xml file i'm getting the result, but If I use #Autowired I'm having problems. Can any one help me? thanks in advance.
You using XmlBeanFactory, but XmlBeanFactory doesn't implements BeanPostProcessor and does not postprocess annotations: then it doesn't use AutowiredAnnotationBeanPostProcessor. That might cause your null pointer exception.
I suggest you use ApplicationContext instead.

How to set the Transaction isolationlevel using Spring with MyBatis

I like to set the Isolationlevel by my self, using the transactionmanager from the Spring Framework combined with myBatis. I was trying a lot of tutorial, but nothing worked.
My application is build as MVC Pattern, that means i have views, models, interfaces used for the dependency-injection from mybatis and a controller class.
I hope someone can give me advice i am new in mybatis and spring. The whole application is running very well but I like to take over controll over the isolationlevels.
This is the spring-configuration.xml file
<!--<mybatis-spring:scan base-package="de.hrw.model.**"/> -->
<mybatis-spring:scan base-package="de.hrw.*" />
<context:component-scan base-package="de.hrw.*" />
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/carrental">
</property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="autoCommit" value="false"></property>
<property name="registerMbeans" value="true"></property>
<property name="transactionIsolation"
value="TRANSACTION_SERIALIZABLE">
</property>
</bean>
<bean id="sqlSessionFactoryBean"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml">
</property>
</bean>
<bean id="carController" class="de.hrw.controller.CarController">
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="carSearchView" class="de.hrw.view.CarSearchView">
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
I am using the dependecy-injection of mybatis to get data from and to the database
example of an iterface
package de.hrw.mgmtDAO;
import java.util.List;
import de.hrw.model.CarModel;
public interface ICarMgmt {
public CarModel selectCarById(final int carId);
public List<CarModel> selectAllCars();
}
this is the main-class where i include a view (frame)
public class Carrental_main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context =
new ClassPathXmlApplicationContext("spring-config.xml");
CarController carController = (CarController) context.getBean("carController");
carController.openSearchView();
carController.getCarSearchView().setVisible(true);
}
}
this is the controller. Here i try to set the isolation level to SERIALIZABLE but it is always set to default (-1)
#Transactional(propagation=Propagation.REQUIRES_NEW , isolation = Isolation.SERIALIZABLE)
public class CarController {
#Autowired
private ICarMgmt carMgmt;
private CarSearchView carSearchView;
private ApplicationContext applicationContext;
#Autowired
private PlatformTransactionManager transactionManager;
private TransactionStatus transactionStatus;
private TransactionDefinition defaultTransactionDefinition;
private DataSource dataSource;
public void openSearchView() {
this.setApplicationContext();
this.setDefaultTransactionDefinition();
this.setTransactionStatus();
this.carSearchView = (CarSearchView) applicationContext
.getBean("carSearchView");
try {
List<CarModel> carList = carMgmt.selectAllCars();
// this.carSearchView.setResultList(carList);
this.carSearchView.setLabelList(carList);
this.carSearchView.createTextFieldList();
this.carSearchView.createLabelFieldList();
transactionManager.commit(transactionStatus);
} catch (DataAccessException e) {
System.out.println("Error in creating record, rolling back");
transactionManager.rollback(transactionStatus);
throw e;
}
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void setDefaultTransactionDefinition() {
this.defaultTransactionDefinition = new DefaultTransactionDefinition();
}
public void setApplicationContext() {
applicationContext = new ClassPathXmlApplicationContext(
"spring-config.xml");
}
public void setTransactionManager(
PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void setTransactionStatus() {
this.transactionStatus = transactionManager.getTransaction(defaultTransactionDefinition);
}
I've finally found a solution. I changed the TransactionDefinition object in the controller to DefaultTransactionDefinition object
private DefaultTransactionDefinition defaultTransactionDefinition;
former it was
private TransactionDefinition defaultTransactionDefinition;
but the TransactionDefinition doesn't provide any setting methods. I was wondering, because in the documentation I found such methods to set the isolationlevel, but this methods are just provided by the DefaultTransactionDefinition. After I've found this failure i added the the following to lines of codes and it finally works
defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
defaultTransactionDefinition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_REPEATABLE_READ);
Thx, for all your advises. If someone knows a really good tutorial for MyBatis + Spring and the transaction manager please post a link :D
You can apply transaction as shown below in mapper interface(though it is recommended to apply transaction annotation for class, however in mybatis, transaction defined in interface will be applied to proxy class)
import java.util.List;
import de.hrw.model.CarModel;
#Transactional
public interface ICarMgmt {
#Transactional(isolation = Isolation.SERIALIZABLE)
public CarModel selectCarById(final int carId);
public List<CarModel> selectAllCars();
}

How to annotate Jersey POJO when Impl is remote?

I have 2 JVM's.
JettyJVM
Runs http requests and has an interface CarFacade that is backed using RmiProxyFactoryBean to the CarFacadeImpl running in the CoreJVM
<bean class="org.springframework.remoting.rmi.RmiProxyFactoryBeanFactory">
<property name="serviceInterface" value="org.foo.CarFacade"/>
<property name="serviceUrl" value="rmi://#{HOST}:1099/CarFacade"/>
</bean>
CoreJVM
Runs core business logic in a spring container and has CarFacadeImpl
<bean id="carFacade" class="org.foo.impl.CarFacadeImpl"></bean>
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="service" ref="carFacade"></property>
<property name="serviceInterface" value="org.foo.CarFacade"></property>
<property name="serviceName" value="CarFacade"></property>
<property name="replaceExistingBinding" value="true"></property>
<property name="registryPort" value="1099"></property>
</bean>
This setup works currently for flex/blazds and my services are exposed nicely.
Is there any way I can also expose this via Jersey?
I tried with the annotations on the Impl (preferred) but the component scan doesn't find the annotations (obviously as the interface doesn't have them)
So I tried with the annotations on the Interface but jersey says it can't instantiate the interface.
// CarFacadeImpl.java - when I had the annotations on the class in the CoreJVM
#Path("car")
public class CarFacadeImpl implements CarFacade {
#GET
public String getName() {
return "CarFacade";
}
}
// CarFacade.java - When I had the annotations on the interface in JettyJVM
#Path("car")
public class CarFacade {
#GET
String getName();
}
I would really like to not have to write an additional layer just to expose via rest.
I have tried the examples from here http://www.webappsolution.com/wordpress/2012/03/23/one-java-service-pojo-for-amfxmljson-with-spring-blazeds-jersey-jax-rs/ and they work without the RMI call in between.
I found an answer, at least for Jersey 2.16. It does require the annotations to be on the interface, but this is far better than creating a whole new layer
Override the default path scanning registration and register using something similar to this:
// Jersey ResourceConfig
final ResourceConfig rc = new ResourceConfig();
// Get my Spring context
final ApplicationContext context = new ClassPathXmlApplicationContext("clientContext.xml");
// Use Springs class path scanner to find #Path annotated classes
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false) {
#Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
return beanDefinition.getMetadata().isIndependent();
}
};
scanner.addIncludeFilter(new AnnotationTypeFilter(Path.class));
// For each class found in package (and sub packages)
for (BeanDefinition bd : scanner.findCandidateComponents("example")) {
try {
// Get the class
Class clazz = HttpServer.class.getClassLoader().loadClass(bd.getBeanClassName());
// Get the proxy
Object bean = context.getBean(clazz);
if (bean != null) {
// Register the proxy with the interface
rc.register(bean, clazz);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

Exception handling for Spring 3.2 "#Scheduled" annotation

How to customize the exception handling for #Scheduled annotation from spring ?
I have Cron jobs which will be triggered in the server (Tomcat 6) and when any exceptions occur I need to do some handling.
Spring version 3.2
Tomcat Server 6
If you want to use Java Config you will need to create configuration implementing SchedulingConfigurer
#EnableScheduling
#Configuration
class SchedulingConfiguration implements SchedulingConfigurer {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final ThreadPoolTaskScheduler taskScheduler;
SchedulingConfiguration() {
taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setErrorHandler(t -> logger.error("Exception in #Scheduled task. ", t));
taskScheduler.setThreadNamePrefix("#scheduled-");
taskScheduler.initialize();
}
#Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskScheduler);
}
}
You can modify error handler for your needs. Here I only log a message.
Don't forget to call taskScheduler.initialize();. Without it you'll get:
java.lang.IllegalStateException: ThreadPoolTaskScheduler not initialized
You could implement and register an ErrorHandler for the ThreadPoolTaskScheduler that is used for your scheduling annotations.
<task:annotation-driven scheduler="yourThreadPoolTaskScheduler" />
<bean id="yourThreadPoolTaskScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
<property name="poolSize" value="5" />
<property name="errorHandler" ref="yourScheduledTaskErrorHandler" />
</bean>
<bean id="yourScheduledTaskErrorHandler"
class="com.example.YourScheduledTaskErrorHandler"/>
Why not wrap your business logic and do a simple try catch in your #schedule method. Then you can log or take whatever action is necessary for failure cases.
#Scheduled(cron = "${schedulerRate}")
public void scheduledJob() {
try {
businessLogicService.doBusinessLogic();
} catch (Exception e) {
log.error(e);
}
}

JMS Unable to consume messages from Oracle queue using spring/jms

I have followed the spring documentation and setup a Spring JMS listener. Yet, even if I add a message to the queue, my code is not detecting this. My spring config is as follows:
<bean id="dataSourceListener" class="oracle.jdbc.pool.OracleDataSource">
<property name="URL" value="xxx"/>
<property name="user" value="xxx"/>
<property name="password" value="xxx"/>
</bean>
<bean id="jmsConnectionFactory" class="OracleAqFactoryBean">
<property name="dataSource" ref="dataSourceListener" />
</bean>
<jms:listener-container connection-factory="jmsConnectionFactory" acknowledge="transacted" concurrency="1-5">
<jms:listener destination="queuename" ref="myMessageListener"/>
</jms:listener-container>
<bean id="myMessageListener" class="Listener"/>
My Java is as follows:
My custom listener:
class Listener implements MessageListener {
#Override
void onMessage(Message message) {
// code to handle message is here
}
}
And my OracleAqFactoryBean:
public class OracleAqFactoryBean implements FactoryBean {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public Object getObject() throws Exception {
return AQjmsFactory.getConnectionFactory( dataSource );
}
#Override
public Class<?> getObjectType() {
return ConnectionFactory.class;
}
#Override
public boolean isSingleton() {
return true;
}
}
[EDIT: THE ABOVE SETUP IS NOW WORKING SUCCESSFULLY]
I do not understand why you are wiring up a FactoryBean implementation to the Spring DMLC destination property. This is clearly not correct because the setDestinationmethod only accepts a javax.jms.Destination type. You've wired up the connectionFactory and the messageListener. That's all that's needed to begin consuming messages. If you remove the testmq ref that you have wired to the destination property, then messages should be successfully consumed.

Resources