Fixes "a bunch of small leaks (closes missing, reported as warnings in Eclipse)" - https://issues.apache.org/jira/browse/OFBIZ-8115

At r1758927 I tried to fixe a bunch of closes missing, reported as warnings in Eclipse

Jacopo noticed and reported on dev ML http://markmail.org/message/b4hvzi7foftfq3j5 2 possible issues:
1) you are adding a close statement to code that already had the close statement in the "finally" block; your modification actually introduces a code pattern that is not correct (if an exception is thrown your close statement are not executed)
2) I suspect that you are closing the socket connection too early in PcChargeApi

1)The best option when closing resources (which implement AutoCloseable) is actually to use the try-with-resources statement. At least when there are no performance issues.
I have fixed the issue (only in DatabaseUtil.java) this way because
* there are not performance issues, we anyway create a Statement in both cases, we don't reuse one.
* The finally part is cleaner

I have also used the try-with-resources statement in other places where it fitted.

There is only 1 place where I was undecided: ScriptUtil.parseScript() which uses GroovyUtil.parseClass().
I put only a logError() there and returned null. 
I did not throw an IOException because else it spreads everywhere in FlexibleStringExpander.
Here introducing Optional would be better, but I have no time or that today.

2) was not a problem


git-svn-id: https://svn.apache.org/repos/asf/ofbiz/trunk@1758951 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Jacques Le Roux
2016-09-02 13:18:35 +00:00
parent 8bf34869da
commit 38e9885d3d
9 changed files with 64 additions and 55 deletions
@@ -1809,7 +1809,6 @@ public class DatabaseUtil {
}
Connection connection = null;
Statement stmt = null;
try {
connection = getConnection();
@@ -1852,8 +1851,7 @@ public class DatabaseUtil {
String sql = sqlBuf.toString();
if (Debug.infoOn()) Debug.logInfo("[addColumn] sql=" + sql, module);
try {
stmt = connection.createStatement();
try (Statement stmt = connection.createStatement()) {
stmt.executeUpdate(sql);
} catch (SQLException e) {
// if that failed try the alternate syntax real quick
@@ -1880,21 +1878,13 @@ public class DatabaseUtil {
String sql2 = sql2Buf.toString();
if (Debug.infoOn()) Debug.logInfo("[addColumn] sql failed, trying sql2=" + sql2, module);
try {
stmt = connection.createStatement();
try (Statement stmt = connection.createStatement()) {
stmt.executeUpdate(sql2);
} catch (SQLException e2) {
// if this also fails report original error, not this error...
return "SQL Exception while executing the following:\n" + sql + "\nError was: " + e.toString();
}
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
Debug.logError(e, module);
}
try {
if (connection != null) {
connection.close();