Calling Method of another class from Recursion Method: Java - java

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.

Related

INVOKE_CHAINCODE failed: transaction ID exists

I have a chaincode with two contracts such that the second contract invoke a transaction of the first one as follows:
class ContractA implements ContractInterface{
.....
#Transaction
public boolean trans1(MyContext ctx, String data) {
...
return result;
}
}
class ContractB implements ContractInterface{
.....
#Transaction
public boolean trans2(MyContext ctx, String data) {
...
Chaincode.Response response = ctx.getStub().invokeChaincode(chaincodeId,
new String[]{ContractA:trans1, "data"});
...
}
}
During the execution of trans2, the invokeChaincode fails with the error: "INVOKE_CHAINCODE failed: transaction ID exists". According to the documentation, no other transaction will be created by calling invokeChaincode, therefore, it is correct that the invocation is created with the same transaction ID.
Is it a bug or am I doing something incorrect in my design?
Many thanks in advance,
Roxana
Performing ctx.getStub().invokeChaincode(chaincodeId, new String[]{ContractA:trans1, "data"}); is asking the peer to perform a chaincode to chaincode invocation, to itself. Recursively calling chaincode is not supported.
The error message here could probably be improved, but essentially, resources are allocated for a chaincode invocation, associated to a txid, which are then cleaned up when the transaction finishes. Because your transaction is already interacting with your chaincode, these resources already exist, and attempting to create them results in the error you see returned.
If you wish to call another function within your own chaincode, simply invoke it as a normal function, rather than attempting to invoke it via the chaincode stub.

How to properly cleanup incorrectly initialized object?

I was asked this question in an interview.
There is a class, lets call it A. It has a default constructor and it initializes 2 different connections in its constructor.
Methods initDB & initSocket creates a DB connection and a socket connection and saves them in an instance field. They are just an example. They could also be file open or anything else.
Lets say a client instantiates an instance of this class. Now initDB executed successfully, but initSocket threw exception. So the object creation was aborted. But the DB connection was not closed prior to the exception. This resulted in a resource leak. How would I tackle this kind of resource leak?
E.g.
class A {
public A(){
this.dbConnection = initDB();
this.socketConnection = initSocket(); // throws exception
}
}
My initial answer was that I would not initialize these in constructor but in a separate init(). He countered by suggesting that this could be a legacy class, and I have been asked to maintain this. In which case I need to somehow clear the resource leak. How would I approach this problem?
I got stumped because instance creation threw an exception I lost any kind of reference to those connection fields. So I cannot call close() on them. But they will still be present in the OS level (this is my guess).
Note 1
As stated by Interviewer, I cannot change the behavior of the already written constructor. I can extend or do something around it, but cannot change the code.
Note 2
I think interviewer was not looking for explicitly any code that would handle this scenario. Would any JMX stuff help? I took a jibe at it & then we moved on. For those who think this is a very good question, I think interviewer knew this is not a general practice and probably would not be able to answer.
We have a few options here...
Box the thing off somewhere else. It's clearly problematic legacy code. Perhaps this "blob" which has access control issues can be moved into something some other process that can communicate with the rest of the system via RPC. You are better off doing this if the system is horribly broken. You can extend it other ways, such as composition; but if it's so sealed off you can't get it it, then you're boned
Use byte code modification. You could do this and you could get enough leverage to get what you need. ByteBuddy would come in handy for this. I wouldn't do this personally but hey, sometimes desperate measures call for desperate solutions...
If you can influence initDB, then you can decorate the return value with something else. For example, let's supposed it was some from some base class we did control or some other method we controlled, then we could perhaps do something like this
Connection initDb() {
try {
this.wrappedProvider.initDb();
} catch(Exception e) {
// .. destroy the connection...
}
}
... and then since you can influence this, you can change the effective semantics of it.
Can you influence the "Connection" of "A"? How does it get "A"? If it gets it from some DI container or something you can influence, then you can sub out the implementation for that class for something that "times out" if not talked to or initialized in some given time. Hacky, sure but without more info that's the best we're going to get...
Solution 1:
Provided that:
You can extend class A, and then use instances of class B instead,
method initSocket is overridable (not final nor private)
field dbConnection is accessible from class B (not private)
You can override method initSocket to close the dbConnection in case of an exception:
#Override
protected Socket initSocket() {
boolean ok = false;
try {
Socket result = super.initSocket();
ok = true;
return result;
} finally {
if (!ok) {
dbConnection.close();
}
}
}
Solution 2:
Provided that:
You can extend class A
method initDb is overridable (not final nor private)
You can wrap your A object in another class, and save the connection so that it can be closed in case of an exception:
class B {
private static ThreadLocal<Connection> CONNECTION = new ThreadLocal<>();
private final A delegate;
public B() {
boolean ok = false;
try {
delegate = new A() {
#Override
protected Connection initDb() {
Connection result = super.initDb();
CONNECTION.set(result);
return result;
}
};
ok = true;
} finally {
if (!ok) {
Connection cnt = CONNECTION.get();
if (cnt != null) {
cnt.close();
}
}
CONNECTION.set(null);
}
}
}

how can I test a void method that insert a record in database using Junit?

I have a method that calls another method to retrieve data and insert it into the database, how can I test this method in Junit since this method retrieve nothing? Can anyone provide me some example of this situation?
public static void method(){
User user = getUser();
try {
String Query = "INSERT INTO users (USER_ID , Name) VALUES ("
+user.getID()+","+user.getName()+")";
Statement statement = conn.createStatement();
statement.executeUpdate(Query);
} catch (Exception e) {
e.printStackTrace();
}
}
I was thinking to use mock object for user, but I'm not sure how can I check if the user is inserted to the database. please help.
There are few pointers here but before that, you have to be sure about what's the code under test. The reason I say this is because that will actually make you refactor your code a lot.
For example, for the code below:
public static void method(){
User user = getUser();
try {
String query = "INSERT INTO users (USER_ID , Name) VALUES ("
+user.getID()+","+user.getName()+")";
Statement statement = conn.createStatement();
statement.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
}
}
you might want to test following:-
Whether the query string is created properly i.e. a valid SQL as expected?
Should the method never throw an exception as we want to catch all the checked exception?
All the resources are closed once the work is done? e.g. in your method connection is opened but never closed.
Now out of above points, there could be some points with higher importance e.g. ensuring query is built correctly.
So, for that, the query builder code should be pulled out of this method and now you could easily test this query in the separate unit test.
Similarly, you would want to make sure a connection is closed after its job is completed. Hence, you might want to extract this code to a method that accepts a query as param, open connection, performs DB CRUD closes the connection and returns the output. And make sure that you are not repeating this code all the time in different methods.
Now, let's go to the pointers:-
If you at any point think that there is some code inside a method that's not testable till that code is part of the method. Please pull it out to a public / private method and test it.
Never try to test DB persistence as part of a unit test. The DB drivers etc are already having their own tests and are globally used.
If you think your method needs to be tested for whether it is called as many times as expected (it's what you want to test). It's called interaction based testing
You could use mocking (Mockito) and stub out the method under test and then assert how many times the method should be called. See this and this link.
Hope it helps!
Classes should be tested against the expected behavior.
Here testing the return type (even if it had other thing as void) makes no sense.
Your method performs a SQL query.
So your unit test has to assert the expected side effect on the database : an insertion with the expected values.
Note that to have reproducible and fast tests, you should favor embedded databases for unit testing.

Can we create and use our own interface instead of defined by the java?

Q1 : (removed)
Q2 : try-with-resource to create own resource implement AutoCloseable interface and override close() method.
From javadoc
Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
So, here I created a simple program MyAuto.java
class Demo implements AutoCloseable {
public void show() {
System.out.println("show");
}
public void close() {
System.out.println("close from demo");
}
}
class MyAuto {
public static void main(String[] args) {
try(Demo d = new Demo()) {
int x = 10/0;
d.show();
}catch(ArithmeticException e) {
System.out.println(e);
}
}
}
This program runs fine. :) and giving output
close from demo : as expected, no matters exception occurs, d will be closed.
But my question is I didn't write any code that close this resource, I simply put a print statement. What here actually closing a resource mean ? Assigning null to reference variable of resource or anything else ?
Or JVM runs any other method after running close() behind the scene.
And finally the most important question..
Q3 : In the above scenario if I add my own interface AutoCloseable
interface AutoCloseable {
void close() throws Exception;
}
It gives compile time error on compiling MyAuto.java
error: incompatible types: try-with-resources not applicable to variable type
try(Demo d = new Demo()) {
^
(Demo cannot be converted to AutoCloseable).
So, please give me answer why it's happening. Why can't we create and use our own Interfaces instead of provided by java. What is difference between my interface and the one predefined, although both are same.
What is difference between my interface and the one predefined, although both are same.
They're not the same. Not by a long shot.
The AutoCloseable required for try-with-resources is java.lang.AutoCloseable. Your custom AutoCloseable doesn't come from that package, so Java isn't going to respect it.
Above all, introducing that would not be the best approach, since it'll only lead to confusing semantics and a bad experience later down the road, even if you elected to have your interface extend java.lang.AutoCloseable for whatever reason.
In the same vein...
...I didn't write any code that close this resource, I simply put a print statement. What here actually closing a resource mean ? Assigning null to reference variable of resource or anything else ? Or JVM runs any other method after running close() behind the scene.
The interface can't enforce anything like that. All it can do is provide a mechanism that, if well-implemented, will behave as you expect.

($Proxy6) org.postgresql.jdbc4.Jdbc4Connection#5894585b, what does it mean?

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();

Categories

Resources