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 2015/07/09 21:30:44 UTC

[01/10] git commit: updated refs/heads/master to b0136c5

Repository: cloudstack
Updated Branches:
  refs/heads/master bcc8182f2 -> b0136c56e


coverity 1116509: heavy entanglement of prepared statements and result sets hope I got the logic right. this is for very old versions, might be worth phasing out unless someone still uses it.

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/3bedeeaa
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/3bedeeaa
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/3bedeeaa

Branch: refs/heads/master
Commit: 3bedeeaacc9bbfde00df24bf63b45c82c6cbe52e
Parents: 79709cd
Author: Daan Hoogland <da...@onecht.net>
Authored: Tue Jul 7 13:20:39 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jul 9 21:30:23 2015 +0200

----------------------------------------------------------------------
 .../com/cloud/upgrade/dao/VersionDaoImpl.java   | 96 ++++++++------------
 1 file changed, 40 insertions(+), 56 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3bedeeaa/engine/schema/src/com/cloud/upgrade/dao/VersionDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/VersionDaoImpl.java b/engine/schema/src/com/cloud/upgrade/dao/VersionDaoImpl.java
index bc9c2f0..0fb2dfe 100644
--- a/engine/schema/src/com/cloud/upgrade/dao/VersionDaoImpl.java
+++ b/engine/schema/src/com/cloud/upgrade/dao/VersionDaoImpl.java
@@ -75,49 +75,39 @@ public class VersionDaoImpl extends GenericDaoBase<VersionVO, Long> implements V
     @Override
     @DB
     public String getCurrentVersion() {
-        Connection conn = null;
-        try {
+        try (Connection conn = TransactionLegacy.getStandaloneConnection();) {
             s_logger.debug("Checking to see if the database is at a version before it was the version table is created");
 
-            conn = TransactionLegacy.getStandaloneConnection();
-
-            PreparedStatement pstmt = conn.prepareStatement("SHOW TABLES LIKE 'version'");
-            ResultSet rs = pstmt.executeQuery();
-            if (!rs.next()) {
-                rs.close();
-                pstmt.close();
-                pstmt = conn.prepareStatement("SHOW TABLES LIKE 'nics'");
-                rs = pstmt.executeQuery();
+            try (
+                    PreparedStatement pstmt = conn.prepareStatement("SHOW TABLES LIKE 'version'");
+                    ResultSet rs = pstmt.executeQuery();
+                ) {
                 if (!rs.next()) {
-                    rs.close();
-                    pstmt.close();
-
-                    pstmt = conn.prepareStatement("SELECT domain_id FROM account_vlan_map LIMIT 1");
-                    try {
-                        pstmt.executeQuery();
-                        return "2.1.8";
-                    } catch (final SQLException e) {
-                        s_logger.debug("Assuming the exception means domain_id is not there.");
-                        s_logger.debug("No version table and no nics table, returning 2.1.7");
-                        return "2.1.7";
-                    } finally {
-                        pstmt.close();
-                    }
-                } else {
-                    try {
-                        rs.close();
-                        pstmt.close();
-                        pstmt = conn.prepareStatement("SELECT is_static_nat from firewall_rules");
-                        rs = pstmt.executeQuery();
-                        return "2.2.1";
-                    } catch (final SQLException e) {
-                        s_logger.debug("Assuming the exception means static_nat field doesn't exist in firewall_rules table, returning version 2.2.2");
-                        return "2.2.2";
-                    } finally {
-                        rs.close();
-                        pstmt.close();
+                    try (PreparedStatement pstmt_nics = conn.prepareStatement("SHOW TABLES LIKE 'nics'");
+                         ResultSet rs_nics = pstmt_nics.executeQuery();
+                        ) {
+                        if (!rs_nics.next()) {
+                            try (PreparedStatement pstmt_domain = conn.prepareStatement("SELECT domain_id FROM account_vlan_map LIMIT 1"); ){
+                                pstmt_domain.executeQuery();
+                                return "2.1.8";
+                            } catch (final SQLException e) {
+                                s_logger.debug("Assuming the exception means domain_id is not there.");
+                                s_logger.debug("No version table and no nics table, returning 2.1.7");
+                                return "2.1.7";
+                            }
+                        } else {
+                            try (PreparedStatement pstmt_static_nat = conn.prepareStatement("SELECT is_static_nat from firewall_rules");
+                                 ResultSet rs_static_nat = pstmt_static_nat.executeQuery();){
+                                return "2.2.1";
+                            } catch (final SQLException e) {
+                                s_logger.debug("Assuming the exception means static_nat field doesn't exist in firewall_rules table, returning version 2.2.2");
+                                return "2.2.2";
+                            }
+                        }
                     }
                 }
+            } catch (final SQLException e) {
+                throw new CloudRuntimeException("Unable to get the current version", e);
             }
 
             SearchCriteria<String> sc = CurrentVersionSearch.create();
@@ -137,24 +127,23 @@ public class VersionDaoImpl extends GenericDaoBase<VersionVO, Long> implements V
                 }
 
                 // Use nics table information and is_static_nat field from firewall_rules table to determine version information
-                try {
-                    s_logger.debug("Version table exists, but it's empty; have to confirm that version is 2.2.2");
-                    pstmt = conn.prepareStatement("SHOW TABLES LIKE 'nics'");
-                    rs = pstmt.executeQuery();
+                s_logger.debug("Version table exists, but it's empty; have to confirm that version is 2.2.2");
+                try (PreparedStatement pstmt = conn.prepareStatement("SHOW TABLES LIKE 'nics'");
+                     ResultSet rs = pstmt.executeQuery();){
                     if (!rs.next()) {
                         throw new CloudRuntimeException("Unable to determine the current version, version table exists and empty, nics table doesn't exist");
                     } else {
-                        pstmt = conn.prepareStatement("SELECT is_static_nat from firewall_rules");
-                        pstmt.executeQuery();
-                        throw new CloudRuntimeException("Unable to determine the current version, version table exists and empty, " +
-                                "nics table doesn't exist, is_static_nat field exists in firewall_rules table");
+                        try (PreparedStatement pstmt_static_nat = conn.prepareStatement("SELECT is_static_nat from firewall_rules"); ) {
+                            pstmt_static_nat.executeQuery();
+                            throw new CloudRuntimeException("Unable to determine the current version, version table exists and empty, " +
+                                    "nics table doesn't exist, is_static_nat field exists in firewall_rules table");
+                        } catch (final SQLException e) {
+                            s_logger.debug("Assuming the exception means static_nat field doesn't exist in firewall_rules table, returning version 2.2.2");
+                            return "2.2.2";
+                        }
                     }
                 } catch (final SQLException e) {
-                    s_logger.debug("Assuming the exception means static_nat field doesn't exist in firewall_rules table, returning version 2.2.2");
-                    return "2.2.2";
-                } finally {
-                    rs.close();
-                    pstmt.close();
+                    throw new CloudRuntimeException("Unable to determine the current version, version table exists and empty, query for nics table yields SQL exception", e);
                 }
             } else {
                 return upgradedVersions.get(0);
@@ -162,11 +151,6 @@ public class VersionDaoImpl extends GenericDaoBase<VersionVO, Long> implements V
 
         } catch (final SQLException e) {
             throw new CloudRuntimeException("Unable to get the current version", e);
-        } finally {
-            try {
-                conn.close();
-            } catch (final SQLException e) {
-            }
         }
 
     }


[06/10] git commit: updated refs/heads/master to b0136c5

Posted by da...@apache.org.
coverity 1116564: complicated update of sequences fixed

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

This closes #564


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

Branch: refs/heads/master
Commit: b0136c56e7b2f53e388516090c9dfe4bba1b5a73
Parents: 0cd8c06
Author: Daan Hoogland <da...@onecht.net>
Authored: Wed Jul 8 00:26:13 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jul 9 21:30:24 2015 +0200

----------------------------------------------------------------------
 .../src/com/cloud/utils/db/SequenceFetcher.java | 80 +++++++++-----------
 1 file changed, 36 insertions(+), 44 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b0136c56/framework/db/src/com/cloud/utils/db/SequenceFetcher.java
----------------------------------------------------------------------
diff --git a/framework/db/src/com/cloud/utils/db/SequenceFetcher.java b/framework/db/src/com/cloud/utils/db/SequenceFetcher.java
index e0b4f97..fafc8ad 100644
--- a/framework/db/src/com/cloud/utils/db/SequenceFetcher.java
+++ b/framework/db/src/com/cloud/utils/db/SequenceFetcher.java
@@ -94,15 +94,14 @@ public class SequenceFetcher {
         @Override
         @SuppressWarnings("unchecked")
         public T call() throws Exception {
-            try {
-                PreparedStatement stmt = null;
-                StringBuilder sql = new StringBuilder("SELECT ");
-                sql.append(_tg.valueColumnName()).append(" FROM ").append(_tg.table());
-                sql.append(" WHERE ").append(_tg.pkColumnName()).append(" = ? FOR UPDATE");
+            StringBuilder sql = new StringBuilder("SELECT ");
+            sql.append(_tg.valueColumnName()).append(" FROM ").append(_tg.table());
+            sql.append(" WHERE ").append(_tg.pkColumnName()).append(" = ? FOR UPDATE");
 
-                TransactionLegacy txn = TransactionLegacy.open("Sequence");
 
-                PreparedStatement selectStmt = txn.prepareStatement(sql.toString());
+            try (TransactionLegacy txn = TransactionLegacy.open("Sequence");
+                 PreparedStatement selectStmt = txn.prepareStatement(sql.toString());
+                ) {
                 if (_key == null) {
                     selectStmt.setString(1, _tg.pkColumnValue());
                 } else {
@@ -113,33 +112,33 @@ public class SequenceFetcher {
                 sql.append(_tg.table()).append(" SET ").append(_tg.valueColumnName()).append("=").append("?+?");
                 sql.append(" WHERE ").append(_tg.pkColumnName()).append("=?");
 
-                PreparedStatement updateStmt = txn.prepareStatement(sql.toString());
-                if (isRandom) {
-                    updateStmt.setInt(2, random.nextInt(10) + 1);
-                } else {
-                    updateStmt.setInt(2, _tg.allocationSize());
-                }
-                if (_key == null) {
-                    updateStmt.setString(3, _tg.pkColumnValue());
-                } else {
-                    updateStmt.setObject(3, _key);
-                }
+                try (PreparedStatement updateStmt = txn.prepareStatement(sql.toString());) {
+                    if (isRandom) {
+                        updateStmt.setInt(2, random.nextInt(10) + 1);
+                    } else {
+                        updateStmt.setInt(2, _tg.allocationSize());
+                    }
+                    if (_key == null) {
+                        updateStmt.setString(3, _tg.pkColumnValue());
+                    } else {
+                        updateStmt.setObject(3, _key);
+                    }
 
-                ResultSet rs = null;
-                try {
                     txn.start();
-
-                    stmt = selectStmt;
-                    rs = stmt.executeQuery();
                     Object obj = null;
-                    while (rs.next()) {
-                        if (_clazz.isAssignableFrom(Long.class)) {
-                            obj = rs.getLong(1);
-                        } else if (_clazz.isAssignableFrom(Integer.class)) {
-                            obj = rs.getInt(1);
-                        } else {
-                            obj = rs.getObject(1);
+                    try (ResultSet rs = selectStmt.executeQuery();) {
+
+                        while (rs.next()) {
+                            if (_clazz.isAssignableFrom(Long.class)) {
+                                obj = rs.getLong(1);
+                            } else if (_clazz.isAssignableFrom(Integer.class)) {
+                                obj = rs.getInt(1);
+                            } else {
+                                obj = rs.getObject(1);
+                            }
                         }
+                    } catch (SQLException e) {
+                        s_logger.warn("Caught this exception when running: " + (selectStmt != null ? selectStmt.toString() : ""), e);
                     }
 
                     if (obj == null) {
@@ -148,20 +147,14 @@ public class SequenceFetcher {
                     }
 
                     updateStmt.setObject(1, obj);
-                    stmt = updateStmt;
-                    int rows = stmt.executeUpdate();
-                    assert rows == 1 : "Come on....how exactly did we update this many rows " + rows + " for " + updateStmt.toString();
-                    txn.commit();
-                    return (T)obj;
-                } catch (SQLException e) {
-                    s_logger.warn("Caught this exception when running: " + (stmt != null ? stmt.toString() : ""), e);
-                } finally {
-                    if (rs != null) {
-                        rs.close();
+                    try {
+                        int rows = updateStmt.executeUpdate();
+                        assert rows == 1 : "Come on....how exactly did we update this many rows " + rows + " for " + updateStmt.toString();
+                        txn.commit();
+                        return (T)obj;
+                    } catch (SQLException e) {
+                        s_logger.warn("Caught this exception when running: " + (updateStmt != null ? updateStmt.toString() : ""), e);
                     }
-                    selectStmt.close();
-                    updateStmt.close();
-                    txn.close();
                 }
             } catch (Exception e) {
                 s_logger.warn("Caught this exception when running.", e);
@@ -169,5 +162,4 @@ public class SequenceFetcher {
             return null;
         }
     }
-
 }


[09/10] git commit: updated refs/heads/master to b0136c5

Posted by da...@apache.org.
coverity 1116680: update datacentre for ip adresses these resources are created often and will create serious leakage if closing failes

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/0cd8c06f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/0cd8c06f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/0cd8c06f

Branch: refs/heads/master
Commit: 0cd8c06f7dceaf999acf202862c5d1d580e7aa0e
Parents: bb2c02d
Author: Daan Hoogland <da...@onecht.net>
Authored: Tue Jul 7 23:13:05 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jul 9 21:30:24 2015 +0200

----------------------------------------------------------------------
 .../network/StorageNetworkManagerImpl.java      | 31 ++++++++++----------
 1 file changed, 15 insertions(+), 16 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0cd8c06f/server/src/com/cloud/network/StorageNetworkManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/StorageNetworkManagerImpl.java b/server/src/com/cloud/network/StorageNetworkManagerImpl.java
index ea3bf5c..76a51d9 100644
--- a/server/src/com/cloud/network/StorageNetworkManagerImpl.java
+++ b/server/src/com/cloud/network/StorageNetworkManagerImpl.java
@@ -104,22 +104,21 @@ public class StorageNetworkManagerImpl extends ManagerBase implements StorageNet
         String insertSql =
             "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)";
         String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
-        PreparedStatement stmt = null;
-        Connection conn = txn.getConnection();
-
-        while (startIPLong <= endIPLong) {
-            stmt = conn.prepareStatement(insertSql);
-            stmt.setLong(1, rangeId);
-            stmt.setString(2, NetUtils.long2Ip(startIPLong++));
-            stmt.setLong(3, zoneId);
-            stmt.setNull(4, java.sql.Types.DATE);
-            stmt.executeUpdate();
-            stmt.close();
-
-            stmt = txn.prepareStatement(updateSql);
-            stmt.setLong(1, zoneId);
-            stmt.executeUpdate();
-            stmt.close();
+        try (Connection conn = txn.getConnection();) {
+            while (startIPLong <= endIPLong) {
+                try (PreparedStatement stmt_insert = conn.prepareStatement(insertSql); ) {
+                    stmt_insert.setLong(1, rangeId);
+                    stmt_insert.setString(2, NetUtils.long2Ip(startIPLong++));
+                    stmt_insert.setLong(3, zoneId);
+                    stmt_insert.setNull(4, java.sql.Types.DATE);
+                    stmt_insert.executeUpdate();
+                }
+
+                try (PreparedStatement stmt_update = txn.prepareStatement(updateSql);) {
+                    stmt_update.setLong(1, zoneId);
+                    stmt_update.executeUpdate();
+                }
+            }
         }
     }
 


[08/10] git commit: updated refs/heads/master to b0136c5

Posted by da...@apache.org.
coverity 1116511 and 1116513: try-with-resource on old upgrade script three issues seen by coverity as two. only one occurence of leakage

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/f8691b2c
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/f8691b2c
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/f8691b2c

Branch: refs/heads/master
Commit: f8691b2c69c9b72e91d30a4008d2c121d8045bd5
Parents: 3bedeea
Author: Daan Hoogland <da...@onecht.net>
Authored: Tue Jul 7 13:28:05 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jul 9 21:30:24 2015 +0200

----------------------------------------------------------------------
 .../upgrade/dao/Upgrade218to22Premium.java      | 32 +++++++++-----------
 1 file changed, 15 insertions(+), 17 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f8691b2c/engine/schema/src/com/cloud/upgrade/dao/Upgrade218to22Premium.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade218to22Premium.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade218to22Premium.java
index edf453c..10ae5b0 100644
--- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade218to22Premium.java
+++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade218to22Premium.java
@@ -57,42 +57,40 @@ public class Upgrade218to22Premium extends Upgrade218to22 {
     }
 
     private void updateUserStats(Connection conn) {
-        try {
-
-            // update device_id information
-            PreparedStatement pstmt =
-                conn.prepareStatement("update cloud_usage.user_statistics uus set device_id = " + "(select device_id from cloud.user_statistics us where uus.id = us.id)");
+        try ( // update device_id information
+            PreparedStatement pstmt = conn.prepareStatement(
+                    "update cloud_usage.user_statistics uus set device_id = (select device_id from cloud.user_statistics us where uus.id = us.id)"
+                    );
+            ) {
             pstmt.executeUpdate();
-            pstmt.close();
 
             s_logger.debug("Upgraded cloud_usage user_statistics with deviceId");
+        } catch (Exception e) {
+            throw new CloudRuntimeException("Failed to upgrade user stats: ", e);
+        }
 
-            // update host_id information in usage_network
-            PreparedStatement pstmt1 =
-                conn.prepareStatement("update cloud_usage.usage_network un set host_id = "
+        try ( // update host_id information in usage_network
+            PreparedStatement pstmt1 = conn.prepareStatement(
+                    "update cloud_usage.usage_network un set host_id = "
                     + "(select device_id from cloud_usage.user_statistics us where us.account_id = un.account_id and us.data_center_id = un.zone_id)");
+                ) {
             pstmt1.executeUpdate();
-            pstmt1.close();
 
             s_logger.debug("Upgraded cloud_usage usage_network with hostId");
-
         } catch (Exception e) {
-            throw new CloudRuntimeException("Failed to upgrade user stats: ", e);
+            throw new CloudRuntimeException("Failed to upgrade network usage stats: ", e);
         }
     }
 
     private void updateUsageIpAddress(Connection conn) {
-        try {
-
-            // update id information
+        try ( // update id information
             PreparedStatement pstmt =
                 conn.prepareStatement("update cloud_usage.usage_ip_address uip set id = "
                     + "(select id from cloud.user_ip_address ip where uip.public_ip_address = ip.public_ip_address and ip.data_center_id = uip.zone_id)");
+            ) {
             pstmt.executeUpdate();
-            pstmt.close();
 
             s_logger.debug("Upgraded cloud_usage usage_ip_address with Id");
-
         } catch (Exception e) {
             throw new CloudRuntimeException("Failed to upgrade usage_ip_address: ", e);
         }


[03/10] git commit: updated refs/heads/master to b0136c5

Posted by da...@apache.org.
coverity 1291768: file input stream not severe unless repetitive (property file usually aren't)

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/dae2e05f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/dae2e05f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/dae2e05f

Branch: refs/heads/master
Commit: dae2e05f3cfe5826bd44b33883ce2c57098bfb8e
Parents: 803d6ed
Author: Daan Hoogland <da...@onecht.net>
Authored: Tue Jul 7 12:45:34 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jul 9 21:30:23 2015 +0200

----------------------------------------------------------------------
 .../src/org/apache/cloudstack/mom/kafka/KafkaEventBus.java    | 7 +------
 1 file changed, 1 insertion(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/dae2e05f/plugins/event-bus/kafka/src/org/apache/cloudstack/mom/kafka/KafkaEventBus.java
----------------------------------------------------------------------
diff --git a/plugins/event-bus/kafka/src/org/apache/cloudstack/mom/kafka/KafkaEventBus.java b/plugins/event-bus/kafka/src/org/apache/cloudstack/mom/kafka/KafkaEventBus.java
index 20a0e4c..6d943df 100644
--- a/plugins/event-bus/kafka/src/org/apache/cloudstack/mom/kafka/KafkaEventBus.java
+++ b/plugins/event-bus/kafka/src/org/apache/cloudstack/mom/kafka/KafkaEventBus.java
@@ -59,9 +59,7 @@ public class KafkaEventBus extends ManagerBase implements EventBus {
 
         final Properties props = new Properties();
 
-        try {
-            final FileInputStream is = new FileInputStream(PropertiesUtil.findConfigFile("kafka.producer.properties"));
-
+        try (final FileInputStream is = new FileInputStream(PropertiesUtil.findConfigFile("kafka.producer.properties"));) {
             props.load(is);
 
             _topic = (String)props.remove("topic");
@@ -76,9 +74,6 @@ public class KafkaEventBus extends ManagerBase implements EventBus {
             if (!props.containsKey("value.serializer")) {
                 props.put("value.serializer", DEFAULT_SERIALIZER);
             }
-
-
-            is.close();
         } catch (Exception e) {
             throw new ConfigurationException("Could not read kafka properties");
         }


[07/10] git commit: updated refs/heads/master to b0136c5

Posted by da...@apache.org.
coverity 1116693: properties template file creation unlikely but if repetitive, serious.

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/bb2c02d1
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/bb2c02d1
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/bb2c02d1

Branch: refs/heads/master
Commit: bb2c02d14478ec3c1256f8739dd3e9a09deacb10
Parents: 2c7e19f
Author: Daan Hoogland <da...@onecht.net>
Authored: Tue Jul 7 22:55:09 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jul 9 21:30:24 2015 +0200

----------------------------------------------------------------------
 .../resource/NfsSecondaryStorageResource.java   | 108 +++++++++----------
 1 file changed, 54 insertions(+), 54 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb2c02d1/services/secondary-storage/server/src/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResource.java
----------------------------------------------------------------------
diff --git a/services/secondary-storage/server/src/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResource.java b/services/secondary-storage/server/src/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResource.java
index 606cc10..a529b87 100644
--- a/services/secondary-storage/server/src/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResource.java
+++ b/services/secondary-storage/server/src/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResource.java
@@ -495,66 +495,66 @@ public class NfsSecondaryStorageResource extends ServerResourceBase implements S
             String destFileFullPath = destFile.getAbsolutePath() + File.separator + fileName;
             s_logger.debug("copy snapshot " + srcFile.getAbsolutePath() + " to template " + destFileFullPath);
             Script.runSimpleBashScript("cp " + srcFile.getAbsolutePath() + " " + destFileFullPath);
+            String metaFileName = destFile.getAbsolutePath() + File.separator + "template.properties";
+            File metaFile = new File(metaFileName);
             try {
-                // generate template.properties file
-                String metaFileName = destFile.getAbsolutePath() + File.separator + "template.properties";
                 _storage.create(destFile.getAbsolutePath(), "template.properties");
-                File metaFile = new File(metaFileName);
-                FileWriter writer = new FileWriter(metaFile);
-                BufferedWriter bufferWriter = new BufferedWriter(writer);
-                // KVM didn't change template unique name, just used the template name passed from orchestration layer, so no need
-                // to send template name back.
-                bufferWriter.write("uniquename=" + destData.getName());
-                bufferWriter.write("\n");
-                bufferWriter.write("filename=" + fileName);
-                bufferWriter.write("\n");
-                long size = _storage.getSize(destFileFullPath);
-                bufferWriter.write("size=" + size);
-                bufferWriter.close();
-                writer.close();
-
-                /**
-                 * Snapshots might be in either QCOW2 or RAW image format
-                 *
-                 * For example RBD snapshots are in RAW format
-                 */
-                Processor processor = null;
-                if (srcFormat == ImageFormat.QCOW2) {
-                    processor = new QCOW2Processor();
-                } else if (srcFormat == ImageFormat.RAW) {
-                    processor = new RawImageProcessor();
-                } else {
-                    throw new ConfigurationException("Unknown image format " + srcFormat.toString());
-                }
-
-                Map<String, Object> params = new HashMap<String, Object>();
-                params.put(StorageLayer.InstanceConfigKey, _storage);
-
-                processor.configure("template processor", params);
-                String destPath = destFile.getAbsolutePath();
-
-                FormatInfo info = processor.process(destPath, null, templateName);
-                TemplateLocation loc = new TemplateLocation(_storage, destPath);
-                loc.create(1, true, destData.getName());
-                loc.addFormat(info);
-                loc.save();
+                try ( // generate template.properties file
+                     FileWriter writer = new FileWriter(metaFile);
+                     BufferedWriter bufferWriter = new BufferedWriter(writer);
+                    ) {
+                    // KVM didn't change template unique name, just used the template name passed from orchestration layer, so no need
+                    // to send template name back.
+                    bufferWriter.write("uniquename=" + destData.getName());
+                    bufferWriter.write("\n");
+                    bufferWriter.write("filename=" + fileName);
+                    bufferWriter.write("\n");
+                    long size = _storage.getSize(destFileFullPath);
+                    bufferWriter.write("size=" + size);
+
+                    /**
+                     * Snapshots might be in either QCOW2 or RAW image format
+                     *
+                     * For example RBD snapshots are in RAW format
+                     */
+                    Processor processor = null;
+                    if (srcFormat == ImageFormat.QCOW2) {
+                        processor = new QCOW2Processor();
+                    } else if (srcFormat == ImageFormat.RAW) {
+                        processor = new RawImageProcessor();
+                    } else {
+                        throw new ConfigurationException("Unknown image format " + srcFormat.toString());
+                    }
 
-                TemplateProp prop = loc.getTemplateInfo();
-                TemplateObjectTO newTemplate = new TemplateObjectTO();
-                newTemplate.setPath(destData.getPath() + File.separator + fileName);
-                newTemplate.setFormat(srcFormat);
-                newTemplate.setSize(prop.getSize());
-                newTemplate.setPhysicalSize(prop.getPhysicalSize());
-                return new CopyCmdAnswer(newTemplate);
-            } catch (ConfigurationException e) {
-                s_logger.debug("Failed to create template:" + e.toString());
-                return new CopyCmdAnswer(e.toString());
+                    Map<String, Object> params = new HashMap<String, Object>();
+                    params.put(StorageLayer.InstanceConfigKey, _storage);
+
+                    processor.configure("template processor", params);
+                    String destPath = destFile.getAbsolutePath();
+
+                    FormatInfo info = processor.process(destPath, null, templateName);
+                    TemplateLocation loc = new TemplateLocation(_storage, destPath);
+                    loc.create(1, true, destData.getName());
+                    loc.addFormat(info);
+                    loc.save();
+
+                    TemplateProp prop = loc.getTemplateInfo();
+                    TemplateObjectTO newTemplate = new TemplateObjectTO();
+                    newTemplate.setPath(destData.getPath() + File.separator + fileName);
+                    newTemplate.setFormat(srcFormat);
+                    newTemplate.setSize(prop.getSize());
+                    newTemplate.setPhysicalSize(prop.getPhysicalSize());
+                    return new CopyCmdAnswer(newTemplate);
+                } catch (ConfigurationException e) {
+                    s_logger.debug("Failed to create template:" + e.toString());
+                    return new CopyCmdAnswer(e.toString());
+                } catch (InternalErrorException e) {
+                    s_logger.debug("Failed to create template:" + e.toString());
+                    return new CopyCmdAnswer(e.toString());
+                }
             } catch (IOException e) {
                 s_logger.debug("Failed to create template:" + e.toString());
                 return new CopyCmdAnswer(e.toString());
-            } catch (InternalErrorException e) {
-                s_logger.debug("Failed to create template:" + e.toString());
-                return new CopyCmdAnswer(e.toString());
             }
         }
 


[02/10] git commit: updated refs/heads/master to b0136c5

Posted by da...@apache.org.
coverity 1116507: one off old upgrade code trivial fix however

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/79709cd4
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/79709cd4
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/79709cd4

Branch: refs/heads/master
Commit: 79709cd490e559e8042c6909c1d60d21fe42d598
Parents: dae2e05
Author: Daan Hoogland <da...@onecht.net>
Authored: Tue Jul 7 12:52:37 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jul 9 21:30:23 2015 +0200

----------------------------------------------------------------------
 .../upgrade/dao/Upgrade222to224Premium.java     | 24 ++++++++++----------
 1 file changed, 12 insertions(+), 12 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/79709cd4/engine/schema/src/com/cloud/upgrade/dao/Upgrade222to224Premium.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade222to224Premium.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade222to224Premium.java
index 921c5e6..775c140 100644
--- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade222to224Premium.java
+++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade222to224Premium.java
@@ -60,25 +60,25 @@ public class Upgrade222to224Premium extends Upgrade222to224 {
     }
 
     private void updateUserStats(Connection conn) {
-        try {
+        try (   // update network_id information
+                PreparedStatement pstmt = conn.prepareStatement(
+                    "update cloud_usage.user_statistics uus, cloud.user_statistics us set uus.network_id = us.network_id where uus.id = us.id"
+                    );
+            ) {
 
-            // update network_id information
-            PreparedStatement pstmt =
-                conn.prepareStatement("update cloud_usage.user_statistics uus, cloud.user_statistics us set uus.network_id = " + "us.network_id where uus.id = us.id");
             pstmt.executeUpdate();
-            pstmt.close();
-
             s_logger.debug("Upgraded cloud_usage user_statistics with networkId");
+        } catch (Exception e) {
+            throw new CloudRuntimeException("Failed to upgrade user stats: ", e);
+        }
 
-            // update network_id information in usage_network
-            PreparedStatement pstmt1 =
-                conn.prepareStatement("update cloud_usage.usage_network un, cloud_usage.user_statistics us set un.network_id = "
+        try (   // update network_id information in usage_network
+                PreparedStatement pstmt1 =
+                    conn.prepareStatement("update cloud_usage.usage_network un, cloud_usage.user_statistics us set un.network_id = "
                     + "us.network_id where us.account_id = un.account_id and us.data_center_id = un.zone_id and us.device_id = un.host_id");
+            ) {
             pstmt1.executeUpdate();
-            pstmt1.close();
-
             s_logger.debug("Upgraded cloud_usage usage_network with networkId");
-
         } catch (Exception e) {
             throw new CloudRuntimeException("Failed to upgrade user stats: ", e);
         }


[05/10] git commit: updated refs/heads/master to b0136c5

Posted by da...@apache.org.
coverity 1296982: standard prepared statement and result set leakage

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/803d6ed7
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/803d6ed7
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/803d6ed7

Branch: refs/heads/master
Commit: 803d6ed7df6ca86298a2da749ef2352ea07d1e75
Parents: 6376503
Author: Daan Hoogland <da...@onecht.net>
Authored: Tue Jul 7 12:40:47 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jul 9 21:30:23 2015 +0200

----------------------------------------------------------------------
 engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/803d6ed7/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java
index 14870e7..2c68210 100644
--- a/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java
+++ b/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java
@@ -641,30 +641,23 @@ public class UserVmDaoImpl extends GenericDaoBase<UserVmVO, Long> implements Use
         TransactionLegacy txn = TransactionLegacy.currentTxn();
         List<Pair<Pair<String, VirtualMachine.Type>, Pair<Long, String>>> vmsDetailByNames = new ArrayList<Pair<Pair<String, VirtualMachine.Type>, Pair<Long, String>>>();
 
-        PreparedStatement pstmt = null;
-        try {
-            pstmt = txn.prepareStatement(VMS_DETAIL_BY_NAME + getQueryBatchAppender(vmNames.size()));
+        try (PreparedStatement pstmt = txn.prepareStatement(VMS_DETAIL_BY_NAME + getQueryBatchAppender(vmNames.size()));) {
             pstmt.setString(1, detail);
             int i = 2;
             for(String name : vmNames) {
                 pstmt.setString(i, name);
                 i++;
             }
-            try {
-                ResultSet rs = pstmt.executeQuery();
+            try (ResultSet rs = pstmt.executeQuery();) {
                 while (rs.next()) {
                     vmsDetailByNames.add(new Pair<Pair<String, VirtualMachine.Type>, Pair<Long, String>>(new Pair<String, VirtualMachine.Type>(
                             rs.getString("vm_instance.instance_name"), VirtualMachine.Type.valueOf(rs.getString("vm_type"))),
                             new Pair<Long, String>(rs.getLong("vm_instance.id"), rs.getString("user_vm_details.value"))));
                 }
-                rs.close();
             } catch (Exception e) {
                 s_logger.error("GetVmsDetailsByNames: Exception: " + e.getMessage());
                 throw new CloudRuntimeException("GetVmsDetailsByNames: Exception: " + e.getMessage());
             }
-            if(pstmt != null) {
-                pstmt.close();
-            }
         } catch (Exception e) {
             s_logger.error("GetVmsDetailsByNames: Exception in sql: " + e.getMessage());
             throw new CloudRuntimeException("GetVmsDetailsByNames: Exception: " + e.getMessage());


[04/10] git commit: updated refs/heads/master to b0136c5

Posted by da...@apache.org.
coverity 1308118: more resources being opened only one closed on exception nothing was closed

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/6376503f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/6376503f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/6376503f

Branch: refs/heads/master
Commit: 6376503fe338496f3936fb10c2d6d30598e07023
Parents: bcc8182
Author: Daan Hoogland <da...@onecht.net>
Authored: Tue Jul 7 12:34:10 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jul 9 21:30:23 2015 +0200

----------------------------------------------------------------------
 .../hypervisor/xenserver/resource/CitrixResourceBase.java   | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6376503f/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
index 48e721f..71cc114 100644
--- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
@@ -5052,12 +5052,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
                         }
 
                         if (result && content != null && !content.isEmpty()) {
-                            try {
-                                final File file = new File(folder+"/"+fileName+".txt");
-                                final OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file.getAbsoluteFile()),"UTF-8");
-                                final BufferedWriter bw = new BufferedWriter(fw);
+                            File file = new File(folder+"/"+fileName+".txt");
+                            try (OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file.getAbsoluteFile()),"UTF-8");
+                                 BufferedWriter bw = new BufferedWriter(fw);
+                                ) {
                                 bw.write(content);
-                                bw.close();
                                 s_logger.debug("created file: "+ file + " in folder:"+folder);
                             } catch (final IOException ex) {
                                 s_logger.debug("Failed to create file "+ ex.getMessage());


[10/10] git commit: updated refs/heads/master to b0136c5

Posted by da...@apache.org.
coverity 1116544: a lot of the same (probably other coverity ids covered as well)

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/2c7e19fa
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/2c7e19fa
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/2c7e19fa

Branch: refs/heads/master
Commit: 2c7e19faff8523deb1d34c86535cf09927c8a085
Parents: f8691b2
Author: Daan Hoogland <da...@onecht.net>
Authored: Tue Jul 7 16:49:14 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Thu Jul 9 21:30:24 2015 +0200

----------------------------------------------------------------------
 .../com/cloud/upgrade/dao/Upgrade303to304.java  | 561 ++++++++-----------
 1 file changed, 226 insertions(+), 335 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2c7e19fa/engine/schema/src/com/cloud/upgrade/dao/Upgrade303to304.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade303to304.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade303to304.java
index 5c74bca..96793d4 100644
--- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade303to304.java
+++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade303to304.java
@@ -59,94 +59,72 @@ public class Upgrade303to304 extends Upgrade30xBase implements DbUpgrade {
     }
 
     private void correctVRProviders(Connection conn) {
-        PreparedStatement pstmtVR = null;
-        ResultSet rsVR = null;
-        PreparedStatement pstmt = null;
-        ResultSet rs = null;
-
-        try {
-            pstmtVR = conn.prepareStatement("SELECT id, nsp_id FROM `cloud`.`virtual_router_providers` where type = 'VirtualRouter' AND removed IS NULL");
-            rsVR = pstmtVR.executeQuery();
+
+        try (PreparedStatement pstmtVR = conn.prepareStatement("SELECT id, nsp_id FROM `cloud`.`virtual_router_providers` where type = 'VirtualRouter' AND removed IS NULL");
+             PreparedStatement pstmt = conn.prepareStatement("SELECT  physical_network_id, provider_name FROM `cloud`.`physical_network_service_providers` where id = ?");
+             PreparedStatement pstmt1 =
+                        conn.prepareStatement("SELECT  id FROM `cloud`.`physical_network_service_providers` where physical_network_id = ? AND provider_name = ? AND removed IS NULL");
+             PreparedStatement pstmtUpdate = conn.prepareStatement("UPDATE `cloud`.`virtual_router_providers` SET nsp_id = ? WHERE id = ?");
+             ResultSet rsVR = pstmtVR.executeQuery();
+            ) {
             while (rsVR.next()) {
                 long vrId = rsVR.getLong(1);
                 long nspId = rsVR.getLong(2);
-
                 //check that this nspId points to a VR provider.
-                pstmt = conn.prepareStatement("SELECT  physical_network_id, provider_name FROM `cloud`.`physical_network_service_providers` where id = ?");
+
                 pstmt.setLong(1, nspId);
-                rs = pstmt.executeQuery();
-                if (rs.next()) {
-                    long physicalNetworkId = rs.getLong(1);
-                    String providerName = rs.getString(2);
-                    if (!providerName.equalsIgnoreCase("VirtualRouter")) {
-                        //mismatch, correct the nsp_id in VR
-                        PreparedStatement pstmt1 = null;
-                        ResultSet rs1 = null;
-                        pstmt1 =
-                            conn.prepareStatement("SELECT  id FROM `cloud`.`physical_network_service_providers` where physical_network_id = ? AND provider_name = ? AND removed IS NULL");
-                        pstmt1.setLong(1, physicalNetworkId);
-                        pstmt1.setString(2, "VirtualRouter");
-                        rs1 = pstmt1.executeQuery();
-                        if (rs1.next()) {
-                            long correctNSPId = rs1.getLong(1);
-
-                            //update VR entry
-                            PreparedStatement pstmtUpdate = null;
-                            String updateNSPId = "UPDATE `cloud`.`virtual_router_providers` SET nsp_id = ? WHERE id = ?";
-                            pstmtUpdate = conn.prepareStatement(updateNSPId);
-                            pstmtUpdate.setLong(1, correctNSPId);
-                            pstmtUpdate.setLong(2, vrId);
-                            pstmtUpdate.executeUpdate();
-                            pstmtUpdate.close();
+                try (ResultSet rs = pstmt.executeQuery();) {
+                    if (rs.next()) {
+                        long physicalNetworkId = rs.getLong(1);
+                        String providerName = rs.getString(2);
+                        if (!providerName.equalsIgnoreCase("VirtualRouter")) {
+                            //mismatch, correct the nsp_id in VR
+                            pstmt1.setLong(1, physicalNetworkId);
+                            pstmt1.setString(2, "VirtualRouter");
+                            try (ResultSet rs1 = pstmt1.executeQuery();) {
+                                if (rs1.next()) {
+                                    long correctNSPId = rs1.getLong(1);
+
+                                    //update VR entry
+                                    pstmtUpdate.setLong(1, correctNSPId);
+                                    pstmtUpdate.setLong(2, vrId);
+                                    pstmtUpdate.executeUpdate();
+                                }
+                            }
                         }
-                        rs1.close();
-                        pstmt1.close();
                     }
                 }
-                rs.close();
-                pstmt.close();
             }
         } catch (SQLException e) {
             throw new CloudRuntimeException("Exception while correcting Virtual Router Entries", e);
-        } finally {
-            if (rsVR != null) {
-                try {
-                    rsVR.close();
-                } catch (SQLException e) {
-                }
-            }
-
-            if (pstmtVR != null) {
-                try {
-                    pstmtVR.close();
-                } catch (SQLException e) {
-                }
-            }
-
-            if (rs != null) {
-                try {
-                    rs.close();
-                } catch (SQLException e) {
-                }
-            }
-
-            if (pstmt != null) {
-                try {
-                    pstmt.close();
-                } catch (SQLException e) {
-                }
-            }
         }
-
     }
 
     private void correctMultiplePhysicaNetworkSetups(Connection conn) {
-        PreparedStatement pstmtZone = null;
-        ResultSet rsZone = null;
-        PreparedStatement pstmt = null;
-        ResultSet rs = null;
 
-        try {
+        try (
+                PreparedStatement pstmtZone = conn.prepareStatement("SELECT id, domain_id, networktype, name, uuid FROM `cloud`.`data_center`");
+                ResultSet rsZone = pstmtZone.executeQuery();
+                PreparedStatement pstmt_count_networks = conn.prepareStatement("SELECT count(n.id) FROM networks n WHERE n.physical_network_id IS NULL AND n.traffic_type = 'Guest' and n.data_center_id = ? and n.removed is null");
+                PreparedStatement pstmtUpdate = conn.prepareStatement("UPDATE `cloud`.`data_center` SET uuid = ? WHERE id = ?");
+                PreparedStatement pstmt_count_traffic_types_and_labels =
+                        conn.prepareStatement("SELECT count(*) FROM `cloud`.`physical_network_traffic_types` pntt JOIN `cloud`.`physical_network` pn ON pntt.physical_network_id = pn.id WHERE pntt.traffic_type ='Guest' AND pn.data_center_id = ? AND pntt.xen_network_label = ?");
+                PreparedStatement pstmt_network_id =
+                        conn.prepareStatement("SELECT n.id FROM networks n WHERE n.physical_network_id IS NULL AND n.traffic_type = 'Guest' and n.data_center_id = ? and n.removed is null");
+                PreparedStatement pstmt_count_traffic_types =
+                        conn.prepareStatement("SELECT count(*) FROM `cloud`.`physical_network_traffic_types` pntt JOIN `cloud`.`physical_network` pn ON pntt.physical_network_id = pn.id WHERE pntt.traffic_type ='Guest' and pn.data_center_id = ?");
+                PreparedStatement pstmt_select_vnets_on_different_physical_net =
+                        conn.prepareStatement("SELECT v.id, v.vnet, v.reservation_id, v.physical_network_id as vpid, n.id, n.physical_network_id as npid FROM `cloud`.`op_dc_vnet_alloc` v JOIN `cloud`.`networks` n ON CONCAT('vlan://' , v.vnet) = n.broadcast_uri WHERE v.taken IS NOT NULL AND v.data_center_id = ? AND n.removed IS NULL AND v.physical_network_id !=  n.physical_network_id");
+                PreparedStatement pstmt_select_vnets =
+                        conn.prepareStatement("SELECT v.id, v.vnet, v.reservation_id FROM `cloud`.`op_dc_vnet_alloc` v LEFT JOIN networks n ON CONCAT('vlan://' , v.vnet) = n.broadcast_uri WHERE v.taken IS NOT NULL AND v.data_center_id = ? AND n.broadcast_uri IS NULL AND n.removed IS NULL");
+                PreparedStatement pstmt_select_nic_ids = conn.prepareStatement("SELECT id, instance_id FROM `cloud`.`nics` where broadcast_uri = ? and removed IS NULL");
+                PreparedStatement pstmt_physical_network_tags =
+                        conn.prepareStatement("SELECT pn.id as pid , ptag.tag as tag FROM `cloud`.`physical_network` pn LEFT JOIN `cloud`.`physical_network_tags` ptag ON pn.id = ptag.physical_network_id where pn.data_center_id = ?");
+                PreparedStatement pstmt_insert_physical_networkTags = conn.prepareStatement("INSERT INTO `cloud`.`physical_network_tags`(tag, physical_network_id) VALUES( ?, ? )");
+                PreparedStatement pstmt_select_distict_netoffers =
+                        conn.prepareStatement("SELECT distinct network_offering_id FROM `cloud`.`networks` where traffic_type= 'Guest' and physical_network_id = ? and removed is null");
+                PreparedStatement pstmt_update_vnet_alloc = conn.prepareStatement("UPDATE `cloud`.`op_dc_vnet_alloc` SET account_id = NULL, taken = NULL, reservation_id = NULL WHERE id = ?");
+                ) {
 
             //check if multiple physical networks with 'Guest' Traffic types are present
             //Yes:
@@ -159,8 +137,6 @@ public class Upgrade303to304 extends Upgrade30xBase implements DbUpgrade {
             //add ntwk service map entries
             //update all guest networks of 1 physical network having this offering id to this new offering id
 
-            pstmtZone = conn.prepareStatement("SELECT id, domain_id, networktype, name, uuid FROM `cloud`.`data_center`");
-            rsZone = pstmtZone.executeQuery();
             while (rsZone.next()) {
                 long zoneId = rsZone.getLong(1);
                 Long domainId = rsZone.getLong(2);
@@ -168,331 +144,246 @@ public class Upgrade303to304 extends Upgrade30xBase implements DbUpgrade {
                 String zoneName = rsZone.getString(4);
                 String uuid = rsZone.getString(5);
 
-                PreparedStatement pstmtUpdate = null;
                 if (uuid == null) {
                     uuid = UUID.randomUUID().toString();
-                    String updateUuid = "UPDATE `cloud`.`data_center` SET uuid = ? WHERE id = ?";
-                    pstmtUpdate = conn.prepareStatement(updateUuid);
                     pstmtUpdate.setString(1, uuid);
                     pstmtUpdate.setLong(2, zoneId);
                     pstmtUpdate.executeUpdate();
-                    pstmtUpdate.close();
                 }
 
                 //check if any networks were untagged and remaining to be mapped to a physical network
-
-                pstmt =
-                    conn.prepareStatement("SELECT count(n.id) FROM networks n WHERE n.physical_network_id IS NULL AND n.traffic_type = 'Guest' and n.data_center_id = ? and n.removed is null");
-                pstmt.setLong(1, zoneId);
-                rs = pstmt.executeQuery();
-                if (rs.next()) {
-                    Long count = rs.getLong(1);
-                    if (count > 0) {
-                        // find the default tag to use from global config or use 'cloud-private'
-                        String xenGuestLabel = getNetworkLabelFromConfig(conn, "xen.guest.network.device");
-                        //Decrypt this value.
-                        xenGuestLabel = DBEncryptionUtil.decrypt(xenGuestLabel);
-
-                        //make sure that no physical network with this traffic label already exists. if yes, error out.
-                        if (xenGuestLabel != null) {
-                            PreparedStatement pstmt5 =
-                                conn.prepareStatement("SELECT count(*) FROM `cloud`.`physical_network_traffic_types` pntt JOIN `cloud`.`physical_network` pn ON pntt.physical_network_id = pn.id WHERE pntt.traffic_type ='Guest' AND pn.data_center_id = ? AND pntt.xen_network_label = ?");
-                            pstmt5.setLong(1, zoneId);
-                            pstmt5.setString(2, xenGuestLabel);
-                            ResultSet rsSameLabel = pstmt5.executeQuery();
-
-                            if (rsSameLabel.next()) {
-                                Long sameLabelcount = rsSameLabel.getLong(1);
-                                if (sameLabelcount > 0) {
-                                    s_logger.error("There are untagged networks for which we need to add a physical network with Xen traffic label = 'xen.guest.network.device' config value, which is: " +
-                                        xenGuestLabel);
-                                    s_logger.error("However already there are " + sameLabelcount + " physical networks setup with same traffic label, cannot upgrade");
-                                    throw new CloudRuntimeException("Cannot upgrade this setup since a physical network with same traffic label: " + xenGuestLabel +
-                                        " already exists, Please check logs and contact Support.");
+                pstmt_count_networks.setLong(1, zoneId);
+                try (ResultSet rsNetworks = pstmt_count_networks.executeQuery();) {
+                    if (rsNetworks.next()) {
+                        Long count = rsNetworks.getLong(1);
+                        if (count > 0) {
+                            // find the default tag to use from global config or use 'cloud-private'
+                            String xenGuestLabel = getNetworkLabelFromConfig(conn, "xen.guest.network.device");
+                            //Decrypt this value.
+                            xenGuestLabel = DBEncryptionUtil.decrypt(xenGuestLabel);
+
+                            //make sure that no physical network with this traffic label already exists. if yes, error out.
+                            if (xenGuestLabel != null) {
+                                pstmt_count_traffic_types_and_labels.setLong(1, zoneId);
+                                pstmt_count_traffic_types_and_labels.setString(2, xenGuestLabel);
+                                try (ResultSet rsSameLabel = pstmt_count_traffic_types_and_labels.executeQuery();) {
+
+                                    if (rsSameLabel.next()) {
+                                        Long sameLabelcount = rsSameLabel.getLong(1);
+                                        if (sameLabelcount > 0) {
+                                            s_logger.error("There are untagged networks for which we need to add a physical network with Xen traffic label = 'xen.guest.network.device' config value, which is: " +
+                                                    xenGuestLabel);
+                                            s_logger.error("However already there are " + sameLabelcount + " physical networks setup with same traffic label, cannot upgrade");
+                                            throw new CloudRuntimeException("Cannot upgrade this setup since a physical network with same traffic label: " + xenGuestLabel +
+                                                    " already exists, Please check logs and contact Support.");
+                                        }
+                                    }
+                                }
+                            }
+                            //Create a physical network with guest traffic type and this tag
+                            long physicalNetworkId = addPhysicalNetworkToZone(conn, zoneId, zoneName, networkType, null, domainId);
+                            addTrafficType(conn, physicalNetworkId, "Guest", xenGuestLabel, null, null);
+                            addDefaultVRProvider(conn, physicalNetworkId, zoneId);
+                            addDefaultSGProvider(conn, physicalNetworkId, zoneId, networkType, true);
+
+                            pstmt_network_id.setLong(1, zoneId);
+                            try (ResultSet rsNet = pstmt_network_id.executeQuery();) {
+                                s_logger.debug("Adding PhysicalNetwork to VLAN");
+                                s_logger.debug("Adding PhysicalNetwork to user_ip_address");
+                                s_logger.debug("Adding PhysicalNetwork to networks");
+                                while (rsNet.next()) {
+                                    Long networkId = rsNet.getLong(1);
+                                    addPhysicalNtwk_To_Ntwk_IP_Vlan(conn, physicalNetworkId, networkId);
                                 }
                             }
                         }
-
-                        //Create a physical network with guest traffic type and this tag
-                        long physicalNetworkId = addPhysicalNetworkToZone(conn, zoneId, zoneName, networkType, null, domainId);
-                        addTrafficType(conn, physicalNetworkId, "Guest", xenGuestLabel, null, null);
-                        addDefaultVRProvider(conn, physicalNetworkId, zoneId);
-                        addDefaultSGProvider(conn, physicalNetworkId, zoneId, networkType, true);
-
-                        PreparedStatement pstmt3 =
-                            conn.prepareStatement("SELECT n.id FROM networks n WHERE n.physical_network_id IS NULL AND n.traffic_type = 'Guest' and n.data_center_id = ? and n.removed is null");
-                        pstmt3.setLong(1, zoneId);
-                        ResultSet rsNet = pstmt3.executeQuery();
-                        s_logger.debug("Adding PhysicalNetwork to VLAN");
-                        s_logger.debug("Adding PhysicalNetwork to user_ip_address");
-                        s_logger.debug("Adding PhysicalNetwork to networks");
-                        while (rsNet.next()) {
-                            Long networkId = rsNet.getLong(1);
-                            addPhysicalNtwk_To_Ntwk_IP_Vlan(conn, physicalNetworkId, networkId);
-                        }
-                        rsNet.close();
-                        pstmt3.close();
                     }
                 }
-                rs.close();
-                pstmt.close();
 
                 boolean multiplePhysicalNetworks = false;
 
-                pstmt =
-                    conn.prepareStatement("SELECT count(*) FROM `cloud`.`physical_network_traffic_types` pntt JOIN `cloud`.`physical_network` pn ON pntt.physical_network_id = pn.id WHERE pntt.traffic_type ='Guest' and pn.data_center_id = ?");
-                pstmt.setLong(1, zoneId);
-                rs = pstmt.executeQuery();
-                if (rs.next()) {
-                    Long count = rs.getLong(1);
-                    if (count > 1) {
-                        s_logger.debug("There are " + count + " physical networks setup");
-                        multiplePhysicalNetworks = true;
+                pstmt_count_traffic_types.setLong(1, zoneId);
+                try (ResultSet rs = pstmt_count_traffic_types.executeQuery();) {
+                    if (rs.next()) {
+                        Long count = rs.getLong(1);
+                        if (count > 1) {
+                            s_logger.debug("There are " + count + " physical networks setup");
+                            multiplePhysicalNetworks = true;
+                        }
                     }
                 }
-                rs.close();
-                pstmt.close();
 
                 if (multiplePhysicalNetworks) {
                     //check if guest vnet is wrongly configured by earlier upgrade. If yes error out
                     //check if any vnet is allocated and guest networks are using vnet But the physical network id does not match on the vnet and guest network.
-                    PreparedStatement pstmt4 =
-                        conn.prepareStatement("SELECT v.id, v.vnet, v.reservation_id, v.physical_network_id as vpid, n.id, n.physical_network_id as npid FROM `cloud`.`op_dc_vnet_alloc` v JOIN `cloud`.`networks` n ON CONCAT('vlan://' , v.vnet) = n.broadcast_uri WHERE v.taken IS NOT NULL AND v.data_center_id = ? AND n.removed IS NULL AND v.physical_network_id !=  n.physical_network_id");
-                    pstmt4.setLong(1, zoneId);
-                    ResultSet rsVNet = pstmt4.executeQuery();
-                    if (rsVNet.next()) {
-                        String vnet = rsVNet.getString(2);
-                        String networkId = rsVNet.getString(5);
-                        String vpid = rsVNet.getString(4);
-                        String npid = rsVNet.getString(6);
-                        s_logger.error("Guest Vnet assignment is set wrongly . Cannot upgrade until that is corrected. Example- Vnet: " + vnet +
-                            " has physical network id: " + vpid + " ,but the guest network: " + networkId + " that uses it has physical network id: " + npid);
-
-                        String message = "Cannot upgrade. Your setup has multiple Physical Networks and is using guest Vnet that is assigned wrongly. "
-                            + "To upgrade, first correct the setup by doing the following: \n"
-                            + "1. Please rollback to your 2.2.14 setup\n"
-                            + "2. Please stop all VMs using isolated(virtual) networks through CloudStack\n"
-                            + "3. Run following query to find if any networks still have nics allocated:\n\t"
-                            + "a) check if any virtual guest networks still have allocated nics by running:\n\t"
-                            + "SELECT DISTINCT op.id from `cloud`.`op_networks` op JOIN `cloud`.`networks` n on op.id=n.id WHERE nics_count != 0 AND guest_type = 'Virtual';\n\t"
-                            + "b) If this returns any networkd ids, then ensure that all VMs are stopped, no new VM is being started, and then shutdown management server\n\t"
-                            + "c) Clean up the nics count for the 'virtual' network id's returned in step (a) by running this:\n\t"
-                            + "UPDATE `cloud`.`op_networks` SET nics_count = 0 WHERE  id = <enter id of virtual network>\n\t"
-                            + "d) Restart management server and wait for all networks to shutdown. "
-                            + "[Networks shutdown will be determined by network.gc.interval and network.gc.wait seconds] \n"
-                            + "4. Please ensure all networks are shutdown and all guest Vnet's are free.\n"
-                            + "5. Run upgrade. This will allocate all your guest vnet range to first physical network.  \n"
-                            + "6. Reconfigure the vnet ranges for each physical network as desired by using updatePhysicalNetwork API \n" + "7. Start all your VMs";
-
-                        s_logger.error(message);
-                        throw new CloudRuntimeException("Cannot upgrade this setup since Guest Vnet assignment to the multiple physical networks " +
-                            "is incorrect. Please check the logs for details on how to proceed");
+                    pstmt_select_vnets_on_different_physical_net.setLong(1, zoneId);
+                    try (ResultSet rsVNet = pstmt_select_vnets_on_different_physical_net.executeQuery();) {
+                        if (rsVNet.next()) {
+                            String vnet = rsVNet.getString(2);
+                            String networkId = rsVNet.getString(5);
+                            String vpid = rsVNet.getString(4);
+                            String npid = rsVNet.getString(6);
+                            s_logger.error("Guest Vnet assignment is set wrongly . Cannot upgrade until that is corrected. Example- Vnet: " + vnet +
+                                    " has physical network id: " + vpid + " ,but the guest network: " + networkId + " that uses it has physical network id: " + npid);
+
+                            String message = "Cannot upgrade. Your setup has multiple Physical Networks and is using guest Vnet that is assigned wrongly. "
+                                    + "To upgrade, first correct the setup by doing the following: \n"
+                                    + "1. Please rollback to your 2.2.14 setup\n"
+                                    + "2. Please stop all VMs using isolated(virtual) networks through CloudStack\n"
+                                    + "3. Run following query to find if any networks still have nics allocated:\n\t"
+                                    + "a) check if any virtual guest networks still have allocated nics by running:\n\t"
+                                    + "SELECT DISTINCT op.id from `cloud`.`op_networks` op JOIN `cloud`.`networks` n on op.id=n.id WHERE nics_count != 0 AND guest_type = 'Virtual';\n\t"
+                                    + "b) If this returns any networkd ids, then ensure that all VMs are stopped, no new VM is being started, and then shutdown management server\n\t"
+                                    + "c) Clean up the nics count for the 'virtual' network id's returned in step (a) by running this:\n\t"
+                                    + "UPDATE `cloud`.`op_networks` SET nics_count = 0 WHERE  id = <enter id of virtual network>\n\t"
+                                    + "d) Restart management server and wait for all networks to shutdown. "
+                                    + "[Networks shutdown will be determined by network.gc.interval and network.gc.wait seconds] \n"
+                                    + "4. Please ensure all networks are shutdown and all guest Vnet's are free.\n"
+                                    + "5. Run upgrade. This will allocate all your guest vnet range to first physical network.  \n"
+                                    + "6. Reconfigure the vnet ranges for each physical network as desired by using updatePhysicalNetwork API \n" + "7. Start all your VMs";
+
+                            s_logger.error(message);
+                            throw new CloudRuntimeException("Cannot upgrade this setup since Guest Vnet assignment to the multiple physical networks " +
+                                    "is incorrect. Please check the logs for details on how to proceed");
 
+                        }
                     }
-                    rsVNet.close();
-                    pstmt4.close();
 
                     //Clean up any vnets that have no live networks/nics
-                    pstmt4 =
-                        conn.prepareStatement("SELECT v.id, v.vnet, v.reservation_id FROM `cloud`.`op_dc_vnet_alloc` v LEFT JOIN networks n ON CONCAT('vlan://' , v.vnet) = n.broadcast_uri WHERE v.taken IS NOT NULL AND v.data_center_id = ? AND n.broadcast_uri IS NULL AND n.removed IS NULL");
-                    pstmt4.setLong(1, zoneId);
-                    rsVNet = pstmt4.executeQuery();
-                    while (rsVNet.next()) {
-                        Long vnet_id = rsVNet.getLong(1);
-                        String vnetValue = rsVNet.getString(2);
-                        String reservationId = rsVNet.getString(3);
-                        //does this vnet have any nic associated?
-                        PreparedStatement pstmt5 = conn.prepareStatement("SELECT id, instance_id FROM `cloud`.`nics` where broadcast_uri = ? and removed IS NULL");
-                        String uri = "vlan://" + vnetValue;
-                        pstmt5.setString(1, uri);
-                        ResultSet rsNic = pstmt5.executeQuery();
-                        Long nic_id = rsNic.getLong(1);
-                        Long instance_id = rsNic.getLong(2);
-                        if (rsNic.next()) {
-                            throw new CloudRuntimeException("Cannot upgrade. Please cleanup the guest vnet: " + vnetValue + " , it is being used by nic_id: " + nic_id +
-                                " , instance_id: " + instance_id);
+                    pstmt_select_vnets.setLong(1, zoneId);
+                    try (ResultSet rsVNet = pstmt_select_vnets.executeQuery();) {
+                        while (rsVNet.next()) {
+                            Long vnet_id = rsVNet.getLong(1);
+                            String vnetValue = rsVNet.getString(2);
+                            // third result parameter is never used: String reservationId = rsVNet.getString(3);
+                            //does this vnet have any nic associated?
+                            String uri = "vlan://" + vnetValue;
+                            pstmt_select_nic_ids.setString(1, uri);
+                            try (ResultSet rsNic = pstmt_select_nic_ids.executeQuery();) {
+                                Long nic_id = rsNic.getLong(1);
+                                Long instance_id = rsNic.getLong(2);
+                                if (rsNic.next()) {
+                                    throw new CloudRuntimeException("Cannot upgrade. Please cleanup the guest vnet: " + vnetValue + " , it is being used by nic_id: " + nic_id +
+                                            " , instance_id: " + instance_id);
+                                }
+                            }
+                            //free this vnet
+                            pstmt_update_vnet_alloc.setLong(1, vnet_id);
+                            pstmt_update_vnet_alloc.executeUpdate();
+                            pstmt_update_vnet_alloc.close();
                         }
-
-                        //free this vnet
-                        String freeVnet = "UPDATE `cloud`.`op_dc_vnet_alloc` SET account_id = NULL, taken = NULL, reservation_id = NULL WHERE id = ?";
-                        pstmtUpdate = conn.prepareStatement(freeVnet);
-                        pstmtUpdate.setLong(1, vnet_id);
-                        pstmtUpdate.executeUpdate();
-                        pstmtUpdate.close();
                     }
-                    rsVNet.close();
-                    pstmt4.close();
 
                     //add tags to the physical networks if not present and clone offerings
 
-                    pstmt =
-                        conn.prepareStatement("SELECT pn.id as pid , ptag.tag as tag FROM `cloud`.`physical_network` pn LEFT JOIN `cloud`.`physical_network_tags` ptag ON pn.id = ptag.physical_network_id where pn.data_center_id = ?");
-                    pstmt.setLong(1, zoneId);
-                    rs = pstmt.executeQuery();
-                    while (rs.next()) {
-                        long physicalNetworkId = rs.getLong("pid");
-                        String tag = rs.getString("tag");
-                        if (tag == null) {
-                            //need to add unique tag
-                            String newTag = "pNtwk-tag-" + physicalNetworkId;
-
-                            String updateVnet = "INSERT INTO `cloud`.`physical_network_tags`(tag, physical_network_id) VALUES( ?, ? )";
-                            pstmtUpdate = conn.prepareStatement(updateVnet);
-                            pstmtUpdate.setString(1, newTag);
-                            pstmtUpdate.setLong(2, physicalNetworkId);
-                            pstmtUpdate.executeUpdate();
-                            pstmtUpdate.close();
-
-                            //clone offerings and tag them with this new tag, if there are any guest networks for this physical network
-
-                            PreparedStatement pstmt2 = null;
-                            ResultSet rs2 = null;
-
-                            pstmt2 =
-                                conn.prepareStatement("SELECT distinct network_offering_id FROM `cloud`.`networks` where traffic_type= 'Guest' and physical_network_id = ? and removed is null");
-                            pstmt2.setLong(1, physicalNetworkId);
-                            rs2 = pstmt2.executeQuery();
-
-                            while (rs2.next()) {
-                                //clone each offering, add new tag, clone offering-svc-map, update guest networks with new offering id
-                                long networkOfferingId = rs2.getLong(1);
-                                cloneOfferingAndAddTag(conn, networkOfferingId, physicalNetworkId, newTag);
+                    pstmt_physical_network_tags.setLong(1, zoneId);
+                    try (ResultSet rs_network_count = pstmt_physical_network_tags.executeQuery();) {
+                        while (rs_network_count.next()) {
+                            long physicalNetworkId = rs_network_count.getLong("pid");
+                            String tag = rs_network_count.getString("tag");
+                            if (tag == null) {
+                                //need to add unique tag
+                                String newTag = "pNtwk-tag-" + physicalNetworkId;
+
+                                pstmt_insert_physical_networkTags.setString(1, newTag);
+                                pstmt_insert_physical_networkTags.setLong(2, physicalNetworkId);
+                                pstmt_insert_physical_networkTags.executeUpdate();
+                                pstmt_insert_physical_networkTags.close();
+
+                                //clone offerings and tag them with this new tag, if there are any guest networks for this physical network
+                                pstmt_select_distict_netoffers.setLong(1, physicalNetworkId);
+                                try (ResultSet rs_netoffers = pstmt_select_distict_netoffers.executeQuery();) {
+                                    while (rs_netoffers.next()) {
+                                        //clone each offering, add new tag, clone offering-svc-map, update guest networks with new offering id
+                                        long networkOfferingId = rs_netoffers.getLong(1);
+                                        cloneOfferingAndAddTag(conn, networkOfferingId, physicalNetworkId, newTag);
+                                    }
+                                }
                             }
-                            rs2.close();
-                            pstmt2.close();
                         }
                     }
-                    rs.close();
-                    pstmt.close();
                 }
             }
         } catch (SQLException e) {
             throw new CloudRuntimeException("Exception while correcting PhysicalNetwork setup", e);
-        } finally {
-            if (rsZone != null) {
-                try {
-                    rsZone.close();
-                } catch (SQLException e) {
-                }
-            }
-
-            if (pstmtZone != null) {
-                try {
-                    pstmtZone.close();
-                } catch (SQLException e) {
-                }
-            }
-
-            if (rs != null) {
-                try {
-                    rs.close();
-                } catch (SQLException e) {
-                }
-            }
-
-            if (pstmt != null) {
-                try {
-                    pstmt.close();
-                } catch (SQLException e) {
-                }
-            }
         }
     }
 
     private void cloneOfferingAndAddTag(Connection conn, long networkOfferingId, long physicalNetworkId, String newTag) {
 
-        PreparedStatement pstmt = null;
-        ResultSet rs = null;
-        try {
-            pstmt = conn.prepareStatement("select count(*) from `cloud`.`network_offerings`");
-            rs = pstmt.executeQuery();
+        try (PreparedStatement pstmt_count_offerings = conn.prepareStatement("select count(*) from `cloud`.`network_offerings`");
+                PreparedStatement pstmt_drop_temp_table = conn.prepareStatement("DROP TEMPORARY TABLE IF EXISTS `cloud`.`network_offerings2`");
+                PreparedStatement pstmt_create_temp_table = conn.prepareStatement("CREATE TEMPORARY TABLE `cloud`.`network_offerings2` ENGINE=MEMORY SELECT * FROM `cloud`.`network_offerings` WHERE id=1");
+                PreparedStatement pstmt_copy_net_offer = conn.prepareStatement("INSERT INTO `cloud`.`network_offerings2` SELECT * FROM `cloud`.`network_offerings` WHERE id=?");
+                PreparedStatement pstmt_unique_name = conn.prepareStatement("SELECT unique_name FROM `cloud`.`network_offerings` WHERE id=?");
+                PreparedStatement pstmt_update_temp_offer = conn.prepareStatement("UPDATE `cloud`.`network_offerings2` SET id=?, unique_name=?, name=?, tags=?, uuid=?  WHERE id=?");
+                PreparedStatement pstmt_update_offering = conn.prepareStatement("INSERT INTO `cloud`.`network_offerings` SELECT * from `cloud`.`network_offerings2` WHERE id= ?");
+                PreparedStatement pstmt_select_service = conn.prepareStatement("select service, provider from `cloud`.`ntwk_offering_service_map` where network_offering_id=?");
+                PreparedStatement pstmt_insert_netofferservicemap =
+                        conn.prepareStatement("INSERT INTO `cloud`.`ntwk_offering_service_map` (`network_offering_id`, `service`, `provider`, `created`) values (?,?,?, now())");
+                PreparedStatement pstmt_update_networks =
+                        conn.prepareStatement("UPDATE `cloud`.`networks` SET network_offering_id=? where physical_network_id=? and traffic_type ='Guest' and network_offering_id= ?");
+                ResultSet rs_net_offer_count = pstmt_count_offerings.executeQuery();
+            ) {
             long ntwkOffCount = 0;
-            while (rs.next()) {
-                ntwkOffCount = rs.getLong(1);
+            while (rs_net_offer_count.next()) {
+                ntwkOffCount = rs_net_offer_count.getLong(1);
             }
-            rs.close();
-            pstmt.close();
 
-            pstmt = conn.prepareStatement("DROP TEMPORARY TABLE IF EXISTS `cloud`.`network_offerings2`");
-            pstmt.executeUpdate();
+            pstmt_drop_temp_table.executeUpdate();
 
-            pstmt = conn.prepareStatement("CREATE TEMPORARY TABLE `cloud`.`network_offerings2` ENGINE=MEMORY SELECT * FROM `cloud`.`network_offerings` WHERE id=1");
-            pstmt.executeUpdate();
-            pstmt.close();
+            pstmt_create_temp_table.executeUpdate();
 
             // clone the record to
-            pstmt = conn.prepareStatement("INSERT INTO `cloud`.`network_offerings2` SELECT * FROM `cloud`.`network_offerings` WHERE id=?");
-            pstmt.setLong(1, networkOfferingId);
-            pstmt.executeUpdate();
-            pstmt.close();
-
-            pstmt = conn.prepareStatement("SELECT unique_name FROM `cloud`.`network_offerings` WHERE id=?");
-            pstmt.setLong(1, networkOfferingId);
-            rs = pstmt.executeQuery();
+            pstmt_copy_net_offer.setLong(1, networkOfferingId);
+            pstmt_copy_net_offer.executeUpdate();
+
+            pstmt_unique_name.setLong(1, networkOfferingId);
             String uniqueName = null;
-            while (rs.next()) {
-                uniqueName = rs.getString(1) + "-" + physicalNetworkId;
+            try (ResultSet rs_unique_name = pstmt_unique_name.executeQuery();) {
+                while (rs_unique_name.next()) {
+                    uniqueName = rs_unique_name.getString(1) + "-" + physicalNetworkId;
+                }
             }
-            rs.close();
-            pstmt.close();
 
-            pstmt = conn.prepareStatement("UPDATE `cloud`.`network_offerings2` SET id=?, unique_name=?, name=?, tags=?, uuid=?  WHERE id=?");
             ntwkOffCount = ntwkOffCount + 1;
             long newNetworkOfferingId = ntwkOffCount;
-            pstmt.setLong(1, newNetworkOfferingId);
-            pstmt.setString(2, uniqueName);
-            pstmt.setString(3, uniqueName);
-            pstmt.setString(4, newTag);
+            pstmt_update_temp_offer.setLong(1, newNetworkOfferingId);
+            pstmt_update_temp_offer.setString(2, uniqueName);
+            pstmt_update_temp_offer.setString(3, uniqueName);
+            pstmt_update_temp_offer.setString(4, newTag);
             String uuid = UUID.randomUUID().toString();
-            pstmt.setString(5, uuid);
-            pstmt.setLong(6, networkOfferingId);
-            pstmt.executeUpdate();
-            pstmt.close();
+            pstmt_update_temp_offer.setString(5, uuid);
+            pstmt_update_temp_offer.setLong(6, networkOfferingId);
+            pstmt_update_temp_offer.executeUpdate();
 
-            pstmt = conn.prepareStatement("INSERT INTO `cloud`.`network_offerings` SELECT * from `cloud`.`network_offerings2` WHERE id=" + newNetworkOfferingId);
-            pstmt.executeUpdate();
-            pstmt.close();
+            pstmt_update_offering.setLong(1, newNetworkOfferingId);
+            pstmt_update_offering.executeUpdate();
 
             //clone service map
-            pstmt = conn.prepareStatement("select service, provider from `cloud`.`ntwk_offering_service_map` where network_offering_id=?");
-            pstmt.setLong(1, networkOfferingId);
-            rs = pstmt.executeQuery();
-            while (rs.next()) {
-                String service = rs.getString(1);
-                String provider = rs.getString(2);
-                pstmt =
-                    conn.prepareStatement("INSERT INTO `cloud`.`ntwk_offering_service_map` (`network_offering_id`, `service`, `provider`, `created`) values (?,?,?, now())");
-                pstmt.setLong(1, newNetworkOfferingId);
-                pstmt.setString(2, service);
-                pstmt.setString(3, provider);
-                pstmt.executeUpdate();
+            pstmt_select_service.setLong(1, networkOfferingId);
+            try (ResultSet rs_service = pstmt_select_service.executeQuery();) {
+                while (rs_service.next()) {
+                    String service = rs_service.getString(1);
+                    String provider = rs_service.getString(2);
+                    pstmt_insert_netofferservicemap.setLong(1, newNetworkOfferingId);
+                    pstmt_insert_netofferservicemap.setString(2, service);
+                    pstmt_insert_netofferservicemap.setString(3, provider);
+                    pstmt_insert_netofferservicemap.executeUpdate();
+                }
             }
-            rs.close();
-            pstmt.close();
-
-            pstmt =
-                conn.prepareStatement("UPDATE `cloud`.`networks` SET network_offering_id=? where physical_network_id=? and traffic_type ='Guest' and network_offering_id=" +
-                    networkOfferingId);
-            pstmt.setLong(1, newNetworkOfferingId);
-            pstmt.setLong(2, physicalNetworkId);
-            pstmt.executeUpdate();
-            pstmt.close();
 
+            pstmt_update_networks.setLong(1, newNetworkOfferingId);
+            pstmt_update_networks.setLong(2, physicalNetworkId);
+            pstmt_update_networks.setLong(3, networkOfferingId);
+            pstmt_update_networks.executeUpdate();
         } catch (SQLException e) {
             throw new CloudRuntimeException("Exception while cloning NetworkOffering", e);
         } finally {
-            try {
-                pstmt = conn.prepareStatement("DROP TEMPORARY TABLE `cloud`.`network_offerings2`");
-                pstmt.executeUpdate();
-
-                if (rs != null) {
-                    rs.close();
-                }
-
-                if (pstmt != null) {
-                    pstmt.close();
-                }
+            try (PreparedStatement pstmt_drop_table = conn.prepareStatement("DROP TEMPORARY TABLE `cloud`.`network_offerings2`");) {
+                pstmt_drop_table.executeUpdate();
             } catch (SQLException e) {
+                s_logger.debug("drop of temp table 'network_offerings2' failed", e);
             }
         }
     }