How to do JNDI in Tomcat by using externalized Property file - java

I am just configuring tomcat for JNDI using the externalized. I have done some thing wrong, but no clue.
In Context.xml
<Resource name="jdbc/AppDB" auth="Container" type="javax.sql.DataSource"
driverClassName="org.postgresql.Driver"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
url="${app.env.database.url}"
username="${app.env.database.user}"
password="${app.env.database.password}"
maxActive="100"
maxIdle="50"
minIdle="10"
suspectTimeout="60"
timeBetweenEvictionRunsMillis="30000"
minEvictableIdleTimeMillis="60000"
validationQuery="select 1"
validationInterval="30000"
testOnBorrow="true"
removeAbandoned="true"
removeAbandonedTimeout="60"
abandonWhenPercentageFull="10"
maxWait="10000"
jdbcInterceptors="ResetAbandonedTimer;StatementFinalizer"
/>
While running the Tomcat , I am setting this
-DappProperties=c:/user/abc/app.properties
On Starting the server, I am getting below error.
Caused by: javax.naming.NamingException: Driver:org.postgresql.Driver#d8cf794 returned null for URL:${app.env.database.url}
at org.apache.naming.NamingContext.lookup(NamingContext.java:858)
at org.apache.naming.NamingContext.lookup(NamingContext.java:152)
at org.apache.naming.NamingContext.lookup(NamingContext.java:829)
at org.apache.naming.NamingContext.lookup(NamingContext.java:152)
at org.apache.naming.NamingContext.lookup(NamingContext.java:829)
at org.apache.naming.NamingContext.lookup(NamingContext.java:152)
at org.apache.naming.NamingContext.lookup(NamingContext.java:829)
at org.apache.naming.NamingContext.lookup(NamingContext.java:166)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:157)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:155)
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:179)
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:106)
at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:231)
at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:217)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
... 31 more
Can any one please help.
Please note : application is working good if I change ${app.env.} with actual values.
Thank you for your help

Are you using Maven? You need to use resource filtering plugin so maven will transform your property file values into actual values. Something like:
<build>
...
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
...
</resources>
...
Where the directory contains your xml file should work

Related

Error when configuring Datasource Oracle 11g into Apache Tomcat 7 (7.0.82)

I am trying to change the configuration in my application to use the datasource into the Apache Tomcat server with Oracle DB 11g, but it is throwing an error about SYS.AUD$ tablespace. Follow my configuration:
$TOMCAT_HOME/conf/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource auth="Container"
name="jdbc/oracleds"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:#HOSTNAME:PORT/SERVICENAME"
username="${db.user}"
password="${db.password}"
maxActive="20"
maxIdle="10"
maxWait="10000"
validationQuery="SELECT SYSDATE FROM DUAL"
/>
</Context>
While the server is loading the following exception is displayed into the console:
Jul 24, 2018 11:17:37 AM org.apache.tomcat.jdbc.pool.ConnectionPool init
SEVERE: Unable to create initial connections of the pool.
java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1
ORA-01653: unable to extend table SYS.AUD$ by 1024 in tablespace SYSTEM
ORA-02002: error while writing to audit trail
ORA-00604: error occurred at recursive SQL level 1
ORA-01653: unable to extend table SYS.AUD$ by 1024 in tablespace SYSTEM
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:389)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:382)
at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:600)
at oracle.jdbc.driver.T4CTTIoauthenticate.processError(T4CTTIoauthenticate.java:445)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:380)
at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:760)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:401)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:546)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:236)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:278)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:182)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:730)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:664)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:482)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:156)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:116)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:103)
at org.apache.tomcat.jdbc.pool.DataSourceFactory.createDataSource(DataSourceFactory.java:560)
at org.apache.tomcat.jdbc.pool.DataSourceFactory.getObjectInstance(DataSourceFactory.java:245)
at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:141)
at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)
at org.apache.naming.NamingContext.lookup(NamingContext.java:848)
at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
at org.apache.naming.NamingContextBindingsEnumeration.nextElementInternal(NamingContextBindingsEnumeration.java:117)
at org.apache.naming.NamingContextBindingsEnumeration.next(NamingContextBindingsEnumeration.java:71)
at org.apache.naming.NamingContextBindingsEnumeration.next(NamingContextBindingsEnumeration.java:34)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:138)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:145)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:110)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.lifecycleEvent(GlobalResourcesLifecycleListener.java:82)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:388)
at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:333)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:751)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.startup.Catalina.start(Catalina.java:694)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:294)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:428)
Try replacing the oracle.jdbc.OracleDriver with oracle.jdbc.driver.OracleDriver
RESOLVED I've discovered that my database FREE SPACE was very low (less than 100 MB) so I've asked the support team to fix it (increasing the memory available) and now the initial configuration has worked as expected.
Giving a look at another resolved question here I've found some interesting information about how to configure the Connection Pool in Tomcat server:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory ( 'v$session.osuser' , value is 'x')

Java Spring Tomcat: Custom DataSource Factory Being Ignored

I am working on a project that requires a database password to be resolved at run time. I am effectively doing this locally by specifying a DataSourceFactory within the Tomcat configuration. This process prevents any credential being stored in a plain text config file and gives us the custom control to resolve passwords at runtime. I have great success with this locally, but when I move my solution to a real/non-embedded Tomcat instance on AWS, I see this error:
Could not invoke the static newInstance method on the named factory
class "org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory".
To start, there are a few fishy details around this error message. Number one (as you'll see below), my factory class is being ignored in the tomcat config file despite the other credentials being valid (e.g. username, password, etc).
The code for my DataSourceFactory needs to reference a class to resolve a value.
Here is the xml configuration that I have for tomcat:
<?xml version='1.0' encoding='UTF-8'?>
<Context useHttpOnly="false">
<Resource auth="Container" name="mail/Session" type="javax.mail.Session"/>
<Resource name="jdbc/jndi"
auth="Container"
scope="Shareable"
type="javax.sql.DataSource"
useLocalSessionState="true"
cacheServerConfiguration="true"
useServerPrepStmts="true"
cachePrepStmts="true"
cacheCallableStmts="true"
elideSetAutoCommits="true"
alwaysSendSetIsolation="false"
enableQueryTimeouts="false"
prepStmtCacheSize="250"
prepStmtCacheSqlLimit="2048"
maxActive="100"
maxIdle="20"
maxWait="10000"
removeAbandoned="true"
driverClassName="com.mysql.jdbc.Driver"
url="${myURL}"
username="${myUsername}"
password="${myPasswordToResolve}"
factory="my.class.CustomDatabaseConfigurationFactory"
testOnBorrow="true"
testWhileIdle="true"
timeBetweenEvictionRunsMillis="20000"
poolPreparedStatements="true"
maxOpenPreparedStatements="50"
validationQuery="select 1"
validationInterval="60000"
defaultTransactionIsolation="READ_COMMITTED"
/>
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
<Loader loaderClass="org.apache.catalina.loader.ParallelWebappClassLoader" />
<Resource auth="Container"
name="jms/JMSConnectionFactory"
type="org.apache.activemq.pool.PooledConnectionFactory"
description="JMS Connection Factory"
factory="org.apache.activemq.jndi.JNDIReferenceFactory"
brokerURL="my.URL"
maxConnections="100"
maximumActiveSessionPerConnection="50"
expiryTimeout="10000"
/>
</Context>
I will not add the code of my my.class.CustomDatabaseConfigurationFactory because I know it works locally. For some reason, when I launch this using a remote configuration and setup, Tomcat completely ignores the custom factory I have put in place for the JNDI resource. Is there anything that I have to add to force Tomcat to look for my custom factory and not ignore it? I have almost the same configuration working on an embedded tomcat instance locally. On top of that, I don't see any clues in the logs that are related to a misconfigured file.
Here is the complete stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring/dataaccess/openjpa/openjpa.xml]: Invocation of ini\
t method failed; nested exception is <openjpa-2.4.0-ep2.1-runknown fatal user error> org.apache.openjpa.persistence.ArgumentException: Could not invoke the static newInstance method on the named fact\
ory class "org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory".
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1119)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:924)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5118)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5634)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:899)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:875)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:679)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1966)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java)
at java.lang.Thread.run(Thread.java:748)
Realistically, this problem should never occur when proper passwords are being resolved by a custom data factory.
A few things for anyone else who is having this issue:
On top of that, I don't see any clues in the logs that are related to
a misconfigured file.
This was a dead giveaway that something was not being loaded or loggers were not being set up properly. After I realized that log4j wasn't configured properly, I was able to see that my factory was in fact being loaded. Later on, after seeing the results, I was able to see that the passwords being set for the database were incorrect.
Although the log error was too high level and without enough detailed information, this issue was fixable with basic debugging methods and can be avoided with attention to logging.

Tomcat DBCP Running out of connections

I'm encountering a ORA-12519, TNS:no appropriate service handler found error when attempting to integrate Tomcat's JDBC Pool into my web application, using Oracle.
I typically see this error appear intermittently, after several minutes of running integration tests against the application.
The configuration I have is:
oracle driver and tomcat-dbcp jars in the tomcat/lib directory
two webapps, both using the same Resources. Configuration done in Spring:
<jee:jndi-lookup id="webDS" jndi-name="jdbc/web"
expected-type="javax.sql.DataSource" />
DataSource Resources defined in conf/context.xml, as follows:
<Resource name="jdbc/web" auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testWhileIdle="true"
testOnBorrow="true"
testOnReturn="false"
validationQuery="SELECT 1"
timeBetweenEvictionRunsMillis="30000"
maxActive="20"
maxIdle="10"
minIdle="5"
removeAbandonedTimeout="60"
removeAbandoned="false"
logAbandoned="true"
minEvictableIdleTimeMillis="30000"
jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
username="${database.user}"
password="${database.password}"
driverClassName="${database.driver}"
url="${database.url}" />
I've tried various suggestions made elsewhere on SO such as increasing or decreasing the maxActive size, but am having no luck thus far. I was previously using c3p0 to manage the pool of connections. With the switch, I'm wondering if there is some additional configuration I need to do that pertains to the closing of connections, because it seems like I'm leaking them.
The stack trace:
Caused by: org.hibernate.exception.GenericJDBCException: Could not open connection
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:124)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:221)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.connection(StatementPreparerImpl.java:56)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:159)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:183)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:157)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1881)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1858)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:906)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:348)
at org.hibernate.loader.Loader.doList(Loader.java:2550)
at org.hibernate.loader.Loader.doList(Loader.java:2536)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2366)
at org.hibernate.loader.Loader.list(Loader.java:2361)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:357)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:198)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1230)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:268)
... 112 more
Caused by: java.sql.SQLException: Listener refused the connection with the following error:
ORA-12519, TNS:no appropriate service handler found
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:489)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:553)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:254)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:528)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:278)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:182)
at org.apache.tomcat.jdbc.pool.PooledConnection.reconnect(PooledConnection.java:315)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:803)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:628)
at org.apache.tomcat.jdbc.pool.ConnectionPool.getConnection(ConnectionPool.java:187)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:128)
at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:70)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:301)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214)
... 132 more
Caused by: oracle.net.ns.NetException: Listener refused the connection with the following error:
ORA-12519, TNS:no appropriate service handler found
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:399)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1140)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:340)
... 146 more
Your validation query (SELECT 1) will not work in Oracle. It has to be select 1 from dual.
Seems that when using a wrong validation query the application is not able to identify healthy connections and and mark all of them as invalid.

shared c3p0 connection pool with hibernate and mysql on tomcat

Iam working on a project where i want to configure a shared connection pool with hibernate on tomcat.
The project is already implemented and i have to change it.
It was configured with hibernate and c3p0 connection pool where all jars where in the project itself.
I copied all jar files for connection pooling into the lib folder of tomcat.
c3p0-0.9.5.2.jar
c3p0-oracle-thin-extras-0.9.5.2.jar
mchange-commons-java-0.2.11.jar
mysql-connector-java-5.1.40-bin.jar
in server.xml i made a Resource
<Resource auth="Container"
description="DB Connection"
driverClass="com.mysql.jdbc.Driver"
maxPoolSize="40"
minPoolSize="10"
acquireIncrement="1"
name="jdbc/test"
user="admin"
password="root"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:mysql://localhost:3306/testDB" />
<ResourceLink
global="jdbc/test"
name="jdbc/test"
type="javax.sql.DataSource" />
after this i can see my connections created by the pool in phpmyadmin(mysql).
In my web.xml file of my project i created
a resource-ref.`
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/testDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
`
And my hibernate.cfg.xml file
`
</hibernate-configuration>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.datasource">java:comp/env/jdbc/testDB</property>
<mapping resource="Database.hbm.xml"/>
</hibernate-configuration>
Thats what i have done till yet. My problem is. In my project i have a sessionfactory where i set my hibernate.cfg.xml and Database.hbm.xml file.
This is now giving me a java.lang.NullPointerException.
Do i have to configure the sessionfactory also on tomcat as resource?
At Tomcat:
Jun 29, 2017 10:06:19 AM org.apache.catalina.mbeans.GlobalResourcesLifecycleListener createMBeans
SCHWERWIEGEND: Exception processing Global JNDI Resources
javax.naming.NamingException: Could not load resource factory class [Root exception is java.lang.ClassNotFoundException: myutil.hibernate.HibernateSessionFactoryTomcatFactory]
at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:82)
at javax.naming.spi.NamingManager.getObjectInstance(Unknown Source)
at org.apache.naming.NamingContext.lookup(NamingContext.java:842)
at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
at org.apache.naming.NamingContextBindingsEnumeration.nextElementInternal(NamingContextBindingsEnumeration.java:117)
at org.apache.naming.NamingContextBindingsEnumeration.next(NamingContextBindingsEnumeration.java:71)
at org.apache.naming.NamingContextBindingsEnumeration.next(NamingContextBindingsEnumeration.java:34)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:138)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:145)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:110)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.lifecycleEvent(GlobalResourcesLifecycleListener.java:82)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402)
at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:347)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: java.lang.ClassNotFoundException: myutil.hibernate.HibernateSessionFactoryTomcatFactory
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:80)
... 23 more
Jun 29, 2017 10:06:17 AM org.apache.tomcat.util.digester.Digester endElement
WARNUNG: No rules found matching 'Server/GlobalNamingResources/ResourceLink'.
Jun 29, 2017 10:06:17 AM org.apache.catalina.core.AprLifecycleListener init
INFORMATION: The APR based Apache Tomcat Native library which allows optimal
performance in production environments was not found on the java.library.path:
EDIT
What i have not mentioned, iam using OSGI equinox and a servlet bridge.
everything that i have configured is right, the only thing i had to change in my case was to change my launch.ini
i had:
osgi.parentClassloader=app
osgi.contextClassLoaderParent=app
changing it to
osgi.parentClassloader=app
osgi.contextClassLoaderParent=fwk <--- changed
here a link where i got my help from
also using
java:/comp/env/jdbc/testDB using a slash before comp solved my problem
in your server.xml Change to this :
<Resource auth="Container"
description="DB Connection"
driverClass="com.mysql.jdbc.Driver"
maxPoolSize="40"
minPoolSize="10"
acquireIncrement="1"
name="jdbc/testDB" <!-- change -->
user="admin"
password="root"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:mysql://localhost:3306/testDB" />
and :
<ResourceLink
global="jdbc/testDB" <!--change -->
name="jdbc/testDB" <!-- & change -->
type="javax.sql.DataSource" />
And your hibernate.cfg.xml file to
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.datasource">java:comp/env/jdbc/testDB</property> <!-- ? -->
<mapping resource="Database.hbm.xml"/>
</session-factory>
</hibernate-configuration>
restart catalina.
osgi.parentClassloader=app
osgi.contextClassLoaderParent=app
changing it to
osgi.parentClassloader=app
osgi.contextClassLoaderParent=fwk <--- changed
here a link where i got my help from when i had NoInitialContextException.
javax.naming.NoInitialContextException:Cannot instantiate class: org.apache.naming.java.javaURLContextFactory (root cause classnotfound for org.apache.naming.java.javaURLContextFactory)
also using java:/comp/env/jdbc/testDB instead of java:comp/env/jdbc/testDB (slash before /comp) solved a different problem i had on the linux tomcat server(JNDI lookup exception):
NameNotFoundException.

Springbatch failing | Could not roll back JDBC transaction

We have several jobs running in springbatch. We restarted the server this morning and afterwards we started having issues with two of the jobs. The BATCH_STEP_EXECUTION table shows the following exit message for each failed execution:
org.springframework.transaction.TransactionSystemException: Could not roll back JDBC transaction; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Connection.close() has already been called. Invalid operation in this state.
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doRollback(DataSourceTransactionManager.java:286)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:846)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:823)
at org.springframework.transaction.support.TransactionTemplate.rollbackOnException(TransactionTemplate.java:162)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:135)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:267)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:77)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:368)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144)
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:253)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:195)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:141)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:151)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:130)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:301)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:134)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.ja
This appears to be in relation to the mysql connection the application is making, however I'm not sure what could have caused this as the application was functioning fine before the reboot. Has anyone stumbled across this before?
EDIT
(caused by message that appears in the logs)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Connection.close() has already been called. Invalid operation in this state.
Datasource
javax.sql.DataSource
Connection Pool
Configured in context.xml file with the following format:
<?xml version="1.0" encoding="UTF-8"?>
<Context docBase="webapps/appname" mapperContextRootRedirectEnabled="true" mapperDirectoryRedirectEnabled="true" path="/appname" reloadable="false" >
<Resource name="jdbc/springbatchmeta"
auth="Container"
type="javax.sql.DataSource"
username="${jobmeta.username}"
password="${jobmeta.password}"
driverClassName="${mysql.driverClass}"
url="${jobmeta.url}"
initialSize="2"
maxTotal="20"
maxIdle="10"
minIdle="2"/>
<Resource name="jdbc/firstjob"
auth="Container"
type="javax.sql.DataSource"
username="${firstjob.username}"
password="${firstjob.password}"
driverClassName="${mysql.driverClass}"
url="${firstjob.url}"
initialSize="2"
maxTotal="20"
maxIdle="10"
minIdle="2"/>
<Resource name="jdbc/secondjob"
auth="Container"
type="javax.sql.DataSource"
username="${secondjob.username}"
password="${secondjob.password}"
driverClassName="${secondjob.driverClass}"
url="${secondjob.url}"
initialSize="2"
maxTotal="20"
maxIdle="10"
minIdle="2"/>
</Context>
This issue was caused by the wait-timeout option in mysql being set to 60 seconds, as most of the jobs we are running take over a minute to complete.

Categories

Resources