I am trying to downcast java.sql.Connection to org.postgresql.jdbc4.Jdbc4Connection like this:
As you can see, Netbeans tells me localConn is ($Proxy6) org.postgresql.jdbc4.Jdbc4Connection#5894585b, and it is not an instance of org.postgresql.jdbc4.Jdbc4Connection.
So here are my questions:
What does ($Proxy6) org.postgresql.jdbc4.Jdbc4Connection#5894585b mean?
How can I get org.postgresql.jdbc4.Jdbc4Connection from it?
Thanks,
Update Information:
localConn instanceof org.postgresql.jdbc4.Jdbc4Connection returns false.
update
I use Mybatis.
I suppose that you are using iBatis/MyBatis. If so, there is a static method on com.ibatis.common.jdbc.SimpleDataSource that returns the unwrapped connection:
public static Connection unwrapConnection(Connection conn)
This method will return the real connection without the proxy, and you will can do the downcast.
A Proxy class is a class that wraps an existing Interface and lets you intercept calls
made to the object.
This causes a problem in that the proxy will only recognise that it is of that interface
type. Which in this case is most likely to be javax.sql.Connection.
you could try this
Connection conn = localConn.createStatement().getConnection();
Related
I came across some JMS calling code that initializes the JMS session inside of its constructor. The calling code implements the ExceptionListener interface and passes a reference to this to the connection factory object, as shown below:
public class JmsCode implements ExceptionListener {
private static final Logger logger = LoggerFactory.getLogger(JmsCode.class);
public JmsCode(String url, String username, String password, String trustStorePath, char[] trustStorePassword) throws JMSException {
ActiveMQSslConnectionFactory connectionFactory = new ActiveMQSslConnectionFactory(url);
connectionFactory.setUserName(username);
connectionFactory.setPassword(password);
connectionFactory.setTrustStore(trustStorePath);
connectionFactory.setTrustStorePassword(new String(trustStorePassword));
connectionFactory.setExceptionListener(this);
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
#Override
public void onException(JMSException e) {
logger.error("Unexpected JMS exception caught", e);
}
}
I am wondering if it is safe to pass a reference to this from the JmsCode constructor given that the object hasn't been fully constructed yet. I came across a similar question which had me reading up on IBM's article on not publishing this during construction. While I agree with their reasoning, I am not sure if it applies in this case since the only thing the exception listener is doing is logging via a static and final member. Is the code above safe (ignoring someone else being tempted to change the exception listener method to use some instance state of the object)?
This is in fact unsafe publishing, and it's theoretically possible for another object to see this one in an inconsistent state.
That said, while this isn't a good pattern (and it's just shown here to demonstrate ExceptionListener), the logic of the constructor shows that the class is in fact fully constructed by the time that the this reference escapes (because it has nothing to construct), and so in this exact case there's nothing that can go wrong.
Whether it is safe or not depends on where that reference to this can escape to. If, as a consequence of this call, this could be read by another thread, then it is not safe.
If you want to ensure an instance is completely initialized for safe publication and you want to publish it, a constructor isn't the right place to publish it. Instead, you'll need to create a Factory object or a static factory method which can construct the object safely and then publish it before returning it to the caller.
It is completely safe. You are just passing the this reference, not using anything in the this scope.
Something will go wrong on that iff the .setExceptionListener(this) method performs something else than being a setter.
I have two class as A and B-
Class A:- This class has getData method, which is used to get data from DB.
class A {
public synchronized getData() {
// get some data from database, in finally block close connection
}
}
Class B:- Which has recursion method m(), inside this method I am calling the getData() of class A.
class B {
m() {
//some condition to terminate the recursion
A a = new A();
a.getData();
m();
}
}
Error I am getting:-
java.lang.NullPointerException: null
at com.mchange.v2.c3p0.impl.NewProxyConnection.getAutoCommit(NewProxyConnection.java:1226) ~[c3p0-0.9.5.1.jar:0.9.5.1]
For the first call of getData() method, I am able to get data from DB, but after second recursion onward I am getting the connection as closed. Any help would be highly appreciated.
Update:
I have DB Util method which is opening the connection each time when getData() method is calling. It's working fine if I am calling this without recursion method(many times) but if I am using recursion I'm getting error. Is any special case I have to handle for recursion method?
The error specifies that connection is closed. Also, in your comment // get some data from database, in finally block close connection, you have mentioned that you have closed the connection after use but, you didn't mentioned that if you are opening the connection in he getData() method or not.
I would suggest following:
Check if you are opening the connection in getData() method. If not then either open the connection in this method only(remove the code for opening connection from some other method) or don't close the connection after use in this method instead use a different method to close the connection as per need.
Check if connection resource is reusable.
DAOClass.makeDBConnection() method returns datasource configured (using lookup) in Application Server (Jboss). Need to implement junit test case for this scenario.
Using Mockito, tested the DAO method as follows. As it's not able to find the datasource(as expected), it's returning NullPointerException. How to handle NullPointerException and return the connection which i am creating in below code? OR is there any other better unit test framework which handles this scenario ?
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://DB:1433;DatabaseName=databasename", "userid", "password");
when(DAOClass.makeDBConnection()).thenReturn(conn);
Mockito can't mock static method calls the way you have it; it effectively works by dynamically overriding all methods via a generated subclass (proxy).
You will need to write a wrapper class around static methods that you want to mock, otherwise refactor the code to avoid the static call, or use a tool such as PowerMock to rewrite your system's bytecode at runtime.
I'm trying the use reflection to invoke a method that has a java.sql.Connection as argument.
public void setAndValidateSessionUUID(java.lang.String, java.sql.Connection);
I am on a Websphere 7 context using a jndi path to retrieve the data source and it's connection.
private java.sql.Connection connection;
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(this.DataSourceJNDIPath);
this.connection = dataSource.getConnection();
I have the following piece of code to retrieve the method using reflection
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... args) throws SecurityException, NoSuchMethodException {
return clazz.getMethod(methodName, args);
}
But when I try to retrieve the method it gives me the following error:
java.lang.NoSuchMethodException: setAndValidateSessionUUID(java.lang.String, com.ibm.ws.rsadapter.jdbc.WSJdbcConnection)
I have no problem executing the method without reflection but using it I can't retrieve the method.
Any ideas?
The server returns proxy objects, which you can observe via dataSource.getClass(). On WAS 8.0 and later, you can use the java.sql.Wrapper APIs to call vendor-specific APIs, but on WAS 7.0 and later, you'll need to use WSCallHelper.jdbcCall.
Yes. You may want to read my blog post here but basically, you need to iterate all of the classes methods for (Method method : cls.getMethods()) until you find one where each (and every) method parameter isAssignableFrom your input parameters...
if (!mTypes[i].isAssignableFrom(parameters[i]
.getClass()))
If it is, store it with toInvoke = method. Then use
toInvoke.invoke(receiver, parameters);
Under .net (specifically C# really), is there an equivalent to Java's DataSource class? I'm used to creating a single DataSource (pooled or non-pooled) and passing it around to objects that require creating new database connections. Helpful in decoupled/dependency injection situations.
However under .net, instantiating a new SqlConnection seems to come from a pool if you use the same connection string. Does that mean you should pass around a connection string (or connection string builder) to your DAO pattern classes, just pass around the single Connection object or create a new ConnectionProvider like class?
eg
class SomethingDao {
DataSource dataSource;
Something getSomething(int id) {
connection = dataSource.GetConnection();
connection.CreateCommand();
... etc
}
}
The Enterprise Library takes care of virtually all of these details for you, so I recommend you consider using it and following the example code shown here:
http://msdn.microsoft.com/en-us/library/ff953187%28v=PandP.50%29.aspx
This link walks you through using it step-by-step. The equivalent using Ent Lib would be the Database class. It has all the code examples, so I won't repeat them here.