Data is not written into the XML file from mongodb using Spring Batch, Why? - spring

I am developing Spring Batch MongoDB to XML example. I was successfully developed the application, but I dont see data is getting written into the XML file. Could you please guide me what is the issue ? I dont see any working example yet on the web.
job-report.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd">
<!-- Actual Job -->
<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="mongodbItemReader" writer="xmlItemWriter" commit-interval="1">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="mongodbItemReader" class="org.springframework.batch.item.data.MongoItemReader">
<property name="template" ref="mongoTemplate" />
<property name="collection" value="report" />
<property name="targetType" value="com.mkyong.model.Report" />
<property name="query" value="{'_id':{$gt:0} }" />
<property name="sort">
<util:map>
<entry key="id" value="#{T(org.springframework.data.domain.Sort.Direction).ASC}" />
</util:map>
</property>
</bean>
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="classpath:xml/report.xml" />
<property name="marshaller" ref="reportUnMarshaller" />
<property name="rootTagName" value="record" />
</bean>
<bean id="reportUnMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<value>com.mkyong.model.Report</value>
</property>
</bean>
</beans>
App.java
public class App {
public static void main(String[] args) {
String[] springConfig = { "database.xml", "context.xml", "job-report.xml" };
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("reportJob");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
Logs from console:
14:58:52.487 [main] DEBUG o.s.b.c.s.c.StepContextRepeatCallback - Preparing chunk execution for StepContext: org.springframework.batch.core.scope.context.StepContext#aa594b
14:58:52.487 [main] DEBUG o.s.b.c.s.c.StepContextRepeatCallback - Chunk execution starting: queue size=0
14:58:52.487 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.487 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Starting repeat context.
14:58:52.487 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Repeat operation about to start at count=1
14:58:52.488 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - find using query: { "_id" : { "$gt" : 0}} fields: null for class: class com.mkyong.model.Report in collection: report
14:58:52.488 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[yourdb]
14:58:52.488 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Registering Spring transaction synchronization for MongoDB instance yourdb.
14:58:52.488 [main] DEBUG org.mongodb.driver.protocol.query - Sending query of namespace yourdb.report on connection [connectionId{localValue:3, serverValue:53}] to server 127.0.0.1:27017
14:58:52.489 [main] DEBUG org.mongodb.driver.protocol.query - Query completed
14:58:52.489 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Repeat is complete according to policy and result value.
14:58:52.489 [main] DEBUG o.s.b.c.s.item.ChunkOrientedTasklet - Inputs not busy, ended: true
14:58:52.489 [main] DEBUG o.s.b.core.step.tasklet.TaskletStep - Applying contribution: [StepContribution: read=0, written=0, filtered=0, readSkips=0, writeSkips=0, processSkips=0, exitStatus=EXECUTING]
14:58:52.489 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Participating in existing transaction
14:58:52.490 [main] DEBUG o.s.b.core.step.tasklet.TaskletStep - Saving step execution before commit: StepExecution: id=1, version=5, name=step1, status=STARTED, exitStatus=EXECUTING, readCount=4, filterCount=0, writeCount=4 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=5, rollbackCount=0, exitDescription=
14:58:52.490 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Participating in existing transaction
14:58:52.491 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.491 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#a8ee09]
14:58:52.492 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Repeat is complete according to policy and result value.
14:58:52.492 [main] DEBUG o.s.batch.core.step.AbstractStep - Step execution success: id=1
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#5b3037]
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.494 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.494 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#baa89c]
14:58:52.495 [main] DEBUG o.s.batch.core.step.AbstractStep - Step execution complete: StepExecution: id=1, version=7, name=step1, status=COMPLETED, exitStatus=COMPLETED, readCount=4, filterCount=0, writeCount=4 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=5, rollbackCount=0
14:58:52.495 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.496 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.496 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#1f2ebae]
14:58:52.496 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Completed state=reportJob.step1 with status=COMPLETED
14:58:52.496 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Handling state=reportJob.end1
14:58:52.496 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Completed state=reportJob.end1 with status=COMPLETED
14:58:52.497 [main] DEBUG o.s.batch.core.job.AbstractJob - Job execution complete: JobExecution: id=0, version=1, startTime=Tue Jan 10 14:58:52 IST 2017, endTime=null, lastUpdated=Tue Jan 10 14:58:52 IST 2017, status=COMPLETED, exitStatus=exitCode=COMPLETED;exitDescription=, job=[JobInstance: id=0, version=0, Job=[reportJob]], jobParameters=[{}]
14:58:52.497 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.501 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.501 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#498b0]
14:58:52.501 [main] INFO o.s.b.c.l.support.SimpleJobLauncher - Job: [FlowJob: [name=reportJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
Exit Status : COMPLETED
Done
In this example, I do need to manually create xml/report.xml into the classpath. Ideally it should be automatic. Right?

I got the solution to this problem from the link: Complex XML using Spring Batch; StaxEventItemWriter ; Jaxb2Marshaller. Also I should use
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="file:outputs/report.xml" />
<property name="encoding" value="ISO-8859-1" />
<property name="version" value="1.0" />
<property name="marshaller" ref="reportMarshaller" />
<property name="rootTagName" value="record" />
</bean>

Related

Spring integration chain error block process

I'm trying to handle errors using the int:poller, I defined an error-channel on the poller when an error occurs the ErrorHandler invoked, but it still executed in a loop and
block the principal process that handle the next correct message.
Here's my config any ideas?
<int:outbound-channel-adapter ref="cvsMessageHandler" method="handleMessage" channel="cvsInputChannel"/>
<int:poller max-messages-per-poll="1" id="defaultPoller" default="true" fixed-rate="5000"
error-channel="cvsErrorChannel">
<int:transactional transaction-manager="transactionManager" />
</int:poller>
<bean id="cvsMessageHandler" class="com.cvs.ws.wrapper.MessageHandler">
</bean>
<int:channel id="cvsErrorChannel"/>
<bean id="cvsErrorMessageHandler" class="com.eplatform.transverse.cvs.ws.service.ErrorHandler">
<property name="eventService" ref="cvsEventService"/>
<property name="eventFactory" ref="cvsEventFactory"/>
</bean>
<int:chain input-channel="cvsErrorChannel">
<int:service-activator ref="cvsErrorMessageHandler" method="handleMessage"/>
</int:chain>
<stream:stderr-channel-adapter channel="errorChannel" append-newline="true"/>
<int:channel id="csdbInputChannel">
<int:queue message-store="messageStore"/>
</int:channel>
<bean id="csdbService" class="com.renault.eplatform.transverse.datapower.csdb.ws.service.CsdbService">
<property name="channel" ref="csdbInputChannel"/>
</bean>
<bean id="csdbWrapper" class="com.renault.eplatform.transverse.datapower.csdb.ws.wrapper.CsdbWrapper">
<property name="httpClient">
<bean class="com.fullsix.framework.net.http.HttpClientFactoryBean"/>
</property>
<property name="url" value="${www}"/>
<property name="enumCountry" ref="currentCountry"/>
<property name="datapowerLoggingService" ref="dxxx"/>
<property name="password" value="${dwwww}"/>
<property name="socketTimeout" value="20000"/>
<property name="timeout" value="20000"/>
</bean>
201803-08 15:34:55,546 ERROR [ErrorHandler.java:28] - Try to fix data
on tables DATAPOWER_CSDB_MESSAGE_GROUP and DATAPOWER_CSDB_MESSAGE
201803-08 15:34:55,547 DEBUG
[AbstractReplyProducingMessageHandler.java:107]
- handler 'ServiceActivator for [org.springframework.integration.handler.MethodInvokingMessageProcessor#4cc7014c]'
produced no reply for request Message:
[Payload=java.lang.NullPointerException][Headers={timestamp=1520519695543,
id=b71d066b-a8e5-4fa3-8b87-a8c1d9e57587}]
201803-08 15:34:55,547
DEBUG [AbstractMessageChannel.java:237] - postSend (sent=true) on
channel 'csdbErrorChannel', message:
[Payload=java.lang.NullPointerException][Headers={timestamp=1520519695543,
id=b71d066b-a8e5-4fa3-8b87-a8c1d9e57587}]
201803-08 15:35:00,515
DEBUG [AbstractPlatformTransactionManager.java:365] - Creating new
transaction with name
201803-08 15:35:00,516 DEBUG
[SessionImpl.java:265] - opened session at timestamp: 15205197005
201803-08 15:35:00,517 DEBUG [HibernateTransactionManager.java:493] -
Opened new Session [org.hibernate.impl.SessionImpl#7e350225] for
Hibernate transaction
201803-08 15:35:00,517 DEBUG
[HibernateTransactionManager.java:504] - Preparing JDBC Connection of
Hibernate Session [org.hibernate.impl.SessionImpl#7e350225]
201803-08
15:35:00,517 DEBUG [JDBCTransaction.java:78] - begin
201803-08
15:35:00,518 DEBUG [ConnectionManager.java:444] - opening JDBC
connection
201803-08 15:35:00,518 DEBUG [JDBCTransaction.java:83] -
current autocommit status: true
201803-08 15:35:00,519 DEBUG
[JDBCTransaction.java:86] - disabling autocommit
201803-08
15:35:00,519 DEBUG [HibernateTransactionManager.java:569] - Exposing
Hibernate transaction as JDBC transaction
[jdbc:oracle:thin:#//active-db-valid:1521/rsite, UserName=RSITE_ES,
Oracle JDBC driver]
201803-08 15:35:00,520 DEBUG
[JdbcTemplate.java:635] - Executing prepared SQL query
201803-08
15:35:00,520 DEBUG [JdbcTemplate.java:570] - Executing prepared SQL
statement [SELECT COUNT(MESSAGE_ID) from DATAPOWER_CSDB_MESSAGE_GROUP
where GROUP_KEY=? AND REGION=?]
201803-08 15:35:00,523 DEBUG
[JdbcTemplate.java:635] - Executing prepared SQL query
201803-08
15:35:00,523 DEBUG [JdbcTemplate.java:570] - Executing prepared SQL
statement [SELECT MESSAGE_ID, CREATED_DATE from
DATAPOWER_CSDB_MESSAGE_GROUP where GROUP_KEY=? and REGION=? order by
UPDATED_DATE]
201803-08 15:35:00,525 DEBUG [JdbcTemplate.java:635] -
Executing prepared SQL query
201803-08 15:35:00,526 DEBUG
[JdbcTemplate.java:570] - Executing prepared SQL statement [SELECT
MESSAGE_ID, CREATED_DATE, MESSAGE_BYTES from DATAPOWER_CSDB_MESSAGE
where MESSAGE_ID=? and REGION=?]
201803-08 15:35:00,528 DEBUG
[DefaultLobHandler.java:117] - Returning BLOB as bytes
201803-08
15:35:00,529 DEBUG [AbstractPlatformTransactionManager.java:843] -
Initiating transaction rollback
201803-08 15:35:00,529 DEBUG
[HibernateTransactionManager.java:672] - Rolling back Hibernate
transaction on Session [org.hibernate.impl.SessionImpl#7e350225]
201803-08 15:35:00,530 DEBUG [JDBCTransaction.java:182] - rollback
201803-08 15:35:00,531 DEBUG [JDBCTransaction.java:223] - re-enabling
autocommit
201803-08 15:35:00,531 DEBUG [JDBCTransaction.java:193] -
rolled back JDBC Connection
201803-08 15:35:00,531 DEBUG
[ConnectionManager.java:325] - transaction completed on session with
on_close connection release mode; be sure to close the session to
release JDBC resources!
201803-08 15:35:00,532 DEBUG
[HibernateTransactionManager.java:734] - Closing Hibernate Session
[org.hibernate.impl.SessionImpl#7e350225] after transaction
201803-08
15:35:00,532 DEBUG [SessionFactoryUtils.java:800] - Closing Hibernate
Session
201803-08 15:35:00,533 DEBUG [ConnectionManager.java:464] -
releasing JDBC connection [ (open PreparedStatements: 0, globally: 0)
(open ResultSets: 0, globally: 0)]
201803-08 15:35:00,533 DEBUG
[ConnectionManager.java:325] - transaction completed on session with
on_close connection release mode; be sure to close the session to
release JDBC resources!
201803-08 15:35:00,534 DEBUG
[AbstractMessageChannel.java:224] - preSend on channel
'csdbErrorChannel', message:
[Payload=java.lang.NullPointerException][Headers={timestamp=1520519700534,
id=fe974a6c-2351-4b95-ac6f-b98a0c02a7b3}]
201803-08 15:35:00,534
DEBUG [AbstractMessageHandler.java:67] -
org.springframework.integration.handler.MessageHandlerChain#0 received
message:
[Payload=java.lang.NullPointerException][Headers={timestamp=1520519700534,
id=fe974a6c-2351-4b95-ac6f-b98a0c02a7b3}]
201803-08 15:35:00,535
DEBUG [AbstractMessageHandler.java:67] - ServiceActivator for
[org.springframework.integration.handler.MethodInvokingMessageProcessor#4cc7014c]
received message:
[Payload=java.lang.NullPointerException][Headers={timestamp=1520519700534,
id=fe974a6c-2351-4b95-ac6f-b98a0c02a7b3}]
201803-08 15:35:00,535
INFO [ErrorHandler.java:25] - Error message handled
201803-08
15:35:00,536 ERROR [ErrorHandler.java:27] -
java.lang.NullPointerException
201803-08 15:35:00,536 ERROR
[ErrorHandler.java:28] - Try to fix data on tables
DATAPOWER_CSDB_MESSAGE_GROUP and DATAPOWER_CSDB_MESSAGE*
*

org.springframework.dao.DataAccessResourceFailureException: Unable to write to file resource: [class path resource [report.xml]]; Spring Batch

I am developing Spring Batch - MongoDB to XML example. I have successfully developed the code, when I run the my main program. I see the following eror comes. I am not sure what is going wrong. I followed many links, but I dont see its not working fine.
org.springframework.dao.DataAccessResourceFailureException: Unable to write to file resource: [class path resource [report.xml]]; nested exception is java.io.FileNotFoundException: class path resource [report.xml] cannot be resolved to URL because it does not exist
at org.springframework.batch.item.xml.StaxEventItemWriter.open(StaxEventItemWriter.java:436) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.item.xml.StaxEventItemWriter.open(StaxEventItemWriter.java:400) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.item.support.CompositeItemStream.open(CompositeItemStream.java:96) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep.open(TaskletStep.java:310) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:197) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:169) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:134) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at com.mkyong.App.main(App.java:21) [classes/:na]
Caused by: java.io.FileNotFoundException: class path resource [report.xml] cannot be resolved to URL because it does not exist
at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:187) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:48) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.batch.item.xml.StaxEventItemWriter.open(StaxEventItemWriter.java:427) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
... 15 common frames omitted
13:21:05.358 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
13:21:05.367 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
13:21:05.368 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#5b202a3a]
13:21:05.368 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
13:21:05.375 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
13:21:05.375 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#5669c5fb]
13:21:05.379 [main] ERROR o.s.batch.core.step.AbstractStep - Exception while closing step execution resources in step step1 in job reportJob
java.lang.NullPointerException: null
at org.springframework.batch.item.xml.StaxEventItemWriter.close(StaxEventItemWriter.java:659) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.item.support.CompositeItemStream.close(CompositeItemStream.java:85) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep.close(TaskletStep.java:305) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:271) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:169) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:134) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at com.mkyong.App.main(App.java:21) [classes/:na]
13:21:05.381 [main] DEBUG o.s.batch.core.step.AbstractStep - Step execution complete: StepExecution: id=1, version=2, name=step1, status=FAILED, exitStatus=FAILED, readCount=0, filterCount=0, writeCount=0 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=0, rollbackCount=0
13:21:05.381 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
13:21:05.383 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
13:21:05.383 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#178213b]
13:21:05.383 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Completed state=reportJob.step1 with status=FAILED
13:21:05.385 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Handling state=reportJob.fail0
13:21:05.385 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Completed state=reportJob.fail0 with status=FAILED
13:21:05.388 [main] DEBUG o.s.batch.core.job.AbstractJob - Job execution complete: JobExecution: id=0, version=1, startTime=Sun Jan 08 13:21:05 IST 2017, endTime=null, lastUpdated=Sun Jan 08 13:21:05 IST 2017, status=FAILED, exitStatus=exitCode=FAILED;exitDescription=, job=[JobInstance: id=0, version=0, Job=[reportJob]], jobParameters=[{}]
13:21:05.388 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
13:21:05.397 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
13:21:05.397 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#2d36e77e]
13:21:05.397 [main] INFO o.s.b.c.l.support.SimpleJobLauncher - Job: [FlowJob: [name=reportJob]] completed with the following parameters: [{}] and the following status: [FAILED]
Exit Status : FAILED
Done
job-report.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch" xmlns:task="http://www.springframework.org/schema/task"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- connect to mongodb -->
<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="yourdb" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="mongodbItemReader" writer="xmlItemWriter" commit-interval="1">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="mongodbItemReader" class="org.springframework.batch.item.data.MongoItemReader">
<property name="template" ref="mongoTemplate" />
<property name="collection" value="report" />
<property name="targetType" value="com.mkyong.Report" />
<property name="query" value="" />
<property name="sort">
<util:map id="sort">
<entry key="id" value="" />
</util:map>
</property>
</bean>
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<!-- <property name="resource" value="classpath:xml/report.xml" /> -->
<property name="resource" value="report.xml" />
<property name="marshaller" ref="reportMarshaller" />
<property name="rootTagName" value="record" />
</bean>
<!-- ==== Solution-1 ==== -->
<bean id="reportMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<value>com.mkyong.Report</value>
</property>
</bean>
<!-- ==== Solution-2 ==== -->
<!-- <bean id="reportMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="aliases">
<util:map id="aliases">
<entry key="record" value="com.mkyong.Report" />
</util:map>
</property>
<property name="converters">
<array>
<ref bean="reportConverter" />
</array>
</property>
</bean> -->
<bean id="reportConverter" class="com.mkyong.ReportConverter" />
</beans>
Report.java
#XmlRootElement(name = "record")
public class Report {
private int id;
private Date date;
private long impression;
private int clicks;
private BigDecimal earning;
#XmlAttribute(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#XmlElement(name = "impression")
public long getImpression() {
return impression;
}
public void setImpression(long impression) {
this.impression = impression;
}
#XmlElement(name = "clicks")
public int getClicks() {
return clicks;
}
public void setClicks(int clicks) {
this.clicks = clicks;
}
#XmlElement(name = "earning")
public BigDecimal getEarning() {
return earning;
}
public void setEarning(BigDecimal earning) {
this.earning = earning;
}
}
App.java
public class App {
public static void main(String[] args) {
String[] springConfig = { "database.xml", "context.xml", "job-report.xml" };
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("reportJob");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
Looking forward to get the response.
It looks like the resource value for xmlItemWriter is incorrect. You can provide a classpath or file/URL.
See "Table 8.1. Resource strings" at this link http://docs.spring.io/spring/docs/current/spring-framework-reference/html/resources.html#resources-resourceloader

XAER_OUTSIDE Exception - Spring 4.0.3 - Hibernate 4.1.12 - JTA - Websphere 8 - DB2

EDIT - I have checked this combinations so it seems there's something wrong with Hibernate 4:
Spring 4 + JPA + Hibernate 4 -> Exception
Spring 4 + Hibernate 4 -> Exception
Spring 4 + JPA + Hibernate 3 -> OK
Spring 4 + Hibernate 3 -> OK
Spring 3 + JPA - Hibernate 4 -> Exception
Spring 3 + JPA - Hibernate 3 -> OK
Spring 3 + Hibernate 3 -> OK
I have recently upgraded an application from Spring 3.2/Hibernate 3.6.10 to Spring 4.0.3 + Hibernate 4.1.12. My environment is IBM Websphere 8.0.0.7 and DB2 and the application is configured to use a XA Datasource.
The point is that at the first database call (subsequent calls are always OK) I am getting this error:
#Transactional(readOnly = true)
public Foo loadFoo(int id) {
LOG.debug("load {}", id);
FooEntity fe = fooDAO.findOne(id);
...
}
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'fooRestController'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'globalControllerAdvice'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=false
org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource DEBUG - Adding transactional method 'findOne' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=true
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Opening JPA EntityManager
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - Skipping JTA sync registration due to auto join checking
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - successfully registered Synchronization
org.hibernate.ejb.AbstractEntityManagerImpl DEBUG - Looking for a JTA transaction to join
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Registering transaction synchronization for JPA EntityManager
org.hibernate.loader.Loader DEBUG - Loading entity: [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtaining JDBC connection
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtained JDBC connection
DSRA0304E: XAException occurred. XAException contents and details are: "".
DSRA0302E: XAException occurred. Error code is: XAER_OUTSIDE (-9). Exception is: XAER_OUTSIDE
J2CA0027E: An exception occurred while invoking start on an XA Resource Adapter from DataSource jdbc/LOCDBD1_XA, within transaction ID {XidImpl: formatId(57415344), gtrid_length(36), bqual_length(54),
data(0000014517a4c063000000015e7f81b4c90865e6b88e167905e5d2ed67f44ed6409cba5c0000014517a4c063000000015e7f81b4c90865e6b88e167905e5d2ed67f44ed6409cba5c000000010000000000000000000000000001)} : com.ibm.db2.jcc.c.zh: XAER_OUTSIDE
Caused by: javax.transaction.RollbackException: XAResource working outside transaction
at com.ibm.tx.jta.impl.RegisteredResources.startRes(RegisteredResources.java:1019)
at com.ibm.ws.tx.jta.RegisteredResources.enlistResource(RegisteredResources.java:1113)
at com.ibm.ws.tx.jta.TransactionImpl.enlistResource(TransactionImpl.java:2214)
at com.ibm.tx.jta.impl.EmbeddableTranManagerSet.enlist(EmbeddableTranManagerSet.java:150)
at com.ibm.ejs.j2c.XATransactionWrapper.enlist(XATransactionWrapper.java:727)
... 140 more
Caused by: com.ibm.db2.jcc.c.zh: XAER_OUTSIDE
at com.ibm.db2.jcc.b.bc.a(bc.java:1651)
at com.ibm.db2.jcc.b.bc.start(bc.java:1530)
at com.ibm.ws.rsadapter.spi.WSRdbXaResourceImpl.start(WSRdbXaResourceImpl.java:1525)
at com.ibm.ejs.j2c.XATransactionWrapper.start(XATransactionWrapper.java:1475)
at com.ibm.ws.Transaction.JTA.JTAResourceBase.start(JTAResourceBase.java:153)
at com.ibm.tx.jta.impl.RegisteredResources.startRes(RegisteredResources.java:1002)
... 144 more
This is the log trace of the second and successful call :
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'fooRestController'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'globalControllerAdvice'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=false
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=true
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Opening JPA EntityManager
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - Skipping JTA sync registration due to auto join checking
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - successfully registered Synchronization
org.hibernate.ejb.AbstractEntityManagerImpl DEBUG - Looking for a JTA transaction to join
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Registering transaction synchronization for JPA EntityManager
org.hibernate.loader.Loader DEBUG - Loading entity: [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtaining JDBC connection
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtained JDBC connection
org.hibernate.loader.Loader DEBUG - Result set row: 0
org.hibernate.loader.Loader DEBUG - Result row: EntityKey[com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.internal.TwoPhaseLoad DEBUG - Resolving associations for [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.internal.TwoPhaseLoad DEBUG - Done materializing entity [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Releasing JDBC connection
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Released JDBC connection
org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler DEBUG - HHH000163: Logical connection releasing its physical connection
org.hibernate.loader.Loader DEBUG - Done entity load
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Returned from WebSphere UOW action: type=1, join=true
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Closing JPA EntityManager
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Aggressively releasing JDBC connection
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Returned from WebSphere UOW action: type=1, join=false
The relevant part of my cfg is:
<bean id="mainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="mainPersistenceUnit"/>
<property name="jtaDataSource" ref="mainDataSource"/>
<property name="packagesToScan" ref="packages-mainEntityManagerFactory"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform</prop>
<prop key="hibernate.current_session_context_class">jta</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory</prop>
</props>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<tx:annotation-driven order="0" />
<bean name="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager">
<property name="allowCustomIsolationLevels" value="true" />
</bean>
Any idea why it fails the first time it's called?
The problem solved by itself upgrading to Spring 4.1.6 and Hibernate 4.2.19. I guess it was a Hibernate-related issue.

Using Spring Expression Language in Camel Marshal and Unmarshal Tags

I've tried searching for this information but haven't been able to find it. I am relatively new to Camel (and Java) so forgive me if I have overlooked something simple. Please keep in mind this is just sample code so it may be a bit brittle.
The real issue can be found in the Java output (all the way at the bottom) at the following line:
org.quartz.JobExecutionException: java.lang.ClassNotFoundException: #{${header.ProtobufType}} [See nested exception: java.lang.ClassNotFoundException: #{${header.ProtobufType}}]
I want to (at runtime) decide what instanceClass to use when marshaling or unmarshaling a message. I think using Spring Expression Language is the way to go but haven't been able to figure out the proper Google queries for what I am looking for. My Spring application context looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="toBean" class="To.ToBean" />
<bean id="fromBean" class="From.FromBean" />
<bean id="addTypeProcessor" class="Processor.AddTypeProcessor" />
<camel:errorHandler id="camelErrorHandler" type="NoErrorHandler" />
<camelContext id="camelContext" errorHandlerRef="camelErrorHandler" xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="quartz://myTimer?trigger.repeatCount=-1&trigger.repeatInterval=5000" />
<to uri="bean:fromBean" />
<process ref="addTypeProcessor" />
<marshal>
<protobuf instanceClass="#{${header.ProtobufType}}" />
</marshal>
<unmarshal>
<protobuf instanceClass="#{${header.ProtobufType}}" />
</unmarshal>
<to uri="bean:toBean" />
<process ref="addTypeProcessor" />
</route>
</camelContext>
</beans>
My AddTypeProcessor looks like this:
package Processor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
public class AddTypeProcessor implements Processor {
#Override
public void process(Exchange exchange) throws Exception {
String headerName = "ProtobufType";
String headerValue = (String) exchange.getIn().getHeader(headerName);
System.out.println(headerName + " was " + headerValue);
exchange.getIn().setHeader(headerName, exchange.getIn().getBody().getClass().getCanonicalName());
headerValue = (String) exchange.getIn().getHeader(headerName);
System.out.println(headerName + " is " + headerValue);
}
}
My output is the following:
0 [main] INFO org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#63c5ab93: startup date [Fri Jun 28 16:33:17 EDT 2013]; root of context hierarchy
46 [main] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
1081 [main] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7cb01f72: defining beans [toBean,fromBean,addTypeProcessor,camelErrorHandler,template,consumerTemplate,camelContext:beanPostProcessor,camelContext]; root of factory hierarchy
1285 [main] INFO org.apache.camel.spring.SpringCamelContext - Apache Camel 2.10.1 (CamelContext: camelContext) is starting
1356 [main] INFO org.apache.camel.management.ManagementStrategyFactory - JMX enabled.
1521 [main] INFO org.apache.camel.impl.converter.DefaultTypeConverter - Loaded 175 type converters
1633 [main] INFO org.quartz.simpl.SimpleThreadPool - Job execution threads will use class loader of thread: main
1645 [main] INFO org.quartz.core.SchedulerSignalerImpl - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
1645 [main] INFO org.quartz.core.QuartzScheduler - Quartz Scheduler v.1.8.5 created.
1646 [main] INFO org.quartz.simpl.RAMJobStore - RAMJobStore initialized.
1647 [main] INFO org.quartz.core.QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v1.8.5) 'DefaultQuartzScheduler-camelContext' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
1647 [main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler 'DefaultQuartzScheduler-camelContext' initialized from an externally provided properties instance.
1647 [main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler version: 1.8.5
1812 [main] INFO org.apache.camel.spring.SpringCamelContext - Route: route1 started and consuming from: Endpoint[quartz://myTimer?trigger.repeatCount=-1&trigger.repeatInterval=5000]
1812 [main] INFO org.apache.camel.management.DefaultManagementLifecycleStrategy - StatisticsLevel at All so enabling load performance statistics
1817 [main] INFO org.apache.camel.component.quartz.QuartzComponent - Starting Quartz scheduler: DefaultQuartzScheduler-camelContext
1817 [main] INFO org.quartz.core.QuartzScheduler - Scheduler DefaultQuartzScheduler-camelContext_$_NON_CLUSTERED started.
1819 [main] INFO org.apache.camel.spring.SpringCamelContext - Total 1 routes, of which 1 is started.
1822 [main] INFO org.apache.camel.spring.SpringCamelContext - Apache Camel 2.10.1 (CamelContext: camelContext) started in 0.535 seconds
ProtobufType was null
ProtobufType is WireFormatProtos.WireFormat.A
1848 [DefaultQuartzScheduler-camelContext_Worker-1] WARN org.apache.camel.util.ObjectHelper - Cannot find class: $header.ProtobufType
1849 [DefaultQuartzScheduler-camelContext_Worker-1] ERROR org.apache.camel.component.quartz.QuartzEndpoint - Error processing exchange. Exchange[Message: ]. Caused by: [org.quartz.JobExecutionException - java.lang.ClassNotFoundException: #{${header.ProtobufType}}]
1850 [DefaultQuartzScheduler-camelContext_Worker-1] INFO org.quartz.core.JobRunShell - Job DEFAULT.quartz-endpoint1 threw a JobExecutionException:
org.quartz.JobExecutionException: java.lang.ClassNotFoundException: #{${header.ProtobufType}} [See nested exception: java.lang.ClassNotFoundException: #{${header.ProtobufType}}]
at org.apache.camel.component.quartz.QuartzEndpoint.onJobExecute(QuartzEndpoint.java:117)
at org.apache.camel.component.quartz.CamelJob.execute(CamelJob.java:54)
at org.quartz.core.JobRunShell.run(JobRunShell.java:216)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
Caused by: java.lang.ClassNotFoundException: #{${header.ProtobufType}}
at org.apache.camel.impl.DefaultClassResolver.resolveMandatoryClass(DefaultClassResolver.java:52)
at org.apache.camel.dataformat.protobuf.ProtobufDataFormat.loadDefaultInstance(ProtobufDataFormat.java:79)
at org.apache.camel.dataformat.protobuf.ProtobufDataFormat.getInstance(ProtobufDataFormat.java:67)
at org.apache.camel.dataformat.protobuf.ProtobufDataFormat.unmarshal(ProtobufDataFormat.java:109)
at org.apache.camel.processor.UnmarshalProcessor.process(UnmarshalProcessor.java:57)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:73)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:91)
at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:45)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.processor.interceptor.DefaultChannel.process(DefaultChannel.java:303)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:117)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:45)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.processor.UnitOfWorkProcessor.processAsync(UnitOfWorkProcessor.java:150)
at org.apache.camel.processor.UnitOfWorkProcessor.process(UnitOfWorkProcessor.java:117)
at org.apache.camel.processor.RouteInflightRepositoryProcessor.processNext(RouteInflightRepositoryProcessor.java:48)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:73)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.loadbalancer.QueueLoadBalancer.process(QueueLoadBalancer.java:44)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:99)
at org.apache.camel.processor.loadbalancer.QueueLoadBalancer.process(QueueLoadBalancer.java:71)
at org.apache.camel.component.quartz.QuartzEndpoint.onJobExecute(QuartzEndpoint.java:113)
... 3 more
This is not possible.
Instead you can use a processor / bean, and then create the marshaller and unmarshaller in the java code, and invoke the marshal/unmarshal method. As this is java code, you can then have the dynamic behavior of defining the instance class from a camel message header.

junit test with jparepository not creating object in database

I am starting a project using Spring 3.2.1.RELEASE, Hibernate 4.1.9.FINAL as jpa provider, spring data 1.2.0.RELEASE for repository and bitronix 2.1.3 as transaction manager. I am new to all of these technologies so I'm sorry if I'm missing some huge point.
I am running a simple unit test to create a User object in a database:
#ContextConfiguration(locations={"classpath:tests-context.xml"})
#Transactional
#TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false)
#RunWith(SpringJUnit4ClassRunner.class)
public class UserTest extends AbstractTransactionalJUnit4SpringContextTests
{
#Autowired
protected UserMgmtService userService;
#Test
public void createUserTest()
{
User user = new User();
user.setFirstName("jonny");
user.setLastName("doe");
user.setUsername("user5");
user.setPasswordHash("1238");
user.setEmail("user5#domain.com");
System.out.println("Created user" + user);
User testUser = userService.saveUser(user);
System.out.println("Saved user" + testUser);
Assert.assertEquals("The user should be equal to saved user", user, testUser);
}
}
My test-context.xml used is as follows:
<context:annotation-config/>
<!-- Bitronix Transaction Manager embedded configuration -->
<bean id="btmConfig" factory-method="getConfiguration"
class="bitronix.tm.TransactionManagerServices">
</bean>
<!-- DataSource definition -->
<bean id="dataSource" class="bitronix.tm.resource.jdbc.PoolingDataSource"
init-method="init" destroy-method="close">
<property name="className" value="bitronix.tm.resource.jdbc.lrc.LrcXADataSource" />
<property name="uniqueName" value="jdbc/MySQL_Test_Repository" />
<property name="minPoolSize" value="0" />
<property name="maxPoolSize" value="5" />
<property name="allowLocalTransactions" value="true" />
<property name="driverProperties">
<props>
<prop key="driverClassName">com.mysql.jdbc.Driver</prop>
<prop key="url">jdbc:mysql://localhost:3306 MySQL_Test_Repository</prop>
<prop key="user">root</prop>
<prop key="password">123654</prop>
</props>
</property>
</bean>
<!-- create BTM transaction manager -->
<bean id="BitronixTransactionManager" factory-method="getTransactionManager"
class="bitronix.tm.TransactionManagerServices" depends-on="btmConfig,dataSource"
destroy-method="shutdown" />
<!-- Transaction manager -->
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"
depends-on="BitronixTransactionManager">
<property name="transactionManager" ref="BitronixTransactionManager" />
<property name="userTransaction" ref="BitronixTransactionManager" />
<property name="allowCustomIsolationLevels" value="true" />
</bean>
<!-- AOP configuration for transactions -->
<aop:config>
<aop:pointcut id="userServiceMethods"
expression="execution(* users.service.UserMgmtService.*(..))" />
<aop:advisor advice-ref="transactionAdvice"
pointcut-ref="userServiceMethods" />
</aop:config>
<!-- Transaction configuration -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- bean declaring the property map for the entity manager factory bean -->
<bean id="jpaPropertyMap" class="org.springframework.beans.factory.config.MapFactoryBean">
<property name="sourceMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<!-- show the sql code executed -->
<entry key="hibernate.show_sql" value="true"/>
<!-- format the shown sql code -->
<entry key="hibernate.format_sql" value="true"/>
<!-- enables hibernate to create db schemas from classes;
Possible values: validate | update | create | create-drop
with create-drop the schema will be created/dropped for each hibernate sesssion open/close-->
<entry key="hibernate.hbm2ddl.auto" value="update"/>
<!-- sets the hibernate classname for the TransactionManagerLookup;
hibernate wraps and hides the underlying transaction system and needs a reference
to the transaction manager used -->
<entry key="hibernate.transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory"/>
<entry key="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.BTMTransactionManagerLookup"/>
</map>
</property>
</bean>
<!-- bean declaring the entity manager factory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="ruleEditor.persistence"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaPropertyMap" ref="jpaPropertyMap"/>
</bean>
<!-- The location where Spring scans for interfaces implementing the JPARepository
and creates their implementation -->
<jpa:repositories base-package="users.repository" />
<!-- Persistence annotations for post processing -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- User service implementation bean -->
<bean id="userMgmtService" class="users.service.impl.UserMgmtServiceImpl"/>
</beans>
The Repository implementation is a standard JPARepository:
public interface UserRepository extends JpaRepository<User, Long>
{
User findByUsername(String username);
}
And the service implementation only makes calls to the repository:
#Service("userMgmtService")
public class UserMgmtServiceImpl implements UserMgmtService
{
#Autowired
private UserRepository userRepository;
#Override
public User saveUser(User user)
{
User savedUser = userRepository.save(user);
return savedUser;
}
The problem is that when I execute the test, it passes, but no user is created in the database. I thought it might be because of the Rollback behavior so I set the defaultRollback=false in the User test. Here is some information provided by the transaction framework when set to DEBUG that might be relevant:
Running UserTest
2013-02-12 13:01:12 INFO XmlBeanDefinitionReader:315 - Loading XML bean definitionsfrom class path resource [tests-context.xml]
2013-02-12 13:01:12 INFO GenericApplicationContext:510 - Refreshing org.springframework.context.support.GenericApplicationContext#7d95609: startup date [Tue Feb 12 13:01:12 CET 2013]; root of context hierarchy
2013-02-12 13:01:12 INFO GenericApplicationContext:1374 - Bean 'dataSource' of type [class bitronix.tm.resource.jdbc.PoolingDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:12 INFO GenericApplicationContext:1374 - Bean 'jpaPropertyMap' of type [class org.springframework.beans.factory.config.MapFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:12 INFO GenericApplicationContext:1374 - Bean 'jpaPropertyMap' of type [class java.util.LinkedHashMap] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:12 INFO LocalContainerEntityManagerFactoryBean:264 - Building JPA container EntityManagerFactory for persistence unit 'ruleEditor.persistence'
2013-02-12 13:01:13 INFO SchemaUpdate:182 - HHH000228: Running hbm2ddl schema update
2013-02-12 13:01:13 INFO SchemaUpdate:193 - HHH000102: Fetching database metadata
2013-02-12 13:01:13 INFO SchemaUpdate:205 - HHH000396: Updating schema
2013-02-12 13:01:13 INFO TableMetadata:65 - HHH000261: Table found: MySQL_Test_Repository.user
2013-02-12 13:01:13 INFO TableMetadata:66 - HHH000037: Columns: [id, enabled, first_name, username, email, password_hash, last_name]
2013-02-12 13:01:13 INFO TableMetadata:68 - HHH000108: Foreign keys: []
2013-02-12 13:01:13 INFO TableMetadata:69 - HHH000126: Indexes: [id, username, primary]
2013-02-12 13:01:13 INFO SchemaUpdate:240 - HHH000232: Schema update complete
2013-02-12 13:01:13 INFO BitronixTransactionManager:390 - Bitronix Transaction Manager version 2.1.3
2013-02-12 13:01:13 WARN Configuration:649 - cannot get this JVM unique ID. Make sure it is configured and you only use ASCII characters. Will use IP address instead (unsafe for production usage!).
2013-02-12 13:01:13 INFO Recoverer:152 - recovery committed 0 dangling transaction(s) and rolled back 0 aborted transaction(s) on 1 resource(s) [jdbc/MySQL_Test_Repository]
2013-02-12 13:01:14 INFO GenericApplicationContext:1374 - Bean 'entityManagerFactory' of type [class org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:14 INFO GenericApplicationContext:1374 - Bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0' of type [class org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:14 INFO GenericApplicationContext:1374 - Bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:14 INFO GenericApplicationContext:1374 - Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:14 INFO JtaTransactionManager:470 - Using JTA UserTransaction: a BitronixTransactionManager with 0 in-flight transaction(s)
2013-02-12 13:01:14 INFO JtaTransactionManager:481 - Using JTA TransactionManager: a BitronixTransactionManager with 0 in-flight transaction(s)
2013-02-12 13:01:14 DEBUG NameMatchTransactionAttributeSource:94 - Adding transactional method [*] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-Exception]
2013-02-12 13:01:14 DEBUG AnnotationTransactionAttributeSource:106 - Adding transactional method 'createUserTest' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2013-02-12 13:01:14 DEBUG AnnotationTransactionAttributeSource:106 - Adding transactional method 'createUserTest' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2013-02-12 13:01:14 DEBUG JtaTransactionManager:365 - Creating new transaction with name [createUserTest]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2013-02-12 13:01:14 INFO TransactionalTestExecutionListener:279 - Began transaction (1): transaction manager [org.springframework.transaction.jta.JtaTransactionManager#2a3998f8]; rollback [false]
Created userusers.model.User#63aa9dc1[userId=0,first name=jonny,last name=doe,email=user5#domain.com,username=user5,password=1238,enabled=false]
2013-02-12 13:01:14 DEBUG JtaTransactionManager:470 - Participating in existing transaction
2013-02-12 13:01:14 DEBUG JtaTransactionManager:470 - Participating in existing transaction
Saved userusers.model.User#6b38579e[userId=0,first name=jonny,last name=doe,email=user5#domain.com,username=user5,password=1238,enabled=false]
2013-02-12 13:01:14 DEBUG JtaTransactionManager:752 - Initiating transaction commit
2013-02-12 13:01:14 WARN Preparer:69 - executing transaction with 0 enlisted resource
2013-02-12 13:01:14 INFO TransactionalTestExecutionListener:299 - Committed transaction after test execution for test context [TestContext#5a93c236 testClass = UserTest, testInstance = UserTest#1ab395af, testMethod = createUserTest#UserTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#42821db testClass = UserTest, locations = '{classpath:tests-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.029 sec
2013-02-12 13:01:14 INFO GenericApplicationContext:1042 - Closing org.springframework.context.support.GenericApplicationContext#7d95609: startup date [Tue Feb 12 13:01:12 CET 2013]; root of context hierarchy
2013-02-12 13:01:14 INFO BitronixTransactionManager:320 - shutting down Bitronix Transaction Manager
2013-02-12 13:01:14 INFO LocalContainerEntityManagerFactoryBean:441 - Closing JPA EntityManagerFactory for persistence unit 'ruleEditor.persistence'
The logs show a testException=[null] but I have no idea why that would be.. I even tried to use the saveAndFlush() method provided by the JPARepository but doing so I get the error javax.persistence.TransactionRequiredException: no transaction is in progress
So if anyone has some idea of what I am doing wrong and can point me in the right direction I would very much appreciate the help.
After some careful reading of the logs, I found this warning:
WARN Ejb3Configuration:1309 - HHH000193: Overriding hibernate.transaction.factory_class is dangerous, this might break the EJB3 specification implementation
This was related to a property that I had set in the jpaPropertyMap bean in my tests-context.xml file:
<entry key="hibernate.transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory" />
It turns out that once I removed this line in the configuration file I could see hibernate performing an "insert" action and the user was actually created in the database. Since I am new to spring and all the technologies I used, I must have copied the configuration from somewhere without really analysing it. So, I am now able to run junit4 tests in a project using spring data, hibernate and bitronix as transaction manager.

Resources