I m struggling with simple task with last two days.I have configured jms Message queue in Jboss6.x. I have configured jndi,jms MQ in spring using jmstemplate in applicationcontext.xml File,
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="messageListener" class="com.test.QueuereceiverDB" />
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.provider.url">localhost:1099</prop>
<prop key="java.naming.factory.url.pkgs">org.jnp.interfaces:org.jboss.naming</prop>
<prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop>
</props>
</property>
</bean>
<bean id="queueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="jndiTemplate" />
</property>
<property name="jndiName">
<value>ConnectionFactory</value>
</property>
</bean>
<bean id="jmsDestinationResolver" class="org.springframework.jms.support.destination.JndiDestinationResolver">
<property name="jndiTemplate">
<ref bean="jndiTemplate" />
</property>
<property name="cache">
<value>true</value>
</property>
</bean>
<bean id="QueueTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="queueConnectionFactory" />
</property>
<property name="destinationResolver">
<ref bean="jmsDestinationResolver" />
</property>
</bean>
<bean id="jmsSender" class="com.test.MessageSender">
<property name="jmsTemplate"> <ref bean="QueueTemplate" />
</property>
</bean>
<bean id="Queue" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate"> <ref bean="jndiTemplate" />
</property>
<property name="jndiName">
<value>queue/MyQueue</value>
</property>
</bean>
<bean id="jmscontainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="concurrentConsumers" value="5" />
<property name="connectionFactory" ref="queueConnectionFactory" />
<property name="destination" ref="Queue" />
<property name="messageListener" ref="messageListener" />
</bean>
Below is Message sender
package com.test;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
public class MessageSender {
private JmsTemplate jmsTemplate;
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void sendMesage() {
MessageCreator messageCreator=new MessageCreator() {
public Message createMessage(Session session) throws
JMSException {
return session.createTextMessage("I am sending Invoice message");}
};
jmsTemplate.send("queue/MyQueue", messageCreator);
}
}
Finally Message receiver class
public class QueuereceiverDB implements MessageListener {
/**
* Default constructor.
*/
public QueuereceiverDB() {
// TODO Auto-generated constructor stub
}
/**
* #see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
System.out.println("Queue: I received a TextMessage at "
+ new Date());
TextMessage msg = (TextMessage) message;
System.out.println("Message is : " + msg.getText());
} else {
System.out.println("Not valid message for this Queue MDB");
}
} catch (JMSException e) {
e.printStackTrace();
}
}
I have loaded applicationcontext.xml file in web.xml file.
After that deploy the war file in jboss there was no error and also message not received.I dont know why the message was not received.Can someone help me.
After adding resourc-ref tag it shows following error
Caused by: java.lang.RuntimeException: Neither any mapped-name/lookup/jndi-name specified nor any ResourceProvider could process resource-ref named env/ConnectionFactory of type javax.jms.QueueConnectionFactory
at org.jboss.switchboard.mc.resource.provider.ResourceRefResourceProviderDelegator.provide(ResourceRefResourceProviderDelegator.java:125) [:1.0.0-alpha-15]
at org.jboss.switchboard.mc.resource.provider.ResourceRefResourceProviderDelegator.provide(ResourceRefResourceProviderDelegator.java:44) [:1.0.0-alpha-15]
at org.jboss.switchboard.mc.JndiEnvironmentProcessor.process(JndiEnvironmentProcessor.java:68) [:1.0.0-alpha-15]
at org.jboss.switchboard.mc.deployer.AbstractSwitchBoardDeployer.process(AbstractSwitchBoardDeployer.java:119) [:1.0.0-alpha-15]
at org.jboss.switchboard.mc.deployer.WebEnvironmentSwitchBoardDeployer.internalDeploy(WebEnvironmentSwitchBoardDeployer.java:66) [:1.0.0-alpha-15]
at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:55) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:179) [:2.2.0.GA]
The following contains queue name details and deployed in jboss/server/default/deploy
mdb-hornetq.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="urn:hornetq"
xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd" >
<queue name="MyQueue2" >
<entry name="/queue/MyQueue" />
</queue>
</configuration>
All is correct , can you verify that in your web.xml you have the ressources declared :
<resource-ref>
<res-ref-name>ConnectionFactory</res-ref-name>
<res-type>javax.jms.QueueConnectionFactory</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<resource-ref>
<res-ref-name>queue/MyQueue</res-ref-name>
<res-type>javax.jms.Queue</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Related
Any help will be greatly appreciated. I am trying to create a replacement for MDB with spring JMSListener. I wanted the destination name to be passed as a annotation, but i noticed that org.springframework.jms.listener.DefaultMessageListenerContainer container config has destinationName or destination as mandatory. Am i missing something ? How to make use of destination resolver to use queue name from #JmsListener annotation?
#Component
public class InitStRspnLstnr {
#JmsListener(destination = "${xyz.company.MQ.INITST.RSPN.FADS.Q}")
public void onMessage(Message msg) throws JMSException {
System.out.println("**********************************************"+msg);
}}
Below is my Xml pasted, I commented the container for now, since spring was trying to connect to dummy queue instead of the one in annotation..
<?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:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cxf="http://cxf.apache.org/core"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
">
<import resource="classpath*:com/xyz/svc/component.xml"/>
<mvc:annotation-driven enable-matrix-variables="true"/>
<context:component-scan base-package="com.xyz.css.rplr.initst"></context:component-scan>
<!-- WebSphere MQ Connection setup start -->
<bean id="mqIdsConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
<property name="hostName"><value>${xyz.company.MQ.HOST.NM}</value></property>
<property name="port"><value>${xyz.company.MQ.PORT}</value></property>
<property name="queueManager"><value>${xyz.company.MQ.QMNGR}</value></property>
<property name="channel"><value>${xyz.company.MQ.CHANNEL}</value></property>
<property name="CCSID"><value>819</value></property>
<property name="transportType">
<util:constant static-field="com.ibm.mq.jms.JMSC.MQJMS_TP_CLIENT_MQ_TCPIP" />
</property>
</bean>
<bean id="jmsQueueIdsConnectionFactory"
class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory">
<ref bean="mqIdsConnectionFactory" />
</property>
</bean>
<bean id="jmsDestinationResolver"
class="org.springframework.jms.support.destination.DynamicDestinationResolver">
</bean>
<bean id="jmsQueueIdsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="jmsQueueIdsConnectionFactory" />
</property>
<property name="destinationResolver">
<ref bean="jmsDestinationResolver" />
</property> <!--
<property name="defaultDestinationName">
<value>${xyz.company.MQ.INITST.Q}</value>
</property>-->
<property name="pubSubDomain">
<value>false</value>
</property>
<property name="receiveTimeout">
<value>20000</value>
</property>
</bean>
<!-- <bean id="jmsContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory">
<ref bean="jmsQueueIdsConnectionFactory" />
</property>
<property name="destinationResolver">
<ref bean="jmsDestinationResolver" />
</property>
<property name="destinationName" value="dummyQueue"/>
<property name="concurrency" value="3-10" />
</bean> -->
<!-- WebSphere MQ Connection setup end -->
</beans>
Added working version below. defaultDestinationName is not needed in xml , if its set up in code via annotation.. ${company.project.MQ.module.Q} and other values are loaded from properties file, it can be hard coded too.
#Component
public class SampleLstner{
#JmsListener(concurrency = "1", destination = "${company.project.MQ.module.Q}", containerFactory = "jmsListenerContainerFactory")
public void onMessage(Message msg) throws JMSException {}
}
XML
<?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:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cxf="http://cxf.apache.org/core"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms-4.1.xsd
">
<import resource="classpath*:com/company/svc/component.xml"/>
<mvc:annotation-driven enable-matrix-variables="true"/>
<context:component-scan base-package="com.company.test.main.module"></context:component-scan>
<!-- WebSphere MQ Connection setup start -->
<bean id="mqIdsConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
<property name="hostName"><value>${company.project.MQ.HOST.NM}</value></property>
<property name="port"><value>${company.project.MQ.PORT}</value></property>
<property name="queueManager"><value>${company.project.MQ.QMNGR}</value></property>
<property name="channel"><value>${company.project.MQ.CHANNEL}</value></property>
<property name="CCSID"><value>819</value></property>
<property name="transportType"><value>1</value></property>
</bean>
<bean id="jmsQueueIdsConnectionFactory"
class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory">
<ref bean="mqIdsConnectionFactory" />
</property>
</bean>
<bean id="jmsDestinationResolver"
class="org.springframework.jms.support.destination.DynamicDestinationResolver">
</bean>
<bean id="jmsQueueIdsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="jmsQueueIdsConnectionFactory" />
</property>
<property name="destinationResolver">
<ref bean="jmsDestinationResolver" />
</property> <!--
<property name="defaultDestinationName">
<value>${company.project.MQ.module.Q}</value>
</property>-->
<property name="pubSubDomain">
<value>false</value>
</property>
<property name="receiveTimeout">
<value>20000</value>
</property>
</bean>
<bean id="jmsListenerContainerFactory" class="org.springframework.jms.config.DefaultJmsListenerContainerFactory">
<property name="connectionFactory">
<ref bean="jmsQueueIdsConnectionFactory" />
</property>
<property name="destinationResolver">
<ref bean="jmsDestinationResolver" />
</property>
<property name="concurrency" value="1" />
</bean>
<!-- WebSphere MQ Connection setup end -->
I have a working cron method but it gives me a null java.lang.NullPointerException on my service class:
public class CronTask {
private JpassatemposService jpassatemposService;
#Autowired(required=true)
#Qualifier(value="jpassatemposService")
public void setJpassatemposService(JpassatemposService concs){
this.jpassatemposService = concs;
}
#Autowired
private ServletContext sCtx;
// #Scheduled(cron ="46 11 * * * ?")
#Scheduled(fixedDelay=30000)
public void sendCodPendentes(){
System.out.println("Start :: "+ new Date());
try {
System.out.println("TRY "+ new Date());
List<Jpassatempos> aTerminar = this.jpassatemposService.listJpassatempos24H();
System.out.println("24 "+ new Date());
List<Jpassatempos> enviados = this.jenviocodpendentesService.listJenviocodpendentes24H("CodPendentes24");
System.out.println("Enviados "+ new Date());
List<Jpassatempos> resultado = new ArrayList<Jpassatempos>();
.....
Any Help is appreciated
Cron xml:
<?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:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
<bean id="cronTask" class="com.setelog.spring.CronTask"></bean>
</beans>
My full config xml:
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.setelog.spring" />
<context:component-scan base-package="com.setelog.spring.cron" />
<context:property-placeholder location="classpath:config.properties"/>
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="org.springframework.mobile.device.DeviceWebArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
<mvc:interceptors>
<bean class="org.springframework.mobile.device.DeviceResolverHandlerInterceptor" />
</mvc:interceptors>
<mvc:interceptors>
<bean class="com.setelog.spring.businessrules.Interceptor" />
</mvc:interceptors>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="com.setelog.spring.dao.UserDetailsDaoImpl.setEmails_Blocked"/>
<property name="arguments">
<list>
<value>${emails_blocked}</value>
</list>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="com.setelog.spring.handler.LimitLoginAuthenticationProvider.setEmails_Help"/>
<property name="arguments">
<list>
<value>${emails_help}</value>
</list>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="10000000" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="pt" />
<property name="cookieName" value="myAppLocaleCookie"></property>
<property name="cookieMaxAge" value="3600"></property>
</bean>
<mvc:interceptors>
<bean
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="locale" />
</bean>
</mvc:interceptors>
</beans>
The output i get is as follows:
Start :: Tue Dec 01 12:51:19 GMT 2015
TRY Tue Dec 01 12:51:19 GMT 2015
java.lang.NullPointerException
After a discussion in the chat with #Kunal, we established that the problem was with the following XML configuration:
<bean id="cronTask" class="com.setelog.spring.CronTask"></bean>
The two services referred to in the code were being created in the XML config, and so needed to be set directly in this <bean> definition, so the following solution worked:
<bean id="cronTask" class="com.setelog.spring.CronTask">
<property name="jpassatemposService" ref="jpassatemposService"/>
<property name="jenviocodpendentesService" ref="jenviocodpendentesService"/>
</bean>
Posting here for others who might find this with the same issue in the future.
I'm trying to execute Spring Batch Example – CSV File To MySQL Database.
when im running the App.java the following error it is displaying.
java.lang.NumberFormatException: Unparseable number: Clicks
java.lang.IllegalArgumentException: Unparseable date: "Order Date", format: [dd/MM/yyyy]
Can anyone pls let me know where i have done mistake..
Source Code :
report.csv
OrderDate,Impressions,Clicks,Earning
6/1/13, "139,237", 37, 227.21
6/2/13, "149,582", 55, 234.71
6/3/13, "457,425", 132, 211.48
6/4/13, "466,870", 141, 298.40
6/5/13,"472,385",194,281.35
......
resources/spring/batch/config/database.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">
<!-- connect to database -->
<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/test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
<!-- create job-meta tables automatically -->
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="org/springframework/batch/core/schema-drop-mysql.sql" />
<jdbc:script location="org/springframework/batch/core/schema-mysql.sql" />
</jdbc:initialize-database>
</beans
resources/spring/batch/config/context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<!-- stored job-metadata in database -->
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseType" value="mysql" />
</bean>
<!-- stored job-metadata in memory -->
<!--
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
-->
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
</beans>
resources/spring/batch/jobs/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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<bean id="report" class="com.mkyong.model.Report" scope="prototype" />
<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="cvsFileItemReader" writer="mysqlItemWriter"
commit-interval="2">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="cvsFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<!-- Read a csv file -->
<property name="resource" value="classpath:cvs/report.csv" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<!-- split it -->
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="date,impressions,clicks,earning" />
</bean>
</property>
<property name="fieldSetMapper">
<!-- map to an object -->
<bean class="com.mkyong.ReportFieldSetMapper" />
</property>
</bean>
</property>
</bean>
<bean id="mysqlItemWriter"
class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
insert into RAW_REPORT(DATE,IMPRESSIONS,CLICKS,EARNING)
values (:date, :impressions, :clicks, :earning)
]]>
</value>
</property>
<!-- It will take care matching between object property and sql name parameter -->
<property name="itemSqlParameterSourceProvider">
<bean
class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider" />
</property>
</bean>
</beans>
com/mkyong/model/Report.java
package com.mkyong.model;
public class Report {
private Date orderDate;
private String impressions;
private int clicks;
private String earning;
//getter and setter methods
}
com/mkyong/App.java
package com.mkyong;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
String[] springConfig =
{ "spring/batch/config/database.xml",
"spring/batch/config/context.xml",
"spring/batch/jobs/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");
}
}
ReportFieldSetMapper.java
package com.mkyong;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;
import com.mkyong.model.Report;
public class ReportFieldSetMapper implements FieldSetMapper<Report> {
#Override
public Report mapFieldSet(FieldSet fieldSet) throws BindException {
Report report = new Report();
report.setOrderDate(fieldSet.readDate(0,"dd/MM/yyyy"));
report.setImpressions(fieldSet.readString (1));
report.setClicks;(fieldSet.readInt(2));
report.setEarning(fieldSet.readString(3));
}
}
Looks like you try to parse the header line
add <property name="linesToSkip" value="1"></property> to your bean <bean id="cvsFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
I have try to run simple spring jmstemplate example.Here goes for source code for sender,
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
public class MessageSender {
#Autowired
private JmsTemplate jmsTemplate;
public void setJmsTemplate(JmsTemplate jmsTemplate)
{
this.jmsTemplate = jmsTemplate;
}
public void sendMessage()
{
jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session)
{
TextMessage message = null;
try
{
message = session.createTextMessage();
message.setStringProperty("text", "Hello World");
}
catch (JMSException e)
{
e.printStackTrace();
}
return message;
}
});
}
}
Here is config file for integrating spring with jmstemplate.
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- Spring AOP -->
<context:component-scan base-package="com.test"/>
<aop:aspectj-autoproxy />
<bean id="messageListener" class="com.test.QueuereceiverDB" />
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.provider.url">jnp://localhost:1099</prop>
<prop key="java.naming.factory.url.pkgs">org.jnp.interfaces:org.jboss.naming</prop>
<prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop>
</props>
</property>
</bean>
<bean id="queueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="jndiTemplate" />
</property>
<property name="jndiName">
<value>ConnectionFactory</value>
</property>
</bean>
<bean id="jmsDestinationResolver" class="org.springframework.jms.support.destination.JndiDestinationResolver">
<property name="jndiTemplate">
<ref bean="jndiTemplate" />
</property>
<property name="cache">
<value>true</value>
</property>
</bean>
<bean id="QueueTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="queueConnectionFactory" />
</property>
<property name="destinationResolver">
<ref bean="jmsDestinationResolver" />
</property>
</bean>
<bean id="jmsSender" class="com.test.MessageSender">
<property name="jmsTemplate"> <ref bean="QueueTemplate" />
</property>
</bean>
<bean id="Queue" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate"> <ref bean="jndiTemplate" />
</property>
<property name="jndiName">
<value>queue/MyQueue</value>
</property>
</bean>
<!-- JmsTemplate Definition -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="queueConnectionFactory" />
<property name="defaultDestination" ref="Queue" />
</bean>
<bean id="jmscontainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="concurrentConsumers" value="5" />
<property name="connectionFactory" ref="queueConnectionFactory" />
<property name="destination" ref="Queue" />
<property name="messageListener" ref="messageListener" />
</bean>
</beans>
If i run the example below is the corresponding stacktrace
SEVERE [com.sun.jersey.spi.container.ContainerResponse] The RuntimeException could not be mapped to a response, re-throwing to the HTTP container: java.lang.NullPointerException
at com.test.MessageSender.sendMessage(MessageSender.java:30) [:]
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149) [:]
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689) [:3.1.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) [:3.1.0.RELEASE]
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55) [:3.1.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161) [:3.1.0.RELEASE]
at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:50) [:3.1.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161) [:3.1.0.RELEASE]
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:50) [:3.1.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161) [:3.1.0.RELEASE]
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:80) [:3.1.0.RELEASE]
After i have debug the code,i have found issue where it is,jmsTemplate.send(new MessageCreator() { While executing this line Null pointer will shown.
I think we need to initialize jmstemplate from xml file.But i dont know how to achieve this?
Please help me someone.
I have configured queue in the following file which will be placed in jboss/server/default/server folder
mdb-hornetq-xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="urn:hornetq"
xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd" >
<queue name="MyQueue2" >
<entry name="/queue/MyQueue" />
</queue>
</configuration>
I find it odd that you have two JmsTemplate beans declared. I have a much simpler configuration that works. There are two JNDI names involved, one is the destination (queue) name, and the other is the connection factory name.
Let's say your queue is MyQueue and your connection factory is MyCF. To send messages, you need to declare just two spring beans:
<bean id="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="MyCF"/>
<property name="lookupOnStartup" value="false"/>
<property name="cache" value="true"/>
<property name="proxyInterface" value="javax.jms.ConnectionFactory"/>
</bean>
<bean name="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="jmsConnectionFactory"/>
</property>
<property name="defaultDestinationName" value="MyQueue" />
</bean>
The source code in the sender class would then contain:
#Autowired
private JmsTemplate jmsTemplate;
private void sendTextMessage(final String message)
MessageCreator messageCreator = new MessageCreator() {
#Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(message);
}
};
jmsTemplate.send(messageCreator);
}
What is missing is the HornetQ configuration of que connection factory and the queue. That configuration defines the JNDI names. In my case, HornetQ runs embedded with JBoss Application Server. Therefore, I configured the connection factory and queue in the JBoss AS configuration (e.g., in the standalone.xml file). Here are the snippets:
<pooled-connection-factory name="hornetq-local">
<transaction mode="local"/>
<connectors>
<connector-ref connector-name="in-vm"/>
</connectors>
<entries>
<entry name="java:/MyCF"/>
</entries>
</pooled-connection-factory>
<jms-destinations>
<jms-queue name="MyQueue">
<entry name="java:jboss/queues/a/b/SomeQueue"/>
<durable>true</durable>
</jms-queue>
</jms-destinations>
I believe you're using HornetQ in standalone mode. It should be easy to map these settings to the factory and queue configuration there.
Why is my spring bean (loginInfoDAO) which is injected properly on server start up, null when I post my form to the controller? I have stepped through the setters on start up and they are injecting properly. However, I run the get method and then the post method and the values that were injected are null. Why would this happen?
Controller
#Controller
#RequestMapping("/login")
public class LoginController extends BaseController{
private LoginInfoDAO loginInfoDAO;
public void setLoginInfoDAO(LoginInfoDAO loginInfoDAO) {
this.loginInfoDAO = loginInfoDAO;
}
#RequestMapping(method=RequestMethod.GET)
public ModelAndView getLogin(#ModelAttribute("user") final User ur) {
ModelAndView mav = new ModelAndView("/login/login");
return mav;
}
#RequestMapping(method=RequestMethod.POST)
public ModelAndView login(#ModelAttribute("user") final User ur) {
loginInfoDAO.login(ur);
ModelAndView mav = new ModelAndView();
return mav;
}
}
application-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean id="myDataSource"
class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost/databasename</value>
</property>
<property name="username">
<value>databaseusername</value>
</property>
<property name="password">
<value>databasepassword</value>
</property>
<!-- Disable the second-level cache -->
<!-- Echo all executed SQL to stdout -->
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.projectname.model.LoginInfo</value>
<value>com.projectname.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="myLoginInfoDAO" class="com.projectname.dao.LoginInfoDAOImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean name="/login" class="com.projectname.controllers.LoginController" >
<property name="loginInfoDAO" ref="myLoginInfoDAO" />
</bean>
</beans>
spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config />
<context:component-scan
base-package="com.projectname" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<value>/WEB-INF/messages/messages</value>
</property>
<property name="cacheSeconds" value="60" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
</beans>
Add #Autowired for loginInfoDAO since you are using context:annotation-config.
#Autowired
private LoginInfoDAO loginInfoDAO;
Then remove the following entries from your context xml (since they are driven with the annotation here).
<bean id="myLoginInfoDAO" class="com.projectname.dao.LoginInfoDAOImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean name="/login" class="com.projectname.controllers.LoginController" >
<property name="loginInfoDAO" ref="myLoginInfoDAO" />
</bean>
This should get you going.