I'm using the Karaf (actually Aetos) OSGi container. I want to have two bundles that use ehcache. Apparently, when the second bundle starts its cache, the cache of the first bundle is stopped.
When the first one is installed, there is no problem. It runs fine.
When I install the second one I get a stack trace like this:
2014-03-25 20:38:18,758 | ERROR | rint Extender: 2 | BlueprintContainerImpl | 9 - org.apache.aries.blueprint - 0.3.2 | Unable to start blueprint container for bundle DataProviderLoadFX
org.osgi.service.blueprint.container.ComponentDefinitionException: Unable to instantiate components
at org.apache.aries.blueprint.container.BlueprintContainerImpl.instantiateEagerComponents(BlueprintContainerImpl.java:635)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintContainerImpl.doRun(BlueprintContainerImpl.java:337)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintContainerImpl.run(BlueprintContainerImpl.java:230)[9:org.apache.aries.blueprint:0.3.2]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)[:1.6.0_41]
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)[:1.6.0_41]
at java.util.concurrent.FutureTask.run(FutureTask.java:138)[:1.6.0_41]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)[:1.6.0_41]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)[:1.6.0_41]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)[:1.6.0_41]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)[:1.6.0_41]
at java.lang.Thread.run(Thread.java:662)[:1.6.0_41]
Caused by: java.lang.NullPointerException
at org.apache.aries.blueprint.container.BeanRecipe.setProperties(BeanRecipe.java:768)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.internalCreate(BeanRecipe.java:722)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.di.AbstractRecipe.create(AbstractRecipe.java:64)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.setProperty(BeanRecipe.java:813)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.setProperties(BeanRecipe.java:787)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.setProperties(BeanRecipe.java:768)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.internalCreate(BeanRecipe.java:722)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.di.AbstractRecipe.create(AbstractRecipe.java:64)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintRepository.createInstances(BlueprintRepository.java:219)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintRepository.createAll(BlueprintRepository.java:147)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintContainerImpl.instantiateEagerComponents(BlueprintContainerImpl.java:631)[9:org.apache.aries.blueprint:0.3.2]
... 10 more
Then I update that second bundle and it starts up just fine. However, when I then exercise the cache on the first bundle, the cache begins to fail with this stack trace:
Caused by: org.apache.camel.language.bean.RuntimeBeanExpressionException: Failed to invoke method: handleFTPDeliveryRequest(${property.requestId},${property.duplicate}) on null due to: java.lang.IllegalStateException: The DRS_RequestServiceLoadSensitivity_jdbcOneHourToLiveCache Cache is not alive (STATUS_SHUTDOWN)
at org.apache.camel.language.bean.BeanExpression$OgnlInvokeProcessor.process(BeanExpression.java:285)
at org.apache.camel.language.bean.BeanExpression.evaluate(BeanExpression.java:114)
... 92 more
Caused by: java.lang.IllegalStateException: The DRS_RequestServiceLoadSensitivity_jdbcOneHourToLiveCache Cache is not alive (STATUS_SHUTDOWN)
at net.sf.ehcache.Cache$CacheStatus.checkAlive(Cache.java:4290)
at net.sf.ehcache.Cache.checkStatus(Cache.java:2731)
at net.sf.ehcache.Cache.get(Cache.java:1610)
at net.sf.ehcache.Cache.get(Cache.java:1591)
at com.windlogics.tsunami.drs.requestservice.LdfxDAO.checkDuplicaeFTPRequest(LdfxDAO.java:843)
at com.windlogics.tsunami.drs.requestservice.RequestProcessor.handleFTPDeliveryRequest(RequestProcessor.java:284)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.camel.component.bean.MethodInfo.invoke(MethodInfo.java:341)
at org.apache.camel.component.bean.MethodInfo$1.proceed(MethodInfo.java:238)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:166)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:99)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:73)
at org.apache.camel.language.bean.BeanExpression$InvokeProcessor.process(BeanExpression.java:189)
at org.apache.camel.language.bean.BeanExpression$OgnlInvokeProcessor.process(BeanExpression.java:281)
... 93 more
The ehcache config files are in the bundles. They are identical except for the names of the ehcache and caches and the names of the files themselves are even different.
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
name="DRS_RequestServiceLoadSensitivity" monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup" properties="jndiName=java:/TransactionManager"
propertySeparator=";" />
<cacheManagerEventListenerFactory class="" properties="" />
<defaultCache maxEntriesLocalHeap="0" eternal="false" timeToIdleSeconds="1200" timeToLiveSeconds="1200">
</defaultCache>
<cache name="DRS_RequestServiceLoadSensitivity_jdbcOneHourToLiveCache" maxBytesLocalHeap="100M" maxBytesLocalDisk="200M" eternal="false"
diskSpoolBufferSizeMB="20" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU" transactionalMode="off">
</ehcache>
I'm using the following bean as a factory:
public class CacheManagerFactory {
private static Logger logger = Logger.getLogger(CacheManagerFactory.class);
private CacheManager cacheManager;
private String configFilename = "ehcache.xml";
private Bundle bundle;
public void afterPropertiesSet() {
InputStream in = null;
try {
URL url = bundle.getEntry(configFilename);
in = url.openStream();
cacheManager = CacheManager.create(in);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
logger.warn("", e);
}
}
}
}
public void dispose() {
cacheManager.shutdown();
}
public Cache getCache(String name) {
return cacheManager.getCache(name);
}
public CacheManager getCacheManager() {
return cacheManager;
}
public void setBundle(Bundle bundle) {
this.bundle = bundle;
}
public void setConfigFilename(String configFilename) {
this.configFilename = configFilename;
}
}
Here is the excerpt from the blueprint.xml files where I use the factory:
<bean id="cacheManagerFactory" class="com.windlogics.tsunami.drs.dataprovider.CacheManagerFactory" init-method="afterPropertiesSet" destroy-method="dispose">
<property name="bundle" ref="blueprintBundle" />
<property name="configFilename" value="DRS_RequestServiceLoadSensitivity_ehcache.xml" />
</bean>
<bean id="dao" class="com.windlogics.tsunami.drs.dataprovider.LdfxDAO">
<property name="dataSource" ref="loadFXDataSource" />
<property name="cache">
<bean factory-ref="cacheManagerFactory" factory-method="getCache">
<argument value="DRS_RequestServiceLoadSensitivity_jdbcOneHourToLiveCache" />
</bean>
</property>
</bean>
I have this in the pom.xml files:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cache</artifactId>
</dependency>
Related
We are using HSQL Database Engine 2.3.2 with Spring 4.2.0.RELEASE while my spring configuration is as following:
Here is applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx" 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-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<bean class="com.chorke.spring.bootstarp.HyperSqlDbServer" id="hsqldb" init-method="start">
<constructor-arg>
<props>
<prop key="server.port">55511</prop>
<prop key="server.dbname.0">chorke</prop>
<prop key="server.remote_open">true</prop>
<prop key="server.database.0">file:~/.hsqldb/chorke/data;sql.syntax_mys=true;user=admin;password=pa55word</prop>
<prop key="hsqldb.default_table_type">text</prop>
<prop key="hsqldb.reconfig_logging">false</prop>
</props>
</constructor-arg>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver" />
<property name="url" value="jdbc:hsqldb:hsql://localhost:55511/chorke" />
<property name="username" value="admin" />
<property name="password" value="pa55word" />
</bean>
</beans>
Here is com.chorke.spring.bootstarp.HyperSqlDbServer
package com.chorke.spring.bootstarp;
import java.io.IOException;
import java.util.Properties;
import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.ServerAcl.AclFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.SmartLifecycle;
public class HyperSqlDbServer implements SmartLifecycle {
private final Logger logger = LoggerFactory.getLogger(HyperSqlDbServer.class);
private HsqlProperties properties;
private Server server;
private boolean running = false;
public HyperSqlDbServer(Properties props) {
properties = new HsqlProperties(props);
}
#Override
public boolean isRunning() {
if (server != null)
server.checkRunning(running);
return running;
}
#Override
public void start() {
if (server == null) {
logger.info("Starting HSQL server...");
server = new Server();
try {
server.setProperties(properties);
server.start();
running = true;
} catch (AclFormatException afe) {
logger.error("Error starting HSQL server.", afe);
} catch (IOException e) {
logger.error("Error starting HSQL server.", e);
}
}
}
#Override
public void stop() {
logger.info("Stopping HSQL server...");
if (server != null) {
server.stop();
running = false;
}
}
#Override
public int getPhase() {
return 0;
}
#Override
public boolean isAutoStartup() {
return true;
}
#Override
public void stop(Runnable runnable) {
stop();
runnable.run();
}
}
Edited:
As the following code snippet we are able to start hsqldb server on port 55511 in my local PC. But unable to start using Openshift JBoss EWS 2.0 inside spring context. Where there is an error occurred as following:
[Server#15a1792]: Initiating startup sequence...
[Server#15a1792]: [Thread[HSQLDB Server #15a1792,5,main]]: run()/openServerSocket():
java.net.BindException: Permission denied
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at org.hsqldb.server.HsqlSocketFactory.createServerSocket(Unknown Source)
at org.hsqldb.server.Server.openServerSocket(Unknown Source)
at org.hsqldb.server.Server.run(Unknown Source)
at org.hsqldb.server.Server.access$000(Unknown Source)
at org.hsqldb.server.Server$ServerThread.run(Unknown Source)
[Server#15a1792]: Initiating shutdown sequence...
[Server#15a1792]: Shutdown sequence completed in 4 ms.
[Server#15a1792]: 2016-03-23 23:41:21.881 SHUTDOWN : System.exit() was not called
Regarding this issue my questionnaires are as following:
How to achieve permission to open an custom server port Like hsqldb, h2db, MLLP, ActiveMQ, HornetQ?
Do we need extra configuration to access custom server port if we are able to open an custom server port?
If there is an configuration required, would you please provide us any guide line regarding this issue?
Finally I beg your help to open an custom server port Like hsqldb, h2db, MLLP, ActiveMQ, HornetQ and access it publicly from Openshift Gear/Cartridge.
I have AuthorJDBCDAO class with basic CRUD methods which extends AbstractJDBCDAO class and implements AuthorDAO interface.
I tested all methods via psv main() method and everything was fine.
But Now I have to test it's methods using DBUnit. And here my troubles start.
I try to test just only create() method and it isn't working properly.
I'm using Unitils, Spring DI, Oracle DB to create my application.
I inject bean DataSource(dbcp2) to beanAuthorJDBCDAO. I use XML configuration for injection beans.
Here's my source code and configuration files.
Test class.
#SpringApplicationContext({"spring-test-config.xml"})
#DataSet(value = "AuthorDAOTest.xml", loadStrategy = CleanInsertLoadStrategy.class)
public class AuthorDAOTest extends UnitilsJUnit4 {
#SpringBean("authorJDBCDAO")
private AuthorJDBCDAO authorDAO;
#Test
public void testCreate() throws DAOException {
Author expected = new Author();
expected.setName("BLABLABLA");
expected.setExpiredDate(Timestamp.valueOf(LocalDateTime.now()));
Author result = null;
result = authorDAO.create(expected);
assertEquals(expected.getId(), result.getId());
System.out.println("Hello from test");
}
Here's stacktrace from execution of Test class.
newsportal.exception.DAOException: java.sql.SQLException: Connection is null.
at newsportal.dao.impl.AbstractJDBCDAO.create(AbstractJDBCDAO.java:115)
at com.epam.ivanou.newsportal.dao.impl.AuthorJDBCDAOTest.testCreate(AuthorJDBCDAOTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:108)
at org.unitils.UnitilsJUnit4TestClassRunner$TestListenerInvokingMethodRoadie.runTestMethod(UnitilsJUnit4TestClassRunner.java:204)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.unitils.UnitilsJUnit4TestClassRunner$TestListenerInvokingMethodRoadie.runBeforesThenTestThenAfters(UnitilsJUnit4TestClassRunner.java:186)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.unitils.UnitilsJUnit4TestClassRunner.invokeTestMethod(UnitilsJUnit4TestClassRunner.java:95)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:59)
at org.unitils.UnitilsJUnit4TestClassRunner.access$000(UnitilsJUnit4TestClassRunner.java:42)
at org.unitils.UnitilsJUnit4TestClassRunner$1.run(UnitilsJUnit4TestClassRunner.java:60)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.unitils.UnitilsJUnit4TestClassRunner.run(UnitilsJUnit4TestClassRunner.java:67)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.sql.SQLException: Connection is null.
at org.apache.commons.dbcp2.DelegatingConnection.checkOpen(DelegatingConnection.java:608)
at org.apache.commons.dbcp2.DelegatingConnection.prepareStatement(DelegatingConnection.java:286)
at com.epam.ivanou.newsportal.dao.impl.AbstractJDBCDAO.create(AbstractJDBCDAO.java:106)
... 29 more
Fragment of code of AbstractJDBCDAO class. In which I get this exception. I tried to debug it and found, that in the second try-catch-with-resources block connection is null. But I can't understand, how does it occur if I try to get connection from DataSource which is BasicDataSource and support connection pooling.
#Override
public T create(T object) throws DAOException {
T persistInstance;
// Add the record
String sql = getCreateQuery();
String idName = getIdString();
String tableName = getTableName();
try (Connection connection = DataSourceUtils.getConnection(dataSource);
PreparedStatement statement = connection.prepareStatement(sql)) {
System.out.println("connection: "+ connection + " data source: " + dataSource);
prepareStatementForInsert(statement, object);
int count = statement.executeUpdate();
if (count != 1) {
throw new DAOException("On persist modify more then 1 record: " + count);
}
} catch (Exception e) {
throw new DAOException(e);
}
// Get recently inserted record
sql = getSelectQuery() + " WHERE " + idName + " = (SELECT MAX(" + idName + ") FROM "
+ tableName + ")";
try (Connection connection = DataSourceUtils.getConnection(dataSource);
PreparedStatement statement = connection.prepareStatement(sql)) //here is connection is null and SQLException is thrown {
System.out.println("connection: "+ connection + " data source: " + dataSource); //TODO connection is null in test method, but is good when using main() method
ResultSet rs = statement.executeQuery();
List<T> list = parseResultSet(rs);
if ((list == null) || (list.size() != 1)) {
throw new DAOException("Exception on findByPK new persist data.");
}
persistInstance = list.iterator().next();
} catch (Exception e) {
throw new DAOException(e);
}
return persistInstance;
}
here're configuration files for my beans:
dao-beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<bean id="authorJDBCDAO" class="newsportal.dao.impl.AuthorJDBCDAO">
<constructor-arg ref="dataSource"/>
</bean>
database-test-config.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-4.2.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>db_test.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxIdle" value="${jdbc.maxIdle}"/>
<property name="minIdle" value="${jdbc.minIdle}"/>
<property name="maxWaitMillis" value="${jdbc.maxWaitMillis}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
spring-test-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="database-test-config.xml" />
<import resource="dao-beans.xml" />
</beans>
db_test.properties
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#localhost:1521:xe
jdbc.username=Yahor_test
jdbc.password=1234
jdbc.maxIdle=100
jdbc.minIdle=10
jdbc.maxWaitMillis=10000
jdbc.initialSize=10
And here's Simple java class for testing:
public class Test {
public static void main(String[] args) throws DAOException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
AuthorJDBCDAO authorDAO = (AuthorJDBCDAO) ctx.getBean("authorJDBCDAO");
Author author = new Author();
author.setName("Yahor");
author = authorDAO.create(author);
System.out.println(author.getId());
}
And it's working fine =)
May be smth wrong with transactional configurations in my DBUnit Test class?
Problem is solved. I should close connection via DataSourceUtils.doReleaseConnection(). Otherwise connection will be closed physically. It was the keystone of my trouble.
Currently I am new to spring to trying to implement data-source with MySQL but I am facing a error but not able to understand what is main reason or error.
Exception in thread "main" java.lang.ExceptionInInitializerError
Apr 26, 2015 8:09:33 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#4ee70b: startup date [Sun Apr 26 20:09:33 IST 2015]; root of context hierarchy
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.springframework.context.support.AbstractRefreshableApplicationContext.createBeanFactory(AbstractRefreshableApplicationContext.java:194)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:127)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:465)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:395)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.rajdeo.jdbcspring.JdbcDemo.main(JdbcDemo.java:12)
Caused by: java.lang.NullPointerException
at org.springframework.beans.factory.support.DefaultListableBeanFactory.<clinit>(DefaultListableBeanFactory.java:104)
... 7 more
JdbcDemo.java
package com.x.jdbcspring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.x.jdbcspring.JdbcDaoImpl;
public class JdbcDemo {
public static void main(String[] args) {
ApplicationContext ctx= new ClassPathXmlApplicationContext("spring.xml");
JdbcDaoImpl dao=ctx.getBean("JdbcDaoImpl",JdbcDaoImpl.class);
/*
//JdbcDaoImpl dao=new JdbcDaoImpl();
Student student=ctx.getStudent(1);
System.out.println("name::\t"+student.getName());
JdbcDaoImpl jdbc=new JdbcDaoImpl();
jdbc.getStudent(1);
System.out.println(jdbc.getStudent(1).getId());*/
}
}
JdbcDaoImpl.java
package com.x.jdbcspring;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class JdbcDaoImpl {
#Autowired
private DataSource datasource;
public DataSource getDatasource() {
return datasource;
}
public void setDatasource(DataSource datasource) {
this.datasource = datasource;
}
public Student getStudent(int id){
Connection con = null;
Student student=null;
try{
/* Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");*/
con = datasource.getConnection();
PreparedStatement stmt=con.prepareStatement("select * from contact where contact_id =?");
stmt.setInt(1, id);
//Excute the query
ResultSet rs=stmt.executeQuery();
while(rs.next()){
String name=rs.getString("name");
student=new Student(id, name);
}
//close the statement and Resultset
stmt.close();
rs.close();
return student;
}catch(Exception e){
e.printStackTrace();
}
finally{
if(con!=null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return student;
}
}
Student.java
package com.rajdeo.jdbcspring;
public class Student {
private int id;
private String name;
public Student(int id, String name) {
// TODO Auto-generated constructor stub
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="com.rajdeo" />
<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/student" />
<property name="username" value="root" />
<property name="password" value="xxxx" />
</bean>
</beans>
What is error I am not able to understand it any help is appreciated.
Your spring.xml says to scan the package com.rajdeo for components, but your class JdbcDaoImpl is in package com.x.jdbcspring and so it will not be picked up, even though it has a #Component annotation.
Make sure to include the package that contains JdbcDaoImpl in the component scanning process:
<context:component-scan base-package="com.rajdeo, com.x.jdbcspring" />
Looks like you are getting a bean from the context
ctx.getBean("JdbcDaoImpl",JdbcDaoImpl.class)
but in the spring.xml this bean is not defined. As a result you get NPE = java.lang.NullPointerException.
To resolve this issue you have to configure JdbcDaoImpl service. E.g.
<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/student" />
<property name="username" value="root" />
<property name="password" value="xxxx" />
</bean>
<bean id="JdbcDaoImpl"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<property name="datasource" ref="datasource"/>
</bean>
I'm trying to write a simple application to learn how Transaction works in Spring (Declarative AOP Style). I'm inserting one record into customer table and then throwing NullPointerException to see if the inserted data is rolled back or not. But to my surprise it's not rolling back the data. Here is the code
ApplicationContext.xml file
<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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
">
<aop:aspectj-autoproxy />
<bean id="BoardingService" class="com.learning.maven.services.BoardingServiceImpl"/>
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<tx:method name="getUser*" rollback-for="throwable" propagation="REQUIRES_NEW"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="boardingServiceOperation" expression="execution(* com.learning.maven.services.BoardingService.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="boardingServiceOperation"/>
</aop:config>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:XE"/>
<property name="username" value="system"/>
<property name="password" value="Manager"/>
</bean>
<bean id="customerDAO" class="com.learning.maven.dao.CustomerDAOImpl">
<property name="dataSource" ref="dataSource" />
</bean>
This is how I call method
public static void main(String[] args) {
context = new FileSystemXmlApplicationContext("C:\\workspace\\learning\\cxf\\SpringTransaction\\cxf.xml");
BoardingService bean = (BoardingService) context.getBean("BoardingService");
bean.getUser("1");
}
And the BoardingService Class Looks like below
public class BoardingServiceImpl implements BoardingService, ApplicationContextAware {
ApplicationContext context = null;
public String getUser(String id) {
String response = "SUCCESS";
try{
System.out.println("Testing");
CustomerDAO customerDAO = (CustomerDAO) Testing.context.getBean("customerDAO");
Customer c = new Customer();
c.setAge(31);
c.setCustId(1);
c.setName("Jagadeesh");
customerDAO.insert(c);
customerDAO.insert(null);
}
catch(Exception e){
throw new RuntimeException();
}
return response;
}
#Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
this.context = arg0;
}
and the CustomerDAOImpl
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void insert(Customer customer) {
String sql = "INSERT INTO CUSTOMER (CUST_ID, NAME, AGE) VALUES (?, ?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, customer.getCustId());
ps.setString(2, customer.getName());
ps.setInt(3, customer.getAge());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
public Customer findByCustomerId(int custId) {
// TODO Auto-generated method stub
return null;
}
Not sure where am I going wrong. Any Pointers will be of great help.
You have rollback-for "throwable" instead of "Throwable".
P.S. Not sure that you should use REQUIRES_NEW as the default strategy.
update: From DataSourceTransactionManager documentation
Application code is required to retrieve the JDBC Connection via
DataSourceUtils.getConnection(DataSource) instead of a standard
J2EE-style DataSource.getConnection() call. Spring classes such as
JdbcTemplate use this strategy implicitly. If not used in combination
with this transaction manager, the DataSourceUtils lookup strategy
behaves exactly like the native DataSource lookup; it can thus be used
in a portable fashion.
In your case you open connection directly and then Oracle commits transaction on close(this is a feature of Oracle RDBMS).
You can also just omit the rollback-for attribute. Then it will rollback if any RuntimeException occurs.
I really hope you can help me. I've been looking all over the internet for answers and none of them works.
I use Spring 3 + JTA + EclipseLink but i'm getting a TransactionRequiredException when flushing a transaction. Now i'm very used to just defining my persistence context and injecting the EntityManager and the transaction is handled by the app server.
So here's what I've got.
persistence.xml
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="CartouchanPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>java:app/jdbc/CartouchanDS</jta-data-source>
<class>com.cartouchan.locator.database.models.Authority</class>
<class>com.cartouchan.locator.database.models.AuthorityPK</class>
<class>com.cartouchan.locator.database.models.User</class>
<class>com.cartouchan.locator.database.models.UserPK</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.ddl-generation" value="none"/>
<property name="eclipselink.target-database" value="MySQL"/>
<property name="eclipselink.jdbc.native-sql" value="true"/>
<property name="eclipselink.jdbc.cache-statements" value="true"/>
</properties>
</persistence-unit>
</persistence>
spring-config.xml
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<jee:jndi-lookup jndi-name="java:app/jdbc/CartouchanDS" id="CartouchanDS" />
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="autodetectUserTransaction" value="true" />
<property name="autodetectTransactionManager" value="true" />
<property name="transactionManagerName" value="java:appserver/TransactionManager"/>
</bean>
<context:annotation-config />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="CartouchanPU" />
<property name="persistenceUnitManager">
<bean class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"/>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
</property>
</bean>
CreateAccount.class
import java.text.MessageFormat;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class CreateAccount implements Controller {
private static final Logger logger = Logger.getLogger(CreateAccount.class);
// #Autowired
// private JtaTransactionManager transactionManager;
#PersistenceContext
private EntityManager entityManager;
#Transactional(propagation = Propagation.REQUIRES_NEW)
#Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info(MessageFormat.format("Called handle request", ""));
String username = ServletRequestUtils.getRequiredStringParameter(request, "username");
logger.info(MessageFormat.format("username {0}", username));
String password = ServletRequestUtils.getRequiredStringParameter(request, "password");
logger.info(MessageFormat.format("password {0}", password));
String passwordConfirm = ServletRequestUtils.getRequiredStringParameter(request, "passwordConfirm");
logger.info(MessageFormat.format("passwordConfirm {0}", passwordConfirm));
if (!password.equals(passwordConfirm)) {
throw new ServletRequestBindingException("Passwords don't match");
}
//transactionManager.getUserTransaction().begin();
User user = new User();
//try {
UserPK userPK = new UserPK();
userPK.setUsername(username);
user.setId(userPK);
user.setPassword(passwordConfirm);
user.setEnabled((byte) 1);
logger.info(MessageFormat.format("persist the user {0}", username));
entityManager.persist(user);
entityManager.flush();
// logger.info(MessageFormat.format("Before Refresh user {0}", username));
// entityManager.refresh(user);
// transactionManager.getUserTransaction().commit();
// } catch (Exception e) {
// logger.error(MessageFormat.format("Got an exception {0}", e.getMessage()), e);
// transactionManager.getUserTransaction().rollback();
// }
// transactionManager.getUserTransaction().begin();
// AuthorityPK authorityPK = new AuthorityPK();
// //try {
// logger.info(MessageFormat.format("Refreshed user {0} = {1}", username, user.getId()));
//
// authorityPK.setUserId(user.getId().getId());
// authorityPK.setAuthority(com.cartouchan.locator.models.Authority.ROLE_USER.toString());
// Authority authority = new Authority();
// authority.setId(authorityPK);
//
// logger.info(MessageFormat.format("Save the authority {0}", com.cartouchan.locator.models.Authority.ROLE_USER.toString()));
// entityManager.persist(authority);
// transactionManager.getUserTransaction().commit();
// } catch (Exception e) {
// logger.error(MessageFormat.format("Got an exception {0}", e.getMessage()), e);
// transactionManager.getUserTransaction().rollback();
// }
logger.info(MessageFormat.format("Go to /index.zul", ""));
ModelAndView modelAndView = new ModelAndView("index");
logger.info(MessageFormat.format("Return ", ""));
return modelAndView;
}
}
So here's the deal, when I uncomment the transactionManager parts, the program operates as expected, which is I can see the insert statements. However, when using the above code, I get the following stacktrace :
INFO: Starting ZK 5.0.7.1 CE (build: 2011051910)
INFO: Parsing jndi:/server/Cartouchan/WEB-INF/zk.xml
INFO: WEB0671: Loading application [Cartouchan-Web] at [/Cartouchan]
INFO: Cartouchan-Web was successfully deployed in 1,537 milliseconds.
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] Called handle request
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] username blah
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] password test
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] passwordConfirm test
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] persist the user blah
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: EclipseLink, version: Eclipse Persistence Services - 2.2.0.v20110202-r8913
CONFIG: connecting(DatabaseLogin(
platform=>MySQLPlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
CONFIG: Connected: jdbc:mysql://localhost:3306/Cartouchan
User: root#localhost
Database: MySQL Version: 5.1.51
Driver: MySQL-AB JDBC Driver Version: mysql-connector-java-5.1.11 ( Revision: ${svn.Revision} )
CONFIG: connecting(DatabaseLogin(
platform=>MySQLPlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
CONFIG: Connected: jdbc:mysql://localhost:3306/Cartouchan
User: root#localhost
Database: MySQL Version: 5.1.51
Driver: MySQL-AB JDBC Driver Version: mysql-connector-java-5.1.11 ( Revision: ${svn.Revision} )
INFO: file:/Applications/NetBeans/glassfish-3.1/glassfish/domains/domain1/eclipseApps/Cartouchan-Web/WEB-INF/classes/_CartouchanPU login successful
WARNING: StandardWrapperValve[cartouchan]: PWC1406: Servlet.service() for servlet cartouchan threw exception
javax.persistence.TransactionRequiredException:
Exception Description: No externally managed transaction is currently active for this thread
at org.eclipse.persistence.internal.jpa.transaction.JTATransactionWrapper.throwCheckTransactionFailedException(JTATransactionWrapper.java:86)
at org.eclipse.persistence.internal.jpa.transaction.JTATransactionWrapper.checkForTransaction(JTATransactionWrapper.java:46)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:1666)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:744)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
at $Proxy151.flush(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at $Proxy151.flush(Unknown Source)
at com.cartouchan.locator.controllers.CreateAccount.handleRequest(CreateAccount.java:56)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:112)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:680)
So as you can see, it connects correctly to the database, and it "persists" the data, but never actually execute the insert statement. Then when flushing the EM, it throws the exception.
Your help will be greatly appreciated.
Best Regards.
Ok, so I figured out how to get this working 100%.
First of all, I don't have to define any persistence(context/unit) in web.xml. Next I removed the transactionmanager and the entityManagerFactory beans. Also removed the context:driven line.
I also made my "beans" Stateless session beans. I then instantiate it through spring through jndi context lookups. This autowires the entitymanager exactly as i want it. No more worrying about transactions, the app server handles that.
so my final config is :
spring-config.xml :
<jee:jndi-lookup jndi-name="java:global/Cartouchan-Web/CategoryController" id="categoryController"/>
<jee:jndi-lookup jndi-name="java:global/Cartouchan-Web/UserController" id="userController"/>
<bean id="applicationContextProvider" class="com.cartouchan.locator.beans.CustomApplicationContext"></bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
bean sample:
import java.text.MessageFormat;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.log4j.Logger;
#Stateless
public class CategoryController {
private static final Logger logger = Logger.getLogger(CategoryController.class);
#PersistenceContext
private EntityManager entityManager;
public CategoryController() {
// TODO Auto-generated constructor stub
}
public boolean createCategory(final String name) {
boolean result = false;
try {
com.cartouchan.locator.database.models.Category category = new com.cartouchan.locator.database.models.Category();
category.setName(name);
entityManager.persist(category);
entityManager.flush();
result = true;
} catch (Exception ex) {
logger.error(MessageFormat.format("Could not create the category {0}", name), ex);
}
return result;
}
public boolean updateCategory(final int id, final String name) {
boolean result = false;
try {
com.cartouchan.locator.database.models.Category category = getCategory(id);
category.setName(name);
entityManager.merge(category);
entityManager.flush();
result = true;
} catch (Exception ex) {
logger.error(MessageFormat.format("Could not update for the category {0} -{1}", id, name), ex);
}
return result;
}
public boolean deleteCategory(final int id) {
boolean result = false;
try {
com.cartouchan.locator.database.models.Category category = getCategory(id);
entityManager.remove(entityManager.merge(category));
entityManager.flush();
result = true;
} catch (Exception ex) {
logger.error(MessageFormat.format("Could not delete for the category {0}", id), ex);
}
return result;
}
public com.cartouchan.locator.database.models.Category getCategory(final int id) {
return (com.cartouchan.locator.database.models.Category) entityManager.createQuery("select p from Category p where p.id=:id").setParameter("id", id).getSingleResult();
}
public List<com.cartouchan.locator.database.models.Category> getAllCategories() {
return (List<com.cartouchan.locator.database.models.Category>) entityManager.createQuery("select p from Category p").getResultList();
}
}
Then to use the bean, just do a standard spring lookup of the bean. Easy as pie.
In order to use JTA transactions managed by the application server you need to use EntityManagerFactroy created by the application server itself.
I.e. you need to remove your LocalContainerEntityManagerFactoryBean declaration and obtain EntityManagerFactory from the application server via <jee:jndi-lookup>. Also you should configure application server to create EntityManagerFactory - see your application server documentation.
See also:
13.5.1.2 Obtaining an EntityManagerFactory from JNDI
property name="eclipselink.target-server" value="WebSphere_7"
set the server type....
hope this one should work..
refer the docs for more details
http://docs.oracle.com/middleware/1212/toplink/TLADG/websphere.htm