Selaa lähdekoodia

Revert "AMBARI-11965 - Fix high impact Outstanding Security Risks (Dmytro Shkvyra via abaranchuk)"

This reverts commit 94c091e280a99e07db5f3910873e70aa3c18394f.
Yusaku Sako 10 vuotta sitten
vanhempi
commit
0fcbabfcd8
16 muutettua tiedostoa jossa 183 lisäystä ja 319 poistoa
  1. 8 10
      ambari-metrics/ambari-metrics-timelineservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/metrics/timeline/PhoenixHBaseAccessor.java
  2. 2 10
      ambari-server/src/main/java/org/apache/ambari/eventdb/db/PostgresConnector.java
  3. 1 6
      ambari-server/src/main/java/org/apache/ambari/server/agent/HeartBeatHandler.java
  4. 1 3
      ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariMetaInfo.java
  5. 3 20
      ambari-server/src/main/java/org/apache/ambari/server/api/services/serializers/CsvSerializer.java
  6. 1 9
      ambari-server/src/main/java/org/apache/ambari/server/controller/gsinstaller/ClusterDefinition.java
  7. 2 8
      ambari-server/src/main/java/org/apache/ambari/server/controller/jdbc/JDBCResourceProvider.java
  8. 3 6
      ambari-server/src/main/java/org/apache/ambari/server/controller/metrics/RestMetricsPropertyProvider.java
  9. 142 195
      ambari-server/src/main/java/org/apache/ambari/server/orm/DBAccessorImpl.java
  10. 0 1
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ViewEntity.java
  11. 1 8
      ambari-server/src/main/java/org/apache/ambari/server/security/encryption/CredentialStoreServiceImpl.java
  12. 9 24
      ambari-server/src/main/java/org/apache/ambari/server/view/ViewRegistry.java
  13. 1 0
      ambari-server/src/test/java/org/apache/ambari/server/orm/DBAccessorImplTest.java
  14. 1 0
      ambari-server/src/test/java/org/apache/ambari/server/security/encryption/CredentialStoreServiceTest.java
  15. 7 7
      ambari-server/src/test/java/org/apache/ambari/server/view/ViewRegistryTest.java
  16. 1 12
      ambari-shell/ambari-groovy-shell/src/main/java/org/apache/ambari/shell/commands/BlueprintCommands.java

+ 8 - 10
ambari-metrics/ambari-metrics-timelineservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/metrics/timeline/PhoenixHBaseAccessor.java

@@ -396,7 +396,7 @@ public class PhoenixHBaseAccessor {
     try {
     try {
       //get latest
       //get latest
       if(condition.isPointInTime()){
       if(condition.isPointInTime()){
-        getLatestMetricRecords(condition, conn, metrics);
+        stmt = getLatestMetricRecords(condition, conn, metrics);
       } else {
       } else {
         stmt = PhoenixTransactSQL.prepareGetMetricsSqlStmt(conn, condition);
         stmt = PhoenixTransactSQL.prepareGetMetricsSqlStmt(conn, condition);
         rs = stmt.executeQuery();
         rs = stmt.executeQuery();
@@ -465,7 +465,7 @@ public class PhoenixHBaseAccessor {
     }
     }
   }
   }
 
 
-  private void getLatestMetricRecords(
+  private PreparedStatement getLatestMetricRecords(
     Condition condition, Connection conn, TimelineMetrics metrics)
     Condition condition, Connection conn, TimelineMetrics metrics)
     throws SQLException, IOException {
     throws SQLException, IOException {
 
 
@@ -490,10 +490,9 @@ public class PhoenixHBaseAccessor {
           // Ignore
           // Ignore
         }
         }
       }
       }
-      if (stmt != null) {
-        stmt.close();
-      }
     }
     }
+
+    return stmt;
   }
   }
 
 
   /**
   /**
@@ -516,7 +515,7 @@ public class PhoenixHBaseAccessor {
     try {
     try {
       //get latest
       //get latest
       if(condition.isPointInTime()) {
       if(condition.isPointInTime()) {
-        getLatestAggregateMetricRecords(condition, conn, metrics, metricFunctions);
+        stmt = getLatestAggregateMetricRecords(condition, conn, metrics, metricFunctions);
       } else {
       } else {
         stmt = PhoenixTransactSQL.prepareGetAggregateSqlStmt(conn, condition);
         stmt = PhoenixTransactSQL.prepareGetAggregateSqlStmt(conn, condition);
 
 
@@ -578,7 +577,7 @@ public class PhoenixHBaseAccessor {
     }
     }
   }
   }
 
 
-  private void getLatestAggregateMetricRecords(Condition condition,
+  private PreparedStatement getLatestAggregateMetricRecords(Condition condition,
       Connection conn, TimelineMetrics metrics,
       Connection conn, TimelineMetrics metrics,
       Map<String, List<Function>> metricFunctions) throws SQLException {
       Map<String, List<Function>> metricFunctions) throws SQLException {
 
 
@@ -620,11 +619,10 @@ public class PhoenixHBaseAccessor {
             // Ignore
             // Ignore
           }
           }
         }
         }
-        if (stmt != null) {
-          stmt.close();
-        }        
       }
       }
     }
     }
+
+    return stmt;
   }
   }
 
 
   private SingleValuedTimelineMetric getAggregateTimelineMetricFromResultSet(ResultSet rs,
   private SingleValuedTimelineMetric getAggregateTimelineMetricFromResultSet(ResultSet rs,

+ 2 - 10
ambari-server/src/main/java/org/apache/ambari/eventdb/db/PostgresConnector.java

@@ -164,12 +164,8 @@ public class PostgresConnector implements DBConnector {
       throw new IOException(e);
       throw new IOException(e);
     } finally {
     } finally {
       try {
       try {
-        if (rs != null){
+        if (rs != null)
           rs.close();
           rs.close();
-        }
-        if (ps != null) {
-          ps.close();
-        }
       } catch (SQLException e) {
       } catch (SQLException e) {
         LOG.error("Exception while closing ResultSet", e);
         LOG.error("Exception while closing ResultSet", e);
       }
       }
@@ -197,12 +193,8 @@ public class PostgresConnector implements DBConnector {
       throw new IOException(e);
       throw new IOException(e);
     } finally {
     } finally {
       try {
       try {
-        if (rs != null) {
+        if (rs != null)
           rs.close();
           rs.close();
-        }
-        if (ps != null) {
-          ps.close();
-        }        
       } catch (SQLException e) {
       } catch (SQLException e) {
         LOG.error("Exception while closing ResultSet", e);
         LOG.error("Exception while closing ResultSet", e);
       }
       }

+ 1 - 6
ambari-server/src/main/java/org/apache/ambari/server/agent/HeartBeatHandler.java

@@ -1125,12 +1125,7 @@ public class HeartBeatHandler {
                   keytabMap.put(KerberosIdentityDataFileReader.KEYTAB_FILE_GROUP_ACCESS, record.get(KerberosIdentityDataFileReader.KEYTAB_FILE_GROUP_ACCESS));
                   keytabMap.put(KerberosIdentityDataFileReader.KEYTAB_FILE_GROUP_ACCESS, record.get(KerberosIdentityDataFileReader.KEYTAB_FILE_GROUP_ACCESS));
 
 
                   BufferedInputStream bufferedIn = new BufferedInputStream(new FileInputStream(keytabFile));
                   BufferedInputStream bufferedIn = new BufferedInputStream(new FileInputStream(keytabFile));
-                  byte[] keytabContent = null;
-                  try {
-                    keytabContent = IOUtils.toByteArray(bufferedIn);
-                  } finally {
-                    bufferedIn.close();
-                  }
+                  byte[] keytabContent = IOUtils.toByteArray(bufferedIn);
                   String keytabContentBase64 = Base64.encodeBase64String(keytabContent);
                   String keytabContentBase64 = Base64.encodeBase64String(keytabContent);
                   keytabMap.put(KerberosServerAction.KEYTAB_CONTENT_BASE64, keytabContentBase64);
                   keytabMap.put(KerberosServerAction.KEYTAB_CONTENT_BASE64, keytabContentBase64);
 
 

+ 1 - 3
ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariMetaInfo.java

@@ -736,9 +736,7 @@ public class AmbariMetaInfo {
     if (!versionFile.exists()) {
     if (!versionFile.exists()) {
       throw new AmbariException("Server version file does not exist.");
       throw new AmbariException("Server version file does not exist.");
     }
     }
-    Scanner scanner = new Scanner(versionFile);
-    serverVersion = scanner.useDelimiter("\\Z").next();
-    scanner.close();
+    serverVersion = new Scanner(versionFile).useDelimiter("\\Z").next();
   }
   }
 
 
   private void getCustomActionDefinitions(File customActionDefinitionRoot) throws JAXBException, AmbariException {
   private void getCustomActionDefinitions(File customActionDefinitionRoot) throws JAXBException, AmbariException {

+ 3 - 20
ambari-server/src/main/java/org/apache/ambari/server/api/services/serializers/CsvSerializer.java

@@ -32,8 +32,6 @@ import java.util.Collection;
 import java.util.List;
 import java.util.List;
 import java.util.Map;
 import java.util.Map;
 import java.util.Set;
 import java.util.Set;
-import java.util.logging.Level;
-import java.util.logging.Logger;
 
 
 /**
 /**
  * CSV serializer used to generate a CSV-formatted document from a result.
  * CSV serializer used to generate a CSV-formatted document from a result.
@@ -79,7 +77,7 @@ public class CsvSerializer implements ResultSerializer {
     if (result.getStatus().isErrorState()) {
     if (result.getStatus().isErrorState()) {
       return serializeError(result.getStatus());
       return serializeError(result.getStatus());
     } else {
     } else {
-      CSVPrinter csvPrinter = null;
+
       try {
       try {
         // A StringBuffer to store the CSV-formatted document while building it.  It may be
         // A StringBuffer to store the CSV-formatted document while building it.  It may be
         // necessary to use file-based storage if the data set is expected to be really large.
         // necessary to use file-based storage if the data set is expected to be really large.
@@ -88,7 +86,7 @@ public class CsvSerializer implements ResultSerializer {
         TreeNode<Resource> root = result.getResultTree();
         TreeNode<Resource> root = result.getResultTree();
 
 
         if (root != null) {
         if (root != null) {
-          csvPrinter = new CSVPrinter(buffer, CSVFormat.DEFAULT);
+          CSVPrinter csvPrinter = new CSVPrinter(buffer, CSVFormat.DEFAULT);
 
 
           // TODO: recursively handle tree structure, for now only handle single level of detail
           // TODO: recursively handle tree structure, for now only handle single level of detail
           if ("true".equalsIgnoreCase(root.getStringProperty("isCollection"))) {
           if ("true".equalsIgnoreCase(root.getStringProperty("isCollection"))) {
@@ -109,23 +107,15 @@ public class CsvSerializer implements ResultSerializer {
       } catch (IOException e) {
       } catch (IOException e) {
         //todo: exception handling.  Create ResultStatus 500 and call serializeError
         //todo: exception handling.  Create ResultStatus 500 and call serializeError
         throw new RuntimeException("Unable to serialize to csv: " + e, e);
         throw new RuntimeException("Unable to serialize to csv: " + e, e);
-      } finally {
-        if (csvPrinter != null) {
-          try {
-            csvPrinter.close();
-          } catch (IOException ex) {
-          }
-        }
       }
       }
     }
     }
   }
   }
 
 
   @Override
   @Override
   public Object serializeError(ResultStatus error) {
   public Object serializeError(ResultStatus error) {
-    CSVPrinter csvPrinter = null;
     try {
     try {
       StringBuffer buffer = new StringBuffer();
       StringBuffer buffer = new StringBuffer();
-      csvPrinter = new CSVPrinter(buffer, CSVFormat.DEFAULT);
+      CSVPrinter csvPrinter = new CSVPrinter(buffer, CSVFormat.DEFAULT);
 
 
       csvPrinter.printRecord(Arrays.asList("status", "message"));
       csvPrinter.printRecord(Arrays.asList("status", "message"));
       csvPrinter.printRecord(Arrays.asList(error.getStatus().getStatus(), error.getMessage()));
       csvPrinter.printRecord(Arrays.asList(error.getStatus().getStatus(), error.getMessage()));
@@ -134,13 +124,6 @@ public class CsvSerializer implements ResultSerializer {
     } catch (IOException e) {
     } catch (IOException e) {
       //todo: exception handling.  Create ResultStatus 500 and call serializeError
       //todo: exception handling.  Create ResultStatus 500 and call serializeError
       throw new RuntimeException("Unable to serialize to csv: " + e, e);
       throw new RuntimeException("Unable to serialize to csv: " + e, e);
-    } finally {
-      if (csvPrinter != null) {
-        try {
-          csvPrinter.close();
-        } catch (IOException ex) {
-        }
-      }
     }
     }
   }
   }
 
 

+ 1 - 9
ambari-server/src/main/java/org/apache/ambari/server/controller/gsinstaller/ClusterDefinition.java

@@ -228,9 +228,8 @@ public class ClusterDefinition {
    * Read the gsInstaller cluster definition file.
    * Read the gsInstaller cluster definition file.
    */
    */
   private void readClusterDefinition() {
   private void readClusterDefinition() {
-    InputStream is = null;
     try {
     try {
-      is = this.getClass().getClassLoader().getResourceAsStream(CLUSTER_DEFINITION_FILE);
+      InputStream    is = this.getClass().getClassLoader().getResourceAsStream(CLUSTER_DEFINITION_FILE);
       BufferedReader br = new BufferedReader(new InputStreamReader(is));
       BufferedReader br = new BufferedReader(new InputStreamReader(is));
 
 
       String line;
       String line;
@@ -281,13 +280,6 @@ public class ClusterDefinition {
     } catch (IOException e) {
     } catch (IOException e) {
       String msg = "Caught exception reading " + CLUSTER_DEFINITION_FILE + ".";
       String msg = "Caught exception reading " + CLUSTER_DEFINITION_FILE + ".";
       throw new IllegalStateException(msg, e);
       throw new IllegalStateException(msg, e);
-    } finally {
-      if (is != null) {
-        try {
-          is.close();
-        } catch (IOException ex) {
-        }
-      }
     }
     }
   }
   }
 
 

+ 2 - 8
ambari-server/src/main/java/org/apache/ambari/server/controller/jdbc/JDBCResourceProvider.java

@@ -416,9 +416,8 @@ public class JDBCResourceProvider extends BaseProvider implements ResourceProvid
             this.importedKeys.put(table, importedKeys);
             this.importedKeys.put(table, importedKeys);
 
 
             DatabaseMetaData metaData = connection.getMetaData();
             DatabaseMetaData metaData = connection.getMetaData();
-            ResultSet rs = null;
-            try {
-            rs = metaData.getImportedKeys(connection.getCatalog(), null, table);
+
+            ResultSet rs = metaData.getImportedKeys(connection.getCatalog(), null, table);
 
 
             while (rs.next()) {
             while (rs.next()) {
 
 
@@ -430,11 +429,6 @@ public class JDBCResourceProvider extends BaseProvider implements ResourceProvid
 
 
                 importedKeys.put(pkPropertyId, fkPropertyId);
                 importedKeys.put(pkPropertyId, fkPropertyId);
             }
             }
-            } finally {
-              if (rs != null) {
-                rs.close();
-              }
-            }
         }
         }
     }
     }
 
 

+ 3 - 6
ambari-server/src/main/java/org/apache/ambari/server/controller/metrics/RestMetricsPropertyProvider.java

@@ -225,16 +225,13 @@ public class RestMetricsPropertyProvider extends ThreadPoolEnabledPropertyProvid
       try {
       try {
         InputStream in = streamProvider.readFrom(getSpec(protocol, hostname, port, url));
         InputStream in = streamProvider.readFrom(getSpec(protocol, hostname, port, url));
         if (!ticket.isValid()) {
         if (!ticket.isValid()) {
-          if (in != null) {
-            in.close();
-          }
           return resource;
           return resource;
-        }       
+        }
         try {
         try {
           extractValuesFromJSON(in, urls.get(url), resource, propertyInfos);
           extractValuesFromJSON(in, urls.get(url), resource, propertyInfos);
         } finally {
         } finally {
-            in.close();
-          }
+          in.close();
+        }
       } catch (IOException e) {
       } catch (IOException e) {
         logException(e);
         logException(e);
       }
       }

+ 142 - 195
ambari-server/src/main/java/org/apache/ambari/server/orm/DBAccessorImpl.java

@@ -41,12 +41,11 @@ import org.eclipse.persistence.sessions.DatabaseLogin;
 import org.eclipse.persistence.sessions.DatabaseSession;
 import org.eclipse.persistence.sessions.DatabaseSession;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
-
+ 
 import java.io.BufferedReader;
 import java.io.BufferedReader;
 import java.io.FileReader;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.InputStreamReader;
-import java.nio.charset.Charset;
 import java.sql.Blob;
 import java.sql.Blob;
 import java.sql.Connection;
 import java.sql.Connection;
 import java.sql.DatabaseMetaData;
 import java.sql.DatabaseMetaData;
@@ -71,7 +70,7 @@ public class DBAccessorImpl implements DBAccessor {
   private static final String dbURLPatternString = "jdbc:(.*?):.*";
   private static final String dbURLPatternString = "jdbc:(.*?):.*";
   private Pattern dbURLPattern = Pattern.compile(dbURLPatternString, Pattern.CASE_INSENSITIVE);
   private Pattern dbURLPattern = Pattern.compile(dbURLPatternString, Pattern.CASE_INSENSITIVE);
   private DbType dbType;
   private DbType dbType;
-  
+
   @Inject
   @Inject
   public DBAccessorImpl(Configuration configuration) {
   public DBAccessorImpl(Configuration configuration) {
     this.configuration = configuration;
     this.configuration = configuration;
@@ -80,14 +79,14 @@ public class DBAccessorImpl implements DBAccessor {
       Class.forName(configuration.getDatabaseDriver());
       Class.forName(configuration.getDatabaseDriver());
 
 
       connection = DriverManager.getConnection(configuration.getDatabaseUrl(),
       connection = DriverManager.getConnection(configuration.getDatabaseUrl(),
-              configuration.getDatabaseUser(),
-              configuration.getDatabasePassword());
+        configuration.getDatabaseUser(),
+        configuration.getDatabasePassword());
 
 
       connection.setAutoCommit(true); //enable autocommit
       connection.setAutoCommit(true); //enable autocommit
 
 
       //TODO create own mapping and platform classes for supported databases
       //TODO create own mapping and platform classes for supported databases
-      String vendorName = connection.getMetaData().getDatabaseProductName()
-              + connection.getMetaData().getDatabaseMajorVersion();
+      String vendorName = connection.getMetaData().getDatabaseProductName() +
+        connection.getMetaData().getDatabaseMajorVersion();
       String dbPlatform = DBPlatformHelper.getDBPlatform(vendorName, new AbstractSessionLog() {
       String dbPlatform = DBPlatformHelper.getDBPlatform(vendorName, new AbstractSessionLog() {
         @Override
         @Override
         public void log(SessionLogEntry sessionLogEntry) {
         public void log(SessionLogEntry sessionLogEntry) {
@@ -107,13 +106,13 @@ public class DBAccessorImpl implements DBAccessor {
     if (databasePlatform instanceof OraclePlatform) {
     if (databasePlatform instanceof OraclePlatform) {
       dbType = DbType.ORACLE;
       dbType = DbType.ORACLE;
       return new OracleHelper(databasePlatform);
       return new OracleHelper(databasePlatform);
-    } else if (databasePlatform instanceof MySQLPlatform) {
+    }else if (databasePlatform instanceof MySQLPlatform) {
       dbType = DbType.MYSQL;
       dbType = DbType.MYSQL;
       return new MySqlHelper(databasePlatform);
       return new MySqlHelper(databasePlatform);
-    } else if (databasePlatform instanceof PostgreSQLPlatform) {
+    }else if (databasePlatform instanceof PostgreSQLPlatform) {
       dbType = DbType.POSTGRES;
       dbType = DbType.POSTGRES;
       return new PostgresHelper(databasePlatform);
       return new PostgresHelper(databasePlatform);
-    } else if (databasePlatform instanceof DerbyPlatform) {
+    }else if (databasePlatform instanceof DerbyPlatform) {
       dbType = DbType.DERBY;
       dbType = DbType.DERBY;
       return new DerbyHelper(databasePlatform);
       return new DerbyHelper(databasePlatform);
     } else {
     } else {
@@ -130,8 +129,8 @@ public class DBAccessorImpl implements DBAccessor {
   public Connection getNewConnection() {
   public Connection getNewConnection() {
     try {
     try {
       return DriverManager.getConnection(configuration.getDatabaseUrl(),
       return DriverManager.getConnection(configuration.getDatabaseUrl(),
-              configuration.getDatabaseUser(),
-              configuration.getDatabasePassword());
+        configuration.getDatabaseUser(),
+        configuration.getDatabasePassword());
     } catch (SQLException e) {
     } catch (SQLException e) {
       throw new RuntimeException("Unable to connect to database", e);
       throw new RuntimeException("Unable to connect to database", e);
     }
     }
@@ -144,7 +143,7 @@ public class DBAccessorImpl implements DBAccessor {
 
 
   @Override
   @Override
   public void createTable(String tableName, List<DBColumnInfo> columnInfo,
   public void createTable(String tableName, List<DBColumnInfo> columnInfo,
-          String... primaryKeyColumns) throws SQLException {
+                          String... primaryKeyColumns) throws SQLException {
     if (!tableExists(tableName)) {
     if (!tableExists(tableName)) {
       String query = dbmsHelper.getCreateTableStatement(tableName, columnInfo, Arrays.asList(primaryKeyColumns));
       String query = dbmsHelper.getCreateTableStatement(tableName, columnInfo, Arrays.asList(primaryKeyColumns));
 
 
@@ -168,24 +167,27 @@ public class DBAccessorImpl implements DBAccessor {
     DatabaseMetaData metaData = getDatabaseMetaData();
     DatabaseMetaData metaData = getDatabaseMetaData();
     if (metaData.storesLowerCaseIdentifiers()) {
     if (metaData.storesLowerCaseIdentifiers()) {
       return objectName.toLowerCase();
       return objectName.toLowerCase();
-    } else if (metaData.storesUpperCaseIdentifiers()) {
+    }else if (metaData.storesUpperCaseIdentifiers()) {
       return objectName.toUpperCase();
       return objectName.toUpperCase();
     }
     }
 
 
     return objectName;
     return objectName;
   }
   }
 
 
+
+
   @Override
   @Override
   public boolean tableExists(String tableName) throws SQLException {
   public boolean tableExists(String tableName) throws SQLException {
     boolean result = false;
     boolean result = false;
     DatabaseMetaData metaData = getDatabaseMetaData();
     DatabaseMetaData metaData = getDatabaseMetaData();
 
 
-    ResultSet res = metaData.getTables(null, null, convertObjectName(tableName), new String[]{"TABLE"});
+    ResultSet res = metaData.getTables(null, null, convertObjectName(tableName), new String[] { "TABLE" });
 
 
     if (res != null) {
     if (res != null) {
       try {
       try {
         if (res.next()) {
         if (res.next()) {
-          return res.getString("TABLE_NAME") != null && res.getString("TABLE_NAME").equalsIgnoreCase(tableName);
+          return res.getString("TABLE_NAME") != null && res.getString
+            ("TABLE_NAME").equalsIgnoreCase(tableName);
         }
         }
       } finally {
       } finally {
         res.close();
         res.close();
@@ -206,7 +208,7 @@ public class DBAccessorImpl implements DBAccessor {
     boolean retVal = false;
     boolean retVal = false;
     ResultSet rs = null;
     ResultSet rs = null;
     try {
     try {
-      rs = statement.executeQuery(query);
+       rs = statement.executeQuery(query);
       if (rs != null) {
       if (rs != null) {
         if (rs.next()) {
         if (rs.next()) {
           return rs.getInt(1) > 0;
           return rs.getInt(1) > 0;
@@ -215,9 +217,6 @@ public class DBAccessorImpl implements DBAccessor {
     } catch (Exception e) {
     } catch (Exception e) {
       LOG.error("Unable to check if table " + tableName + " has any data. Exception: " + e.getMessage());
       LOG.error("Unable to check if table " + tableName + " has any data. Exception: " + e.getMessage());
     } finally {
     } finally {
-      if (statement != null) {
-        statement.close();
-      }
       if (rs != null) {
       if (rs != null) {
         rs.close();
         rs.close();
       }
       }
@@ -234,7 +233,8 @@ public class DBAccessorImpl implements DBAccessor {
     if (rs != null) {
     if (rs != null) {
       try {
       try {
         if (rs.next()) {
         if (rs.next()) {
-          return rs.getString("COLUMN_NAME") != null && rs.getString("COLUMN_NAME").equalsIgnoreCase(columnName);
+          return rs.getString("COLUMN_NAME") != null && rs.getString
+            ("COLUMN_NAME").equalsIgnoreCase(columnName);
         }
         }
       } finally {
       } finally {
         rs.close();
         rs.close();
@@ -245,7 +245,7 @@ public class DBAccessorImpl implements DBAccessor {
   }
   }
 
 
   @Override
   @Override
-  public boolean tableHasColumn(String tableName, String... columnName) throws SQLException {
+  public boolean tableHasColumn(String tableName, String... columnName) throws SQLException{
     List<String> columnsList = new ArrayList<String>(Arrays.asList(columnName));
     List<String> columnsList = new ArrayList<String>(Arrays.asList(columnName));
     DatabaseMetaData metaData = getDatabaseMetaData();
     DatabaseMetaData metaData = getDatabaseMetaData();
 
 
@@ -292,18 +292,19 @@ public class DBAccessorImpl implements DBAccessor {
 
 
   @Override
   @Override
   public boolean tableHasForeignKey(String tableName, String refTableName,
   public boolean tableHasForeignKey(String tableName, String refTableName,
-          String columnName, String refColumnName) throws SQLException {
+              String columnName, String refColumnName) throws SQLException {
     return tableHasForeignKey(tableName, refTableName, new String[]{columnName}, new String[]{refColumnName});
     return tableHasForeignKey(tableName, refTableName, new String[]{columnName}, new String[]{refColumnName});
   }
   }
 
 
   @Override
   @Override
   public boolean tableHasForeignKey(String tableName, String referenceTableName, String[] keyColumns,
   public boolean tableHasForeignKey(String tableName, String referenceTableName, String[] keyColumns,
-          String[] referenceColumns) throws SQLException {
+                                    String[] referenceColumns) throws SQLException {
     DatabaseMetaData metaData = getDatabaseMetaData();
     DatabaseMetaData metaData = getDatabaseMetaData();
 
 
     //NB: reference table contains pk columns while key table contains fk columns
     //NB: reference table contains pk columns while key table contains fk columns
+
     ResultSet rs = metaData.getCrossReference(null, null, convertObjectName(referenceTableName),
     ResultSet rs = metaData.getCrossReference(null, null, convertObjectName(referenceTableName),
-            null, null, convertObjectName(tableName));
+      null, null, convertObjectName(tableName));
 
 
     List<String> pkColumns = new ArrayList<String>(referenceColumns.length);
     List<String> pkColumns = new ArrayList<String>(referenceColumns.length);
     for (String referenceColumn : referenceColumns) {
     for (String referenceColumn : referenceColumns) {
@@ -331,10 +332,12 @@ public class DBAccessorImpl implements DBAccessor {
               fkColumns.remove(fkIndex);
               fkColumns.remove(fkIndex);
             }
             }
 
 
+
           } else {
           } else {
             LOG.debug("pkCol={}, fkCol={} not found in provided column names, skipping", pkColumn, fkColumn); //TODO debug
             LOG.debug("pkCol={}, fkCol={} not found in provided column names, skipping", pkColumn, fkColumn); //TODO debug
           }
           }
 
 
+
         }
         }
         if (pkColumns.isEmpty() && fkColumns.isEmpty()) {
         if (pkColumns.isEmpty() && fkColumns.isEmpty()) {
           return true;
           return true;
@@ -345,13 +348,14 @@ public class DBAccessorImpl implements DBAccessor {
       }
       }
     }
     }
 
 
+
     return false;
     return false;
 
 
   }
   }
 
 
   @Override
   @Override
   public void createIndex(String indexName, String tableName,
   public void createIndex(String indexName, String tableName,
-          String... columnNames) throws SQLException {
+                          String... columnNames) throws SQLException {
     String query = dbmsHelper.getCreateIndexStatement(indexName, tableName, columnNames);
     String query = dbmsHelper.getCreateIndexStatement(indexName, tableName, columnNames);
 
 
     executeQuery(query);
     executeQuery(query);
@@ -359,49 +363,48 @@ public class DBAccessorImpl implements DBAccessor {
 
 
   @Override
   @Override
   public void addFKConstraint(String tableName, String constraintName,
   public void addFKConstraint(String tableName, String constraintName,
-          String keyColumn, String referenceTableName,
-          String referenceColumn, boolean ignoreFailure) throws SQLException {
+                              String keyColumn, String referenceTableName,
+                              String referenceColumn, boolean ignoreFailure) throws SQLException {
 
 
     addFKConstraint(tableName, constraintName, new String[]{keyColumn}, referenceTableName,
     addFKConstraint(tableName, constraintName, new String[]{keyColumn}, referenceTableName,
-            new String[]{referenceColumn}, false, ignoreFailure);
+        new String[]{referenceColumn}, false, ignoreFailure);
   }
   }
-
   @Override
   @Override
   public void addFKConstraint(String tableName, String constraintName,
   public void addFKConstraint(String tableName, String constraintName,
-          String keyColumn, String referenceTableName,
-          String referenceColumn, boolean shouldCascadeOnDelete,
-          boolean ignoreFailure) throws SQLException {
+                              String keyColumn, String referenceTableName,
+                              String referenceColumn, boolean shouldCascadeOnDelete,
+                              boolean ignoreFailure) throws SQLException {
 
 
     addFKConstraint(tableName, constraintName, new String[]{keyColumn}, referenceTableName,
     addFKConstraint(tableName, constraintName, new String[]{keyColumn}, referenceTableName,
-            new String[]{referenceColumn}, shouldCascadeOnDelete, ignoreFailure);
+      new String[]{referenceColumn}, shouldCascadeOnDelete, ignoreFailure);
   }
   }
 
 
   @Override
   @Override
   public void addFKConstraint(String tableName, String constraintName,
   public void addFKConstraint(String tableName, String constraintName,
-          String[] keyColumns, String referenceTableName,
-          String[] referenceColumns,
-          boolean ignoreFailure) throws SQLException {
+                              String[] keyColumns, String referenceTableName,
+                              String[] referenceColumns,
+                              boolean ignoreFailure) throws SQLException {
     addFKConstraint(tableName, constraintName, keyColumns, referenceTableName, referenceColumns, false, ignoreFailure);
     addFKConstraint(tableName, constraintName, keyColumns, referenceTableName, referenceColumns, false, ignoreFailure);
   }
   }
 
 
   @Override
   @Override
   public void addFKConstraint(String tableName, String constraintName,
   public void addFKConstraint(String tableName, String constraintName,
-          String[] keyColumns, String referenceTableName,
-          String[] referenceColumns, boolean shouldCascadeOnDelete,
-          boolean ignoreFailure) throws SQLException {
+                              String[] keyColumns, String referenceTableName,
+                              String[] referenceColumns, boolean shouldCascadeOnDelete,
+                              boolean ignoreFailure) throws SQLException {
     if (!tableHasForeignKey(tableName, referenceTableName, keyColumns, referenceColumns)) {
     if (!tableHasForeignKey(tableName, referenceTableName, keyColumns, referenceColumns)) {
       String query = dbmsHelper.getAddForeignKeyStatement(tableName, constraintName,
       String query = dbmsHelper.getAddForeignKeyStatement(tableName, constraintName,
-              Arrays.asList(keyColumns),
-              referenceTableName,
-              Arrays.asList(referenceColumns),
-              shouldCascadeOnDelete);
+          Arrays.asList(keyColumns),
+          referenceTableName,
+          Arrays.asList(referenceColumns),
+          shouldCascadeOnDelete);
 
 
       try {
       try {
         executeQuery(query, ignoreFailure);
         executeQuery(query, ignoreFailure);
       } catch (SQLException e) {
       } catch (SQLException e) {
-        LOG.warn("Add FK constraint failed"
-                + ", constraintName = " + constraintName
-                + ", tableName = " + tableName, e.getMessage());
+        LOG.warn("Add FK constraint failed" +
+                ", constraintName = " + constraintName +
+                ", tableName = " + tableName, e.getMessage());
         if (!ignoreFailure) {
         if (!ignoreFailure) {
           throw e;
           throw e;
         }
         }
@@ -411,13 +414,13 @@ public class DBAccessorImpl implements DBAccessor {
     }
     }
   }
   }
 
 
-  public boolean tableHasConstraint(String tableName, String constraintName) throws SQLException {
+  public boolean tableHasConstraint(String tableName, String constraintName) throws SQLException{
     // this kind of request is well lower level as we querying system tables, due that we need for some the name of catalog.
     // this kind of request is well lower level as we querying system tables, due that we need for some the name of catalog.
     String query = dbmsHelper.getTableConstraintsStatement(connection.getCatalog(), tableName);
     String query = dbmsHelper.getTableConstraintsStatement(connection.getCatalog(), tableName);
     ResultSet rs = executeSelect(query);
     ResultSet rs = executeSelect(query);
-    if (rs != null) {
+    if (rs != null){
       while (rs.next()) {
       while (rs.next()) {
-        if (rs.getString("CONSTRAINT_NAME").equalsIgnoreCase(constraintName)) {
+        if (rs.getString("CONSTRAINT_NAME").equalsIgnoreCase(constraintName)){
           return true;
           return true;
         }
         }
       }
       }
@@ -427,7 +430,7 @@ public class DBAccessorImpl implements DBAccessor {
 
 
   @Override
   @Override
   public void addUniqueConstraint(String tableName, String constraintName, String... columnNames)
   public void addUniqueConstraint(String tableName, String constraintName, String... columnNames)
-          throws SQLException {
+    throws SQLException{
     if (!tableHasConstraint(tableName, constraintName)) {
     if (!tableHasConstraint(tableName, constraintName)) {
       String query = dbmsHelper.getAddUniqueConstraintStatement(tableName, constraintName, columnNames);
       String query = dbmsHelper.getAddUniqueConstraintStatement(tableName, constraintName, columnNames);
       try {
       try {
@@ -442,25 +445,25 @@ public class DBAccessorImpl implements DBAccessor {
   }
   }
 
 
   @Override
   @Override
-  public void addPKConstraint(String tableName, String constraintName, boolean ignoreErrors, String... columnName) throws SQLException {
+  public void addPKConstraint(String tableName, String constraintName, boolean ignoreErrors, String... columnName) throws SQLException{
     if (!tableHasPrimaryKey(tableName, null) && tableHasColumn(tableName, columnName)) {
     if (!tableHasPrimaryKey(tableName, null) && tableHasColumn(tableName, columnName)) {
       String query = dbmsHelper.getAddPrimaryKeyConstraintStatement(tableName, constraintName, columnName);
       String query = dbmsHelper.getAddPrimaryKeyConstraintStatement(tableName, constraintName, columnName);
 
 
       executeQuery(query, ignoreErrors);
       executeQuery(query, ignoreErrors);
     } else {
     } else {
       LOG.warn("Primary constraint {} not altered to table {} as column {} not present or constraint already exists",
       LOG.warn("Primary constraint {} not altered to table {} as column {} not present or constraint already exists",
-              constraintName, tableName, columnName);
+        constraintName, tableName, columnName);
     }
     }
   }
   }
 
 
   @Override
   @Override
-  public void addPKConstraint(String tableName, String constraintName, String... columnName) throws SQLException {
+  public void addPKConstraint(String tableName, String constraintName, String... columnName) throws SQLException{
     addPKConstraint(tableName, constraintName, false, columnName);
     addPKConstraint(tableName, constraintName, false, columnName);
   }
   }
 
 
   @Override
   @Override
   public void renameColumn(String tableName, String oldColumnName,
   public void renameColumn(String tableName, String oldColumnName,
-          DBColumnInfo columnInfo) throws SQLException {
+                           DBColumnInfo columnInfo) throws SQLException {
     //it is mandatory to specify type in column change clause for mysql
     //it is mandatory to specify type in column change clause for mysql
     String renameColumnStatement = dbmsHelper.getRenameColumnStatement(tableName, oldColumnName, columnInfo);
     String renameColumnStatement = dbmsHelper.getRenameColumnStatement(tableName, oldColumnName, columnInfo);
     executeQuery(renameColumnStatement);
     executeQuery(renameColumnStatement);
@@ -485,7 +488,7 @@ public class DBAccessorImpl implements DBAccessor {
 
 
   @Override
   @Override
   public void alterColumn(String tableName, DBColumnInfo columnInfo)
   public void alterColumn(String tableName, DBColumnInfo columnInfo)
-          throws SQLException {
+      throws SQLException {
     //varchar extension only (derby limitation, but not too much for others),
     //varchar extension only (derby limitation, but not too much for others),
     if (dbmsHelper.supportsColumnTypeChange()) {
     if (dbmsHelper.supportsColumnTypeChange()) {
       String statement = dbmsHelper.getAlterColumnStatement(tableName,
       String statement = dbmsHelper.getAlterColumnStatement(tableName,
@@ -494,9 +497,9 @@ public class DBAccessorImpl implements DBAccessor {
     } else {
     } else {
       //use addColumn: add_tmp-update-drop-rename for Derby
       //use addColumn: add_tmp-update-drop-rename for Derby
       DBColumnInfo columnInfoTmp = new DBColumnInfo(
       DBColumnInfo columnInfoTmp = new DBColumnInfo(
-              columnInfo.getName() + "_TMP",
-              columnInfo.getType(),
-              columnInfo.getLength());
+          columnInfo.getName() + "_TMP",
+          columnInfo.getType(),
+          columnInfo.getLength());
       String statement = dbmsHelper.getAddColumnStatement(tableName, columnInfoTmp);
       String statement = dbmsHelper.getAddColumnStatement(tableName, columnInfoTmp);
       executeQuery(statement);
       executeQuery(statement);
       updateTable(tableName, columnInfo, columnInfoTmp);
       updateTable(tableName, columnInfo, columnInfoTmp);
@@ -507,43 +510,32 @@ public class DBAccessorImpl implements DBAccessor {
 
 
   @Override
   @Override
   public void updateTable(String tableName, DBColumnInfo columnNameFrom,
   public void updateTable(String tableName, DBColumnInfo columnNameFrom,
-          DBColumnInfo columnNameTo) throws SQLException {
+      DBColumnInfo columnNameTo) throws SQLException {
     LOG.info("Executing query: UPDATE TABLE " + tableName + " SET "
     LOG.info("Executing query: UPDATE TABLE " + tableName + " SET "
-            + columnNameTo.getName() + "=" + columnNameFrom.getName());
+        + columnNameTo.getName() + "=" + columnNameFrom.getName());
 
 
     String statement = "SELECT * FROM " + tableName;
     String statement = "SELECT * FROM " + tableName;
     int typeFrom = getColumnType(tableName, columnNameFrom.getName());
     int typeFrom = getColumnType(tableName, columnNameFrom.getName());
     int typeTo = getColumnType(tableName, columnNameTo.getName());
     int typeTo = getColumnType(tableName, columnNameTo.getName());
-    Statement dbStatement = null;
-    ResultSet rs = null;
-    try {
-    dbStatement = getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
-            ResultSet.CONCUR_UPDATABLE); 
-    rs = dbStatement.executeQuery(statement);
+    ResultSet rs = executeSelect(statement, ResultSet.TYPE_SCROLL_SENSITIVE,
+            ResultSet.CONCUR_UPDATABLE);
 
 
     while (rs.next()) {
     while (rs.next()) {
       convertUpdateData(rs, columnNameFrom, typeFrom, columnNameTo, typeTo);
       convertUpdateData(rs, columnNameFrom, typeFrom, columnNameTo, typeTo);
       rs.updateRow();
       rs.updateRow();
     }
     }
-    } finally {
-      if (rs != null) {
-        rs.close();
-      }
-      if (dbStatement != null) {
-        dbStatement.close();
-      }
-    }
+    rs.close();
   }
   }
 
 
   private void convertUpdateData(ResultSet rs, DBColumnInfo columnNameFrom,
   private void convertUpdateData(ResultSet rs, DBColumnInfo columnNameFrom,
-          int typeFrom,
-          DBColumnInfo columnNameTo, int typeTo) throws SQLException {
+      int typeFrom,
+      DBColumnInfo columnNameTo, int typeTo) throws SQLException {
     if (typeFrom == Types.BLOB && typeTo == Types.CLOB) {
     if (typeFrom == Types.BLOB && typeTo == Types.CLOB) {
       //BLOB-->CLOB
       //BLOB-->CLOB
       Blob data = rs.getBlob(columnNameFrom.getName());
       Blob data = rs.getBlob(columnNameFrom.getName());
       if (data != null) {
       if (data != null) {
         rs.updateClob(columnNameTo.getName(),
         rs.updateClob(columnNameTo.getName(),
-                new BufferedReader(new InputStreamReader(data.getBinaryStream(), Charset.defaultCharset())));
+            new BufferedReader(new InputStreamReader(data.getBinaryStream())));
       }
       }
     } else {
     } else {
       Object data = rs.getObject(columnNameFrom.getName());
       Object data = rs.getObject(columnNameFrom.getName());
@@ -562,7 +554,7 @@ public class DBAccessorImpl implements DBAccessor {
 
 
     for (int i = 0; i < columnNames.length; i++) {
     for (int i = 0; i < columnNames.length; i++) {
       builder.append(columnNames[i]);
       builder.append(columnNames[i]);
-      if (i != columnNames.length - 1) {
+      if(i!=columnNames.length-1){
         builder.append(",");
         builder.append(",");
       }
       }
     }
     }
@@ -571,7 +563,7 @@ public class DBAccessorImpl implements DBAccessor {
 
 
     for (int i = 0; i < values.length; i++) {
     for (int i = 0; i < values.length; i++) {
       builder.append(values[i]);
       builder.append(values[i]);
-      if (i != values.length - 1) {
+      if(i!=values.length-1){
         builder.append(",");
         builder.append(",");
       }
       }
     }
     }
@@ -588,20 +580,18 @@ public class DBAccessorImpl implements DBAccessor {
       if (!ignoreFailure) {
       if (!ignoreFailure) {
         throw e;
         throw e;
       }
       }
-    } finally {
-      if (statement != null) {
-        statement.close();
-      }
     }
     }
 
 
     return rowsUpdated != 0;
     return rowsUpdated != 0;
   }
   }
 
 
+
   @Override
   @Override
   public int updateTable(String tableName, String columnName, Object value,
   public int updateTable(String tableName, String columnName, Object value,
-          String whereClause) throws SQLException {
+                         String whereClause) throws SQLException {
 
 
-    StringBuilder query = new StringBuilder(String.format("UPDATE %s SET %s = ", tableName, columnName));
+    StringBuilder query = new StringBuilder
+      (String.format("UPDATE %s SET %s = ", tableName, columnName));
 
 
     // Only String and number supported.
     // Only String and number supported.
     // Taken from: org.eclipse.persistence.internal.databaseaccess.appendParameterInternal
     // Taken from: org.eclipse.persistence.internal.databaseaccess.appendParameterInternal
@@ -616,31 +606,24 @@ public class DBAccessorImpl implements DBAccessor {
     query.append(whereClause);
     query.append(whereClause);
 
 
     Statement statement = getConnection().createStatement();
     Statement statement = getConnection().createStatement();
-    int res = -1;
-    try {
-      res = statement.executeUpdate(query.toString());
-    } finally {
-      if (statement != null) {
-        statement.close();
-      }
-    }
-    return res;
+
+    return statement.executeUpdate(query.toString());
   }
   }
 
 
   @Override
   @Override
-  public int executeUpdate(String query) throws SQLException {
-    return executeUpdate(query, false);
+  public int executeUpdate(String query) throws SQLException{
+    return  executeUpdate(query, false);
   }
   }
 
 
   @Override
   @Override
-  public int executeUpdate(String query, boolean ignoreErrors) throws SQLException {
+  public int executeUpdate(String query, boolean ignoreErrors) throws SQLException{
     Statement statement = getConnection().createStatement();
     Statement statement = getConnection().createStatement();
     try {
     try {
       return statement.executeUpdate(query);
       return statement.executeUpdate(query);
-    } catch (SQLException e) {
-      LOG.warn("Error executing query: " + query + ", "
-              + "errorCode = " + e.getErrorCode() + ", message = " + e.getMessage());
-      if (!ignoreErrors) {
+    } catch (SQLException e){
+      LOG.warn("Error executing query: " + query + ", " +
+                 "errorCode = " + e.getErrorCode() + ", message = " + e.getMessage());
+      if (!ignoreErrors){
         throw e;
         throw e;
       }
       }
     }
     }
@@ -648,8 +631,8 @@ public class DBAccessorImpl implements DBAccessor {
   }
   }
 
 
   @Override
   @Override
-  public void executeQuery(String query, String tableName, String hasColumnName) throws SQLException {
-    if (tableHasColumn(tableName, hasColumnName)) {
+  public void executeQuery(String query, String tableName, String hasColumnName) throws SQLException{
+    if (tableHasColumn(tableName, hasColumnName)){
       executeQuery(query);
       executeQuery(query);
     }
     }
   }
   }
@@ -662,19 +645,9 @@ public class DBAccessorImpl implements DBAccessor {
   @Override
   @Override
   public ResultSet executeSelect(String query) throws SQLException {
   public ResultSet executeSelect(String query) throws SQLException {
     Statement statement = getConnection().createStatement();
     Statement statement = getConnection().createStatement();
-    ResultSet rs = statement.executeQuery(query);
-    statement.closeOnCompletion();
-    return rs;
+    return statement.executeQuery(query);
   }
   }
 
 
-  @Override
-  public ResultSet executeSelect(String query, int resultSetType, int resultSetConcur) throws SQLException {
-    Statement statement = getConnection().createStatement(resultSetType, resultSetConcur);
-    ResultSet rs = statement.executeQuery(query);
-    statement.closeOnCompletion();
-    return rs;
-  }  
-  
   @Override
   @Override
   public void executeQuery(String query, boolean ignoreFailure) throws SQLException {
   public void executeQuery(String query, boolean ignoreFailure) throws SQLException {
     LOG.info("Executing query: {}", query);
     LOG.info("Executing query: {}", query);
@@ -686,12 +659,8 @@ public class DBAccessorImpl implements DBAccessor {
         LOG.error("Error executing query: " + query, e);
         LOG.error("Error executing query: " + query, e);
         throw e;
         throw e;
       } else {
       } else {
-        LOG.warn("Error executing query: " + query + ", "
-                + "errorCode = " + e.getErrorCode() + ", message = " + e.getMessage());
-      }
-    } finally {
-      if (statement != null) {
-        statement.close();
+        LOG.warn("Error executing query: " + query + ", " +
+          "errorCode = " + e.getErrorCode() + ", message = " + e.getMessage());
       }
       }
     }
     }
   }
   }
@@ -702,8 +671,12 @@ public class DBAccessorImpl implements DBAccessor {
     executeQuery(query);
     executeQuery(query);
   }
   }
 
 
-
   @Override
   @Override
+  public ResultSet executeSelect(String query, int resultSetType, int resultSetConcur) throws SQLException {
+    Statement statement = getConnection().createStatement(resultSetType, resultSetConcur);
+    return statement.executeQuery(query);
+  }
+
   public void truncateTable(String tableName) throws SQLException {
   public void truncateTable(String tableName) throws SQLException {
     String query = "DELETE FROM " + tableName;
     String query = "DELETE FROM " + tableName;
     executeQuery(query);
     executeQuery(query);
@@ -739,8 +712,8 @@ public class DBAccessorImpl implements DBAccessor {
   }
   }
 
 
   @Override
   @Override
-  public void dropUniqueConstraint(String tableName, String constraintName, boolean ignoreFailure) throws SQLException {
-    if (tableHasConstraint(convertObjectName(tableName), convertObjectName(constraintName))) {
+  public void dropUniqueConstraint(String tableName, String constraintName, boolean ignoreFailure) throws SQLException{
+    if (tableHasConstraint(convertObjectName(tableName), convertObjectName(constraintName))){
       String query = dbmsHelper.getDropUniqueConstraintStatement(tableName, constraintName);
       String query = dbmsHelper.getDropUniqueConstraintStatement(tableName, constraintName);
       executeQuery(query, ignoreFailure);
       executeQuery(query, ignoreFailure);
     } else {
     } else {
@@ -749,22 +722,22 @@ public class DBAccessorImpl implements DBAccessor {
   }
   }
 
 
   @Override
   @Override
-  public void dropUniqueConstraint(String tableName, String constraintName) throws SQLException {
+  public void dropUniqueConstraint(String tableName, String constraintName) throws SQLException{
     dropUniqueConstraint(tableName, constraintName, false);
     dropUniqueConstraint(tableName, constraintName, false);
   }
   }
 
 
   @Override
   @Override
-  public void dropPKConstraint(String tableName, String constraintName, String columnName) throws SQLException {
-    if (tableHasPrimaryKey(tableName, columnName)) {
-      String query = dbmsHelper.getDropPrimaryKeyStatement(convertObjectName(tableName), constraintName);
-      executeQuery(query, false);
-    } else {
-      LOG.warn("Primary key doesn't exists for {} table, skipping", tableName);
+  public void dropPKConstraint(String tableName, String constraintName, String columnName) throws SQLException{
+    if (tableHasPrimaryKey(tableName, columnName)){
+        String query = dbmsHelper.getDropPrimaryKeyStatement(convertObjectName(tableName), constraintName);
+        executeQuery(query, false);
+    } else{
+        LOG.warn("Primary key doesn't exists for {} table, skipping", tableName);
     }
     }
   }
   }
 
 
   @Override
   @Override
-  public void dropPKConstraint(String tableName, String constraintName, boolean ignoreFailure) throws SQLException {
+  public void dropPKConstraint(String tableName, String constraintName, boolean ignoreFailure) throws SQLException{
     /*
     /*
      * Note, this is un-safe implementation as constraint name checking will work only for PostgresSQL,
      * Note, this is un-safe implementation as constraint name checking will work only for PostgresSQL,
      * MySQL and Oracle doesn't use constraint name for drop primary key
      * MySQL and Oracle doesn't use constraint name for drop primary key
@@ -773,31 +746,24 @@ public class DBAccessorImpl implements DBAccessor {
     if (tableHasPrimaryKey(tableName, null)) {
     if (tableHasPrimaryKey(tableName, null)) {
       String query = dbmsHelper.getDropPrimaryKeyStatement(convertObjectName(tableName), constraintName);
       String query = dbmsHelper.getDropPrimaryKeyStatement(convertObjectName(tableName), constraintName);
       executeQuery(query, ignoreFailure);
       executeQuery(query, ignoreFailure);
-    } else {
+    } else{
       LOG.warn("Primary key doesn't exists for {} table, skipping", tableName);
       LOG.warn("Primary key doesn't exists for {} table, skipping", tableName);
     }
     }
   }
   }
 
 
   @Override
   @Override
-  public void dropPKConstraint(String tableName, String constraintName) throws SQLException {
+  public void dropPKConstraint(String tableName, String constraintName) throws SQLException{
     dropPKConstraint(tableName, constraintName, false);
     dropPKConstraint(tableName, constraintName, false);
   }
   }
 
 
   @Override
   @Override
   /**
   /**
-   * Execute script with autocommit and error tolerance, like psql and sqlplus
-   * do by default
+   * Execute script with autocommit and error tolerance, like psql and sqlplus do by default
    */
    */
   public void executeScript(String filePath) throws SQLException, IOException {
   public void executeScript(String filePath) throws SQLException, IOException {
     BufferedReader br = new BufferedReader(new FileReader(filePath));
     BufferedReader br = new BufferedReader(new FileReader(filePath));
-    try {
-      ScriptRunner scriptRunner = new ScriptRunner(getConnection(), false, false);
-      scriptRunner.runScript(br);
-    } finally {
-      if (br != null) {
-        br.close();
-      }
-    }
+    ScriptRunner scriptRunner = new ScriptRunner(getConnection(), false, false);
+    scriptRunner.runScript(br);
   }
   }
 
 
   @Override
   @Override
@@ -813,55 +779,31 @@ public class DBAccessorImpl implements DBAccessor {
   }
   }
 
 
   @Override
   @Override
-  public boolean tableHasPrimaryKey(String tableName, String columnName) throws SQLException {
+  public boolean tableHasPrimaryKey(String tableName, String columnName) throws SQLException{
     ResultSet rs = getDatabaseMetaData().getPrimaryKeys(null, null, convertObjectName(tableName));
     ResultSet rs = getDatabaseMetaData().getPrimaryKeys(null, null, convertObjectName(tableName));
-    boolean res = false;
-    try {
-      if (rs != null && columnName != null) {
-        while (rs.next()) {
-          if (rs.getString("COLUMN_NAME").equalsIgnoreCase(columnName)) {
-            res = true;
-            break;
-          }
+    if (rs != null && columnName != null){
+      while (rs.next()){
+        if (rs.getString("COLUMN_NAME").equalsIgnoreCase(columnName)) {
+          return true;
         }
         }
-      } else if (rs != null) {
-        res = rs.next();
-      }
-    } finally {
-      if (rs != null) {
-        rs.close();
       }
       }
+    } else if (rs != null){
+      return rs.next();
     }
     }
-    return res;
+    return false;
   }
   }
 
 
   @Override
   @Override
   public int getColumnType(String tableName, String columnName)
   public int getColumnType(String tableName, String columnName)
-          throws SQLException {
+      throws SQLException {
     // We doesn't require any actual result except metadata, so WHERE clause shouldn't match
     // We doesn't require any actual result except metadata, so WHERE clause shouldn't match
-    int res;
-    String query;
-    Statement statement = null;
-    ResultSet rs = null;
-    ResultSetMetaData rsmd = null;
-    try {
-    query = String.format("SELECT %s FROM %s WHERE 1=2", columnName, convertObjectName(tableName));
-    statement = getConnection().createStatement();
-    rs = statement.executeQuery(query);
-    rsmd = rs.getMetaData();
-    res = rsmd.getColumnType(1);
-    } finally {
-      if (rs != null){
-        rs.close();
-      }
-      if (statement != null) {
-        statement.close();
-      }
-    }
-    return res;
+    String query = String.format("SELECT %s FROM %s WHERE 1=2", columnName, convertObjectName(tableName));
+    ResultSet rs = executeSelect(query);
+    ResultSetMetaData rsmd = rs.getMetaData();
+    return rsmd.getColumnType(1);
   }
   }
 
 
-  private ResultSetMetaData getColumnMetadata(String tableName, String columnName) throws SQLException {
+  private ResultSetMetaData getColumnMetadata(String tableName, String columnName) throws SQLException{
     // We doesn't require any actual result except metadata, so WHERE clause shouldn't match
     // We doesn't require any actual result except metadata, so WHERE clause shouldn't match
     String query = String.format("SELECT %s FROM %s WHERE 1=2", convertObjectName(columnName), convertObjectName(tableName));
     String query = String.format("SELECT %s FROM %s WHERE 1=2", convertObjectName(columnName), convertObjectName(tableName));
     ResultSet rs = executeSelect(query);
     ResultSet rs = executeSelect(query);
@@ -870,20 +812,20 @@ public class DBAccessorImpl implements DBAccessor {
 
 
   @Override
   @Override
   public Class getColumnClass(String tableName, String columnName)
   public Class getColumnClass(String tableName, String columnName)
-          throws SQLException, ClassNotFoundException {
-    ResultSetMetaData rsmd = getColumnMetadata(tableName, columnName);
-    return Class.forName(rsmd.getColumnClassName(1));
+          throws SQLException, ClassNotFoundException{
+      ResultSetMetaData rsmd = getColumnMetadata(tableName, columnName);
+      return Class.forName(rsmd.getColumnClassName(1));
   }
   }
 
 
   @Override
   @Override
-  public boolean isColumnNullable(String tableName, String columnName) throws SQLException {
+  public boolean isColumnNullable(String tableName, String columnName) throws SQLException{
     ResultSetMetaData rsmd = getColumnMetadata(tableName, columnName);
     ResultSetMetaData rsmd = getColumnMetadata(tableName, columnName);
     return !(rsmd.isNullable(1) == ResultSetMetaData.columnNoNulls);
     return !(rsmd.isNullable(1) == ResultSetMetaData.columnNoNulls);
   }
   }
 
 
   @Override
   @Override
   public void setColumnNullable(String tableName, DBAccessor.DBColumnInfo columnInfo, boolean nullable)
   public void setColumnNullable(String tableName, DBAccessor.DBColumnInfo columnInfo, boolean nullable)
-          throws SQLException {
+      throws SQLException {
 
 
     String statement = dbmsHelper.getSetNullableStatement(tableName, columnInfo, nullable);
     String statement = dbmsHelper.getSetNullableStatement(tableName, columnInfo, nullable);
     executeQuery(statement);
     executeQuery(statement);
@@ -900,7 +842,7 @@ public class DBAccessorImpl implements DBAccessor {
         executeQuery(query);
         executeQuery(query);
       } else {
       } else {
         LOG.info("Column nullability property is not changed due to {} column from {} table is already in {} state, skipping",
         LOG.info("Column nullability property is not changed due to {} column from {} table is already in {} state, skipping",
-                columnName, tableName, (nullable) ? "nullable" : "not nullable");
+                   columnName, tableName, (nullable)?"nullable":"not nullable");
       }
       }
     } catch (ClassNotFoundException e) {
     } catch (ClassNotFoundException e) {
       LOG.error("Could not modify table=[], column={}, error={}", tableName, columnName, e.getMessage());
       LOG.error("Could not modify table=[], column={}, error={}", tableName, columnName, e.getMessage());
@@ -912,22 +854,27 @@ public class DBAccessorImpl implements DBAccessor {
     // ToDo: create column with more random name
     // ToDo: create column with more random name
     String tempColumnName = columnName + "_temp";
     String tempColumnName = columnName + "_temp";
 
 
-    switch (configuration.getDatabaseType()) {
+    switch (configuration.getDatabaseType()){
       case ORACLE:
       case ORACLE:
-        if (String.class.equals(fromType)
-                && (toType.equals(Character[].class))
-                || toType.equals(char[].class)) {
+        // ToDo: add check, if target column is a part of constraint.
+        // oracle doesn't support direct type change from varchar2 -> clob
+        if (String.class.equals(fromType) && (Character[].class.equals(toType) || char[].class.equals(toType))){
           addColumn(tableName, new DBColumnInfo(tempColumnName, toType));
           addColumn(tableName, new DBColumnInfo(tempColumnName, toType));
           executeUpdate(String.format("UPDATE %s SET %s = %s", convertObjectName(tableName),
           executeUpdate(String.format("UPDATE %s SET %s = %s", convertObjectName(tableName),
-                  convertObjectName(tempColumnName), convertObjectName(columnName)));
+                                       convertObjectName(tempColumnName), convertObjectName(columnName)));
           dropColumn(tableName, columnName);
           dropColumn(tableName, columnName);
-          renameColumn(tableName, tempColumnName, new DBColumnInfo(columnName, toType));
+          renameColumn(tableName,tempColumnName, new DBColumnInfo(columnName, toType));
           return;
           return;
         }
         }
-        break;
     }
     }
 
 
     alterColumn(tableName, new DBColumnInfo(columnName, toType, null));
     alterColumn(tableName, new DBColumnInfo(columnName, toType, null));
   }
   }
 
 
+
+
+
+
+
+
 }
 }

+ 0 - 1
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ViewEntity.java

@@ -802,7 +802,6 @@ public class ViewEntity implements ViewDefinition {
    *
    *
    * @return the mask class name.
    * @return the mask class name.
    */
    */
-  @Override
   public String getMask() {
   public String getMask() {
     return mask;
     return mask;
   }
   }

+ 1 - 8
ambari-server/src/main/java/org/apache/ambari/server/security/encryption/CredentialStoreServiceImpl.java

@@ -33,7 +33,6 @@ import java.security.KeyStoreException;
 import java.security.NoSuchAlgorithmException;
 import java.security.NoSuchAlgorithmException;
 import java.security.UnrecoverableKeyException;
 import java.security.UnrecoverableKeyException;
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateException;
-import java.util.logging.Level;
 
 
 public class CredentialStoreServiceImpl implements CredentialStoreService {
 public class CredentialStoreServiceImpl implements CredentialStoreService {
   private static final String CREDENTIALS_SUFFIX = "credentials.jceks";
   private static final String CREDENTIALS_SUFFIX = "credentials.jceks";
@@ -132,9 +131,8 @@ public class CredentialStoreServiceImpl implements CredentialStoreService {
   }
   }
 
 
   private void createKeystore(String filename, String keystoreType) {
   private void createKeystore(String filename, String keystoreType) {
-    FileOutputStream out = null;
     try {
     try {
-      out = new FileOutputStream(filename);
+      FileOutputStream out = new FileOutputStream(filename);
       KeyStore ks = KeyStore.getInstance(keystoreType);
       KeyStore ks = KeyStore.getInstance(keystoreType);
       ks.load(null, null);
       ks.load(null, null);
       ks.store(out, masterService.getMasterSecret());
       ks.store(out, masterService.getMasterSecret());
@@ -148,11 +146,6 @@ public class CredentialStoreServiceImpl implements CredentialStoreService {
       e.printStackTrace();
       e.printStackTrace();
     } catch (IOException e) {
     } catch (IOException e) {
       e.printStackTrace();
       e.printStackTrace();
-    } finally {
-      try {
-        out.close();
-      } catch (IOException ex) {
-      }
     }
     }
   }
   }
 
 

+ 9 - 24
ambari-server/src/main/java/org/apache/ambari/server/view/ViewRegistry.java

@@ -98,10 +98,7 @@ import javax.inject.Provider;
 import javax.inject.Singleton;
 import javax.inject.Singleton;
 
 
 import java.beans.IntrospectionException;
 import java.beans.IntrospectionException;
-import java.io.Closeable;
 import java.io.File;
 import java.io.File;
-import java.io.IOException;
-import java.net.URLClassLoader;
 import java.util.Collection;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashMap;
@@ -114,7 +111,6 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeUnit;
-import java.util.logging.Level;
 
 
 /**
 /**
  * Registry for view and view instance definitions.
  * Registry for view and view instance definitions.
@@ -1537,31 +1533,28 @@ public class ViewRegistry {
     String extractedArchiveDirPath = extractedArchiveDirFile.getAbsolutePath();
     String extractedArchiveDirPath = extractedArchiveDirFile.getAbsolutePath();
 
 
     LOG.info("Reading view archive " + archiveFile + ".");
     LOG.info("Reading view archive " + archiveFile + ".");
-    ClassLoader cl = null;
+
     try {
     try {
       // extract the archive and get the class loader
       // extract the archive and get the class loader
-      cl = extractor.extractViewArchive(viewDefinition, archiveFile, extractedArchiveDirFile);
+      ClassLoader cl = extractor.extractViewArchive(viewDefinition, archiveFile, extractedArchiveDirFile);
 
 
       ViewConfig viewConfig = archiveUtility.getViewConfigFromExtractedArchive(extractedArchiveDirPath,
       ViewConfig viewConfig = archiveUtility.getViewConfigFromExtractedArchive(extractedArchiveDirPath,
           configuration.isViewValidationEnabled());
           configuration.isViewValidationEnabled());
 
 
       if (viewConfig == null) {
       if (viewConfig == null) {
         setViewStatus(viewDefinition, ViewEntity.ViewStatus.ERROR, "View configuration not found");
         setViewStatus(viewDefinition, ViewEntity.ViewStatus.ERROR, "View configuration not found");
-      } else {
-        viewDefinition.setConfiguration(viewConfig);
-      }
+      } 
+      viewDefinition.setConfiguration(viewConfig);
 
 
       if (checkViewVersions(viewDefinition, serverVersion)) {
       if (checkViewVersions(viewDefinition, serverVersion)) {
         setupViewDefinition(viewDefinition, cl);
         setupViewDefinition(viewDefinition, cl);
 
 
         Set<ViewInstanceEntity> instanceDefinitions = new HashSet<ViewInstanceEntity>();
         Set<ViewInstanceEntity> instanceDefinitions = new HashSet<ViewInstanceEntity>();
-        List<InstanceConfig> instanceConfigs = viewConfig.getInstances();
-        if (instanceConfigs != null) {
-          for (InstanceConfig instanceConfig : instanceConfigs) {
-            ViewInstanceEntity instanceEntity = createViewInstanceDefinition(viewConfig, viewDefinition, instanceConfig);
-            instanceEntity.setXmlDriven(true);
-            instanceDefinitions.add(instanceEntity);
-          }
+
+        for (InstanceConfig instanceConfig : viewConfig.getInstances()) {
+          ViewInstanceEntity instanceEntity = createViewInstanceDefinition(viewConfig, viewDefinition, instanceConfig);
+          instanceEntity.setXmlDriven(true);
+          instanceDefinitions.add(instanceEntity);
         }
         }
         persistView(viewDefinition, instanceDefinitions);
         persistView(viewDefinition, instanceDefinitions);
 
 
@@ -1574,14 +1567,6 @@ public class ViewRegistry {
 
 
       setViewStatus(viewDefinition, ViewEntity.ViewStatus.ERROR, msg + " : " + e.getMessage());
       setViewStatus(viewDefinition, ViewEntity.ViewStatus.ERROR, msg + " : " + e.getMessage());
       LOG.error(msg, e);
       LOG.error(msg, e);
-    } finally {
-      if (cl instanceof Closeable) {
-        try {
-          ((URLClassLoader)cl).close();
-        } catch (IOException ex) {
-        }
-      }
-      
     }
     }
   }
   }
 
 

+ 1 - 0
ambari-server/src/test/java/org/apache/ambari/server/orm/DBAccessorImplTest.java

@@ -19,6 +19,7 @@
 package org.apache.ambari.server.orm;
 package org.apache.ambari.server.orm;
 
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
 import static org.junit.matchers.JUnitMatchers.containsString;
 import static org.junit.matchers.JUnitMatchers.containsString;
 
 
 import java.sql.ResultSet;
 import java.sql.ResultSet;

+ 1 - 0
ambari-server/src/test/java/org/apache/ambari/server/security/encryption/CredentialStoreServiceTest.java

@@ -21,6 +21,7 @@ import junit.framework.Assert;
 import junit.framework.TestCase;
 import junit.framework.TestCase;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.commons.logging.LogFactory;
+import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
 import org.junit.rules.TemporaryFolder;

+ 7 - 7
ambari-server/src/test/java/org/apache/ambari/server/view/ViewRegistryTest.java

@@ -108,19 +108,19 @@ import org.springframework.security.core.GrantedAuthority;
  */
  */
 public class ViewRegistryTest {
 public class ViewRegistryTest {
 
 
-  private static final String view_xml1 = "<view>\n" +
+  private static String view_xml1 = "<view>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <label>My View!</label>\n" +
       "    <label>My View!</label>\n" +
       "    <version>1.0.0</version>\n" +
       "    <version>1.0.0</version>\n" +
       "</view>";
       "</view>";
 
 
-  private static final String view_xml2 = "<view>\n" +
+  private static String view_xml2 = "<view>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <label>My View!</label>\n" +
       "    <label>My View!</label>\n" +
       "    <version>2.0.0</version>\n" +
       "    <version>2.0.0</version>\n" +
       "</view>";
       "</view>";
 
 
-  private static final String xml_valid_instance = "<view>\n" +
+  private static String xml_valid_instance = "<view>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <label>My View!</label>\n" +
       "    <label>My View!</label>\n" +
       "    <version>1.0.0</version>\n" +
       "    <version>1.0.0</version>\n" +
@@ -149,7 +149,7 @@ public class ViewRegistryTest {
       "    </instance>\n" +
       "    </instance>\n" +
       "</view>";
       "</view>";
 
 
-  private static final String xml_invalid_instance = "<view>\n" +
+  private static String xml_invalid_instance = "<view>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <label>My View!</label>\n" +
       "    <label>My View!</label>\n" +
       "    <version>1.0.0</version>\n" +
       "    <version>1.0.0</version>\n" +
@@ -169,7 +169,7 @@ public class ViewRegistryTest {
       "    </instance>\n" +
       "    </instance>\n" +
       "</view>";
       "</view>";
 
 
-  private static final String AUTO_VIEW_XML = "<view>\n" +
+  private static String AUTO_VIEW_XML = "<view>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <label>My View!</label>\n" +
       "    <label>My View!</label>\n" +
       "    <version>1.0.0</version>\n" +
       "    <version>1.0.0</version>\n" +
@@ -180,7 +180,7 @@ public class ViewRegistryTest {
       "    </auto-instance>\n" +
       "    </auto-instance>\n" +
       "</view>";
       "</view>";
 
 
-  private static final String AUTO_VIEW_WILD_STACK_XML = "<view>\n" +
+  private static String AUTO_VIEW_WILD_STACK_XML = "<view>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <label>My View!</label>\n" +
       "    <label>My View!</label>\n" +
       "    <version>1.0.0</version>\n" +
       "    <version>1.0.0</version>\n" +
@@ -191,7 +191,7 @@ public class ViewRegistryTest {
       "    </auto-instance>\n" +
       "    </auto-instance>\n" +
       "</view>";
       "</view>";
 
 
-  private static final String AUTO_VIEW_BAD_STACK_XML = "<view>\n" +
+  private static String AUTO_VIEW_BAD_STACK_XML = "<view>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <name>MY_VIEW</name>\n" +
       "    <label>My View!</label>\n" +
       "    <label>My View!</label>\n" +
       "    <version>1.0.0</version>\n" +
       "    <version>1.0.0</version>\n" +

+ 1 - 12
ambari-shell/ambari-groovy-shell/src/main/java/org/apache/ambari/shell/commands/BlueprintCommands.java

@@ -24,8 +24,6 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.IOException;
 import java.net.URL;
 import java.net.URL;
-import java.util.logging.Level;
-import java.util.logging.Logger;
 
 
 import org.apache.ambari.groovy.client.AmbariClient;
 import org.apache.ambari.groovy.client.AmbariClient;
 import org.apache.ambari.shell.completion.Blueprint;
 import org.apache.ambari.shell.completion.Blueprint;
@@ -170,19 +168,10 @@ public class BlueprintCommands implements CommandMarker {
 
 
   private String readContent(File file) {
   private String readContent(File file) {
     String content = null;
     String content = null;
-    FileInputStream fis = null;
     try {
     try {
-      fis = new FileInputStream(file);
-      content = IOUtils.toString(fis);
+      content = IOUtils.toString(new FileInputStream(file));
     } catch (IOException e) {
     } catch (IOException e) {
       // not important
       // not important
-    } finally {
-      if (fis != null) {
-        try {
-          fis.close();
-        } catch (IOException ex) {
-        }
-      }
     }
     }
     return content;
     return content;
   }
   }