You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by da...@apache.org on 2014/06/23 08:25:55 UTC

git commit: updated refs/heads/4.4-forward to c690320

Repository: cloudstack
Updated Branches:
  refs/heads/4.4-forward 31e250a9d -> c690320f0


Fixed Resource Leaks

Signed-off-by: Daan Hoogland <da...@onecht.net>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/c690320f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/c690320f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/c690320f

Branch: refs/heads/4.4-forward
Commit: c690320f0b10b2465dfcb06581f62299a2fa641c
Parents: 31e250a
Author: Santhosh Edukulla <sa...@gmail.com>
Authored: Mon Jun 23 11:40:36 2014 +0530
Committer: Daan Hoogland <da...@onecht.net>
Committed: Mon Jun 23 08:25:36 2014 +0200

----------------------------------------------------------------------
 .../cloud/upgrade/dao/DatabaseAccessObject.java | 54 ++++++--------
 .../utils/crypt/EncryptionSecretKeyChanger.java | 18 +++--
 .../db/src/com/cloud/utils/db/ScriptRunner.java | 74 +++++++++-----------
 .../jobs/dao/AsyncJobJoinMapDaoImpl.java        | 39 ++++++-----
 4 files changed, 83 insertions(+), 102 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c690320f/engine/schema/src/com/cloud/upgrade/dao/DatabaseAccessObject.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/DatabaseAccessObject.java b/engine/schema/src/com/cloud/upgrade/dao/DatabaseAccessObject.java
index 836a537..4cc88bd 100644
--- a/engine/schema/src/com/cloud/upgrade/dao/DatabaseAccessObject.java
+++ b/engine/schema/src/com/cloud/upgrade/dao/DatabaseAccessObject.java
@@ -26,63 +26,49 @@ public class DatabaseAccessObject {
 
     private static Logger s_logger = Logger.getLogger(DatabaseAccessObject.class);
 
-    public void dropKey(Connection conn, String tableName, String key, boolean isForeignKey) {
-        PreparedStatement pstmt = null;
-        try {
-            if (isForeignKey) {
-                pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP FOREIGN KEY " + key);
-            } else {
-                pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP KEY " + key);
-            }
+    public void dropKey(Connection conn, String tableName, String key, boolean isForeignKey)
+    {
+        String alter_sql_str;
+        if (isForeignKey) {
+            alter_sql_str = "ALTER TABLE " + tableName + " DROP FOREIGN KEY " + key;
+        } else {
+            alter_sql_str = "ALTER TABLE " + tableName + " DROP KEY " + key;
+        }
+        try(PreparedStatement pstmt = conn.prepareStatement(alter_sql_str);)
+        {
             pstmt.executeUpdate();
             s_logger.debug("Key " + key + " is dropped successfully from the table " + tableName);
         } catch (SQLException e) {
-            s_logger.warn("Ignored SQL Exception when trying to drop " + (isForeignKey ? "foreign " : "") + "key " + key + " on table " + tableName, e);
-        } finally {
-            closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement atfer dropping " + (isForeignKey ? "foreign " : "") + "key " + key
-                    + " on table " + tableName);
+            s_logger.warn("dropKey:Exception:"+e.getMessage());
         }
     }
 
     public void dropPrimaryKey(Connection conn, String tableName) {
-        PreparedStatement pstmt = null;
-        try {
-            pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP PRIMARY KEY ");
+        try(PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP PRIMARY KEY ");) {
             pstmt.executeUpdate();
             s_logger.debug("Primary key is dropped successfully from the table " + tableName);
-        } catch (SQLException e) {
-            s_logger.warn("Ignored SQL Exception when trying to drop primary key on table " + tableName, e);
-        } finally {
-            closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement atfer dropping primary key on table " + tableName);
+        } catch (Exception e) {
+            s_logger.warn("dropPrimaryKey:Exception:"+e.getMessage());
         }
     }
 
     public void dropColumn(Connection conn, String tableName, String columnName) {
-        PreparedStatement pstmt = null;
-        try {
-            pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP COLUMN " + columnName);
+        try (PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP COLUMN " + columnName);){
             pstmt.executeUpdate();
             s_logger.debug("Column " + columnName + " is dropped successfully from the table " + tableName);
-        } catch (SQLException e) {
-            s_logger.warn("Unable to drop columns using query " + pstmt + " due to exception", e);
-        } finally {
-            closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement after dropping column " + columnName + " on table " + tableName);
+        } catch (Exception e) {
+            s_logger.warn("dropColumn:Exception:"+e.getMessage());
         }
     }
 
     public boolean columnExists(Connection conn, String tableName, String columnName) {
         boolean columnExists = false;
-        PreparedStatement pstmt = null;
-        try {
-            pstmt = conn.prepareStatement("SELECT " + columnName + " FROM " + tableName);
+        try (PreparedStatement pstmt = conn.prepareStatement("SELECT " + columnName + " FROM " + tableName);){
             pstmt.executeQuery();
             columnExists = true;
-        } catch (SQLException e) {
-            s_logger.warn("Field " + columnName + " doesn't exist in " + tableName, e);
-        } finally {
-            closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement atfer checking if column " + columnName + " existed on table " + tableName);
+        } catch (Exception e) {
+            s_logger.warn("columnExists:Exception:"+e.getMessage());
         }
-
         return columnExists;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c690320f/framework/db/src/com/cloud/utils/crypt/EncryptionSecretKeyChanger.java
----------------------------------------------------------------------
diff --git a/framework/db/src/com/cloud/utils/crypt/EncryptionSecretKeyChanger.java b/framework/db/src/com/cloud/utils/crypt/EncryptionSecretKeyChanger.java
index 4cee081..ae103ff 100755
--- a/framework/db/src/com/cloud/utils/crypt/EncryptionSecretKeyChanger.java
+++ b/framework/db/src/com/cloud/utils/crypt/EncryptionSecretKeyChanger.java
@@ -105,8 +105,8 @@ public class EncryptionSecretKeyChanger {
         PropertiesConfiguration backupDBProps = null;
 
         System.out.println("Parsing db.properties file");
-        try {
-            dbProps.load(new FileInputStream(dbPropsFile));
+        try(FileInputStream db_prop_fstream = new FileInputStream(dbPropsFile);) {
+            dbProps.load(db_prop_fstream);
             backupDBProps = new PropertiesConfiguration(dbPropsFile);
         } catch (FileNotFoundException e) {
             System.out.println("db.properties file not found while reading DB secret key" + e.getMessage());
@@ -142,11 +142,10 @@ public class EncryptionSecretKeyChanger {
                 //db.properties updated successfully
                 if (encryptionType.equals("file")) {
                     //update key file with new MS key
-                    try {
-                        FileWriter fwriter = new FileWriter(keyFile);
-                        BufferedWriter bwriter = new BufferedWriter(fwriter);
+                    try (FileWriter fwriter = new FileWriter(keyFile);
+                         BufferedWriter bwriter = new BufferedWriter(fwriter);)
+                    {
                         bwriter.write(newMSKey);
-                        bwriter.close();
                     } catch (IOException e) {
                         System.out.println("Failed to write new secret to file. Please update the file manually");
                     }
@@ -180,11 +179,10 @@ public class EncryptionSecretKeyChanger {
             }
             if (encryptionType.equals("file")) {
                 //revert secret key in file
-                try {
-                    FileWriter fwriter = new FileWriter(keyFile);
-                    BufferedWriter bwriter = new BufferedWriter(fwriter);
+                try (FileWriter fwriter = new FileWriter(keyFile);
+                     BufferedWriter bwriter = new BufferedWriter(fwriter);)
+                {
                     bwriter.write(oldMSKey);
-                    bwriter.close();
                 } catch (IOException e) {
                     System.out.println("Failed to revert to old secret to file. Please update the file manually");
                 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c690320f/framework/db/src/com/cloud/utils/db/ScriptRunner.java
----------------------------------------------------------------------
diff --git a/framework/db/src/com/cloud/utils/db/ScriptRunner.java b/framework/db/src/com/cloud/utils/db/ScriptRunner.java
index 932b37b..45494b9 100644
--- a/framework/db/src/com/cloud/utils/db/ScriptRunner.java
+++ b/framework/db/src/com/cloud/utils/db/ScriptRunner.java
@@ -131,52 +131,44 @@ public class ScriptRunner {
                 } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                     command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                     command.append(" ");
-                    Statement statement = conn.createStatement();
-
-                    println(command);
-
-                    boolean hasResults = false;
-                    if (stopOnError) {
-                        hasResults = statement.execute(command.toString());
-                    } else {
-                        try {
-                            statement.execute(command.toString());
-                        } catch (SQLException e) {
-                            e.fillInStackTrace();
-                            printlnError("Error executing: " + command);
-                            printlnError(e);
+                    try (Statement statement = conn.createStatement();) {
+                        println(command);
+                        boolean hasResults = false;
+                        if (stopOnError) {
+                            hasResults = statement.execute(command.toString());
+                        } else {
+                            try {
+                                statement.execute(command.toString());
+                            } catch (SQLException e) {
+                                e.fillInStackTrace();
+                                printlnError("Error executing: " + command);
+                                printlnError(e);
+                            }
                         }
-                    }
-
-                    if (autoCommit && !conn.getAutoCommit()) {
-                        conn.commit();
-                    }
-
-                    ResultSet rs = statement.getResultSet();
-                    if (hasResults && rs != null) {
-                        ResultSetMetaData md = rs.getMetaData();
-                        int cols = md.getColumnCount();
-                        for (int i = 0; i < cols; i++) {
-                            String name = md.getColumnLabel(i);
-                            print(name + "\t");
+                        if (autoCommit && !conn.getAutoCommit()) {
+                            conn.commit();
                         }
-                        println("");
-                        while (rs.next()) {
-                            for (int i = 1; i <= cols; i++) {
-                                String value = rs.getString(i);
-                                print(value + "\t");
+                        try(ResultSet rs = statement.getResultSet();) {
+                            if (hasResults && rs != null) {
+                                ResultSetMetaData md = rs.getMetaData();
+                                int cols = md.getColumnCount();
+                                for (int i = 0; i < cols; i++) {
+                                    String name = md.getColumnLabel(i);
+                                    print(name + "\t");
+                                }
+                                println("");
+                                while (rs.next()) {
+                                    for (int i = 1; i <= cols; i++) {
+                                        String value = rs.getString(i);
+                                        print(value + "\t");
+                                    }
+                                    println("");
+                                }
                             }
-                            println("");
+                            command = null;
+                            Thread.yield();
                         }
                     }
-
-                    command = null;
-                    try {
-                        statement.close();
-                    } catch (Exception e) {
-                        // Ignore to workaround a bug in Jakarta DBCP
-                    }
-                    Thread.yield();
                 } else {
                     int idx = line.indexOf("--");
                     if (idx != -1)

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c690320f/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/AsyncJobJoinMapDaoImpl.java
----------------------------------------------------------------------
diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/AsyncJobJoinMapDaoImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/AsyncJobJoinMapDaoImpl.java
index 7bc29db..fcdea76 100644
--- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/AsyncJobJoinMapDaoImpl.java
+++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/AsyncJobJoinMapDaoImpl.java
@@ -214,12 +214,14 @@ public class AsyncJobJoinMapDaoImpl extends GenericDaoBase<AsyncJobJoinMapVO, Lo
         List<Long> standaloneList = new ArrayList<Long>();
         TransactionLegacy txn = TransactionLegacy.currentTxn();
         String sql = "SELECT job_id FROM async_job_join_map WHERE join_job_id = ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
-        try {
-            PreparedStatement pstmt = txn.prepareStatement(sql);
+        try (PreparedStatement pstmt = txn.prepareStatement(sql);){
             pstmt.setLong(1, joinedJobId);
-            ResultSet rs = pstmt.executeQuery();
-            while (rs.next()) {
-                standaloneList.add(rs.getLong(1));
+            try(ResultSet rs = pstmt.executeQuery();) {
+                while (rs.next()) {
+                    standaloneList.add(rs.getLong(1));
+                }
+            }catch (SQLException e) {
+                throw new CloudRuntimeException("Unable to execute " + sql, e);
             }
         } catch (SQLException e) {
             throw new CloudRuntimeException("Unable to execute " + sql, e);
@@ -231,23 +233,26 @@ public class AsyncJobJoinMapDaoImpl extends GenericDaoBase<AsyncJobJoinMapVO, Lo
     public List<Long> findJobsToWakeBetween(Date cutDate) {
         List<Long> standaloneList = new ArrayList<Long>();
         TransactionLegacy txn = TransactionLegacy.currentTxn();
-        try {
-            String sql = "SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
-            PreparedStatement pstmt = txn.prepareStatement(sql);
+        String sql = "SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
+        try (PreparedStatement pstmt = txn.prepareStatement(sql);){
             pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
             pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
-            ResultSet rs = pstmt.executeQuery();
-            while (rs.next()) {
-                standaloneList.add(rs.getLong(1));
+            try(ResultSet rs = pstmt.executeQuery();) {
+                while (rs.next()) {
+                    standaloneList.add(rs.getLong(1));
+                }
+            }catch (SQLException e) {
+                throw new CloudRuntimeException("Unable to handle SQL exception", e);
             }
-
             // update for next wake-up
             sql = "UPDATE async_job_join_map SET next_wakeup=DATE_ADD(next_wakeup, INTERVAL wakeup_interval SECOND) WHERE next_wakeup < ? AND expiration > ?";
-            pstmt = txn.prepareStatement(sql);
-            pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
-            pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
-            pstmt.executeUpdate();
-
+            try(PreparedStatement update_pstmt = txn.prepareStatement(sql);) {
+                update_pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
+                update_pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
+                update_pstmt.executeUpdate();
+            }catch (SQLException e) {
+                throw new CloudRuntimeException("Unable to handle SQL exception", e);
+            }
             return standaloneList;
         } catch (SQLException e) {
             throw new CloudRuntimeException("Unable to handle SQL exception", e);