CQ DataSourcePool java.lang.IllegalStateException: Pool not open - osgi

I have configured Adobe CQ to use connection pooling to handle connections with MySql database. Everything works fine, but after a few hours I see this exception while trying to connect to database.
Caused by: java.lang.IllegalStateException: Pool not open
at org.apache.commons.pool.BaseObjectPool.assertOpen(BaseObjectPool.java:99)
at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:917)
at org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:96)
I have seen such errors being reported in several instances/applications. I wanted to know if there is something wrong with the way this works on CQ.
I am using CQ5.6.1 and below is the code snippet I use to get a connection
#Reference
private DataSourcePool dataSourceService;
DataSource ds;
Connection connection;
try{
ds = (DataSource) dataSourceService.getDataSource("datasource_name);
connection = ds.getConnection();//this line causes the exception
catch(Exception e){
e.printStackTrace();
}finally{ connection.close(); }
This is my datasource configuration
Is there anything that I am missing?
Thanks!

I had the similar problem. You need to double check your configurations. Check in OSGI, check on your code every little detail for your database settings. These are the two things to look at. Then try to install the bundle/package again.

Related

org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection

I sometimes notice below mentioned error in my springboot app logs.
org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
I suspect it could be because of exception thrown from #Transactional method ( only at times though).
Is it Ok to throw excaption from #Transactional method? or it is a bad practice?
Here is my service layer code
#Override
#Transactional
public void updateMessageStatus(String status, String sid, String errorCode) throws NotFoundException {
OutgoingMessage outgoingMessage = outgoingMessageRepository.findByResourceSid(sid);
if (outgoingMessage == null) {
throw new NotFoundException(ErrorCode.MESSAGE_NOT_FOUND, sid);
}
outgoingMessage.setStatus(status);
outgoingMessage.setUpdatedTime(Calendar.getInstance().getTime());
outgoingMessageRepository.save(outgoingMessage);
}
This usually happens when app is idle for longer time than the server’s connection timeout period.
So if a connection has been idle longer than this timeout value, it will be dropped by the server. By default, Hibernate uses its internal database connection pool library,
keeping the connection open to be reused later.
Hibernate reuses the idle connection which was already dropped by the server, hence we get JDBCConnectionExceptionis error.
What I noticed is even with the following database auto-reconnect setup should not work in this case.
spring.datasource.validation-query=select 1
spring.datasource.testOnBorrow=true
May be need to increase the pool size OR Entity Manager needs to be closed once the transaction is done.
spring.datasource.hikari.maximum-pool-size=10.
Please let me know if this worked for you.

Is it possible to have a remote pooled JMS connection factory (WildFly 10)?

I have a remote java client which looks up a JMS connection factory on Wildfly 10, and everything works fine as expected. It is just a test program; a simple JMS chat system. When I start more than one instance of the chat client sometimes the following message appears:
WARN: AMQ212051: Invalid concurrent session usage. Sessions are not supposed to be used by more than one thread concurrently.
Followed by a trace.
Now I want to fix this warning, therefore I need a pooled connection factory. But the pooled connection factory isn't available remotely (and as I read it shouldn't be available remotely).
What can I do to fix this warning when I want to start multiple JMS chat clients locally?
I know that the error won't appear when I just different machines.
This is the working non-pooled remote code (but with warning)
final Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
properties.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080");
try {
context = new InitialContext(properties);
ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("jms/RemoteConnectionFactory");
jmsContext = connectionFactory.createContext("quickstartUser", "quickstartPwd1!");
} catch (NamingException e) {
e.printStackTrace();
}
The problem isn't caused by not using a pooled connection factory and won't be solved by using a pooled connection factory. The problem is the way your application is using the same JMS session concurrently between multiple threads (as the WARN message indicates). The stack-trace which is logged will show you which class & method is triggering the WARN message.
You need to ensure that your application does not use the same JMS session concurrently between multiple threads. You can do this by giving each thread its own JMS session or by setting up concurrency controls around the session so that only one thread at a time can access it.

Specified JDBC Driver: org.h2.jdbc - initialization failed

Can't connect to database.
I also added the latest h2-1.4.178.jar to classpath, create table, check connection through tools.
It's working, but Tomcat said: "HTTP Status 500 - com.vaadin.server.ServiceException: java.lang.RuntimeException: Specified JDBC Driver: org.h2.jdbc - initialization failed."
How can I call it? I use Eclipse. This is my src (I use Vaadin):
try {
JDBCConnectionPool pool = new SimpleJDBCConnectionPool(
"org.h2.jdbc",
"jdbc:h2:~test", "SA", "", 2, 5);
screen.polulate("TEST", pool);
} catch (SQLException e) {
throw new RuntimeException(e);
}
I found my problem (https://superuser.com/questions/290999/where-can-i-find-h2-jdbc-driver), but i cant understand what does it mean:
And then call
Class.forName("org.h2.Driver");
The answer you link to is not really relevant to your problem. The problem probably (educated guess) is that the first parameter of the constructor of SimpleJDBCConnectionPool expects the JDBC driver name, and "org.h2.jdbc" is not the JDBC driver name (it's "org.h2.Driver").
Using Class.forName("org.h2.Driver"); is no longer necessary for modern JDBC drivers. With old drivers (that don't include a file META-INF/services/java.sql.Driver with its driver implementation(s)) using Class.forName("org.h2.Driver"); will load the driver and then the driver will register itself with java.sql.DriverManager so it can be used to create connections.

Pre-bound JDBC Connection found

We have an app that is using hibernate, spring, and DB2 in websphere 7. We have audit triggers and we need to set so the triggers can know the logged in user (we use generic logon to the database). We came up with a new scheme for setting this in a new app so that it can automatically join in new transactions. We overrode the transaction manager and did the work in the doBegin.
These scheme worked great in one app, and seemed to work great in a second app, but now, weeks later, and not consistently (behavior is intermittent and does not happen in local development), we are getting this Pre-bound JDBC Connection found error. Looking online most posts say this is when you use two transaction managers against one data source. That is now what we are doing.
I also read one post wondering if it was because he mixed annotation and AOP based transactions. This app does some of that. I don't really buy that theory, but thought I'd mention it.
Exception:
Caused by:
org.springframework.transaction.IllegalTransactionStateException: Pre-bound JDBC Connection found! HibernateTransactionManager does not support running within DataSourceTransactionManager if told to manage the DataSource itself. It is recommended to use a single HibernateTransactionManager for all transactions on a single DataSource, no matter whether Hibernate or JDBC access.
at java.lang.Throwable.<init>(Throwable.java:67)
at org.springframework.core.NestedRuntimeException.<init>(NestedRuntimeException.java:54)
at org.springframework.transaction.TransactionException.<init>(TransactionException.java:34)
at org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:475)
at gov.usdoj.afms.umc.utils.hibernate.AfmsHibernateTransactionManager.doBegin(AfmsHibernateTransactionManager.java:28)
Code (note that the exception comes from the super.doBegin()):
protected void doBegin(Object arg0, TransactionDefinition arg1) {
super.doBegin(arg0, arg1);
if (!Db2ClientInfo.exists()) {
clearDBProperty();
} else {
setDBProperty(Db2ClientInfo.getClientUserId(), Db2ClientInfo.getClientApplicationId());
}
}
private void setDBProperty(String uId, String appName) {
Session session = getSessionFactory().getCurrentSession();
Properties props = new Properties();
props.setProperty(WSConnection.CLIENT_ID, uId);
props.setProperty(WSConnection.CLIENT_APPLICATION_NAME, appName);
try {
Connection nativeConn = new SimpleNativeJdbcExtractor().getNativeConnection(session.connection());
if (nativeConn instanceof WSConnection) {
WSConnection wconn = (WSConnection) nativeConn;
wconn.setClientInformation(props);
} else {
logger.error("Connection was NOT an instance of WSConnection so client ID and app could not be set");
}
} catch (Exception e) {
throw new RuntimeException("Cannot set DB parameters!", e);
}
}
I just realized I never answered this. It turns out that the exception had nothing whatever to do with our Tx manager. It was the fact that this particular EAR has two apps in it, each pointing to the same data source. Evidently this confuses hibernate. We've plans to separate the apps some day, but creating an identical (except in name) data source and pointing the apps at them separately fixes the issue for now.
Instead of modifying the transaction manager it might be easier (better?) to create a wrapper around your datasource (extending DelegatingDataSource from spring) and override the 2 getConnection methods. For the cleanup you could wrap the connection in a proxy and intercept the close method.
That should be a safer (and easier I guess) way then trying to fiddle with the transaction manager and it works for every technology (JDBC, Hibernate, JPA etc.) as long as you use the wrapped datasource. (The registration could be done with a BeanPostProcessor which detects DataSource instances and simply wraps them in the delegate).
If that is to radical (as it means changing your current applications instead of updating a library). It could be a configuration problem, make sure that you are only loading your configuration (and thus DataSource and TransactionManager) only once, duplicating bean instances might lead to a similair behavior.
For posterity, I just got this problem and the answers here weren't very helpful. We resolved the problem by removing a double import of a core XML file which had the AOP transaction manager definition in it:
<tx:annotation-driven transaction-manager="..."
proxy-target-class="true" />
I'm thinking that it causes there to be 2 transaction managers overlapping the same namespace. To fix it, we moved the imports around so they were being done once.
Hope this helps someone else.

how to change Java code to access database using JDBC after creating JDBC connection pool in GlassFish?

I'm new to JDBC. I've installed GlassFish 3.1.1 on Centos 6.2 and need to use it with an application that connects to an Oracle 11G database on another server. I've read through the documentation for GlassFish and think I understand how to create a JDBC connection pool as well as a JDBC resource. My question is, how do I use this information when coding the java middle-tier to connect to the database?
Currently (with just GlassFish install and no JDBC configuration), I am relying on the CentOS enviroment variables for java (such as CLASSPATH) to allow the web application to use the JDBC drivers. However, I'm getting the following error:
java.lang.NoClassDefFoundError: oracle/jdbc/pool/OracleDataSource
Thus, my attempt to create a JDBC connection pool and resource in GlassFish (so the app can use the JDBC driver). My java file starts out:
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
class JDBCexample {
public static void main(String args[]) throws SQLException {
Connection conn;
Statement stmt;
ResultSet rset;
String query;
String sqlString;
String person_firstName;
String person_lastName;
String person_email;
int person_salary;
// connect to database
OracleDataSource ds = new OracleDataSource();
ds.setURL("jdbc:oracle:thin:myID/myPWD#192.168.0.1:1521:mySID");
conn = ds.getConnection();
// read something in database
stmt = conn.createStatement();
query = "SELECT first_name, last_name, email, salary FROM HR.Employees where rownum < 6";
rset = stmt.executeQuery(query);
while (rset.next()) {
person_firstName = rset.getString("first_name");
person_lastName = rset.getString("last_name");
person_email = rset.getString("email");
person_salary = rset.getInt("salary");
System.out.format(person_firstName + " " + person_lastName + " " + person_email + " %d%n", person_salary)
}
and so on...
QUESTION: How would I change the above code after I create a JDBC Connection Pool (named: myPool) and a JDBC Resource (named: myDBPool)? If it matters, I'm using Oracle 11.2, CentOS 6.2, GlassFish 3.1.1 with mod_jk and fronted by Apache 2.2 webserver, JDK 1.6. I don't have any clustering or load-balancing.
UPDATE 1: I thought this link was a good reference (see section titled: "Creating a Data Source Instance, Registering with JNDI, and Connecting"). But when I modify the above Java file as follows (just preparing the java file; haven't touched GlassFish yet),
// Add These:
import javax.naming.Context;
import javax.naming.InitialContext;
// Change from this:
// connect to database
OracleDataSource ds = new OracleDataSource();
ds.setURL("jdbc:oracle:thin:myID/myPWD#192.168.0.1:1521:mySID");
conn = ds.getConnection();
// To this:
// connect to database
Context ctext = new InitialContext();
OracleDataSource ds = (OracleDataSource)ctext.lookup("jdbc/myDBPool");
conn = ds.getConnection();
I get the errors:
JitterClass.java:67: unreported exception javax.naming.NamingException; must be caught or declared to be thrown
Context ctext = new InitialContext();
^
JitterClass.java:68: unreported exception javax.naming.NamingException; must be caught or declared to be thrown
OracleDataSource ds = (OracleDataSource)ctext.lookup("jdbc/myDBPool");
^
UPDATE 2: I cleared those compile errors using cyril's comments below (to throw all exceptions). Then I created JDBC Connection Pool and JDBC Resource, and the Ping was successful. So then I run the application from the client and observe the following error:
java.lang.ClassCastException : com.sun.gjc.spi.jdbc40.DataSource40 cannot be cast to oracle.jdbc.pool.OracleDataSource
At this point, if I add an include javax.sql.DataSource to the program, and change this line:
OracleDataSource ds = (OracleDataSource)ctext.lookup("jdbc/myDBPool");
to become this line:
DataSource ds = (DataSource)ctext.lookup("jdbc/myDBPool");
it compiles without errors. But now I'm confused... aren't we supposed to be using OracleDataSource here? Or, does GlassFish somehow implement OracleDataSource since I do see a setting for this connection pool for Datasource Classname set to oracle.jdbc.pool.OracleDataSource (?). Hoping someone can explain this.
Do pings on your connection pool work?
If not, check your pool configuration w/ http://docs.oracle.com/cd/E18930_01/html/821-2416/beamw.html#beanh
Once pings work and the JDBC Resource is configured, you should be able to access it in your app code through JNDI:
InitialContext context = new InitialContext();
DataSource ds = (DataSource) context.lookup("jdbc/myDBPool"); // or whatever name you used when creating the resource
conn = ds.getConnection();
Hope it helps,
RESPONSE TO UPDATE 1:
That's just the compiler telling you to formally catch or declare a checked exception which may be thrown by JNDI.
For testing purposes, the easiest way out of this (and future errors like this) is to just widen your method signature to throw all exceptions, i.e.:
public static void main(String args[]) throws /*SQL*/Exception {
RESPONSE TO UPDATE 2:
There's no reason to cast JDBC interfaces down to Oracle implementations unless you need to access any custom feature not specified in the JDBC spec. The purpose of a DataSource is to be a factory for Connections, whose API is defined in the JDBC interface, so that should be all you need. When you define a connection pool and resource in GlassFish, the app server is adding value by wrapping the JDBC driver classes and proxying them seamlessly for you as long as you stick to import java.sql.*. No need for oracle imports :) The main advantage being that if you ever decide to switch to MySQL or some other data store later on, your code is then portable and doesn't need any change.
To add to cyril's good answer:
Instead of the JNDI lookup, you can also use Resource Injection to set up your DataSource:
#Resource(name = "jdbc/Your_DB_Res")
private DataSource ds;
On startup, the application server will then inject the JDBC ressource. This section of Java EE Tutorial has more on that matter.
By using resource injection, you can reduce the amount of boilerplate code. This article introduces the concepts.
Besides adding the driver to your classpath, you should try adding the appserv-rt.jar file to your project's build path (the jar is located in Glassfish's lib directory). If you don't want to include all the other jars you should first create a library containing the appserv-rt jar and then add it to your project's build path.

Resources