DD anomaly, and cleaning up database resources: is there a clean solution? - jdbc

Here's a piece of code we've all written:
public CustomerTO getCustomerByCustDel(final String cust, final int del)
throws SQLException {
final PreparedStatement query = getFetchByCustDel();
ResultSet records = null;
try {
query.setString(1, cust);
query.setInt(2, del);
records = query.executeQuery();
return this.getCustomer(records);
} finally {
if (records != null) {
records.close();
}
query.close();
}
}
If you omit the 'finally' block, then you leave database resources dangling, which obviously is a potential problem. However, if you do what I've done here - set the ResultSet to null outside the **try** block, and then set it to the desired value inside the block - PMD reports a 'DD anomaly'. In the documentation, a DD anomaly is described as follows:
DataflowAnomalyAnalysis: The dataflow analysis tracks local definitions, undefinitions and references to variables on different paths on the data flow.From those informations there can be found various problems. [...] DD - Anomaly: A recently defined variable is redefined. This is ominous but don't have to be a bug.
If you declare the ResultSet outside the block without setting a value, you rightly get a 'variable might not have been initialised' error when you do the if (records != null) test.
Now, in my opinion my use here isn't a bug. But is there a way of rewriting cleanly which would not trigger the PMD warning? I don't particularly want to disable PMD's DataFlowAnomalyAnalysis rule, as identifying UR and DU anomalies would be actually useful; but these DD anomalies make me suspect I could be doing something better - and, if there's no better way of doing this, they amount to clutter (and I should perhaps look at whether I can rewrite the PMD rule)

I think this is clearer:
PreparedStatement query = getFetchByCustDel();
try {
query.setString(1, cust);
query.setInt(2, del);
ResultSet records = query.executeQuery();
try {
return this.getCustomer(records);
} finally {
records.close();
}
} finally {
query.close();
}
Also, in your version the query doesn't get closed if records.close() throws an exception.

I think that DD anomaly note is more bug, than a feature
Also, the way you free resources is a bit incomplete, for example
PreparedStatement pstmt = null;
Statement st = null;
try {
...
} catch (final Exception e) {
...
} finally {
try{
if (pstmt != null) {
pstmt.close();
}
} catch (final Exception e) {
e.printStackTrace(System.err);
} finally {
try {
if (st != null) {
st.close();
}
} catch (final Exception e) {
e.printStackTrace(System.err);
}
}
}
moreover this is not right again, cuz you should close resources like that
PreparedStatement pstmt = null;
Throwable th = null;
try {
...
} catch (final Throwable e) {
<something here>
th = e;
throw e;
} finally {
if (th == null) {
pstmt.close();
} else {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (Throwable u) {
}
}
}

Related

org.hibernate.MappingException: Could not locate CollectionPersister for role : com.jbk.Entity.Product.productName

`Whenever, I try to run below method it is giving above error
public static List<Product> productGettingWithSize(int size) {
Session session = factory.openSession();
List<Product> list = null;
try {
Criteria criteria = session.createCriteria(Product.class);
criteria.add(Restrictions.sizeEq("productName", size));
list = criteria.list();
if (list.isEmpty()) {
System.out.println("No Data Found..!!");
} else {
System.out.println(list);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
So, here in this code in DB productName is REDMI so, I m passing 5 as an size but, I m not getting the expected output.
So could anyone help me regarding this code or Can any anyone Tell how to use Restrictions(Size), all method related to size or can anyone send me the documentation where it is been explained explicitly.
Thank You...!!!
Expecting a solution on This..!!`

jTable that will listen to jDateChooser's 'textfield'?

Hello everyone I'm trying to make a scheduling system for my System and Analysis Design thesis and I am having trouble trying to connect/bind/make the jTable listen to the jDateChooser's input. Elaborately, I want my scheduling to be like this:
I choose a date in the jDateChooser
jTable will 'sort out' itself via the date inputted on the jDatechooser
is there anyway to do this?
For now all I have is a table propertyChangelistener:
private void sched_tablePropertyChangeListener(java.beans.PropertyChangeEvent evt) {
try{
String calendar = ((JTextField)jdc.getDateEditor().getUiComponent()).getText();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/accountsDB?zeroDateTimeBehavior=convertToNull","root","");
String query = "select * from accountsdb.schedules where Date= ?";
ps= conn.prepareStatement(query);
ps.setString(1, calendar);
ResultSet rs = ps.executeQuery();
sched_table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
if (conn != null)
try { conn.close();
} catch (SQLException ignore) {}
if (ps != null){
try {
ps.close();
} catch (SQLException ignore){}
}
}
}
Somehow when I run my application it doesn't seem to open if that block of code is on it which means I really did do something wrong. Can anyone change or tell me what I should do or where should I start with the jTable listening to the jDatechooser thing?
~Thanks in advance for those who will answer!~
Nevermind, turns out all I had to do was change the jDateChooser's Date Format since it wasn't exactly the same formatting hence I couldn't call anything from the database. If anyone's interested on what I did I'll just leave this here
private void jdcPropertyChange(java.beans.PropertyChangeEvent evt) {
try{
String d1 = ((JTextField)jdc.getDateEditor().getUiComponent()).getText();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/accountsDB?zeroDateTimeBehavior=convertToNull","root","");
String query = "select * from accountsdb.schedules where Date= ? order by time,timezone";
ps = conn.prepareStatement(query);
ps.setString(1, d1);
ResultSet rs = ps.executeQuery();
sched_table.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
if (conn != null) {
try { conn.close();
} catch (SQLException ignore) {}
}
if (ps != null){
try {
ps.close();
} catch (SQLException ignore){}
}
}
}
What this does is that everytime I pick on a date from the jDateChooser(named it jdc) the table/database calls that date and sorts it out. Which is what I wanted.

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll

I am using Janus(Third Party) Grid and getting the "System.StackOverflowException". Don't know how to solve it. I would like to appreciate for any help.
private void gridEX1_FormattingRow(object sender, RowLoadEventArgs e)
{
int index = e.Row.RowIndex;
try
{
if (!Convert.IsDBNull(gridEX1.GetRow(index).Cells["HEADER_ORDER_PACKAGE_ROW_ID"].Value))
{
if (Convert.ToInt32(gridEX1.GetRow(index).Cells["HEADER_ORDER_PACKAGE_ROW_ID"].Value) == PARENT_ORDER_PACKAGE_ID)
{
**gridEX1.MoveToRowIndex(index);**
GridEXRow curRow = gridEX1.GetRow();
if (curRow != null)
{
curRow.Expanded = true;
}
}
}
}
catch (Exception ex)
{
}
}
It seems that one of the lines inside your handler invoke the handler itself again. And so on, so you get StackOverflow.

Wrapping all method body in try block vs wrapping only particular instructions

Looking at the code I recently wrote made me wonder:
public void process(Deque<OperandToken> stack, EvaluationConfig context) {
OperandToken a;
OperandToken b;
try {
b = stack.pop();
a = stack.pop();
} catch (NoSuchElementException e) {
throw new EvaluationException("Syntax error: not enough operands");
}
if (!a.isValueTypeOf(Number.class) || !b.isValueTypeOf(Number.class)) {
throw new EvaluationException("Syntax error...");
}
// more actions on a and b and finally stack.push(result)
}
Same but with catch in the end:
public void process(Deque<OperandToken> stack, EvaluationConfig context) {
try {
OperandToken b = stack.pop();
OperandToken a = stack.pop();
if (!a.isValueTypeOf(Number.class) || !b.isValueTypeOf(Number.class)) {
throw new EvaluationException("Syntax error...");
}
// more actions on a and b and finally stack.push(result)
} catch (NoSuchElementException e) {
throw new EvaluationException("Syntax error: not enough operands");
}
}
Is there any rule about preferred method, or some arguments (e.g. performance) that the first / the second style should be used? In both cases NoSuchElementException is the only exception that can appear, but the question is also valid for cases when there are multiple exceptions that can be thrown on different lines.

C3P0 Statement.close deadlock

Google returns lots of people with deadlock issues in C3P0, but none of the solutions appear to apply (most people suggest setting maxStatements = 0 and maxStatementsPerConnection = 0, both of which we have).
I am using a ComboPooledDataSource from C3P0, initialised as;
cpds = new ComboPooledDataSource();
cpds.setDriverClass("org.postgresql.Driver");
cpds.setJdbcUrl("jdbc:postgresql://" + host + ":5432/" + database);
cpds.setUser(user);
cpds.setPassword(pass);
My query function looks like;
public static List<Map<String, Object>> query(String q) {
Connection c = null;
Statement s = null;
ResultSet r = null;
try {
c = cpds.getConnection();
s = c.createStatement();
s.executeQuery(q);
r = s.getResultSet();
/* parse result set into results List<Map> */
return results;
}
catch(Exception e) { MyUtils.logException(e); }
finally {
closeQuietly(r);
closeQuietly(s);
closeQuietly(c);
}
return null;
}
No queries are returning, despite the query() method reaching the return results; line. The issue is that the finally block is hanging. I have determined that the closeQuietly(s); is the line that is hanging indefinitely.
The closeQuietly() method in question is as you would expect;
public static void closeQuietly(Statement s) {
try { if(s != null) s.close(); }
catch(Exception e) { MyUtils.logException(e); }
}
Why would this method hang on s.close()? I guess it is something to do with the way I am using C3P0.
My complete C3P0 configuration (almost entirely defaults) can be viewed here -> http://pastebin.com/K8XDdiBg
MyUtils.logException(); looks something like;
public static void logException(Exception e) {
StackTraceElement ste[] = e.getStackTrace();
String message = " !ERROR!: ";
for(int i = 0; i < ste.length; i++) {
if(ste[i].getClassName().contains("packagename")) {
message += String.format("%s at %s:%d", e.toString(), ste[i].getFileName(), ste[i].getLineNumber());
break;
}
}
System.err.println(message);
}
Everything runs smoothly if I remove the closeQuietly(s); line. Both closing the ResultSet and Connection object work without problem - apart from Connection starvation of course.

Resources