I am integrating Spring-4 and Active-MQ 5.8. I have written small test code. It send message properly but it does not exit.
The Sender Code is
package sample.jms.activemq;
import java.util.Map;
import org.springframework.jms.core.JmsTemplate;
public class MessageSender {
private final JmsTemplate jmsTemplate;
public MessageSender(final JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void send(final Map map) {
jmsTemplate.convertAndSend(map);
}
}
** Configuration file is **
<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-2.5.xsd">
<!-- Activemq connection factory -->
<bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<constructor-arg index="0" value="pass"/>
<constructor-arg index="1" value="pass"/>
<constructor-arg index="2" value="tcp://queueURL:61616"/>
</bean>
<!-- ConnectionFactory Definition -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
</bean>
<!-- Default Destination Queue Definition-->
<bean id="defaultDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0" value="simplesample"/>
</bean>
<!-- JmsTemplate Definition -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="defaultDestination" />
</bean>
<!-- Message Sender Definition -->
<bean id="messageSender" class="sample.jms.activemq.MessageSender">
<constructor-arg index="0" ref="jmsTemplate" />
</bean>
</beans>
** The Main Class code is **
package sample.jms.activemq;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
*/
public class JMSMain {
public static void main(String a[]) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"/sample/jms/resources/Spring-Module.xml");
MessageSender sender = (MessageSender) context.getBean("messageSender");
Map<String, String> map = new HashMap<String, String>();
map.put("Name", "SampleName");
sender.send(map);
System.out.println("Exiting");
context.registerShutdownHook();
}
}
Try to add tcp://queueURL:61616?daemon=true to you config
The JMS just keeps listening messages so to close it it should be daemon.
Related
I'm struggling to implement a WatchServiceDirectoryScanner. I want to use the scanner to monitor new file uploads to a directory + sub directories. This will exist as part of a Spring boot MVC microservice. I can do this using Java 7's WatchService but would prefer a spring file integration style, AOP style
I have it registered as a #Bean in my app config but I'm struggling to figure out how to have it poll and scan a directory and then call... something (a message endpoint?) when a file is detected. Is anyone able to point me in the right direction for even conceptually how this is done. I cannot find an example implementation of this anywhere.
http://docs.spring.io/spring-integration/reference/html/files.html#_watchservicedirectoryscanner
http://docs.spring.io/spring-integration/api/org/springframework/integration/file/DefaultDirectoryScanner.html#listFiles-java.io.File-
here is my Spring appConfig:
public class appConfig {
#Bean
public DirectoryScanner scanner() {
return new WatchServiceDirectoryScanner("/uploads/test");
}
}
# create one configuration file and bind an input file channel here
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-file="http://www.springframework.org/schema/integration/file"
xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/integration/mail http://www.springframework.org/schema/integration/mail/spring-integration-mail.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/file http://www.springframework.org/schema/integration/file/spring-integration-file.xsd
http://www.springframework.org/schema/integration/stream http://www.springframework.org/schema/integration/stream/spring-integration-stream.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<int:annotation-config />
<int:channel id="cfpFileIn"></int:channel>
<int-file:inbound-channel-adapter id="cfpFileIn"
directory="${cfp.flight.data.dir}" auto-startup="true" scanner="csvDirScanner">
<int:poller fixed-delay="${cfp.flight.data.dir.polling.delay}"></int:poller>
</int-file:inbound-channel-adapter>
<bean id="csvDirScanner"
class="org.springframework.integration.file.WatchServiceDirectoryScanner">
<constructor-arg index="0" value="${cfp.flight.data.dir}" />
<property name="filter" ref="csvCompositeFilter" />
<property name="autoStartup" value="true" />
</bean>
<bean id="csvCompositeFilter"
class="org.springframework.integration.file.filters.CompositeFileListFilter">
<constructor-arg>
<list>
<bean
class="org.springframework.integration.file.filters.SimplePatternFileListFilter">
<constructor-arg value="*.csv" />
</bean>
<ref bean="persistentFilter" />
</list>
</constructor-arg>
</bean>
<bean id="persistentFilter"
class="org.springframework.integration.file.filters.FileSystemPersistentAcceptOnceFileListFilter">
<constructor-arg index="0" ref="metadataStore" />
<constructor-arg index="1" name="prefix" value="" />
<property name="flushOnUpdate" value="true" />
</bean>
<bean name="metadataStore"
class="org.springframework.integration.metadata.PropertiesPersistingMetadataStore">
<property name="baseDirectory" value="${metadata.dir}"></property>
</bean>
</beans>
import java.io.File;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.stereotype.Component;
#Component
public class BatchJobScheduler {
private static final Logger logger = LoggerFactory.getLogger(BatchJobScheduler.class);
#Autowired
protected JobLauncher jobLauncher;
#Autowired
#Qualifier(value = "job")
private Job job;
#ServiceActivator(inputChannel = "cfpFileIn")
public void run(File file) {
String fileName = file.getAbsolutePath();
logger.info("BatchJobScheduler Running #################"+fileName);
JobParameters jobParameters = new JobParametersBuilder().addString(
"input.file", fileName).toJobParameters();
try {
JobExecution execution = jobLauncher.run(job,
jobParameters);
logger.info(" BatchJobScheduler Exit Status : " + execution.getStatus() +"::"+execution.getAllFailureExceptions());
} catch (JobExecutionAlreadyRunningException | JobRestartException
| JobInstanceAlreadyCompleteException
| JobParametersInvalidException e) {
logger.error(" BatchJobScheduler Exit Status : Exception ::",e);
}
}
}
here is my 'GenericQuartzJob' class
public class GenericQuartzJob extends QuartzJobBean
{
private String batchProcessorName;
public String getBatchProcessorName() {
return batchProcessorName;
}
public void setBatchProcessorName(String name) {
// System.out.println("jo"+name);
this.batchProcessorName = name;
}
protected void executeInternal(JobExecutionContext jobCtx) throws JobExecutionException
{
try {
// System.out.println("jo");
SchedulerContext schedCtx = jobCtx.getScheduler().getContext();
ApplicationContext appCtx =
(ApplicationContext) schedCtx.get("applicationContext");
java.lang.Runnable proc = (java.lang.Runnable) appCtx.getBean(batchProcessorName);
proc.run();
}
catch (Exception ex) {
// ex.printStackTrace();
throw new JobExecutionException("Unable to execute batch job: " + batchProcessorName, ex);
}
}
}
Here is my MyRunnableJob Class
#Configuration
#ComponentScan("com.ehydromet.service")
public class MyRunnableJob implements Runnable {
//#Resource private SpringService myService;
#Autowired
public UserService service;
#Override
public void run() {
// System.out.println("hu");
try{
service.getAllAdminUser();
}catch(Exception ex){
System.out.println(ex.getMessage()+" MyRunnableJob");
}MqttImplement mqtt=new MqttImplement();
mqtt.publishMessage();
//Run the Job. This code will run in the Spring context so you can use injected dependencies here.
}
}
Below is my MqttImplement class
public class MqttImplement implements MqttCallback {
#Autowired
private static UserService service;
#RequestMapping("/publish")
public void publishData(ModelMap map){
MyTask.map=map;
pubTopic="tmsdata";
susTopic="tmsack";
if(initializeMqTTParameters() ){
if(suscribeForAck()){
// new ClassPathXmlApplicationContext("spring-quartz.xml");
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
}
}
// initializeMqTTParameters();
// suscribeForAck();
// publishMessage();
}
public void publishMessage(){
try{
// System.out.print("sending ");
Received received=service.getReceivedDataToPublishTMS();
if(received!=null){
System.out.print("sending you not null");
String publisgMSG=createMessageToPublish(received);
pubMessage="lava," ;
publishMessageTms();
}else{
System.out.println("null hora");
}
}catch(Exception ex){
System.out.println("hora"+ex.getLocalizedMessage()+" "+ex.toString());
}
}
}
and here is 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- <bean id="exampleBusinessObject" class="com.ehydromet"/> -->
<!-- Old JobDetail Definition
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="exampleBusinessObject"/>
<property name="targetMethod" value="doIt"/>
</bean>
-->
<!-- Runnable Job: this will be used to call my actual job. Must implement runnable -->
<bean name="myRunnableJob" class="com.ehydromet.controller.MyRunnableJob"></bean>
<!-- New Clusterable Definition -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.ehydromet.schedule.GenericQuartzJob" />
<property name="jobDataAsMap">
<map>
<entry key="batchProcessorName" value="myRunnableJob" />
</map>
</property>
</bean>
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<!-- see the example of method invoking job above -->
<property name="jobDetail" ref="jobDetail"/>
<!-- 10 seconds -->
<property name="startDelay" value="5000"/>
<!-- repeat every 50 seconds -->
<property name="repeatInterval" value="5000"/>
</bean>
<context:component-scan base-package="com.ehydromet.service"/>
<context:component-scan base-package="com.ehydromet.dao"/>
<context:component-scan base-package="com.ehydromet.service.impl"/>
<context:component-scan base-package="com.ehydromet.dao.impl"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.ehydromet.entity.Alarms</value>
<value>com.ehydromet.entity.UserData</value>
<value>com.ehydromet.entity.ModemInfo</value>
<value>com.ehydromet.entity.Received</value>
<value>com.ehydromet.entity.Modems</value>
<value>com.ehydromet.entity.AdminLogin</value>
<value>com.ehydromet.entity.UserPolicy</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
</props>
</property>
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
<property name="triggers">
<list>
<ref bean="simpleTrigger" />
</list>
</property>
<!-- Add this to make the Spring Context Available -->
<property name="applicationContextSchedulerContextKey"><value>applicationContext</value></property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/ejava" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
</beans>
Dao classes are #Transactional and #Repository.
in MqttImplement class service object is null i think autowired is not working with Quartz scheduler. Any suggestion????
i think autowired is kind of resolved. but
error is-- org.springframework.beans.NotWritablePropertyException: Invalid property 'sessionFactory' of bean class [org.springframework.scheduling.quartz.SchedulerFactoryBean]: Bean property 'sessionFactory' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
i am new to it. so may be some foolish mistakes i have done, please have a look.
Have you tried #Autowired without static? Seems weird for me...
From other side you do this:
MqttImplement mqttPublishTms=new MqttImplement();
................
mqttPublishTms.publishMessage();
So, it's new not Dependency Injection. There is no surprise that the service property there is null.
I am trying to pass string messages from one class to another (from Class1 to Class2) within the same application so I am trying to solve it using Spring Integration.
My context.xml file looks like below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/jms http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-jms="http://www.springframework.org/schema/integration/jms">
<int:channel id="processEmpChannel">
<int:queue/>
</int:channel>
<int-jms:inbound-channel-adapter
channel="processEmpChannel" connection-factory="connectionFactory"
destination-name="empQueue">
<int:poller fixed-delay="500" />
</int-jms:inbound-channel-adapter>
<bean id="connectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost?broker.persistent=false" />
</bean>
</property>
<property name="sessionCacheSize" value="10" />
<property name="cacheProducers" value="false" />
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<bean id="springIntExample"
class="com.distributed.analyzer.Manager">
<property name="jmsTemplate" ref="jmsTemplate" />
</bean>
<int:service-activator input-channel="processEmpChannel" ref="springIntExample" method="processMessage">
<int:poller fixed-delay="500"/>
</int:service-activator>
</beans>
Class Class1:
package com.my.package;
public class Class1 implements Runnable {
#Autowired
private ApplicationContext appContext;
private JmsTemplate jmsTemplate;
...
public void someMethod() {
Class1 c = (Class1) appContext.getBean("springIntExample");
c.send();
}
public void send() {
getJmsTemplate().convertAndSend("empQueue", "one message to test");
}
public JmsTemplate getJmsTemplate() {
return jmsTemplate;
}
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
...
}
Class Class2:
package com.my.package;
public class Class2 implements Runnable {
...
public void processMessage(String msg) {
System.out.println("message recived: " + msg);
}
...
}
Problem I have:
If I open my context.xml file, the below lines in context.xml are marked with a cross (error):
<int:poller fixed-delay="500" />
Anyway I can build and execute application but in run time an exception message saying fixe-delay not allowed in int:poller appears.
Also, is my implementation correct? I am not sure if after solving the problem commented it will work. I am new in spring sorry.
I am getting
org.springframework.beans.factory.BeanCreationException....java.lang.NoClassDefFoundError:
com/atomikos/diagnostics/Console
Main.java
package com.nody.client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.nody.spring.global.AccountInter;
public class Main {
public static void main(String arg[]) throws Exception
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Object o=ctx.getBean("accimpl");
AccountInter inter=(AccountInter)o;
inter.transferMoney(101,102,2000);
}
}
Here is my Interface
AccountInter.java
package com.nody.spring.global;
public interface AccountInter {
void transferMoney(int accno1,int accno2,int amount) throws Exception;
}
Here is Implement class AccountImpl.java
package com.nody.spring.global;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
public class AccountImpl implements AccountInter {
private JdbcTemplate jt1;
private JdbcTemplate jt2;
public void setJt1(JdbcTemplate jt1) {
this.jt1 = jt1;
}
public void setJt2(JdbcTemplate jt2) {
this.jt2 = jt2;
}
#SuppressWarnings("deprecation")
#Override
#Transactional(timeout=5)
public void transferMoney(int accno1, int accno2, int amount) throws Exception
{
int s1=jt1.queryForInt("select bal from Account1 where acno=?",accno1);
//Deducting amount from balance
int s2=s1-amount;
if(s2<500)
{
throw new Exception();
}
int s3=jt2.queryForInt("select bal from Account2 where accno=?",accno2);
//adding amount to account2
int s4=s3+amount;
jt1.update("update Account1 set bal=? where accno=?",s2,accno1);
jt2.update("update Account2 set bal=? where accno=?",s4,accno2);
System.out.println("Transaction Successfull !");
}
}
Here is applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!--- Business bean Configuration -->
<bean id="accimpl" class="com.nody.spring.global.AccountImpl">
<property name="jt1" ref="jt1"></property>
<property name="jt2" ref="jt2"></property>
</bean>
<!--JdbcTemplate -->
<bean id="jt1" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds1"></property>
</bean>
<bean id="jt2" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds2"></property>
</bean>
<!-- -DataSource Configuration DATABASE-1 -->
<bean id="ds1" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
<property name="uniqueResourceName" value="A"></property>
<property name="xaDataSourceClassName" value="oracle.jdbc.xa.client.OracleXADataSource"></property>
<property name="xaProperties">
<props>
<prop key="databaseName">xe</prop>
<prop key="user">scott</prop>
<prop key="password">tiger</prop>
<prop key="URL">jdbc:oracle:thin:#localhost:1521:xe</prop>
</props>
</property>
<property name="poolSize" value="1"></property>
</bean>
<!-- DataSource Configuration DATABASE2 -->
<bean id="ds2" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
<property name="uniqueResourceName" value="B"></property>
<property name="xaDataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"></property>
<property name="xaProperties">
<props>
<prop key="databaseName">nody</prop>
<prop key="user">root</prop>
<prop key="password"></prop>
<prop key="URL">jdbc:mysql://localhost:3306/nody</prop>
</props>
</property>
<property name="poolSize" value="1"></property>
</bean>
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">
</bean>
<bean id="txm" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<ref bean="atomikosTransactionManager"></ref>
</property>
</bean>
<tx:annotation-driven transaction-manager="txm"/>
</beans>
Here my application Directory structure
aopalliance.jar
aspectjrt-1.8.5.jar
aspectj-weaver.jar
atomikos-transactions-api.jar
atomikos-transactions-jta.jar
atomikos-util-4.0.0M4.jar
commons-logging-api-1.1.1.jar
jta.jar
mysql-connector-java-5.1.6.jar
ojdbc14.jar
spring-aop-4.1.4.RELEASE.jar
spring-beans-4.1.4.RELEASE.jar
spring-context-4.1.4.RELEASE.jar
spring-context-support-4.1.4.RELEASE.jar
spring-core-4.1.4.RELEASE.jar
spring-expression-4.1.4.RELEASE.jar
spring-jdbc-4.1.4.RELEASE.jar
spring-tx-4.1.4.RELEASE.jar
transactions-3.7.0.jar
transactions-jdbc-3.7.0.jar
Here is complete Exception details
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jt1' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'ds1' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ds1' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/atomikos/diagnostics/Console
I am really tried but not getting what happening. Please help me.
The runtime cannot find the class com.atomikos.diagnostics.Console on the class path.
If you are building with Maven, add this dependency:
<dependency>
<groupId>com.atomikos</groupId>
<artifactId>atomikos-util</artifactId>
<version>3.7.1</version>
</dependency>
http://mvnrepository.com/artifact/com.atomikos/atomikos-util
Otherwise download the atomikos-util.jar from this site and add it to your class path.
Edit: 3.7.1 seems to be the last version with the Console class in it
Download from http://mvnrepository.com/artifact/com.atomikos/atomikos-util/3.7.1
I am using Hibernate4 in my application for multitenancy implementation while building application war i got following error in my catalina of tomcat.
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field:
protected org.hibernate.SessionFactory com.boxco.blip.dao.BaseDao.sessionFactory;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext-persistence.xml]:
Invocation of init method failed; nested exception is java.lang.NullPointerException
Here is my application -persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">
<context:annotation-config />
<tx:annotation-driven />
<context:component-scan base-package="com.boxco.blip">
</context:component-scan>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/blip</value>
</property>
<property name="resourceRef">
<value>true</value>
</property>
</bean>
<!-- Hibernate Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.boxco.blip.model.Address</value>
</list>
</property>
<property name="hibernateProperties">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.show_sql" value="true" />
<entry key="hibernate.connection.autocommit" value="false" />
<entry key="hibernate.jdbc.batch_size" value="0" />
<entry key="hibernate.connection.release_mode" value="after_transaction" />
<entry key="hibernate.multiTenancy" value="SCHEMA" />
<entry key="hibernate.tenant_identifier_resolver" value-ref="multiTenantIdentifierResolver1" />
<entry key="hibernate.multi_tenant_connection_provider" value-ref="multiTenantConnectionProvider1" />
</map>
</property>
</bean>
<bean id="multiTenantConnectionProvider1" class="com.boxco.blip.web.util.SchemaMultiTenantConnectionProviderBlip">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="multiTenantIdentifierResolver1" class="com.boxco.blip.web.util.SchemaCurrentTenantIdentifierResolverBlip" />
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
MY AddressDao.java File
package com.boxco.blip.dao;
import com.boxco.blip.model.Address;
public interface AddressDao {
public Address getAddressByAddressId(int addressId);
}
My AddressDaoImpl.java file
package com.boxco.blip.dao;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.boxco.blip.model.Address;
#Component
#Repository(value = "addressDao")
public class AddressDaoImpl extends BaseDao implements AddressDao {
private static final Logger logger = Logger.getLogger(AddressDaoImpl.class);
#Override
public Address getAddressByAddressId(int addressId) {
logger.info("Entering getAddressByAddressId()........");
Address address = null;
Criteria criteria = getSession().createCriteria(Address.class);
criteria.add(Restrictions.eq("addressId", addressId));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
address = (Address)criteria.uniqueResult();
logger.info("Exiting getAddressByAddressId()..........");
return address;
}
}
My Base Dao file where i init sessionFactory object:
package com.boxco.blip.dao;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.mysql.jdbc.Connection;
public abstract class BaseDao
{
#Autowired
#Qualifier("sessionFactory")
protected SessionFactory sessionFactory;
protected void init(SessionFactory factory) {
try {
setSessionFactory(factory);
} catch (Exception e) {
e.printStackTrace();
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() throws HibernateException {
// return sessionFactory.getCurrentSession();
return sessionFactory.withOptions().tenantIdentifier("BLIP1314ERP")
.openSession();
}
//some more methods
}
My Dispatcher-servlet.xml file where is added
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">
<mvc:annotation-driven/>
<context:component-scan base-package="com.boxco">
<!-- <context:exclude-filter type="regex" expression="com.boxco.blip.dao.*" /> -->
</context:component-scan>
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basenames" value="views"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<value>messages,error_codes</value>
</property>
</bean>
<bean id="validatorFactory"
class="org.springmodules.validation.commons.DefaultValidatorFactory">
<property name="validationConfigLocations">
<list>
<value>/WEB-INF/validator-rules.xml</value>
<value>/WEB-INF/validator.xml</value>
<value>/WEB-INF/validatorFas.xml</value>
<value>/WEB-INF/validatorFas-rules.xml</value>
</list>
</property>
</bean>
<bean id="validator" class="org.springmodules.validation.commons.DefaultBeanValidator">
<property name="validatorFactory" ref="validatorFactory"/>
</bean>
Error is in my SessionFactory initialization but why it is not getting init is my problem..?
(I am handling this error first time)..
Any suggestion appreciated.
It shouldn't be your solution, in any case the #component annotation over #repository is useless. Either you insert #repository (better for exception translation) or #component.
I resolved it by replacing my JAR files from 4.3.4 to 4.1.7 (downgraded my jar) hibernate version ,I dont know why its not working with latest versions of Hibernate