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/12 14:44:36 UTC

git commit: updated refs/heads/4.4 to 87c3d77

Repository: cloudstack
Updated Branches:
  refs/heads/4.4 80d8cef24 -> 87c3d7751


Fixed coverity issues

(cherry picked from commit 4ba3aae2ea0290ca012623083e13625e08a9dde5)


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

Branch: refs/heads/4.4
Commit: 87c3d77518c6abeb5f2775efd00d788eb58c6842
Parents: 80d8cef
Author: Santhosh Edukulla <sa...@gmail.com>
Authored: Thu Jun 12 17:45:48 2014 +0530
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jun 12 14:44:26 2014 +0200

----------------------------------------------------------------------
 .../src/com/cloud/upgrade/DatabaseCreator.java  |  45 ++--
 .../cloud/upgrade/DatabaseIntegrityChecker.java | 203 +++++++++++--------
 .../cloud/upgrade/DatabaseUpgradeChecker.java   |  10 +-
 .../utils/crypt/EncryptionSecretKeyChanger.java |  92 ++-------
 .../db/src/com/cloud/utils/db/Merovingian2.java |   8 +-
 .../db/src/com/cloud/utils/db/ScriptRunner.java |   2 +-
 .../com/cloud/utils/db/TransactionLegacy.java   |   2 +-
 server/src/com/cloud/test/IPRangeConfig.java    | 168 ++++++++-------
 .../src/com/cloud/usage/UsageSanityChecker.java |  47 ++---
 .../utils/crypt/EncryptionSecretKeySender.java  |  40 ++--
 10 files changed, 291 insertions(+), 326 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/87c3d775/engine/schema/src/com/cloud/upgrade/DatabaseCreator.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/DatabaseCreator.java b/engine/schema/src/com/cloud/upgrade/DatabaseCreator.java
index 91ef318..b04607d 100755
--- a/engine/schema/src/com/cloud/upgrade/DatabaseCreator.java
+++ b/engine/schema/src/com/cloud/upgrade/DatabaseCreator.java
@@ -20,14 +20,13 @@ package com.cloud.upgrade;
 
 import java.io.File;
 import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.Reader;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.SQLException;
 import java.sql.Statement;
+import java.sql.SQLException;
+import java.sql.DriverManager;
+import java.sql.Connection;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
@@ -75,13 +74,10 @@ public class DatabaseCreator {
 
     private static void runQuery(String host, String port, String rootPassword, String query, boolean dryRun) {
         System.out.println("============> Running query: " + query);
-        Connection conn = null;
-        try {
-            conn = DriverManager.getConnection(String.format("jdbc:mysql://%s:%s/", host, port), "root", rootPassword);
-            Statement stmt = conn.createStatement();
-            if (!dryRun)
+        try (Connection conn = DriverManager.getConnection(String.format("jdbc:mysql://%s:%s/", host, port), "root", rootPassword);
+             Statement stmt = conn.createStatement();){
+             if (!dryRun)
                 stmt.executeUpdate(query);
-            conn.close();
         } catch (SQLException e) {
             System.out.println("SQL exception in trying initDB: " + e);
             System.exit(1);
@@ -186,24 +182,23 @@ public class DatabaseCreator {
             }
 
             System.out.println("========> Processing SQL file at " + sqlScript.getAbsolutePath());
-            Connection conn = TransactionLegacy.getStandaloneConnection();
-            try {
-                FileReader reader = null;
-                try {
-                    reader = new FileReader(sqlScript);
-                } catch (FileNotFoundException e) {
-                    System.err.println("Unable to read " + sqlFile + ": " + e.getMessage());
-                    System.exit(1);
-                }
+
+            try(Connection conn = TransactionLegacy.getStandaloneConnection();
+                FileReader reader = new FileReader(sqlScript);
+            ) {
                 if (!dryRun)
                     runScript(conn, reader, sqlFile, verbosity);
-            } finally {
-                try {
-                    conn.close();
-                } catch (SQLException e) {
-                    System.err.println("Unable to close DB connection: " + e.getMessage());
-                }
+            }catch (SQLException e)
+            {
+                System.err.println("Sql Exception:" + e.getMessage());
+                System.exit(1);
+            }
+            catch (IOException e)
+            {
+                System.err.println("File IO Exception : " + e.getMessage());
+                System.exit(1);
             }
+
         }
 
         TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/87c3d775/engine/schema/src/com/cloud/upgrade/DatabaseIntegrityChecker.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/DatabaseIntegrityChecker.java b/engine/schema/src/com/cloud/upgrade/DatabaseIntegrityChecker.java
index c20a418..2001fae 100755
--- a/engine/schema/src/com/cloud/upgrade/DatabaseIntegrityChecker.java
+++ b/engine/schema/src/com/cloud/upgrade/DatabaseIntegrityChecker.java
@@ -75,81 +75,106 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg
     }
 
     private Boolean checkDuplicateHostWithTheSameLocalStorage() {
+
         TransactionLegacy txn = TransactionLegacy.open("Integrity");
-        txn.start();
         try {
-            Connection conn;
+            txn.start();
+            Connection conn = txn.getConnection();
+            try (PreparedStatement pstmt =
+                             conn.prepareStatement("SELECT pool_id FROM host INNER JOIN storage_pool_host_ref INNER JOIN storage_pool WHERE storage_pool.id = storage_pool_host_ref.pool_id and storage_pool.pool_type='LVM' AND host.id=storage_pool_host_ref.host_id AND host.removed IS NULL group by pool_id having count(*) > 1");
+                 ResultSet rs = pstmt.executeQuery();)
+            {
+                    boolean noDuplicate = true;
+                    StringBuffer helpInfo = new StringBuffer();
+                    String note =
+                        "DATABASE INTEGRITY ERROR\nManagement server detected there are some hosts connect to the same loacal storage, please contact CloudStack support team for solution. Below are detialed info, please attach all of them to CloudStack support. Thank you\n";
+                    helpInfo.append(note);
+                    while (rs.next()) {
+                        try ( PreparedStatement sel_pstmt =
+                                conn.prepareStatement("select id, status, removed, private_ip_address from host where id in (select host_id from storage_pool_host_ref where pool_id=?)");
+                        ){
+                                long poolId = rs.getLong(1);
+                                pstmt.setLong(1, poolId);
+                                try(ResultSet dhrs = sel_pstmt.executeQuery();) {
+                                    String help = formatDuplicateHostToReadText(poolId, dhrs);
+                                    helpInfo.append(help);
+                                    helpInfo.append("\n");
+                                    noDuplicate = false;
+                                }
+                                catch (Exception e)
+                                {
+                                    s_logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage());
+                                    throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage(),e);
+                                }
+                        }
+                        catch (Exception e)
+                        {
+                                s_logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage());
+                                throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage(),e);
+                        }
+                    }
+                    if (noDuplicate) {
+                        s_logger.debug("No duplicate hosts with the same local storage found in database");
+                    } else {
+                        s_logger.error(helpInfo.toString());
+                    }
+                    txn.commit();
+                    return noDuplicate;
+            }catch (Exception e)
+            {
+                  s_logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage());
+                  throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage(),e);
+            }
+        }
+        catch (Exception e)
+        {
+            s_logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage());
+            throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage(),e);
+        }
+        finally
+        {
             try {
-                conn = txn.getConnection();
-                PreparedStatement pstmt =
-                    conn.prepareStatement("SELECT pool_id FROM host INNER JOIN storage_pool_host_ref INNER JOIN storage_pool WHERE storage_pool.id = storage_pool_host_ref.pool_id and storage_pool.pool_type='LVM' AND host.id=storage_pool_host_ref.host_id AND host.removed IS NULL group by pool_id having count(*) > 1");
-                ResultSet rs = pstmt.executeQuery();
-
-                boolean noDuplicate = true;
-                StringBuffer helpInfo = new StringBuffer();
-                String note =
-                    "DATABASE INTEGRITY ERROR\nManagement server detected there are some hosts connect to the same loacal storage, please contact CloudStack support team for solution. Below are detialed info, please attach all of them to CloudStack support. Thank you\n";
-                helpInfo.append(note);
-                while (rs.next()) {
-                    long poolId = rs.getLong(1);
-                    pstmt =
-                        conn.prepareStatement("select id, status, removed, private_ip_address from host where id in (select host_id from storage_pool_host_ref where pool_id=?)");
-                    pstmt.setLong(1, poolId);
-                    ResultSet dhrs = pstmt.executeQuery();
-                    String help = formatDuplicateHostToReadText(poolId, dhrs);
-                    helpInfo.append(help);
-                    helpInfo.append("\n");
-                    noDuplicate = false;
+                if (txn != null) {
+                    txn.close();
                 }
-
-                if (noDuplicate) {
-                    s_logger.debug("No duplicate hosts with the same local storage found in database");
-                } else {
-                    s_logger.error(helpInfo.toString());
-                }
-
-                return noDuplicate;
-            } catch (SQLException e) {
-                s_logger.error("Unable to check duplicate hosts with the same local storage in database", e);
-                throw new CloudRuntimeException("Unable to check duplicate hosts with the same local storage in database", e);
+            }catch(Exception e)
+            {
+                s_logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception:"+ e.getMessage());
             }
-        } finally {
-            txn.commit();
-            txn.close();
         }
     }
 
     private boolean check21to22PremiumUprage(Connection conn) throws SQLException {
-        PreparedStatement pstmt = conn.prepareStatement("show tables in cloud_usage");
-        ResultSet rs = pstmt.executeQuery();
-        int num = 0;
-
-        while (rs.next()) {
-            String tableName = rs.getString(1);
-            if (tableName.equalsIgnoreCase("usage_event") || tableName.equalsIgnoreCase("usage_port_forwarding") || tableName.equalsIgnoreCase("usage_network_offering")) {
-                num++;
-                s_logger.debug("Checking 21to22PremiumUprage table " + tableName + " found");
-            }
-            if (num == 3) {
-                return true;
+        try (PreparedStatement pstmt = conn.prepareStatement("show tables in cloud_usage");
+             ResultSet rs = pstmt.executeQuery();) {
+            int num = 0;
+            while (rs.next()) {
+                String tableName = rs.getString(1);
+                if (tableName.equalsIgnoreCase("usage_event") || tableName.equalsIgnoreCase("usage_port_forwarding") || tableName.equalsIgnoreCase("usage_network_offering")) {
+                    num++;
+                    s_logger.debug("Checking 21to22PremiumUprage table " + tableName + " found");
+                }
+                if (num == 3) {
+                    return true;
+                }
             }
+            return false;
         }
-
-        return false;
     }
 
     private boolean isColumnExisted(Connection conn, String dbName, String tableName, String column) throws SQLException {
-        PreparedStatement pstmt = conn.prepareStatement(String.format("describe %1$s.%2$s", dbName, tableName));
-        ResultSet rs = pstmt.executeQuery();
-        boolean found = false;
-        while (rs.next()) {
-            if (column.equalsIgnoreCase(rs.getString(1))) {
-                s_logger.debug(String.format("Column %1$s.%2$s.%3$s found", dbName, tableName, column));
-                found = true;
-                break;
+        try (PreparedStatement pstmt = conn.prepareStatement(String.format("describe %1$s.%2$s", dbName, tableName));
+             ResultSet rs = pstmt.executeQuery();) {
+            boolean found = false;
+            while (rs.next()) {
+                if (column.equalsIgnoreCase(rs.getString(1))) {
+                    s_logger.debug(String.format("Column %1$s.%2$s.%3$s found", dbName, tableName, column));
+                    found = true;
+                    break;
+                }
             }
+            return found;
         }
-        return found;
     }
 
     private boolean check221to222PremiumUprage(Connection conn) throws SQLException {
@@ -174,22 +199,23 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg
 
     private boolean checkMissedPremiumUpgradeFor228() {
         TransactionLegacy txn = TransactionLegacy.open("Integrity");
-        txn.start();
         try {
-            String dbVersion = _dao.getCurrentVersion();
-
-            if (dbVersion == null)
-                return false;
+            txn.start();
+            Connection conn = txn.getConnection();
+            try (
+                PreparedStatement pstmt = conn.prepareStatement("show databases");
+                ResultSet rs = pstmt.executeQuery();) {
+                String dbVersion = _dao.getCurrentVersion();
 
-            if (Version.compare(Version.trimToPatch(dbVersion), Version.trimToPatch("2.2.8")) != 0) {
-                return true;
-            }
+                if (dbVersion == null) {
+                    txn.commit();
+                    return false;
+                }
 
-            Connection conn;
-            try {
-                conn = txn.getConnection();
-                PreparedStatement pstmt = conn.prepareStatement("show databases");
-                ResultSet rs = pstmt.executeQuery();
+                if (Version.compare(Version.trimToPatch(dbVersion), Version.trimToPatch("2.2.8")) != 0) {
+                    txn.commit();
+                    return true;
+                }
                 boolean hasUsage = false;
                 while (rs.next()) {
                     String dbName = rs.getString(1);
@@ -198,35 +224,46 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg
                         break;
                     }
                 }
-
                 if (!hasUsage) {
                     s_logger.debug("No cloud_usage found in database, no need to check missed premium upgrade");
+                    txn.commit();
                     return true;
                 }
-
                 if (!check21to22PremiumUprage(conn)) {
                     s_logger.error("21to22 premium upgrade missed");
+                    txn.commit();
                     return false;
                 }
-
                 if (!check221to222PremiumUprage(conn)) {
                     s_logger.error("221to222 premium upgrade missed");
+                    txn.commit();
                     return false;
                 }
-
                 if (!check222to224PremiumUpgrade(conn)) {
                     s_logger.error("222to224 premium upgrade missed");
+                    txn.commit();
                     return false;
                 }
-
+                txn.commit();
                 return true;
-            } catch (SQLException e) {
-                s_logger.error("Unable to check missed premiumg upgrade");
-                throw new CloudRuntimeException("Unable to check missed premiumg upgrade");
+            } catch (Exception e) {
+                s_logger.error("checkMissedPremiumUpgradeFor228: Exception:" + e.getMessage());
+                throw new CloudRuntimeException("checkMissedPremiumUpgradeFor228: Exception:" + e.getMessage(), e);
+            }
+        }catch (Exception e) {
+            s_logger.error("checkMissedPremiumUpgradeFor228: Exception:"+ e.getMessage());
+            throw new CloudRuntimeException("checkMissedPremiumUpgradeFor228: Exception:" + e.getMessage(),e);
+        }
+        finally
+        {
+            try {
+                if (txn != null) {
+                    txn.close();
+                }
+            }catch(Exception e)
+            {
+                s_logger.error("checkMissedPremiumUpgradeFor228: Exception:"+ e.getMessage());
             }
-        } finally {
-            txn.commit();
-            txn.close();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/87c3d775/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java b/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java
index 0761c9f..8586ed4 100755
--- a/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java
+++ b/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java
@@ -237,8 +237,8 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
     }
 
     protected void runScript(Connection conn, File file) {
-        try {
-            FileReader reader = new FileReader(file);
+
+        try(FileReader reader = new FileReader(file);) {
             ScriptRunner runner = new ScriptRunner(conn, false, true);
             runner.runScript(reader);
         } catch (FileNotFoundException e) {
@@ -251,6 +251,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
             s_logger.error("Unable to execute upgrade script: " + file.getAbsolutePath(), e);
             throw new CloudRuntimeException("Unable to execute upgrade script: " + file.getAbsolutePath(), e);
         }
+
     }
 
     protected void upgrade(String dbVersion, String currentVersion) {
@@ -314,10 +315,9 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
                     // we don't have VersionDao in 2.1.x
                     upgradeVersion = false;
                 } else if (upgrade.getUpgradedVersion().equals("2.2.4")) {
-                    try {
+                    try(PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM version WHERE version='2.2.4'");
+                        ResultSet rs = pstmt.executeQuery();) {
                         // specifically for domain vlan update from 2.1.8 to 2.2.4
-                        PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM version WHERE version='2.2.4'");
-                        ResultSet rs = pstmt.executeQuery();
                         if (rs.next()) {
                             upgradeVersion = false;
                         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/87c3d775/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 58584f9..4cee081 100755
--- a/framework/db/src/com/cloud/utils/crypt/EncryptionSecretKeyChanger.java
+++ b/framework/db/src/com/cloud/utils/crypt/EncryptionSecretKeyChanger.java
@@ -266,11 +266,10 @@ public class EncryptionSecretKeyChanger {
 
     private void migrateConfigValues(Connection conn) {
         System.out.println("Begin migrate config values");
-        PreparedStatement pstmt = null;
-        ResultSet rs = null;
-        try {
-            pstmt = conn.prepareStatement("select name, value from configuration where category in ('Hidden', 'Secure')");
-            rs = pstmt.executeQuery();
+        try(PreparedStatement select_pstmt = conn.prepareStatement("select name, value from configuration where category in ('Hidden', 'Secure')");
+            ResultSet rs = select_pstmt.executeQuery();
+            PreparedStatement update_pstmt = conn.prepareStatement("update configuration set value=? where name=?");
+        ) {
             while (rs.next()) {
                 String name = rs.getString(1);
                 String value = rs.getString(2);
@@ -278,37 +277,25 @@ public class EncryptionSecretKeyChanger {
                     continue;
                 }
                 String encryptedValue = migrateValue(value);
-                pstmt = conn.prepareStatement("update configuration set value=? where name=?");
-                pstmt.setBytes(1, encryptedValue.getBytes("UTF-8"));
-                pstmt.setString(2, name);
-                pstmt.executeUpdate();
+                update_pstmt.setBytes(1, encryptedValue.getBytes("UTF-8"));
+                update_pstmt.setString(2, name);
+                update_pstmt.executeUpdate();
             }
         } catch (SQLException e) {
             throw new CloudRuntimeException("Unable to update configuration values ", e);
         } catch (UnsupportedEncodingException e) {
             throw new CloudRuntimeException("Unable to update configuration values ", e);
-        } finally {
-            try {
-                if (rs != null) {
-                    rs.close();
-                }
-
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-            }
         }
         System.out.println("End migrate config values");
     }
 
     private void migrateHostDetails(Connection conn) {
         System.out.println("Begin migrate host details");
-        PreparedStatement pstmt = null;
-        ResultSet rs = null;
-        try {
-            pstmt = conn.prepareStatement("select id, value from host_details where name = 'password'");
-            rs = pstmt.executeQuery();
+
+        try( PreparedStatement sel_pstmt = conn.prepareStatement("select id, value from host_details where name = 'password'");
+        ResultSet rs = sel_pstmt.executeQuery();
+        PreparedStatement pstmt = conn.prepareStatement("update host_details set value=? where id=?");
+        ) {
             while (rs.next()) {
                 long id = rs.getLong(1);
                 String value = rs.getString(2);
@@ -316,7 +303,6 @@ public class EncryptionSecretKeyChanger {
                     continue;
                 }
                 String encryptedValue = migrateValue(value);
-                pstmt = conn.prepareStatement("update host_details set value=? where id=?");
                 pstmt.setBytes(1, encryptedValue.getBytes("UTF-8"));
                 pstmt.setLong(2, id);
                 pstmt.executeUpdate();
@@ -325,28 +311,16 @@ public class EncryptionSecretKeyChanger {
             throw new CloudRuntimeException("Unable update host_details values ", e);
         } catch (UnsupportedEncodingException e) {
             throw new CloudRuntimeException("Unable update host_details values ", e);
-        } finally {
-            try {
-                if (rs != null) {
-                    rs.close();
-                }
-
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-            }
         }
         System.out.println("End migrate host details");
     }
 
     private void migrateVNCPassword(Connection conn) {
         System.out.println("Begin migrate VNC password");
-        PreparedStatement pstmt = null;
-        ResultSet rs = null;
-        try {
-            pstmt = conn.prepareStatement("select id, vnc_password from vm_instance");
-            rs = pstmt.executeQuery();
+        try(PreparedStatement  select_pstmt = conn.prepareStatement("select id, vnc_password from vm_instance");
+        ResultSet rs = select_pstmt.executeQuery();
+        PreparedStatement pstmt = conn.prepareStatement("update vm_instance set vnc_password=? where id=?");
+        ) {
             while (rs.next()) {
                 long id = rs.getLong(1);
                 String value = rs.getString(2);
@@ -354,7 +328,7 @@ public class EncryptionSecretKeyChanger {
                     continue;
                 }
                 String encryptedValue = migrateValue(value);
-                pstmt = conn.prepareStatement("update vm_instance set vnc_password=? where id=?");
+
                 pstmt.setBytes(1, encryptedValue.getBytes("UTF-8"));
                 pstmt.setLong(2, id);
                 pstmt.executeUpdate();
@@ -363,28 +337,16 @@ public class EncryptionSecretKeyChanger {
             throw new CloudRuntimeException("Unable update vm_instance vnc_password ", e);
         } catch (UnsupportedEncodingException e) {
             throw new CloudRuntimeException("Unable update vm_instance vnc_password ", e);
-        } finally {
-            try {
-                if (rs != null) {
-                    rs.close();
-                }
-
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-            }
         }
         System.out.println("End migrate VNC password");
     }
 
     private void migrateUserCredentials(Connection conn) {
         System.out.println("Begin migrate user credentials");
-        PreparedStatement pstmt = null;
-        ResultSet rs = null;
-        try {
-            pstmt = conn.prepareStatement("select id, secret_key from user");
-            rs = pstmt.executeQuery();
+        try(PreparedStatement select_pstmt = conn.prepareStatement("select id, secret_key from user");
+        ResultSet rs = select_pstmt.executeQuery();
+        PreparedStatement pstmt = conn.prepareStatement("update user set secret_key=? where id=?");
+        ) {
             while (rs.next()) {
                 long id = rs.getLong(1);
                 String secretKey = rs.getString(2);
@@ -392,7 +354,6 @@ public class EncryptionSecretKeyChanger {
                     continue;
                 }
                 String encryptedSecretKey = migrateValue(secretKey);
-                pstmt = conn.prepareStatement("update user set secret_key=? where id=?");
                 pstmt.setBytes(1, encryptedSecretKey.getBytes("UTF-8"));
                 pstmt.setLong(2, id);
                 pstmt.executeUpdate();
@@ -401,17 +362,6 @@ public class EncryptionSecretKeyChanger {
             throw new CloudRuntimeException("Unable update user secret key ", e);
         } catch (UnsupportedEncodingException e) {
             throw new CloudRuntimeException("Unable update user secret key ", e);
-        } finally {
-            try {
-                if (rs != null) {
-                    rs.close();
-                }
-
-                if (pstmt != null) {
-                    pstmt.close();
-                }
-            } catch (SQLException e) {
-            }
         }
         System.out.println("End migrate user credentials");
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/87c3d775/framework/db/src/com/cloud/utils/db/Merovingian2.java
----------------------------------------------------------------------
diff --git a/framework/db/src/com/cloud/utils/db/Merovingian2.java b/framework/db/src/com/cloud/utils/db/Merovingian2.java
index 6eeea9f..4e2c684 100644
--- a/framework/db/src/com/cloud/utils/db/Merovingian2.java
+++ b/framework/db/src/com/cloud/utils/db/Merovingian2.java
@@ -444,14 +444,12 @@ public class Merovingian2 extends StandardMBean implements MerovingianMBean {
     @Override
     public boolean releaseLockAsLastResortAndIReallyKnowWhatIAmDoing(String key) {
         s_logger.info("Releasing a lock from JMX lck-" + key);
-        PreparedStatement pstmt = null;
-        try {
-            pstmt = _concierge.conn().prepareStatement(RELEASE_LOCK_SQL);
+        try(PreparedStatement pstmt = _concierge.conn().prepareStatement(RELEASE_LOCK_SQL);) {
             pstmt.setString(1, key);
             int rows = pstmt.executeUpdate();
             return rows > 0;
-        } catch (SQLException e) {
-            s_logger.error("Unable to release lock " + key, e);
+        } catch (Exception e) {
+            s_logger.error("releaseLockAsLastResortAndIReallyKnowWhatIAmDoing : Exception: " +  e.getMessage());
             return false;
         }
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/87c3d775/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 6614527..932b37b 100644
--- a/framework/db/src/com/cloud/utils/db/ScriptRunner.java
+++ b/framework/db/src/com/cloud/utils/db/ScriptRunner.java
@@ -162,7 +162,7 @@ public class ScriptRunner {
                         }
                         println("");
                         while (rs.next()) {
-                            for (int i = 0; i < cols; i++) {
+                            for (int i = 1; i <= cols; i++) {
                                 String value = rs.getString(i);
                                 print(value + "\t");
                             }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/87c3d775/framework/db/src/com/cloud/utils/db/TransactionLegacy.java
----------------------------------------------------------------------
diff --git a/framework/db/src/com/cloud/utils/db/TransactionLegacy.java b/framework/db/src/com/cloud/utils/db/TransactionLegacy.java
index ac0ea21..aedf939 100755
--- a/framework/db/src/com/cloud/utils/db/TransactionLegacy.java
+++ b/framework/db/src/com/cloud/utils/db/TransactionLegacy.java
@@ -791,7 +791,7 @@ public class TransactionLegacy {
             it.remove();
 
             try {
-                if (item.type == type && (ref == null || item.ref == ref)) {
+                if ( (type == null || type.equals(item.type)) && (ref == null || ref.equals(item.ref))) {
                     break;
                 }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/87c3d775/server/src/com/cloud/test/IPRangeConfig.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/test/IPRangeConfig.java b/server/src/com/cloud/test/IPRangeConfig.java
index 1d56471..29feba6 100755
--- a/server/src/com/cloud/test/IPRangeConfig.java
+++ b/server/src/com/cloud/test/IPRangeConfig.java
@@ -318,31 +318,31 @@ public class IPRangeConfig {
         String isPublicIPAllocatedSelectSql = "SELECT * FROM `cloud`.`user_ip_address` WHERE public_ip_address = ? AND vlan_id = ?";
 
         Vector<String> problemIPs = new Vector<String>();
-        PreparedStatement stmt = null;
-        PreparedStatement isAllocatedStmt = null;
-
         Connection conn = null;
         try {
             conn = txn.getConnection();
-            stmt = conn.prepareStatement(deleteSql);
-            isAllocatedStmt = conn.prepareStatement(isPublicIPAllocatedSelectSql);
-        } catch (SQLException e) {
+        }
+        catch (SQLException e) {
+            System.out.println("deletePublicIPRange. Exception: " +e.getMessage());
             return null;
         }
-
-        while (startIP <= endIP) {
-            if (!isPublicIPAllocated(startIP, vlanDbId, isAllocatedStmt)) {
-                try {
-                    stmt.clearParameters();
-                    stmt.setLong(1, startIP);
-                    stmt.setLong(2, vlanDbId);
-                    stmt.executeUpdate();
-                } catch (Exception ex) {
+        try(PreparedStatement stmt = conn.prepareStatement(deleteSql);
+            PreparedStatement isAllocatedStmt = conn.prepareStatement(isPublicIPAllocatedSelectSql);) {
+            while (startIP <= endIP) {
+                if (!isPublicIPAllocated(startIP, vlanDbId, isAllocatedStmt)) {
+                        stmt.clearParameters();
+                        stmt.setLong(1, startIP);
+                        stmt.setLong(2, vlanDbId);
+                        stmt.executeUpdate();
+                    }
+                else {
+                    problemIPs.add(NetUtils.long2Ip(startIP));
                 }
-            } else {
-                problemIPs.add(NetUtils.long2Ip(startIP));
+                startIP += 1;
             }
-            startIP += 1;
+        }catch (Exception ex) {
+           System.out.println("deletePublicIPRange. Exception: " +ex.getMessage());
+           return null;
         }
 
         return problemIPs;
@@ -351,52 +351,46 @@ public class IPRangeConfig {
     private Vector<String> deletePrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) {
         String deleteSql = "DELETE FROM `cloud`.`op_dc_ip_address_alloc` WHERE ip_address = ? AND pod_id = ? AND data_center_id = ?";
         String isPrivateIPAllocatedSelectSql = "SELECT * FROM `cloud`.`op_dc_ip_address_alloc` WHERE ip_address = ? AND data_center_id = ? AND pod_id = ?";
-
         Vector<String> problemIPs = new Vector<String>();
-        PreparedStatement stmt = null;
-        PreparedStatement isAllocatedStmt = null;
-
-        Connection conn = null;
         try {
-            conn = txn.getConnection();
-            stmt = conn.prepareStatement(deleteSql);
-            isAllocatedStmt = conn.prepareStatement(isPrivateIPAllocatedSelectSql);
-        } catch (SQLException e) {
-            System.out.println("Exception: " + e.getMessage());
-            printError("Unable to start DB connection to delete private IPs. Please contact Cloud Support.");
-        }
-
-        while (startIP <= endIP) {
-            if (!isPrivateIPAllocated(NetUtils.long2Ip(startIP), podId, zoneId, isAllocatedStmt)) {
-                try {
-                    stmt.clearParameters();
-                    stmt.setString(1, NetUtils.long2Ip(startIP));
-                    stmt.setLong(2, podId);
-                    stmt.setLong(3, zoneId);
-                    stmt.executeUpdate();
-                } catch (Exception ex) {
+            Connection conn = txn.getConnection();
+            try (PreparedStatement stmt = conn.prepareStatement(deleteSql);
+                 PreparedStatement isAllocatedStmt = conn.prepareStatement(isPrivateIPAllocatedSelectSql);) {
+                while (startIP <= endIP) {
+                    if (!isPrivateIPAllocated(NetUtils.long2Ip(startIP), podId, zoneId, isAllocatedStmt)) {
+                        stmt.clearParameters();
+                        stmt.setString(1, NetUtils.long2Ip(startIP));
+                        stmt.setLong(2, podId);
+                        stmt.setLong(3, zoneId);
+                        stmt.executeUpdate();
+                    } else {
+                        problemIPs.add(NetUtils.long2Ip(startIP));
+                    }
+                    startIP += 1;
                 }
-            } else {
-                problemIPs.add(NetUtils.long2Ip(startIP));
+            } catch (SQLException e) {
+                System.out.println("deletePrivateIPRange. Exception: " + e.getMessage());
+                printError("deletePrivateIPRange. Exception: " + e.getMessage());
             }
-            startIP += 1;
+        }catch (SQLException e) {
+            System.out.println("deletePrivateIPRange. Exception: " + e.getMessage());
+            printError("deletePrivateIPRange. Exception: " + e.getMessage());
         }
-
         return problemIPs;
     }
 
     private boolean isPublicIPAllocated(long ip, long vlanDbId, PreparedStatement stmt) {
-        try {
+        try(ResultSet rs = stmt.executeQuery();) {
             stmt.clearParameters();
             stmt.setLong(1, ip);
             stmt.setLong(2, vlanDbId);
-            ResultSet rs = stmt.executeQuery();
             if (rs.next()) {
                 return (rs.getString("allocated") != null);
             } else {
                 return false;
             }
-        } catch (SQLException ex) {
+        }
+        catch (SQLException ex) {
             System.out.println(ex.getMessage());
             return true;
         }
@@ -408,11 +402,16 @@ public class IPRangeConfig {
             stmt.setString(1, ip);
             stmt.setLong(2, zoneId);
             stmt.setLong(3, podId);
-            ResultSet rs = stmt.executeQuery();
-            if (rs.next()) {
-                return (rs.getString("taken") != null);
-            } else {
-                return false;
+            try(ResultSet rs = stmt.executeQuery();) {
+                if (rs.next()) {
+                    return (rs.getString("taken") != null);
+                } else {
+                    return false;
+                }
+            }
+            catch (Exception ex) {
+                System.out.println(ex.getMessage());
+                return true;
             }
         } catch (SQLException ex) {
             System.out.println(ex.getMessage());
@@ -451,7 +450,6 @@ public class IPRangeConfig {
             "INSERT INTO `cloud`.`user_ip_address` (public_ip_address, data_center_id, vlan_db_id, mac_address, source_network_id, physical_network_id, uuid) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?, ?, ?)";
         String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
         Vector<String> problemIPs = new Vector<String>();
-        PreparedStatement stmt = null;
 
         Connection conn = null;
         try {
@@ -459,23 +457,20 @@ public class IPRangeConfig {
         } catch (SQLException e) {
             return null;
         }
-
         while (startIP <= endIP) {
-            try {
-                stmt = conn.prepareStatement(insertSql);
-                stmt.setString(1, NetUtils.long2Ip(startIP));
-                stmt.setLong(2, zoneId);
-                stmt.setLong(3, vlanDbId);
-                stmt.setLong(4, zoneId);
-                stmt.setLong(5, sourceNetworkId);
-                stmt.setLong(6, physicalNetworkId);
-                stmt.setString(7, UUID.randomUUID().toString());
-                stmt.executeUpdate();
-                stmt.close();
-                stmt = conn.prepareStatement(updateSql);
-                stmt.setLong(1, zoneId);
-                stmt.executeUpdate();
-                stmt.close();
+            try (PreparedStatement insert_stmt = conn.prepareStatement(insertSql);
+            PreparedStatement update_stmt = conn.prepareStatement(updateSql);
+            ){
+                insert_stmt.setString(1, NetUtils.long2Ip(startIP));
+                insert_stmt.setLong(2, zoneId);
+                insert_stmt.setLong(3, vlanDbId);
+                insert_stmt.setLong(4, zoneId);
+                insert_stmt.setLong(5, sourceNetworkId);
+                insert_stmt.setLong(6, physicalNetworkId);
+                insert_stmt.setString(7, UUID.randomUUID().toString());
+                insert_stmt.executeUpdate();
+                update_stmt.setLong(1, zoneId);
+                update_stmt.executeUpdate();
             } catch (Exception ex) {
                 problemIPs.add(NetUtils.long2Ip(startIP));
             }
@@ -492,21 +487,19 @@ public class IPRangeConfig {
         Vector<String> problemIPs = new Vector<String>();
 
         try {
-            Connection conn = null;
-            conn = txn.getConnection();
+            Connection conn = txn.getConnection();
             while (startIP <= endIP) {
-                try {
-                    PreparedStatement stmt = conn.prepareStatement(insertSql);
-                    stmt.setString(1, NetUtils.long2Ip(startIP));
-                    stmt.setLong(2, zoneId);
-                    stmt.setLong(3, podId);
-                    stmt.setLong(4, zoneId);
-                    stmt.executeUpdate();
-                    stmt.close();
-                    stmt = conn.prepareStatement(updateSql);
-                    stmt.setLong(1, zoneId);
-                    stmt.executeUpdate();
-                    stmt.close();
+                try (PreparedStatement insert_stmt = conn.prepareStatement(insertSql);
+                     PreparedStatement update_stmt = conn.prepareStatement(updateSql);
+                )
+                {
+                    insert_stmt.setString(1, NetUtils.long2Ip(startIP));
+                    insert_stmt.setLong(2, zoneId);
+                    insert_stmt.setLong(3, podId);
+                    insert_stmt.setLong(4, zoneId);
+                    insert_stmt.executeUpdate();
+                    update_stmt.setLong(1, zoneId);
+                    update_stmt.executeUpdate();
                 } catch (Exception e) {
                     problemIPs.add(NetUtils.long2Ip(startIP));
                 }
@@ -531,10 +524,10 @@ public class IPRangeConfig {
             System.out.println("Exception: " + e.getMessage());
             printError("Unable to start DB connection to save private IPs. Please contact Cloud Support.");
         }
+        long start = startIP;
 
-        try {
-            long start = startIP;
-            PreparedStatement stmt = conn.prepareStatement(insertSql);
+        try(PreparedStatement stmt = conn.prepareStatement(insertSql);)
+        {
             while (startIP <= endIP) {
                 stmt.setString(1, NetUtils.long2Ip(startIP++));
                 stmt.setLong(2, zoneId);
@@ -547,10 +540,9 @@ public class IPRangeConfig {
                     problemIPs.add(NetUtils.long2Ip(start + (i / 2)));
                 }
             }
-            stmt.close();
         } catch (Exception ex) {
+            System.out.println("saveLinkLocalPrivateIPRange. Exception: " + ex.getMessage());
         }
-
         return problemIPs;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/87c3d775/usage/src/com/cloud/usage/UsageSanityChecker.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/UsageSanityChecker.java b/usage/src/com/cloud/usage/UsageSanityChecker.java
index 5e6123b..1c9e666 100644
--- a/usage/src/com/cloud/usage/UsageSanityChecker.java
+++ b/usage/src/com/cloud/usage/UsageSanityChecker.java
@@ -170,9 +170,7 @@ public class UsageSanityChecker {
     }
 
     protected void readLastCheckId(){
-        BufferedReader reader = null;
-        try {
-            reader = new BufferedReader(new FileReader(lastCheckFile));
+        try(BufferedReader reader = new BufferedReader(new FileReader(lastCheckFile));) {
             String lastIdText = null;
             lastId = -1;
             if ((reader != null) && (lastIdText = reader.readLine()) != null) {
@@ -180,42 +178,33 @@ public class UsageSanityChecker {
             }
         } catch (IOException e) {
             s_logger.error(e);
-        } finally {
-            try {
-                reader.close();
-            } catch (IOException e) {
-                s_logger.error(e);
-            }
         }
     }
 
     protected void readMaxId() throws SQLException {
-        PreparedStatement pstmt = conn.prepareStatement("select max(id) from cloud_usage.cloud_usage");
-        ResultSet rs = pstmt.executeQuery();
-        maxId = -1;
-        if (rs.next() && (rs.getInt(1) > 0)) {
-            maxId = rs.getInt(1);
-            lastCheckId += " and cu.id <= ?";
+        try(PreparedStatement pstmt = conn.prepareStatement("select max(id) from cloud_usage.cloud_usage");
+            ResultSet rs = pstmt.executeQuery();)
+        {
+            maxId = -1;
+            if (rs.next() && (rs.getInt(1) > 0)) {
+                maxId = rs.getInt(1);
+                lastCheckId += " and cu.id <= ?";
+            }
+        }
+        catch (Exception e)
+        {
+           s_logger.error("readMaxId: Exception :"+ e.getMessage());
         }
     }
 
     protected void updateNewMaxId() {
-        FileWriter fstream = null;
-        try {
-            fstream = new FileWriter(lastCheckFile);
-            BufferedWriter out = new BufferedWriter(fstream);
+
+        try(FileWriter fstream = new FileWriter(lastCheckFile);
+        BufferedWriter out = new BufferedWriter(fstream);
+        ) {
             out.write("" + maxId);
-            out.close();
         } catch (IOException e) {
-            // Error while writing last check id
-        } finally {
-            if (fstream != null) {
-                try {
-                    fstream.close();
-                } catch (IOException e) {
-                    s_logger.error(e);
-                }
-            }
+            s_logger.error("updateMaxId: Exception :"+ e.getMessage());
         }
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/87c3d775/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
index 086e8a8..ed44ac6 100755
--- a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
+++ b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
@@ -19,16 +19,16 @@
 
 package com.cloud.utils.crypt;
 
+
 import java.io.PrintWriter;
 import java.net.InetAddress;
 import java.net.Socket;
-
 import com.cloud.utils.NumbersUtil;
 
+
 public class EncryptionSecretKeySender {
     public static void main(String args[]) {
         try {
-
             // Create a socket to the host
             String hostname = "localhost";
             int port = 8097;
@@ -37,25 +37,29 @@ public class EncryptionSecretKeySender {
                 hostname = args[0];
                 port = NumbersUtil.parseInt(args[1], port);
             }
-
             InetAddress addr = InetAddress.getByName(hostname);
-            Socket socket = new Socket(addr, port);
-            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
-            java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
-            String validationWord = "cloudnine";
-            String validationInput = "";
-            while (!validationWord.equals(validationInput)) {
-                System.out.print("Enter Validation Word:");
-                validationInput = stdin.readLine();
-                System.out.println();
-            }
-            System.out.print("Enter Secret Key:");
-            String input = stdin.readLine();
-            if (input != null) {
-                out.println(input);
+            try(Socket socket = new Socket(addr, port);
+                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);)
+            {
+                java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
+                String validationWord = "cloudnine";
+                String validationInput = "";
+                while (!validationWord.equals(validationInput)) {
+                    System.out.print("Enter Validation Word:");
+                    validationInput = stdin.readLine();
+                    System.out.println();
+                }
+                System.out.print("Enter Secret Key:");
+                String input = stdin.readLine();
+                if (input != null) {
+                    out.println(input);
+                }
+            }catch (Exception e)
+            {
+                System.out.println("Exception " + e.getMessage());
             }
         } catch (Exception e) {
             System.out.print("Exception while sending secret key " + e);
         }
-    }
+   }
 }