From 35feca591cbb06d628b2b76b60a84f3d44513870 Mon Sep 17 00:00:00 2001 From: Sven Diedrichsen Date: Mon, 17 Sep 2018 21:53:02 +0200 Subject: [PATCH] Fixing sonar bugs of severity blocker from module Batch Connector for Glassfish --- .../rdbms/DB2PersistenceManager.java | 70 +- .../rdbms/JBatchJDBCPersistenceManager.java | 1521 ++++++----------- .../rdbms/MySqlPersistenceManager.java | 119 +- .../rdbms/OraclePersistenceManager.java | 193 +-- .../rdbms/PostgresPersistenceManager.java | 299 ++-- .../rdbms/SQLServerPersistenceManager.java | 219 ++- 6 files changed, 942 insertions(+), 1479 deletions(-) diff --git a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/DB2PersistenceManager.java b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/DB2PersistenceManager.java index 52f7374c7ef..6e05bb873f0 100644 --- a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/DB2PersistenceManager.java +++ b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/DB2PersistenceManager.java @@ -60,7 +60,7 @@ import static org.glassfish.batch.spi.impl.BatchRuntimeHelper.PAYARA_TABLE_SUFFIX_PROPERTY; /** - * + * * DB2 Persistence Manager */ @@ -72,7 +72,7 @@ public class DB2PersistenceManager extends JBatchJDBCPersistenceManager implemen private final static Logger logger = Logger.getLogger(CLASSNAME); private IBatchConfig batchConfig = null; - + // db2 create table strings protected Map createDB2Strings; @@ -87,7 +87,7 @@ public void init(IBatchConfig batchConfig) jndiName = batchConfig.getDatabaseConfigurationBean().getJndiName(); prefix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_PREFIX_PROPERTY, ""); suffix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_SUFFIX_PROPERTY, ""); - + try { Context ctx = new InitialContext(); dataSource = (DataSource) ctx.lookup(jndiName); @@ -119,7 +119,7 @@ public void init(IBatchConfig batchConfig) "JNDI name is not defined."); } - + try { if (!isSchemaValid()) { setDefaultSchema(); @@ -133,7 +133,7 @@ public void init(IBatchConfig batchConfig) logger.config("Exiting CLASSNAME.init()"); } - + /** * Check the schema exists * @return @@ -143,43 +143,37 @@ public void init(IBatchConfig batchConfig) protected boolean isSchemaValid() throws SQLException { boolean result = false; - Connection conn = null; - DatabaseMetaData dbmd = null; - ResultSet rs = null; logger.entering(CLASSNAME, "isDB2SchemaValid"); - try { - conn = getConnectionToDefaultSchema(); - dbmd = conn.getMetaData(); - rs = dbmd.getSchemas(); - - while (rs.next()) { - - String schemaname = rs.getString("TABLE_SCHEM"); - if (schema.equalsIgnoreCase(schemaname)) { - logger.exiting(CLASSNAME, "isSchemaValid", true); - return true; + try (Connection conn = getConnectionToDefaultSchema()) { + DatabaseMetaData dbmd = conn.getMetaData(); + try (ResultSet rs = dbmd.getSchemas()) { + while (rs.next()) { + String schemaname = rs.getString("TABLE_SCHEM"); + if (schema.equalsIgnoreCase(schemaname)) { + logger.exiting(CLASSNAME, "isSchemaValid", true); + return true; + } } } + } catch (SQLException e) { logger.severe(e.getLocalizedMessage()); throw e; - } finally { - cleanupConnection(conn, rs, null); } logger.exiting(CLASSNAME, "isDB2SchemaValid", false); return result; } - + /** * Check the relevant db2 tables exist in the relevant schema * @throws SQLException */ @Override protected void checkTables() throws SQLException { - + logger.entering(CLASSNAME, "checkDB2Tables"); setCreateDB2StringsMap(tableNames); createTableIfNotExists(tableNames.get(CHECKPOINT_TABLE_KEY), @@ -206,8 +200,6 @@ protected void checkTables() throws SQLException { @Override public boolean checkIfTableExists(DataSource dSource, String tableName, String schemaName) { - Statement statement = null; - ResultSet resultSet = null; dataSource = dSource; boolean result = true; @@ -219,26 +211,30 @@ public boolean checkIfTableExists(DataSource dSource, String tableName, String s setDefaultSchema(); } - statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - String query = "select name from sysibm.systables where name =" - + "\'" + tableName.toUpperCase() + "\'" + "and type = 'T'"; - resultSet = statement.executeQuery(query); + try (Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY)) { - int rowcount = getTableRowCount(resultSet); + String query = "select name from sysibm.systables where name =" + + "\'" + tableName.toUpperCase() + "\'" + "and type = 'T'"; - if (rowcount == 0) { - if (!resultSet.next()) { - result = false; - } - } + try (ResultSet resultSet = statement.executeQuery(query)) { + int rowcount = getTableRowCount(resultSet); + + if (rowcount == 0) { + if (!resultSet.next()) { + result = false; + } + } + } + + } } catch (SQLException ex) { logger.severe(ex.getLocalizedMessage()); } return result; } - + /** * Method invoked to insert the DB2 create table strings into a hashmap **/ diff --git a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/JBatchJDBCPersistenceManager.java b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/JBatchJDBCPersistenceManager.java index 9b94c80fd26..d2d5f12d6b3 100644 --- a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/JBatchJDBCPersistenceManager.java +++ b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/JBatchJDBCPersistenceManager.java @@ -102,7 +102,7 @@ import org.glassfish.batch.spi.impl.BatchRuntimeConfiguration; /** - * + * * Base Persistence Manager Class. All Persistence Managers extend this base * persistence manager class */ @@ -133,17 +133,17 @@ public class JBatchJDBCPersistenceManager implements protected Map createDerbyStrings; protected RequestTracingService requestTracing; - + /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.impl.AbstractPersistenceManagerImpl * #init(com.ibm.jbatch.container.IBatchConfig) */ @Override public void init(IBatchConfig batchConfig) throws BatchContainerServiceException { - + logger.config("Entering CLASSNAME.init(), batchConfig =" + batchConfig); this.batchConfig = batchConfig; @@ -152,7 +152,7 @@ public void init(IBatchConfig batchConfig) throws BatchContainerServiceException jndiName = batchConfig.getDatabaseConfigurationBean().getJndiName(); prefix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_PREFIX_PROPERTY, ""); suffix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_SUFFIX_PROPERTY, ""); - + logger.config("JNDI name = " + jndiName); if (jndiName == null || jndiName.equals("")) { @@ -163,7 +163,7 @@ public void init(IBatchConfig batchConfig) throws BatchContainerServiceException dataSource = (DataSource) new InitialContext().lookup(jndiName); } catch (NamingException e) { logger.severe( - "Lookup failed for JNDI name: " + jndiName + ". " + + "Lookup failed for JNDI name: " + jndiName + ". " + " One cause of this could be that the batch runtime is incorrectly configured to EE mode when it should be in SE mode."); throw new BatchContainerServiceException(e); } @@ -192,7 +192,7 @@ public void init(IBatchConfig batchConfig) throws BatchContainerServiceException requestTracing = getDefaultHabitat().getService(RequestTracingService.class); } catch (NullPointerException ex) { logger.log(INFO, - "Error retrieving Request Tracing service " + + "Error retrieving Request Tracing service " + "during initialisation of JBatchJDBCPersistenceManager - NullPointerException"); } @@ -201,7 +201,7 @@ public void init(IBatchConfig batchConfig) throws BatchContainerServiceException /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.impl.AbstractPersistenceManagerImpl * #getCheckpointData @@ -210,18 +210,18 @@ public void init(IBatchConfig batchConfig) throws BatchContainerServiceException @Override public CheckpointData getCheckpointData(CheckpointDataKey key) { logger.entering(CLASSNAME, "getCheckpointData", key == null ? "" : key); - + tryObtainTableLock(); - + CheckpointData checkpointData = queryCheckpointData(key.getCommaSeparatedKey()); - + logger.exiting(CLASSNAME, "getCheckpointData", checkpointData == null ? "" : checkpointData); return checkpointData; } - + /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.impl.AbstractPersistenceManagerImpl * #updateCheckpointData @@ -231,22 +231,22 @@ public CheckpointData getCheckpointData(CheckpointDataKey key) { @Override public void updateCheckpointData(CheckpointDataKey key, CheckpointData value) { logger.entering(CLASSNAME, "updateCheckpointData", new Object[] { key, value }); - + tryObtainTableLock(); - + CheckpointData data = queryCheckpointData(key.getCommaSeparatedKey()); if (data != null) { updateCheckpointData(key.getCommaSeparatedKey(), value); } else { createCheckpointData(key, value); } - + logger.exiting(CLASSNAME, "updateCheckpointData"); } - + /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.impl.AbstractPersistenceManagerImpl * #createCheckpointData @@ -256,9 +256,9 @@ public void updateCheckpointData(CheckpointDataKey key, CheckpointData value) { @Override public void createCheckpointData(CheckpointDataKey key, CheckpointData value) { logger.entering(CLASSNAME, "createCheckpointData", new Object[] { key, value }); - + insertCheckpointData(key.getCommaSeparatedKey(), value); - + logger.exiting(CLASSNAME, "createCheckpointData"); } @@ -286,7 +286,7 @@ public String setDefaultSchema() throws SQLException { logger.severe(e.getLocalizedMessage()); throw e; } - + logger.finest("Exiting setDefaultSchema"); return schema; } @@ -294,17 +294,17 @@ public String setDefaultSchema() throws SQLException { private boolean isDerby(Connection connection) throws SQLException { return connection.getMetaData().getDatabaseProductName().toLowerCase().contains("derby"); } - + /** * Checks if the schema exists in the database. If not connect to the * default schema - * + * * @return true if the schema exists, false otherwise. * @throws SQLException */ protected boolean isSchemaValid() throws SQLException { logger.entering(CLASSNAME, "isDerbySchemaValid"); - + try (Connection connection = getConnectionToDefaultSchema()) { try (ResultSet rs = connection.getMetaData().getSchemas()) { while (rs.next()) { @@ -325,9 +325,8 @@ protected boolean isSchemaValid() throws SQLException { /** * Check if the derby jbatch tables exist, if not create them - * - * @param tableNames - * @throws java.sql.SQLException + * + * @throws java.sql.SQLException **/ protected void checkTables() throws SQLException { setCreateDerbyStringsMap(tableNames); @@ -356,7 +355,7 @@ public void createTables(DataSource dataSource, BatchRuntimeConfiguration batchR suffix = batchRuntimeConfiguration.getTableSuffix(); schema = batchRuntimeConfiguration.getSchemaName(); tableNames = getSharedTableMap(); - + try { if (!isSchemaValid()) { setDefaultSchema(); @@ -366,13 +365,13 @@ public void createTables(DataSource dataSource, BatchRuntimeConfiguration batchR logger.severe(ex.getLocalizedMessage()); } } - + /** * Create the jbatch tables if they do not exist **/ protected void createTableIfNotExists(String tableName, String createTableStatement) throws SQLException { logger.entering(CLASSNAME, "createTableIfNotExists", new Object[] { tableName, createTableStatement }); - + try (Connection connection = getConnection()) { if (!checkIfTableExists(dataSource, tableName, schema)) { logger.log(INFO, tableName + " table does not exists. Trying to create it."); @@ -385,9 +384,9 @@ protected void createTableIfNotExists(String tableName, String createTableStatem throw e; } finally { logger.exiting(CLASSNAME, "createTableIfNotExists"); - } + } } - + public boolean checkIfTableExists(DataSource dSource, String tableName, String schemaName) { boolean result = true; dataSource = dSource; @@ -414,7 +413,7 @@ public boolean checkIfTableExists(DataSource dSource, String tableName, String s * Retrieve the number of rows in the resultset. This method is used to * check if a table exists in a given schema **/ - + public int getTableRowCount(ResultSet resultSet) throws SQLException { int rowcount = 0; @@ -433,7 +432,7 @@ public int getTableRowCount(ResultSet resultSet) throws SQLException { /** * Executes the provided SQL statement - * + * * @param statement * @throws SQLException */ @@ -454,9 +453,9 @@ protected void executeStatement(String statement) throws SQLException { /** * Get a connection from the datasource - * + * * @return the database connection and sets the schema - * + * * @throws SQLException */ protected Connection getConnection() throws SQLException { @@ -505,7 +504,7 @@ protected void logException(String msg, Exception e) { /** * Set the schema to the default schema or the schema defined at batch * configuration time - * + * * @param connection * @throws SQLException */ @@ -524,36 +523,37 @@ protected void setSchemaOnConnection(Connection connection) throws SQLException /** * select data from DB table - * + * * @param key * - the IPersistenceDataKey object * @return List of serializable objects store in the DB table - * + * * Ex. select id, obj from tablename where id = ? */ protected CheckpointData queryCheckpointData(Object key) { logger.entering(CLASSNAME, "queryCheckpointData", new Object[] { key, SELECT_CHECKPOINTDATA }); - + CheckpointData data = null; - + try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(queryStrings.get(SELECT_CHECKPOINTDATA))) { statement.setObject(1, key); - ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - data = (CheckpointData) deserializeObject(resultSet.getBytes("obj")); - } + try (ResultSet resultSet = statement.executeQuery()) { + if (resultSet.next()) { + data = (CheckpointData) deserializeObject(resultSet.getBytes("obj")); + } + } } - } catch (SQLException |IOException | ClassNotFoundException e) { + } catch (SQLException | IOException | ClassNotFoundException e) { throw new PersistenceException(e); - } - + } + logger.exiting(CLASSNAME, "queryCheckpointData"); return data; } - + private void tryObtainTableLock() { - + try (Connection connection = getConnection()) { if (isDerby(connection)) { try (PreparedStatement statement = connection.prepareStatement(queryStrings.get(LOCK_CHECKPOINTDATA))) { @@ -562,103 +562,81 @@ private void tryObtainTableLock() { } } catch (SQLException e) { throw new PersistenceException(e); - } + } } /** * Insert data to DB table - * + * * @param key * - the IPersistenceDataKey object * @param value * - serializable object to store - * + * * Ex. insert into tablename values(?, ?) */ protected void insertCheckpointData(Object key, T value) { logger.entering(CLASSNAME, "insertCheckpointData", new Object[] { key, value }); - + try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(queryStrings.get(INSERT_CHECKPOINTDATA))) { ByteArrayOutputStream baos = new ByteArrayOutputStream();; try (ObjectOutputStream oout = new ObjectOutputStream(baos)) { oout.writeObject(value); - + statement.setObject(1, key); statement.setBytes(2, baos.toByteArray()); statement.executeUpdate(); } - + } } catch (SQLException | IOException e) { throw new PersistenceException(e); - } - + } + logger.exiting(CLASSNAME, "insertCheckpointData"); } /** * update data in DB table - * + * * @param value * - serializable object to store * @param key * - the IPersistenceDataKey object * @param query * - SQL statement to execute. - * + * * Ex. update tablename set obj = ? where id = ? */ protected void updateCheckpointData(Object key, CheckpointData value) { logger.entering(CLASSNAME, "updateCheckpointData", new Object[] { key, value }); - Connection conn = null; - PreparedStatement statement = null; - ByteArrayOutputStream baos = null; - ObjectOutputStream oout = null; - byte[] b; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(UPDATE_CHECKPOINTDATA)); - baos = new ByteArrayOutputStream(); - oout = new ObjectOutputStream(baos); + + try (Connection conn = getConnection(); + PreparedStatement statement = + conn.prepareStatement(queryStrings.get(UPDATE_CHECKPOINTDATA)); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(baos)) { + oout.writeObject(value); - b = baos.toByteArray(); + byte[] b = baos.toByteArray(); statement.setBytes(1, b); statement.setObject(2, key); statement.executeUpdate(); - } catch (SQLException e) { - logger.severe(e.getLocalizedMessage()); - throw new PersistenceException(e); - } catch (IOException e) { + + } catch (SQLException | IOException e) { logger.severe(e.getLocalizedMessage()); throw new PersistenceException(e); - } finally { - if (baos != null) { - try { - baos.close(); - } catch (IOException e) { - throw new PersistenceException(e); - } - } - if (oout != null) { - try { - oout.close(); - } catch (IOException e) { - throw new PersistenceException(e); - } - } - cleanupConnection(conn, null, statement); } logger.exiting(CLASSNAME, "updateCheckpointData"); } /** * closes connection, result set and statement - * + * * @param conn * - connection object to close * @param rs @@ -707,7 +685,7 @@ protected void cleanupConnection(Connection conn, ResultSet rs, /** * closes connection and statement - * + * * @param conn * - connection object to close * @param statement @@ -746,26 +724,21 @@ protected void cleanupConnection(Connection conn, @Override public int jobOperatorGetJobInstanceCount(String jobName, String appTag) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; int count; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(JOBOPERATOR_GET_JOB_INSTANCE_COUNT)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOBOPERATOR_GET_JOB_INSTANCE_COUNT))) { statement.setString(1, jobName); statement.setString(2, appTag); - rs = statement.executeQuery(); - rs.next(); - count = rs.getInt("jobinstancecount"); + try (ResultSet rs = statement.executeQuery()) { + rs.next(); + count = rs.getInt("jobinstancecount"); + } } catch (SQLException e) { logger.severe(e.getLocalizedMessage()); throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return count; } @@ -773,24 +746,18 @@ public int jobOperatorGetJobInstanceCount(String jobName, String appTag) { @Override public int jobOperatorGetJobInstanceCount(String jobName) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; int count; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(SELECT_JOBINSTANCEDATA_COUNT)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(SELECT_JOBINSTANCEDATA_COUNT))) { statement.setString(1, jobName); - rs = statement.executeQuery(); - rs.next(); - count = rs.getInt("jobinstancecount"); - + try (ResultSet rs = statement.executeQuery()) { + rs.next(); + count = rs.getInt("jobinstancecount"); + } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return count; } @@ -798,29 +765,24 @@ public int jobOperatorGetJobInstanceCount(String jobName) { @Override public List jobOperatorGetJobInstanceIds(String jobName, String appTag, int start, int count) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - List data = new ArrayList(); + List data = new ArrayList<>(); - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(JOBOPERATOR_GET_JOB_INSTANCE_IDS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOBOPERATOR_GET_JOB_INSTANCE_IDS))) { statement.setObject(1, jobName); statement.setObject(2, appTag); - rs = statement.executeQuery(); - while (rs.next()) { - long id = rs.getLong("jobinstanceid"); - data.add(id); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + long id = rs.getLong("jobinstanceid"); + data.add(id); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } - if (data.size() > 0) { + if (!data.isEmpty()) { try { return data.subList(start, start + count); } catch (IndexOutOfBoundsException oobEx) { @@ -835,28 +797,24 @@ public List jobOperatorGetJobInstanceIds(String jobName, public List jobOperatorGetJobInstanceIds(String jobName, int start, int count) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - List data = new ArrayList(); + List data = new ArrayList<>(); + + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(SELECT_JOBINSTANCEDATA_IDS))) { - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(SELECT_JOBINSTANCEDATA_IDS)); statement.setObject(1, jobName); - rs = statement.executeQuery(); - while (rs.next()) { - long id = rs.getLong("jobinstanceid"); - data.add(id); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + long id = rs.getLong("jobinstanceid"); + data.add(id); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } - if (data.size() > 0) { + if (!data.isEmpty()) { try { return data.subList(start, start + count); } catch (IndexOutOfBoundsException oobEx) { @@ -870,31 +828,25 @@ public List jobOperatorGetJobInstanceIds(String jobName, int start, @Override public Map jobOperatorGetExternalJobInstanceData() { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - HashMap data = new HashMap(); + Map data = new HashMap<>(); - try { - conn = getConnection(); + final String filter = "not like '" + + PartitionedStepBuilder.JOB_ID_SEPARATOR + "%'"; + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOB_OPERATOR_GET_EXTERNAL_JOB_INSTANCE_DATA) + filter)) { // Filter out 'subjob' parallel execution entries which start with // the special character - final String filter = "not like '" - + PartitionedStepBuilder.JOB_ID_SEPARATOR + "%'"; - - statement = conn.prepareStatement(queryStrings - .get(JOB_OPERATOR_GET_EXTERNAL_JOB_INSTANCE_DATA) + filter); - rs = statement.executeQuery(); - while (rs.next()) { - long id = rs.getLong("jobinstanceid"); - String name = rs.getString("name"); - data.put(id, name); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + long id = rs.getLong("jobinstanceid"); + String name = rs.getString("name"); + data.put(id, name); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return data; @@ -904,30 +856,25 @@ public Map jobOperatorGetExternalJobInstanceData() { public Timestamp jobOperatorQueryJobExecutionTimestamp(long key, TimestampType timestampType) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; Timestamp createTimestamp = null; Timestamp endTimestamp = null; Timestamp updateTimestamp = null; Timestamp startTimestamp = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(JOB_OPERATOR_QUERY_JOB_EXECUTION_TIMESTAMP)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOB_OPERATOR_QUERY_JOB_EXECUTION_TIMESTAMP))) { statement.setObject(1, key); - rs = statement.executeQuery(); - while (rs.next()) { - createTimestamp = rs.getTimestamp(1); - endTimestamp = rs.getTimestamp(2); - updateTimestamp = rs.getTimestamp(3); - startTimestamp = rs.getTimestamp(4); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + createTimestamp = rs.getTimestamp(1); + endTimestamp = rs.getTimestamp(2); + updateTimestamp = rs.getTimestamp(3); + startTimestamp = rs.getTimestamp(4); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } if (timestampType.equals(TimestampType.CREATE)) { @@ -946,24 +893,19 @@ public Timestamp jobOperatorQueryJobExecutionTimestamp(long key, @Override public String jobOperatorQueryJobExecutionBatchStatus(long key) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; String status = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(JOB_OPERATOR_QUERY_JOB_EXECUTION_BATCH_STATUS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOB_OPERATOR_QUERY_JOB_EXECUTION_BATCH_STATUS))) { statement.setLong(1, key); - rs = statement.executeQuery(); - while (rs.next()) { - status = rs.getString(1); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + status = rs.getString(1); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return status; @@ -972,24 +914,19 @@ public String jobOperatorQueryJobExecutionBatchStatus(long key) { @Override public String jobOperatorQueryJobExecutionExitStatus(long key) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; String status = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(JOB_OPERATOR_QUERY_JOB_EXECUTION_EXIT_STATUS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOB_OPERATOR_QUERY_JOB_EXECUTION_EXIT_STATUS))) { statement.setLong(1, key); - rs = statement.executeQuery(); - while (rs.next()) { - status = rs.getString(1); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + status = rs.getString(1); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return status; @@ -999,29 +936,24 @@ public String jobOperatorQueryJobExecutionExitStatus(long key) { public long jobOperatorQueryJobExecutionJobInstanceId(long executionID) throws NoSuchJobExecutionException { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; long jobinstanceID = 0; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(JOB_OPERATOR_QUERY_JOB_EXECUTION_JOB_ID)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOB_OPERATOR_QUERY_JOB_EXECUTION_JOB_ID))) { statement.setLong(1, executionID); - rs = statement.executeQuery(); - if (rs.next()) { - jobinstanceID = rs.getLong("jobinstanceid"); - } else { - String msg = "Did not find job instance associated with executionID =" - + executionID; - logger.fine(msg); - throw new NoSuchJobExecutionException(msg); + try (ResultSet rs = statement.executeQuery()) { + if (rs.next()) { + jobinstanceID = rs.getLong("jobinstanceid"); + } else { + String msg = "Did not find job instance associated with executionID =" + + executionID; + logger.fine(msg); + throw new NoSuchJobExecutionException(msg); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return jobinstanceID; @@ -1030,44 +962,25 @@ public long jobOperatorQueryJobExecutionJobInstanceId(long executionID) @Override public Properties getParameters(long executionId) throws NoSuchJobExecutionException { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; Properties props = null; - ObjectInputStream objectIn = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings.get(GET_PARAMETERS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings.get(GET_PARAMETERS))) { statement.setLong(1, executionId); - rs = statement.executeQuery(); - - if (rs.next()) { - // get the object based data - byte[] buf = rs.getBytes("parameters"); - props = (Properties) deserializeObject(buf); - } else { - String msg = "Did not find table entry for executionID =" - + executionId; - logger.fine(msg); - throw new NoSuchJobExecutionException(msg); - } - - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { - throw new PersistenceException(e); - } catch (ClassNotFoundException e) { - throw new PersistenceException(e); - } finally { - if (objectIn != null) { - try { - objectIn.close(); - } catch (IOException e) { - throw new PersistenceException(e); + try (ResultSet rs = statement.executeQuery()) { + if (rs.next()) { + // get the object based data + byte[] buf = rs.getBytes("parameters"); + props = (Properties) deserializeObject(buf); + } else { + String msg = "Did not find table entry for executionID =" + + executionId; + logger.fine(msg); + throw new NoSuchJobExecutionException(msg); } } - cleanupConnection(conn, rs, statement); + } catch (SQLException | IOException | ClassNotFoundException e) { + throw new PersistenceException(e); } return props; @@ -1077,67 +990,112 @@ public Properties getParameters(long executionId) public Map getMostRecentStepExecutionsForJobInstance( long instanceId) { - Map data = new HashMap(); + Map data = new HashMap<>(); - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(MOST_RECENT_STEPS_FOR_JOB))) { + statement.setLong(1, instanceId); + try (ResultSet rs = statement.executeQuery()) { + + while (rs.next()) { + String stepname = null; + + stepname = rs.getString("stepname"); + if (data.containsKey(stepname)) { + continue; + } else { + long jobexecid = rs.getLong("jobexecid"); + long stepexecid = rs.getLong("stepexecid"); + String batchstatus = rs.getString("batchstatus"); + String exitstatus = rs.getString("exitstatus"); + long readCount = rs.getLong("readcount"); + long writeCount = rs.getLong("writecount"); + long commitCount = rs.getLong("commitcount"); + long rollbackCount = rs.getLong("rollbackcount"); + long readSkipCount = rs.getLong("readskipcount"); + long processSkipCount = rs.getLong("processskipcount"); + long filterCount = rs.getLong("filtercount"); + long writeSkipCount = rs.getLong("writeSkipCount"); + Timestamp startTS = rs.getTimestamp("startTime"); + Timestamp endTS = rs.getTimestamp("endTime"); + + // get the object based data + Serializable persistentData = null; + byte[] pDataBytes = rs.getBytes("persistentData"); + if (pDataBytes != null) { + try (ObjectInputStream objectIn = + new TCCLObjectInputStream(new ByteArrayInputStream(pDataBytes))) { + persistentData = (Serializable) objectIn.readObject(); + } + } + + StepExecutionImpl stepEx = new StepExecutionImpl(jobexecid, stepexecid); + stepEx.setBatchStatus(BatchStatus.valueOf(batchstatus)); + stepEx.setExitStatus(exitstatus); + stepEx.setStepName(stepname); + stepEx.setReadCount(readCount); + stepEx.setWriteCount(writeCount); + stepEx.setCommitCount(commitCount); + stepEx.setRollbackCount(rollbackCount); + stepEx.setReadSkipCount(readSkipCount); + stepEx.setProcessSkipCount(processSkipCount); + stepEx.setFilterCount(filterCount); + stepEx.setWriteSkipCount(writeSkipCount); + stepEx.setStartTime(startTS); + stepEx.setEndTime(endTS); + stepEx.setPersistentUserData(persistentData); + + data.put(stepname, stepEx); + } + } + } + } catch (SQLException | IOException | ClassNotFoundException e) { + throw new PersistenceException(e); + } - long jobexecid = 0; - long stepexecid = 0; - String stepname = null; - String batchstatus = null; - String exitstatus = null; - Exception ex = null; - long readCount = 0; - long writeCount = 0; - long commitCount = 0; - long rollbackCount = 0; - long readSkipCount = 0; - long processSkipCount = 0; - long filterCount = 0; - long writeSkipCount = 0; - Timestamp startTS = null; - Timestamp endTS = null; - StepExecutionImpl stepEx = null; - ObjectInputStream objectIn = null; + return data; + } - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(MOST_RECENT_STEPS_FOR_JOB)); - statement.setLong(1, instanceId); - rs = statement.executeQuery(); - while (rs.next()) { - stepname = rs.getString("stepname"); - if (data.containsKey(stepname)) { - continue; - } else { + @Override + public List getStepExecutionsForJobExecution(long execid) { - jobexecid = rs.getLong("jobexecid"); - batchstatus = rs.getString("batchstatus"); - exitstatus = rs.getString("exitstatus"); - readCount = rs.getLong("readcount"); - writeCount = rs.getLong("writecount"); - commitCount = rs.getLong("commitcount"); - rollbackCount = rs.getLong("rollbackcount"); - readSkipCount = rs.getLong("readskipcount"); - processSkipCount = rs.getLong("processskipcount"); - filterCount = rs.getLong("filtercount"); - writeSkipCount = rs.getLong("writeSkipCount"); - startTS = rs.getTimestamp("startTime"); - endTS = rs.getTimestamp("endTime"); + + List data = new ArrayList<>(); + + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(STEP_EXECUTIONS_FOR_JOB_EXECUTION))) { + statement.setLong(1, execid); + try (ResultSet rs = statement.executeQuery()) { + + while (rs.next()) { + long jobexecid = rs.getLong("jobexecid"); + long stepexecid = rs.getLong("stepexecid"); + String stepname = rs.getString("stepname"); + String batchstatus = rs.getString("batchstatus"); + String exitstatus = rs.getString("exitstatus"); + long readCount = rs.getLong("readcount"); + long writeCount = rs.getLong("writecount"); + long commitCount = rs.getLong("commitcount"); + long rollbackCount = rs.getLong("rollbackcount"); + long readSkipCount = rs.getLong("readskipcount"); + long processSkipCount = rs.getLong("processskipcount"); + long filterCount = rs.getLong("filtercount"); + long writeSkipCount = rs.getLong("writeSkipCount"); + Timestamp startTS = rs.getTimestamp("startTime"); + Timestamp endTS = rs.getTimestamp("endTime"); // get the object based data Serializable persistentData = null; byte[] pDataBytes = rs.getBytes("persistentData"); if (pDataBytes != null) { - objectIn = new TCCLObjectInputStream( - new ByteArrayInputStream(pDataBytes)); - persistentData = (Serializable) objectIn.readObject(); + try (ObjectInputStream objectIn = + new TCCLObjectInputStream(new ByteArrayInputStream(pDataBytes))) { + persistentData = (Serializable) objectIn.readObject(); + } } - stepEx = new StepExecutionImpl(jobexecid, stepexecid); - + StepExecutionImpl stepEx = new StepExecutionImpl(jobexecid, stepexecid); stepEx.setBatchStatus(BatchStatus.valueOf(batchstatus)); stepEx.setExitStatus(exitstatus); stepEx.setStepName(stepname); @@ -1153,111 +1111,15 @@ public Map getMostRecentStepExecutionsForJobInstance( stepEx.setEndTime(endTS); stepEx.setPersistentUserData(persistentData); - data.put(stepname, stepEx); - } - } - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { - throw new PersistenceException(e); - } catch (ClassNotFoundException e) { - throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); - } - - return data; - } + logger.fine("BatchStatus: " + batchstatus + " | StepName: " + + stepname + " | JobExecID: " + jobexecid + + " | StepExecID: " + stepexecid); - @Override - public List getStepExecutionsForJobExecution(long execid) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - - long jobexecid = 0; - long stepexecid = 0; - String stepname = null; - String batchstatus = null; - String exitstatus = null; - Exception ex = null; - long readCount = 0; - long writeCount = 0; - long commitCount = 0; - long rollbackCount = 0; - long readSkipCount = 0; - long processSkipCount = 0; - long filterCount = 0; - long writeSkipCount = 0; - Timestamp startTS = null; - Timestamp endTS = null; - StepExecutionImpl stepEx = null; - ObjectInputStream objectIn = null; - - List data = new ArrayList(); - - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(STEP_EXECUTIONS_FOR_JOB_EXECUTION)); - statement.setLong(1, execid); - rs = statement.executeQuery(); - while (rs.next()) { - jobexecid = rs.getLong("jobexecid"); - stepexecid = rs.getLong("stepexecid"); - stepname = rs.getString("stepname"); - batchstatus = rs.getString("batchstatus"); - exitstatus = rs.getString("exitstatus"); - readCount = rs.getLong("readcount"); - writeCount = rs.getLong("writecount"); - commitCount = rs.getLong("commitcount"); - rollbackCount = rs.getLong("rollbackcount"); - readSkipCount = rs.getLong("readskipcount"); - processSkipCount = rs.getLong("processskipcount"); - filterCount = rs.getLong("filtercount"); - writeSkipCount = rs.getLong("writeSkipCount"); - startTS = rs.getTimestamp("startTime"); - endTS = rs.getTimestamp("endTime"); - // get the object based data - Serializable persistentData = null; - byte[] pDataBytes = rs.getBytes("persistentData"); - if (pDataBytes != null) { - objectIn = new TCCLObjectInputStream( - new ByteArrayInputStream(pDataBytes)); - persistentData = (Serializable) objectIn.readObject(); + data.add(stepEx); } - - stepEx = new StepExecutionImpl(jobexecid, stepexecid); - - stepEx.setBatchStatus(BatchStatus.valueOf(batchstatus)); - stepEx.setExitStatus(exitstatus); - stepEx.setStepName(stepname); - stepEx.setReadCount(readCount); - stepEx.setWriteCount(writeCount); - stepEx.setCommitCount(commitCount); - stepEx.setRollbackCount(rollbackCount); - stepEx.setReadSkipCount(readSkipCount); - stepEx.setProcessSkipCount(processSkipCount); - stepEx.setFilterCount(filterCount); - stepEx.setWriteSkipCount(writeSkipCount); - stepEx.setStartTime(startTS); - stepEx.setEndTime(endTS); - stepEx.setPersistentUserData(persistentData); - - logger.fine("BatchStatus: " + batchstatus + " | StepName: " - + stepname + " | JobExecID: " + jobexecid - + " | StepExecID: " + stepexecid); - - data.add(stepEx); } - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { + } catch (SQLException | IOException | ClassNotFoundException e) { throw new PersistenceException(e); - } catch (ClassNotFoundException e) { - throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return data; @@ -1265,88 +1127,63 @@ public List getStepExecutionsForJobExecution(long execid) { @Override public StepExecution getStepExecutionByStepExecutionId(long stepExecId) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - - long jobexecid = 0; - long stepexecid = 0; - String stepname = null; - String batchstatus = null; - String exitstatus = null; - Exception ex = null; - long readCount = 0; - long writeCount = 0; - long commitCount = 0; - long rollbackCount = 0; - long readSkipCount = 0; - long processSkipCount = 0; - long filterCount = 0; - long writeSkipCount = 0; - Timestamp startTS = null; - Timestamp endTS = null; + StepExecutionImpl stepEx = null; - ObjectInputStream objectIn = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(STEP_EXECUTIONS_BY_STEP_ID)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(STEP_EXECUTIONS_BY_STEP_ID))) { statement.setLong(1, stepExecId); - rs = statement.executeQuery(); - while (rs.next()) { - jobexecid = rs.getLong("jobexecid"); - stepexecid = rs.getLong("stepexecid"); - stepname = rs.getString("stepname"); - batchstatus = rs.getString("batchstatus"); - exitstatus = rs.getString("exitstatus"); - readCount = rs.getLong("readcount"); - writeCount = rs.getLong("writecount"); - commitCount = rs.getLong("commitcount"); - rollbackCount = rs.getLong("rollbackcount"); - readSkipCount = rs.getLong("readskipcount"); - processSkipCount = rs.getLong("processskipcount"); - filterCount = rs.getLong("filtercount"); - writeSkipCount = rs.getLong("writeSkipCount"); - startTS = rs.getTimestamp("startTime"); - endTS = rs.getTimestamp("endTime"); - // get the object based data - Serializable persistentData = null; - byte[] pDataBytes = rs.getBytes("persistentData"); - if (pDataBytes != null) { - objectIn = new TCCLObjectInputStream( - new ByteArrayInputStream(pDataBytes)); - persistentData = (Serializable) objectIn.readObject(); - } + try (ResultSet rs = statement.executeQuery()) { + + while (rs.next()) { + long jobexecid = rs.getLong("jobexecid"); + long stepexecid = rs.getLong("stepexecid"); + String stepname = rs.getString("stepname"); + String batchstatus = rs.getString("batchstatus"); + String exitstatus = rs.getString("exitstatus"); + long readCount = rs.getLong("readcount"); + long writeCount = rs.getLong("writecount"); + long commitCount = rs.getLong("commitcount"); + long rollbackCount = rs.getLong("rollbackcount"); + long readSkipCount = rs.getLong("readskipcount"); + long processSkipCount = rs.getLong("processskipcount"); + long filterCount = rs.getLong("filtercount"); + long writeSkipCount = rs.getLong("writeSkipCount"); + Timestamp startTS = rs.getTimestamp("startTime"); + Timestamp endTS = rs.getTimestamp("endTime"); + // get the object based data + Serializable persistentData = null; + byte[] pDataBytes = rs.getBytes("persistentData"); + if (pDataBytes != null) { + try (ObjectInputStream objectIn = + new TCCLObjectInputStream(new ByteArrayInputStream(pDataBytes))) { + persistentData = (Serializable) objectIn.readObject(); + } + } + + stepEx = new StepExecutionImpl(jobexecid, stepexecid); + stepEx.setBatchStatus(BatchStatus.valueOf(batchstatus)); + stepEx.setExitStatus(exitstatus); + stepEx.setStepName(stepname); + stepEx.setReadCount(readCount); + stepEx.setWriteCount(writeCount); + stepEx.setCommitCount(commitCount); + stepEx.setRollbackCount(rollbackCount); + stepEx.setReadSkipCount(readSkipCount); + stepEx.setProcessSkipCount(processSkipCount); + stepEx.setFilterCount(filterCount); + stepEx.setWriteSkipCount(writeSkipCount); + stepEx.setStartTime(startTS); + stepEx.setEndTime(endTS); + stepEx.setPersistentUserData(persistentData); - stepEx = new StepExecutionImpl(jobexecid, stepexecid); - - stepEx.setBatchStatus(BatchStatus.valueOf(batchstatus)); - stepEx.setExitStatus(exitstatus); - stepEx.setStepName(stepname); - stepEx.setReadCount(readCount); - stepEx.setWriteCount(writeCount); - stepEx.setCommitCount(commitCount); - stepEx.setRollbackCount(rollbackCount); - stepEx.setReadSkipCount(readSkipCount); - stepEx.setProcessSkipCount(processSkipCount); - stepEx.setFilterCount(filterCount); - stepEx.setWriteSkipCount(writeSkipCount); - stepEx.setStartTime(startTS); - stepEx.setEndTime(endTS); - stepEx.setPersistentUserData(persistentData); - - logger.fine("stepExecution BatchStatus: " + batchstatus - + " StepName: " + stepname); + logger.fine("stepExecution BatchStatus: " + batchstatus + + " StepName: " + stepname); + } } - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { + } catch (SQLException | IOException | ClassNotFoundException e) { throw new PersistenceException(e); - } catch (ClassNotFoundException e) { - throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return stepEx; @@ -1354,99 +1191,42 @@ public StepExecution getStepExecutionByStepExecutionId(long stepExecId) { @Override public void updateBatchStatusOnly(long key, BatchStatus batchStatus, - Timestamp updatets) { - Connection conn = null; - PreparedStatement statement = null; - ByteArrayOutputStream baos = null; - ObjectOutputStream oout = null; - byte[] b; - - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(UPDATE_BATCH_STATUS_ONLY)); + Timestamp updates) { + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(UPDATE_BATCH_STATUS_ONLY))) { statement.setString(1, batchStatus.name()); - statement.setTimestamp(2, updatets); + statement.setTimestamp(2, updates); statement.setLong(3, key); statement.executeUpdate(); } catch (SQLException e) { - e.printStackTrace(); throw new PersistenceException(e); - } finally { - if (baos != null) { - try { - baos.close(); - } catch (IOException e) { - throw new PersistenceException(e); - } - } - if (oout != null) { - try { - oout.close(); - } catch (IOException e) { - throw new PersistenceException(e); - } - } - cleanupConnection(conn, null, statement); } } @Override public void updateWithFinalExecutionStatusesAndTimestamps(long key, - BatchStatus batchStatus, String exitStatus, Timestamp updatets) { - // TODO Auto-generated methddod stub - Connection conn = null; - PreparedStatement statement = null; - ByteArrayOutputStream baos = null; - ObjectOutputStream oout = null; - byte[] b; - - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(UPDATE_FINAL_STATUS_AND_TIMESTAMP)); - + BatchStatus batchStatus, String exitStatus, Timestamp updates) { + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(UPDATE_FINAL_STATUS_AND_TIMESTAMP))) { statement.setString(1, batchStatus.name()); statement.setString(2, exitStatus); - statement.setTimestamp(3, updatets); - statement.setTimestamp(4, updatets); + statement.setTimestamp(3, updates); + statement.setTimestamp(4, updates); statement.setLong(5, key); statement.executeUpdate(); } catch (SQLException e) { - e.printStackTrace(); throw new PersistenceException(e); - } finally { - if (baos != null) { - try { - baos.close(); - } catch (IOException e) { - throw new PersistenceException(e); - } - } - if (oout != null) { - try { - oout.close(); - } catch (IOException e) { - throw new PersistenceException(e); - } - } - cleanupConnection(conn, null, statement); } - } public void markJobStarted(long key, Timestamp startTS) { - Connection conn = null; - PreparedStatement statement = null; - ByteArrayOutputStream baos = null; - ObjectOutputStream oout = null; - - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(MARK_JOB_STARTED)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(MARK_JOB_STARTED))) { statement.setString(1, BatchStatus.STARTED.name()); statement.setTimestamp(2, startTS); statement.setTimestamp(3, startTS); @@ -1454,94 +1234,43 @@ public void markJobStarted(long key, Timestamp startTS) { statement.executeUpdate(); } catch (SQLException e) { - e.printStackTrace(); throw new PersistenceException(e); - } finally { - if (baos != null) { - try { - baos.close(); - } catch (IOException e) { - throw new PersistenceException(e); - } - } - if (oout != null) { - try { - oout.close(); - } catch (IOException e) { - throw new PersistenceException(e); - } - } - cleanupConnection(conn, null, statement); } } @Override public IJobExecution jobOperatorGetJobExecution(long jobExecutionId) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - IJobExecution jobEx = null; - ObjectInputStream objectIn = null; + IJobExecution jobEx; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(JOB_OPERATOR_GET_JOB_EXECUTION)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOB_OPERATOR_GET_JOB_EXECUTION))) { statement.setLong(1, jobExecutionId); - rs = statement.executeQuery(); - - jobEx = (rs.next()) ? readJobExecutionRecord(rs) : null; - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { - throw new PersistenceException(e); - } catch (ClassNotFoundException e) { - throw new PersistenceException(e); - } finally { - if (objectIn != null) { - try { - objectIn.close(); - } catch (IOException e) { - throw new PersistenceException(e); - } + try (ResultSet rs = statement.executeQuery()) { + jobEx = (rs.next()) ? readJobExecutionRecord(rs) : null; } - cleanupConnection(conn, rs, statement); + } catch (SQLException | IOException | ClassNotFoundException e) { + throw new PersistenceException(e); } + return jobEx; } @Override public List jobOperatorGetJobExecutions(long jobInstanceId) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - List data = new ArrayList(); - ObjectInputStream objectIn = null; + List data = new ArrayList<>(); - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(JOB_OPERATOR_GET_JOB_EXECUTIONS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOB_OPERATOR_GET_JOB_EXECUTIONS))) { statement.setLong(1, jobInstanceId); - rs = statement.executeQuery(); - while (rs.next()) { - data.add(readJobExecutionRecord(rs)); - } - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { - throw new PersistenceException(e); - } catch (ClassNotFoundException e) { - throw new PersistenceException(e); - } finally { - if (objectIn != null) { - try { - objectIn.close(); - } catch (IOException e) { - throw new PersistenceException(e); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + data.add(readJobExecutionRecord(rs)); } } - cleanupConnection(conn, rs, statement); + } catch (SQLException | IOException | ClassNotFoundException e) { + throw new PersistenceException(e); } return data; } @@ -1572,53 +1301,43 @@ protected IJobExecution readJobExecutionRecord(ResultSet rs) @Override public Set jobOperatorGetRunningExecutions(String jobName) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - Set executionIds = new HashSet(); + Set executionIds = new HashSet<>(); - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(JOB_OPERATOR_GET_RUNNING_EXECUTIONS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOB_OPERATOR_GET_RUNNING_EXECUTIONS))) { statement.setString(1, BatchStatus.STARTED.name()); statement.setString(2, BatchStatus.STARTING.name()); statement.setString(3, BatchStatus.STOPPING.name()); statement.setString(4, jobName); - rs = statement.executeQuery(); - while (rs.next()) { - executionIds.add(rs.getLong("jobexecid")); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + executionIds.add(rs.getLong("jobexecid")); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return executionIds; } @Override public String getJobCurrentTag(long jobInstanceId) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; String apptag = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(SELECT_JOBINSTANCEDATA_APPTAG)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(SELECT_JOBINSTANCEDATA_APPTAG))) { statement.setLong(1, jobInstanceId); - rs = statement.executeQuery(); - while (rs.next()) { - apptag = rs.getString(APPTAG); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + apptag = rs.getString(APPTAG); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return apptag; @@ -1632,27 +1351,21 @@ public void purge(String apptag) { String deleteJobExecutions = queryStrings.get(DELETE_JOB_EXECUTIONS); String deleteStepExecutions = queryStrings.get(DELETE_STEP_EXECUTIONS); - Connection conn = null; - PreparedStatement statement = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(deleteStepExecutions); - statement.setString(1, apptag); - statement.executeUpdate(); - - statement = conn.prepareStatement(deleteJobExecutions); - statement.setString(1, apptag); - statement.executeUpdate(); - - statement = conn.prepareStatement(deleteJobs); - statement.setString(1, apptag); - statement.executeUpdate(); - + try (Connection conn = getConnection()) { + try (PreparedStatement statement = conn.prepareStatement(deleteStepExecutions)) { + statement.setString(1, apptag); + statement.executeUpdate(); + } + try (PreparedStatement statement = conn.prepareStatement(deleteJobExecutions)) { + statement.setString(1, apptag); + statement.executeUpdate(); + } + try (PreparedStatement statement = conn.prepareStatement(deleteJobs)) { + statement.setString(1, apptag); + statement.executeUpdate(); + } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - - cleanupConnection(conn, null, statement); } logger.exiting(CLASSNAME, "purge"); @@ -1661,26 +1374,21 @@ public void purge(String apptag) { @Override public JobStatus getJobStatusFromExecution(long executionId) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; JobStatus retVal = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(GET_JOB_STATUS_FROM_EXECUTIONS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(GET_JOB_STATUS_FROM_EXECUTIONS))) { statement.setLong(1, executionId); - rs = statement.executeQuery(); - byte[] buf = null; - if (rs.next()) { - buf = rs.getBytes("obj"); + try (ResultSet rs = statement.executeQuery()) { + byte[] buf = null; + if (rs.next()) { + buf = rs.getBytes("obj"); + } + retVal = (JobStatus) deserializeObject(buf); } - retVal = (JobStatus) deserializeObject(buf); } catch (Exception e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } logger.exiting(CLASSNAME, "executeQuery"); return retVal; @@ -1690,28 +1398,22 @@ public long getJobInstanceIdByExecutionId(long executionId) throws NoSuchJobExecutionException { long instanceId = 0; - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(JOB_INSTANCE_ID_BY_EXECUTION_ID)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(JOB_INSTANCE_ID_BY_EXECUTION_ID))) { statement.setObject(1, executionId); - rs = statement.executeQuery(); - if (rs.next()) { - instanceId = rs.getLong("jobinstanceid"); - } else { - String msg = "Did not find job instance associated with executionID =" - + executionId; - logger.fine(msg); - throw new NoSuchJobExecutionException(msg); + try (ResultSet rs = statement.executeQuery()) { + if (rs.next()) { + instanceId = rs.getLong("jobinstanceid"); + } else { + String msg = "Did not find job instance associated with executionID =" + + executionId; + logger.fine(msg); + throw new NoSuchJobExecutionException(msg); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return instanceId; @@ -1720,28 +1422,24 @@ public long getJobInstanceIdByExecutionId(long executionId) /** * This method is used to serialized an object saved into a table BLOB * field. - * + * * @param theObject * the object to be serialized * @return a object byte array * @throws IOException */ protected byte[] serializeObject(Serializable theObject) throws IOException { - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oout = new ObjectOutputStream(baos); - oout.writeObject(theObject); - byte[] data = baos.toByteArray(); - baos.close(); - oout.close(); - - return data; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(baos)) { + oout.writeObject(theObject); + return baos.toByteArray(); + } } /** * This method is used to de-serialized a table BLOB field to its original * object form. - * + * * @param buffer * the byte array save a BLOB * @return the object saved as byte array @@ -1750,59 +1448,49 @@ protected byte[] serializeObject(Serializable theObject) throws IOException { */ protected Serializable deserializeObject(byte[] buffer) throws IOException, ClassNotFoundException { - Serializable theObject = null; - ObjectInputStream objectIn = null; - if (buffer != null) { - objectIn = new ObjectInputStream(new ByteArrayInputStream(buffer)); - theObject = (Serializable) objectIn.readObject(); - objectIn.close(); + try (ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(buffer))) { + theObject = (Serializable) objectIn.readObject(); + } } return theObject; } /* * (non-Javadoc) - * + * * @see com.ibm.jbatch.container.services.IPersistenceManagerService# * createJobInstance(java.lang.String, java.lang.String, java.lang.String, * java.util.Properties) */ @Override public JobInstance createSubJobInstance(String name, String apptag) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; JobInstanceImpl jobInstance = null; - try { - conn = getConnection(); - - statement = conn.prepareStatement( - queryStrings.get(CREATE_SUB_JOB_INSTANCE), - new String[] { "JOBINSTANCEID" }); - + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement( + queryStrings.get(CREATE_SUB_JOB_INSTANCE), + new String[] { "JOBINSTANCEID" })) { statement.setString(1, name); statement.setString(2, apptag); statement.executeUpdate(); - rs = statement.getGeneratedKeys(); - if (rs.next()) { - long jobInstanceID = rs.getLong(1); - jobInstance = new JobInstanceImpl(jobInstanceID); - jobInstance.setJobName(name); + try (ResultSet rs = statement.getGeneratedKeys()) { + if (rs.next()) { + long jobInstanceID = rs.getLong(1); + jobInstance = new JobInstanceImpl(jobInstanceID); + jobInstance.setJobName(name); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return jobInstance; } /* * (non-Javadoc) - * + * * @see com.ibm.jbatch.container.services.IPersistenceManagerService# * createJobInstance(java.lang.String, java.lang.String, java.lang.String, * java.util.Properties) @@ -1810,40 +1498,32 @@ public JobInstance createSubJobInstance(String name, String apptag) { @Override public JobInstance createJobInstance(String name, String apptag, String jobXml) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; JobInstanceImpl jobInstance = null; - try { - conn = getConnection(); - - statement = conn.prepareStatement( - queryStrings.get(CREATE_JOB_INSTANCE), - new String[] { "JOBINSTANCEID" }); - + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement( + queryStrings.get(CREATE_JOB_INSTANCE), + new String[] { "JOBINSTANCEID" })) { statement.setString(1, name); statement.setString(2, apptag); statement.executeUpdate(); - - rs = statement.getGeneratedKeys(); - - if (rs.next()) { - long jobInstanceID = rs.getLong(1); - jobInstance = new JobInstanceImpl(jobInstanceID, jobXml); - jobInstance.setJobName(name); + try (ResultSet rs = statement.getGeneratedKeys()) { + if (rs.next()) { + long jobInstanceID = rs.getLong(1); + jobInstance = new JobInstanceImpl(jobInstanceID, jobXml); + jobInstance.setJobName(name); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } + return jobInstance; } /* * (non-Javadoc) - * + * * @see com.ibm.jbatch.container.services.IPersistenceManagerService# * createJobExecution(com.ibm.jbatch.container.jsl.JobNavigator, * javax.batch.runtime.JobInstance, java.util.Properties, @@ -1860,47 +1540,40 @@ public RuntimeJobExecution createJobExecution(JobInstance jobInstance, jobExecution.setBatchStatus(batchStatus.name()); jobExecution.setCreateTime(now); jobExecution.setLastUpdateTime(now); - - if (requestTracing != null && requestTracing.isRequestTracingEnabled() + + if (requestTracing != null && requestTracing.isRequestTracingEnabled() && requestTracing.isTraceInProgress()) { RequestTraceSpanLog spanLog = constructJBatchExecutionSpanLog(jobExecution); requestTracing.addSpanLog(spanLog); } - + return jobExecution; } protected long createRuntimeJobExecutionEntry(JobInstance jobInstance, Properties jobParameters, BatchStatus batchStatus, Timestamp timestamp) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; long newJobExecutionId = 0L; - try { - conn = getConnection(); - - statement = conn.prepareStatement( - queryStrings.get(CREATE_JOB_EXECUTION_ENTRY), - new String[] { "JOBEXECID" }); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement( + queryStrings.get(CREATE_JOB_EXECUTION_ENTRY), + new String[] { "JOBEXECID" })) { statement.setLong(1, jobInstance.getInstanceId()); statement.setTimestamp(2, timestamp); statement.setTimestamp(3, timestamp); statement.setString(4, batchStatus.name()); statement.setObject(5, serializeObject(jobParameters)); statement.executeUpdate(); - rs = statement.getGeneratedKeys(); - if (rs.next()) { - newJobExecutionId = rs.getLong(1); + try (ResultSet rs = statement.getGeneratedKeys()) { + if (rs.next()) { + newJobExecutionId = rs.getLong(1); + } } - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { + } catch (SQLException | IOException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } + return newJobExecutionId; } @@ -1920,7 +1593,7 @@ public RuntimeFlowInSplitExecution createFlowInSplitExecution( /* * (non-Javadoc) - * + * * @see com.ibm.jbatch.container.services.IPersistenceManagerService# * createStepExecution(long, * com.ibm.jbatch.container.context.impl.StepContextImpl) @@ -2001,18 +1674,12 @@ protected StepExecutionImpl createStepExecution(long rootJobExecId, endTime == null ? "" : endTime, persistentData == null ? "" : persistentData }); - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; StepExecutionImpl stepExecution = null; String query = queryStrings.get(CREATE_STEP_EXECUTION); - try { - conn = getConnection(); - - statement = conn.prepareStatement(query, - new String[] { "STEPEXECID" }); - + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(query, + new String[] { "STEPEXECID" })) { statement.setLong(1, rootJobExecId); statement.setString(2, batchStatus); statement.setString(3, exitStatus); @@ -2030,19 +1697,17 @@ protected StepExecutionImpl createStepExecution(long rootJobExecId, statement.setObject(15, serializeObject(persistentData)); statement.executeUpdate(); - rs = statement.getGeneratedKeys(); - if (rs.next()) { - long stepExecutionId = rs.getLong(1); - stepExecution = new StepExecutionImpl(rootJobExecId, - stepExecutionId); - stepExecution.setStepName(stepName); + + try (ResultSet rs = statement.getGeneratedKeys()) { + if (rs.next()) { + long stepExecutionId = rs.getLong(1); + stepExecution = new StepExecutionImpl(rootJobExecId, + stepExecutionId); + stepExecution.setStepName(stepName); + } } - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { + } catch (SQLException | IOException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, null, statement); } logger.exiting(CLASSNAME, "createStepExecution"); @@ -2051,7 +1716,7 @@ protected StepExecutionImpl createStepExecution(long rootJobExecId, /* * (non-Javadoc) - * + * * @see com.ibm.jbatch.container.services.IPersistenceManagerService# * updateStepExecution * (com.ibm.jbatch.container.context.impl.StepContextImpl) @@ -2105,14 +1770,14 @@ public void updateStepExecution(StepContextImpl stepContext) { /** * Obviously would be nice if the code writing this special format were in * the same place as this code reading it. - * + * * Assumes format like: - * + * * JOBINSTANCEDATA (jobinstanceid name, ...) - * + * * 1197,"partitionMetrics","NOTSET" 1198,":1197:step1:0","NOTSET" * 1199,":1197:step1:1","NOTSET" 1200,":1197:step2:0","NOTSET" - * + * * @param rootJobExecutionId * JobExecution id of the top-level job * @param stepName @@ -2136,10 +1801,6 @@ protected String getPartitionLevelJobInstanceWildCard( public void updateWithFinalPartitionAggregateStepExecution( long rootJobExecutionId, StepContextImpl stepContext) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - long readCount = 0; long writeCount = 0; long commitCount = 0; @@ -2149,30 +1810,27 @@ public void updateWithFinalPartitionAggregateStepExecution( long filterCount = 0; long writeSkipCount = 0; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(UPDATE_WITH_FINAL_PARTITION_STEP_EXECUTION)); - + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(UPDATE_WITH_FINAL_PARTITION_STEP_EXECUTION))) { statement.setString( 1, getPartitionLevelJobInstanceWildCard(rootJobExecutionId, stepContext.getStepName())); - rs = statement.executeQuery(); - if (rs.next()) { - readCount = rs.getLong("readcount"); - writeCount = rs.getLong("writecount"); - commitCount = rs.getLong("commitcount"); - rollbackCount = rs.getLong("rollbackcount"); - readSkipCount = rs.getLong("readskipcount"); - processSkipCount = rs.getLong("processskipcount"); - filterCount = rs.getLong("filtercount"); - writeSkipCount = rs.getLong("writeSkipCount"); + try (ResultSet rs = statement.executeQuery()) { + if (rs.next()) { + readCount = rs.getLong("readcount"); + writeCount = rs.getLong("writecount"); + commitCount = rs.getLong("commitcount"); + rollbackCount = rs.getLong("rollbackcount"); + readSkipCount = rs.getLong("readskipcount"); + processSkipCount = rs.getLong("processskipcount"); + filterCount = rs.getLong("filtercount"); + writeSkipCount = rs.getLong("writeSkipCount"); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } updateStepExecutionWithMetrics(stepContext, readCount, writeCount, @@ -2215,13 +1873,10 @@ protected void updateStepExecutionWithMetrics(StepContextImpl stepContext, persistentData == null ? "" : persistentData }); } - Connection conn = null; - PreparedStatement statement = null; String query = queryStrings.get(UPDATE_STEP_EXECUTION_WITH_METRICS); - try { - conn = getConnection(); - statement = conn.prepareStatement(query); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(query)) { statement.setString(1, batchStatus); statement.setString(2, exitStatus); statement.setString(3, stepName); @@ -2238,18 +1893,14 @@ protected void updateStepExecutionWithMetrics(StepContextImpl stepContext, statement.setObject(14, serializeObject(persistentData)); statement.setLong(15, stepExecutionId); statement.executeUpdate(); - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { + } catch (SQLException | IOException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, null, statement); } } /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.IPersistenceManagerService#createJobStatus * (long) @@ -2257,23 +1908,16 @@ protected void updateStepExecutionWithMetrics(StepContextImpl stepContext, @Override public JobStatus createJobStatus(long jobInstanceId) { logger.entering(CLASSNAME, "createJobStatus", jobInstanceId); - Connection conn = null; - PreparedStatement statement = null; JobStatus jobStatus = new JobStatus(jobInstanceId); - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(CREATE_JOBSTATUS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(CREATE_JOBSTATUS))) { statement.setLong(1, jobInstanceId); statement.setBytes(2, serializeObject(jobStatus)); statement.executeUpdate(); - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { + } catch (SQLException | IOException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, null, statement); } logger.exiting(CLASSNAME, "createJobStatus"); return jobStatus; @@ -2281,7 +1925,7 @@ public JobStatus createJobStatus(long jobInstanceId) { /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.IPersistenceManagerService#getJobStatus * (long) @@ -2289,29 +1933,19 @@ public JobStatus createJobStatus(long jobInstanceId) { @Override public JobStatus getJobStatus(long instanceId) { logger.entering(CLASSNAME, "getJobStatus", instanceId); - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - RuntimeJobExecution jobExecution = null; String query = queryStrings.get(GET_JOB_STATUS); JobStatus jobStatus = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(query); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(query)) { statement.setLong(1, instanceId); - rs = statement.executeQuery(); - if (rs.next()) { - jobStatus = (JobStatus) deserializeObject(rs.getBytes(1)); + try (ResultSet rs = statement.executeQuery()) { + if (rs.next()) { + jobStatus = (JobStatus) deserializeObject(rs.getBytes(1)); + } } - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { - throw new PersistenceException(e); - } catch (ClassNotFoundException e) { + } catch (SQLException | IOException | ClassNotFoundException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } logger.exiting(CLASSNAME, "getJobStatus", jobStatus); return jobStatus; @@ -2319,7 +1953,7 @@ public JobStatus getJobStatus(long instanceId) { /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.IPersistenceManagerService#updateJobStatus * (long, com.ibm.jbatch.container.status.JobStatus) @@ -2331,28 +1965,21 @@ public void updateJobStatus(long instanceId, JobStatus jobStatus) { if (logger.isLoggable(Level.FINE)) { logger.fine("Updating Job Status to: " + jobStatus.getBatchStatus()); } - Connection conn = null; - PreparedStatement statement = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(UPDATE_JOBSTATUS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(UPDATE_JOBSTATUS))) { statement.setBytes(1, serializeObject(jobStatus)); statement.setLong(2, instanceId); statement.executeUpdate(); - } catch (SQLException e) { + } catch (SQLException | IOException e) { throw new PersistenceException(e); - } catch (IOException e) { - throw new PersistenceException(e); - } finally { - cleanupConnection(conn, null, statement); } logger.exiting(CLASSNAME, "updateJobStatus"); } /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.IPersistenceManagerService#createStepStatus * (long) @@ -2360,22 +1987,15 @@ public void updateJobStatus(long instanceId, JobStatus jobStatus) { @Override public StepStatus createStepStatus(long stepExecId) { logger.entering(CLASSNAME, "createStepStatus", stepExecId); - Connection conn = null; - PreparedStatement statement = null; StepStatus stepStatus = new StepStatus(stepExecId); - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(CREATE_STEP_STATUS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(CREATE_STEP_STATUS))) { statement.setLong(1, stepExecId); statement.setBytes(2, serializeObject(stepStatus)); statement.executeUpdate(); - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { + } catch (SQLException | IOException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, null, statement); } logger.exiting(CLASSNAME, "createStepStatus"); return stepStatus; @@ -2383,7 +2003,7 @@ public StepStatus createStepStatus(long stepExecId) { /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.IPersistenceManagerService#getStepStatus * (long, java.lang.String) @@ -2392,30 +2012,20 @@ public StepStatus createStepStatus(long stepExecId) { public StepStatus getStepStatus(long instanceId, String stepName) { logger.entering(CLASSNAME, "getStepStatus", new Object[] { instanceId, stepName }); - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; - RuntimeJobExecution jobExecution = null; String query = queryStrings.get(GET_STEP_STATUS); StepStatus stepStatus = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(query); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(query)) { statement.setLong(1, instanceId); statement.setString(2, stepName); - rs = statement.executeQuery(); - if (rs.next()) { - stepStatus = (StepStatus) deserializeObject(rs.getBytes(1)); + try (ResultSet rs = statement.executeQuery()) { + if (rs.next()) { + stepStatus = (StepStatus) deserializeObject(rs.getBytes(1)); + } } - } catch (SQLException e) { + } catch (SQLException | IOException | ClassNotFoundException e) { throw new PersistenceException(e); - } catch (IOException e) { - throw new PersistenceException(e); - } catch (ClassNotFoundException e) { - throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } logger.exiting(CLASSNAME, "getStepStatus", stepStatus == null ? "" : stepStatus); @@ -2424,7 +2034,7 @@ public StepStatus getStepStatus(long instanceId, String stepName) { /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.IPersistenceManagerService#updateStepStatus * (long, com.ibm.jbatch.container.status.StepStatus) @@ -2438,28 +2048,21 @@ public void updateStepStatus(long stepExecutionId, StepStatus stepStatus) { logger.fine("Updating StepStatus to: " + stepStatus.getBatchStatus()); } - Connection conn = null; - PreparedStatement statement = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(UPDATE_STEP_STATUS)); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(UPDATE_STEP_STATUS))) { statement.setBytes(1, serializeObject(stepStatus)); statement.setLong(2, stepExecutionId); statement.executeUpdate(); - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { + } catch (SQLException | IOException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, null, statement); } logger.exiting(CLASSNAME, "updateStepStatus"); } /* * (non-Javadoc) - * + * * @see * com.ibm.jbatch.container.services.IPersistenceManagerService#getTagName * (long) @@ -2468,22 +2071,17 @@ public void updateStepStatus(long stepExecutionId, StepStatus stepStatus) { public String getTagName(long jobExecutionId) { logger.entering(CLASSNAME, "getTagName", jobExecutionId); String apptag = null; - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; String query = queryStrings.get(GET_TAGNAME); - try { - conn = getConnection(); - statement = conn.prepareStatement(query); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(query)) { statement.setLong(1, jobExecutionId); - rs = statement.executeQuery(); - if (rs.next()) { - apptag = rs.getString(1); + try (ResultSet rs = statement.executeQuery()) { + if (rs.next()) { + apptag = rs.getString(1); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } logger.exiting(CLASSNAME, "getTagName"); return apptag; @@ -2493,23 +2091,18 @@ public String getTagName(long jobExecutionId) { public long getMostRecentExecutionId(long jobInstanceId) { logger.entering(CLASSNAME, "getMostRecentExecutionId", jobInstanceId); long mostRecentId = -1; - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; String query = queryStrings.get(GET_MOST_RECENT_EXECUTION_ID); - try { - conn = getConnection(); - statement = conn.prepareStatement(query); + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(query)) { statement.setLong(1, jobInstanceId); - rs = statement.executeQuery(); - if (rs.next()) { - mostRecentId = rs.getLong(1); + try (ResultSet rs = statement.executeQuery()) { + if (rs.next()) { + mostRecentId = rs.getLong(1); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } logger.exiting(CLASSNAME, "getMostRecentExecutionId"); return mostRecentId; @@ -2534,52 +2127,52 @@ protected Map getSharedTableMap() { result.put(JOB_STATUS_TABLE_KEY, prefix + "JOBSTATUS" + suffix); result.put(STEP_STATUS_TABLE_KEY, prefix + "STEPSTATUS" + suffix); result.put(CHECKPOINT_TABLE_KEY, prefix + "CHECKPOINTDATA" + suffix); - + return result; } /** * Method invoked to insert the query strings used by all database types * into a hashmap - * @throws SQLException + * @throws SQLException **/ protected Map getSharedQueryMap(IBatchConfig batchConfig) throws SQLException { queryStrings = new HashMap<>(); - + queryStrings.put( - Q_SET_SCHEMA, + Q_SET_SCHEMA, "SET SCHEMA ?"); - + queryStrings.put( - SELECT_CHECKPOINTDATA, - "select id, obj from " + - tableNames.get(CHECKPOINT_TABLE_KEY) + + SELECT_CHECKPOINTDATA, + "select id, obj from " + + tableNames.get(CHECKPOINT_TABLE_KEY) + " where id = ?"); - + queryStrings.put( INSERT_CHECKPOINTDATA, - "insert into " + - tableNames.get(CHECKPOINT_TABLE_KEY) + + "insert into " + + tableNames.get(CHECKPOINT_TABLE_KEY) + " values(?, ?)"); - + queryStrings.put( UPDATE_CHECKPOINTDATA, - "update " + - tableNames.get(CHECKPOINT_TABLE_KEY) + + "update " + + tableNames.get(CHECKPOINT_TABLE_KEY) + " set obj = ? where id = ?"); - + queryStrings.put( LOCK_CHECKPOINTDATA, - "lock table " + - tableNames.get(CHECKPOINT_TABLE_KEY) + + "lock table " + + tableNames.get(CHECKPOINT_TABLE_KEY) + " in exclusive mode"); - + queryStrings.put(JOBOPERATOR_GET_JOB_INSTANCE_COUNT, "select count(jobinstanceid) as jobinstancecount from " + tableNames.get(JOB_INSTANCE_TABLE_KEY) + " where name = ? and apptag = ?"); - + queryStrings.put(SELECT_JOBINSTANCEDATA_COUNT, "select count(jobinstanceid) as jobinstancecount from " + tableNames.get(JOB_INSTANCE_TABLE_KEY) @@ -2872,10 +2465,10 @@ private Map setCreateDerbyStringsMap(Map tableNa return createDerbyStrings; } - + private RequestTraceSpanLog constructJBatchExecutionSpanLog(RuntimeJobExecution jobExecution) { RequestTraceSpanLog spanLog = new RequestTraceSpanLog("jBatchExecutionContextEvent"); - + try { spanLog.addLogEntry("Execution ID", Long.toString(jobExecution.getExecutionId())); spanLog.addLogEntry("Job ID", Long.toString(jobExecution.getInstanceId())); @@ -2886,11 +2479,11 @@ private RequestTraceSpanLog constructJBatchExecutionSpanLog(RuntimeJobExecution spanLog.addLogEntry("Job Parameters", jobExecution.getJobParameters().toString()); } else { spanLog.addLogEntry("Job Parameters", "null"); - } + } } catch (NullPointerException e) { logger.log(Level.INFO, "NullPointerException when creating request tracing JBatchExecutionContextEvent"); - } - + } + return spanLog; } } \ No newline at end of file diff --git a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/MySqlPersistenceManager.java b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/MySqlPersistenceManager.java index ea1b46af389..b1741db12e6 100644 --- a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/MySqlPersistenceManager.java +++ b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/MySqlPersistenceManager.java @@ -43,21 +43,16 @@ import com.ibm.jbatch.container.exception.BatchContainerServiceException; import com.ibm.jbatch.spi.services.IBatchConfig; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; +import java.sql.*; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; import static org.glassfish.batch.spi.impl.BatchRuntimeHelper.PAYARA_TABLE_PREFIX_PROPERTY; import static org.glassfish.batch.spi.impl.BatchRuntimeHelper.PAYARA_TABLE_SUFFIX_PROPERTY; @@ -74,10 +69,10 @@ public class MySqlPersistenceManager extends JBatchJDBCPersistenceManager implem private final static Logger logger = Logger.getLogger(CLASSNAME); private IBatchConfig batchConfig = null; - + // mysql create table strings protected Map createMySQLStrings; - + @Override public void init(IBatchConfig batchConfig) throws BatchContainerServiceException { @@ -89,7 +84,7 @@ public void init(IBatchConfig batchConfig) jndiName = batchConfig.getDatabaseConfigurationBean().getJndiName(); prefix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_PREFIX_PROPERTY, ""); suffix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_SUFFIX_PROPERTY, ""); - + if (jndiName == null || jndiName.equals("")) { throw new BatchContainerServiceException( "JNDI name is not defined."); @@ -146,24 +141,17 @@ protected boolean isSchemaValid() throws SQLException { logger.entering(CLASSNAME, "isMySQLSchemaValid"); boolean result = false; - Connection conn = null; - DatabaseMetaData dbmd = null; - ResultSet rs = null; - PreparedStatement ps = null; - try { - conn = getConnectionToDefaultSchema(); - ps = conn.prepareStatement("SHOW DATABASES like ?"); - ps.setString(1, schema); - rs = ps.executeQuery(); - - if (rs.next()) { - result = true; + try (Connection conn = getConnectionToDefaultSchema(); + PreparedStatement ps = conn.prepareStatement("SHOW DATABASES like ?")) { + ps.setString(1, schema); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + result = true; + } } } catch (SQLException e) { logger.severe(e.getLocalizedMessage()); throw e; - } finally { - cleanupConnection(conn, rs, ps); } logger.exiting(CLASSNAME, "isMySQLSchemaValid", false); @@ -173,13 +161,11 @@ protected boolean isSchemaValid() throws SQLException { /** * Verify the relevant JBatch tables exist. - * - * @param tableNames * @throws SQLException */ @Override protected void checkTables() throws SQLException { - + logger.entering(CLASSNAME, "checkMySQLTables"); setCreateMySQLStringsMap(tableNames); @@ -189,15 +175,15 @@ protected void checkTables() throws SQLException { createTableIfNotExists(tableNames.get(JOB_INSTANCE_TABLE_KEY), createMySQLStrings.get(MYSQL_CREATE_TABLE_JOBINSTANCEDATA)); - + createTableIfNotExists( tableNames.get(EXECUTION_INSTANCE_TABLE_KEY), createMySQLStrings.get(MYSQL_CREATE_TABLE_EXECUTIONINSTANCEDATA)); - + createTableIfNotExists( tableNames.get(STEP_EXECUTION_INSTANCE_TABLE_KEY), createMySQLStrings.get(MYSQL_CREATE_TABLE_STEPINSTANCEDATA)); - + createTableIfNotExists(tableNames.get(JOB_STATUS_TABLE_KEY), createMySQLStrings.get(MYSQL_CREATE_TABLE_JOBSTATUS)); createTableIfNotExists(tableNames.get(STEP_STATUS_TABLE_KEY), @@ -205,11 +191,9 @@ protected void checkTables() throws SQLException { logger.exiting(CLASSNAME, "checkMySQLTables"); } - + @Override public boolean checkIfTableExists(DataSource dSource, String tableName, String schemaName) { - Statement statement = null; - ResultSet resultSet = null; dataSource = dSource; boolean result = true; @@ -220,32 +204,31 @@ public boolean checkIfTableExists(DataSource dSource, String tableName, String s if (!isSchemaValid()) { setDefaultSchema(); } - - statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - String query = "select lower(table_schema),lower(table_name) FROM information_schema.tables where lower(table_schema)= " - + "\'" - + schema - + "\'" - + " and lower(table_name)= " - + "\'" - + tableName.toLowerCase() + "\'"; - resultSet = statement.executeQuery(query); - - int rowcount = getTableRowCount(resultSet); - - if (rowcount == 0) { - if (!resultSet.next()) { - result = false; - } - } + try (Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY)) { + String query = "select lower(table_schema),lower(table_name) FROM information_schema.tables where lower(table_schema)= " + + "\'" + + schema + + "\'" + + " and lower(table_name)= " + + "\'" + + tableName.toLowerCase() + "\'"; + try (ResultSet resultSet = statement.executeQuery(query)) { + int rowcount = getTableRowCount(resultSet); + if (rowcount == 0) { + if (!resultSet.next()) { + result = false; + } + } + } + } } catch (SQLException ex) { logger.severe(ex.getLocalizedMessage()); } return result; } - + @Override protected Map getSharedQueryMap(IBatchConfig batchConfig) throws SQLException { Map result = super.getSharedQueryMap(batchConfig); @@ -253,38 +236,38 @@ protected Map getSharedQueryMap(IBatchConfig batchConfig) throws { schema = setDefaultSchema(); } - + result.put(Q_SET_SCHEMA, "USE " + schema); - + return result; } @Override - protected void setSchemaOnConnection(Connection connection) throws SQLException { + protected void setSchemaOnConnection(Connection connection) throws SQLException { logger.log(Level.FINEST, "Entering {0}.setSchemaOnConnection()", CLASSNAME); try (PreparedStatement preparedStatement = connection.prepareStatement("USE " + schema)) { preparedStatement.executeUpdate(); } finally { logger.log(Level.FINEST, "Exiting {0}.setSchemaOnConnection()", CLASSNAME); - } + } } - + /** * Method invoked to insert the MySql create table strings into a hashmap **/ private Map setCreateMySQLStringsMap (Map tableNames) { createMySQLStrings = new HashMap<>(); - + createMySQLStrings.put(MYSQL_CREATE_TABLE_CHECKPOINTDATA, "CREATE TABLE " + tableNames.get(CHECKPOINT_TABLE_KEY) + " (id VARCHAR(512),obj BLOB)"); - + createMySQLStrings.put(MYSQL_CREATE_TABLE_JOBINSTANCEDATA,"CREATE TABLE " + tableNames.get(JOB_INSTANCE_TABLE_KEY) + " (jobinstanceid BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,name VARCHAR(512), apptag VARCHAR(512))"); - - + + createMySQLStrings.put(MYSQL_CREATE_TABLE_EXECUTIONINSTANCEDATA,"CREATE TABLE " + tableNames.get(EXECUTION_INSTANCE_TABLE_KEY) + "(" @@ -323,8 +306,8 @@ private Map setCreateMySQLStringsMap (Map tableN + "CONSTRAINT JOBEXEC_STEPEXEC_FK FOREIGN KEY (jobexecid) REFERENCES " + tableNames.get(EXECUTION_INSTANCE_TABLE_KEY) + "(jobexecid))"); - - + + createMySQLStrings.put(MYSQL_CREATE_TABLE_JOBSTATUS,"CREATE TABLE " @@ -347,6 +330,6 @@ private Map setCreateMySQLStringsMap (Map tableN return createMySQLStrings; } - + } \ No newline at end of file diff --git a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/OraclePersistenceManager.java b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/OraclePersistenceManager.java index 6ff7cfdf928..c6d7b2c271d 100644 --- a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/OraclePersistenceManager.java +++ b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/OraclePersistenceManager.java @@ -69,7 +69,7 @@ import static org.glassfish.batch.spi.impl.BatchRuntimeHelper.PAYARA_TABLE_SUFFIX_PROPERTY; /** - * + * * Oracle Persistence Manager */ @@ -81,11 +81,11 @@ public class OraclePersistenceManager extends JBatchJDBCPersistenceManager imple private final static Logger logger = Logger.getLogger(CLASSNAME); private IBatchConfig batchConfig = null; - + // oracle create table strings protected Map createOracleTableStrings; protected Map createOracleIndexStrings; - + protected Map oracleObjectNames; @Override @@ -132,8 +132,8 @@ public void init(IBatchConfig batchConfig) jndiName = batchConfig.getDatabaseConfigurationBean().getJndiName(); prefix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_PREFIX_PROPERTY, ""); suffix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_SUFFIX_PROPERTY, ""); - - + + if (jndiName == null || jndiName.equals("")) { throw new BatchContainerServiceException( "JNDI name is not defined."); @@ -162,7 +162,7 @@ public void init(IBatchConfig batchConfig) // TODO Auto-generated catch block throw new BatchContainerServiceException(e1); } - + logger.config("JNDI name = " + jndiName); @@ -191,28 +191,23 @@ protected boolean isSchemaValid() throws SQLException { logger.entering(CLASSNAME, "isOracleSchemaValid"); boolean result = false; - Connection conn = null; - DatabaseMetaData dbmd = null; - ResultSet rs = null; - - try { - conn = getConnectionToDefaultSchema(); - dbmd = conn.getMetaData(); - rs = dbmd.getSchemas(); - while (rs.next()) { + try (Connection conn = getConnectionToDefaultSchema()) { + DatabaseMetaData dbmd = conn.getMetaData(); + try (ResultSet rs = dbmd.getSchemas()) { + while (rs.next()) { - String schemaname = rs.getString("TABLE_SCHEM"); - if (schema.equalsIgnoreCase(schemaname)) { - logger.exiting(CLASSNAME, "isSchemaValid", true); - return true; + String schemaname = rs.getString("TABLE_SCHEM"); + if (schema.equalsIgnoreCase(schemaname)) { + logger.exiting(CLASSNAME, "isSchemaValid", true); + return true; + } } } + } catch (SQLException e) { logger.severe(e.getLocalizedMessage()); throw e; - } finally { - cleanupConnection(conn, rs, null); } logger.exiting(CLASSNAME, "isOracleSchemaValid", false); @@ -233,7 +228,7 @@ private void checkOracleTables() throws SQLException { createOracleTableStrings.get(CREATE_TABLE_CHECKPOINTDATA)); // do same check for indexes, triggers and sequences - // for triggers and indexes, also check for old names that did not include a prefix/suffix for backward compatibility + // for triggers and indexes, also check for old names that did not include a prefix/suffix for backward compatibility if (!checkOracleIndexExists(oracleObjectNames.get(CREATE_CHECKPOINTDATA_INDEX_KEY), CREATE_CHECKPOINTDATA_INDEX_KEY, tableNames.get(CHECKPOINT_TABLE_KEY))) { @@ -249,7 +244,7 @@ private void checkOracleTables() throws SQLException { createOracleTableStrings.get(CREATE_JOBINSTANCEDATA_TRG), DEFAULT_JOBINSTANCEDATA_TRG_KEY, tableNames.get(JOB_INSTANCE_TABLE_KEY)); - + createOracleTableNotExists( tableNames.get(EXECUTION_INSTANCE_TABLE_KEY), @@ -260,7 +255,7 @@ private void checkOracleTables() throws SQLException { createOracleTableStrings.get(CREATE_EXECUTIONINSTANCEDATA_TRG), DEFAULT_EXECUTIONINSTANCEDATA_TRG_KEY, tableNames.get(EXECUTION_INSTANCE_TABLE_KEY)); - + createOracleTableNotExists( tableNames.get(STEP_EXECUTION_INSTANCE_TABLE_KEY), @@ -279,7 +274,7 @@ private void checkOracleTables() throws SQLException { logger.exiting(CLASSNAME, "checkOracleTables"); } - + @Override public void createTables(DataSource dataSource, BatchRuntimeConfiguration batchRuntimeConfiguration){ this.dataSource = dataSource; @@ -288,7 +283,7 @@ public void createTables(DataSource dataSource, BatchRuntimeConfiguration batchR schema = batchRuntimeConfiguration.getSchemaName(); tableNames = getSharedTableMap(); oracleObjectNames = getOracleObjectsMap(); - + try { if (!isSchemaValid()) { setDefaultSchema(); @@ -310,14 +305,9 @@ protected void createOracleTableNotExists(String tableName, logger.entering(CLASSNAME, "createOracleTableNotExists", new Object[] { tableName, createTableStatement }); - Connection conn = null; - Statement stmt = null; - ResultSet rs = null; - PreparedStatement ps = null; - try { - conn = getConnection(); - stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); + try (Connection conn = getConnection(); + Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY)) { String query = "SELECT lower(owner),lower(table_name) FROM all_tables where lower(owner) = " + "\'" + schema.toLowerCase() @@ -325,24 +315,24 @@ protected void createOracleTableNotExists(String tableName, + " and lower(table_name)= " + "\'" + tableName.toLowerCase() + "\'"; - rs = stmt.executeQuery(query); - - int rowcount = getTableRowCount(rs); - // Create table if it does not exist - if (rowcount == 0) { - if (!rs.next()) { - logger.log(Level.INFO, tableName - + " table does not exists. Trying to create it."); - ps = conn.prepareStatement(createTableStatement); - ps.executeUpdate(); + try (ResultSet rs = stmt.executeQuery(query)) { + int rowcount = getTableRowCount(rs); + // Create table if it does not exist + if (rowcount == 0) { + if (!rs.next()) { + logger.log(Level.INFO, tableName + + " table does not exists. Trying to create it."); + try (PreparedStatement ps = conn.prepareStatement(createTableStatement)) { + ps.executeUpdate(); + } + } } } + } catch (SQLException e) { logger.severe(e.getLocalizedMessage()); throw e; - } finally { - cleanupConnection(conn, ps); } logger.exiting(CLASSNAME, "createOracleTableNotExists"); @@ -350,8 +340,6 @@ protected void createOracleTableNotExists(String tableName, @Override public boolean checkIfTableExists(DataSource dSource, String tableName, String schemaName) { - Statement statement = null; - ResultSet resultSet = null; dataSource = dSource; boolean result = false; @@ -363,16 +351,16 @@ public boolean checkIfTableExists(DataSource dSource, String tableName, String s setDefaultSchema(); } - statement = connection.createStatement(); String query = "select lower(sequence_name) from user_sequences where lower(sequence_name)=" + "\'" + tableName.toLowerCase() + "\'"; - resultSet = statement.executeQuery(query); - - while (resultSet.next()) { - result = true; - break; - } + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(query)) { + while (resultSet.next()) { + result = true; + break; + } + } } catch (SQLException ex) { logger.severe(ex.getLocalizedMessage()); } @@ -385,47 +373,33 @@ public boolean checkIfTableExists(DataSource dSource, String tableName, String s * @param trgstmt * @throws SQLException */ - public void createOracleTriggerNotExists(String triggername, String trgstmt, + public void createOracleTriggerNotExists(String triggername, String trgstmt, String defaultTriggername, String tablename) throws SQLException { logger.entering(CLASSNAME, "createOracleTableNotExists", new Object[] { triggername, trgstmt, defaultTriggername, tablename }); - Connection conn = null; boolean triggerexists = false; - ResultSet results = null; - Statement ps = null; - try { - conn = getConnection(); - Statement stmt = conn.createStatement(); - - String query = "select lower(trigger_name) from user_triggers " - + " where lower(table_owner)=\'" + schema.toLowerCase()+ "\'" - + " and lower(trigger_name) in (" - + "\'" + triggername.toLowerCase() + "\'," - + "\'" + defaultTriggername.toLowerCase() + "\')" - + " and lower(table_name)=\'" + tablename.toLowerCase() + "\'"; - results = stmt.executeQuery(query); - - while (results.next()) { - - triggerexists = true; - break; - + try (Connection conn = getConnection(); + Statement stmt = conn.createStatement()) { + + String query = "select lower(trigger_name) from user_triggers " + + " where lower(table_owner)=\'" + schema.toLowerCase()+ "\'" + + " and lower(trigger_name) in (" + + "\'" + triggername.toLowerCase() + "\'," + + "\'" + defaultTriggername.toLowerCase() + "\')" + + " and lower(table_name)=\'" + tablename.toLowerCase() + "\'"; + try (ResultSet results = stmt.executeQuery(query)) { + triggerexists = results.next(); } if (!triggerexists) { // create the trigger - - ps = conn.createStatement(); - ps.executeUpdate(trgstmt); - + try (Statement ps = conn.createStatement()) { + ps.executeUpdate(trgstmt); + } } } catch (SQLException e) { - - e.printStackTrace(); throw e; - } finally { - cleanupConnection(conn, results, null); } logger.exiting(CLASSNAME, "createOracleTriggerNotExists"); @@ -439,39 +413,26 @@ public void createOracleTriggerNotExists(String triggername, String trgstmt, public boolean checkOracleIndexExists(String indexname, String defaultIndexname, String tablename) throws SQLException { logger.entering(CLASSNAME, "createOracleIndexNotExists",new Object[] { indexname, defaultIndexname, tablename }); - Connection conn = null; boolean indexexists = false; - ResultSet results = null; - try { - conn = getConnection(); - Statement stmt = conn.createStatement(); - - String query = "select lower(index_name) from user_indexes" - + " where lower(table_owner)=\'" + schema.toLowerCase()+ "\'" - + " and lower(index_name) in (" - + "\'" + indexname.toLowerCase() + "\'," - + "\'" + defaultIndexname.toLowerCase() + "\')" - + " and lower(table_name)=\'" + tablename.toLowerCase() + "\'"; - - results = stmt.executeQuery(query); - - while (results.next()) { - - indexexists = true; - break; - + try (Connection conn = getConnection(); + Statement stmt = conn.createStatement()) { + String query = "select lower(index_name) from user_indexes" + + " where lower(table_owner)=\'" + schema.toLowerCase()+ "\'" + + " and lower(index_name) in (" + + "\'" + indexname.toLowerCase() + "\'," + + "\'" + defaultIndexname.toLowerCase() + "\')" + + " and lower(table_name)=\'" + tablename.toLowerCase() + "\'"; + + try (ResultSet results = stmt.executeQuery(query)) { + indexexists = results.next(); } } catch (SQLException e) { - - e.printStackTrace(); throw e; - } finally { - cleanupConnection(conn, results, null); } logger.exiting(CLASSNAME, "createOracleIndexNotExists"); return indexexists; } - + /** * Method invoked to insert the Oracle create table, trigger and sequence * strings into a hashmap @@ -492,11 +453,11 @@ private Map setOracleTableMap() { "CREATE SEQUENCE " + oracleObjectNames.get(JOBINSTANCEDATA_SEQ_KEY)); createOracleTableStrings .put(CREATE_JOBINSTANCEDATA_TRG, - "CREATE OR REPLACE TRIGGER " + oracleObjectNames.get(JOBINSTANCEDATA_TRG_KEY) + "CREATE OR REPLACE TRIGGER " + oracleObjectNames.get(JOBINSTANCEDATA_TRG_KEY) + " BEFORE INSERT ON " + tableNames.get(JOB_INSTANCE_TABLE_KEY) + " FOR EACH ROW BEGIN SELECT " - + oracleObjectNames.get(JOBINSTANCEDATA_SEQ_KEY) + + oracleObjectNames.get(JOBINSTANCEDATA_SEQ_KEY) + ".nextval INTO :new.jobinstanceid FROM dual; END;"); createOracleTableStrings @@ -577,20 +538,20 @@ private Map setOracleIndexMap() { + " on " + tableNames.get(CHECKPOINT_TABLE_KEY) + "(id)"); return createOracleIndexStrings; } - + protected Map getOracleObjectsMap() { Map result = new HashMap(7); - + result.put(JOBINSTANCEDATA_SEQ_KEY, prefix + JOBINSTANCEDATA_SEQ_KEY + suffix); result.put(EXECUTIONINSTANCEDATA_SEQ_KEY, prefix + EXECUTIONINSTANCEDATA_SEQ_KEY + suffix); result.put(STEPINSTANCEDATA_SEQ_KEY, prefix + STEPINSTANCEDATA_SEQ_KEY + suffix); - + result.put(JOBINSTANCEDATA_TRG_KEY, prefix + JOBINSTANCEDATA_TRG_KEY + suffix); result.put(EXECUTIONINSTANCEDATA_TRG_KEY, prefix + EXECUTIONINSTANCEDATA_TRG_KEY + suffix); result.put(STEPINSTANCEDATA_TRG_KEY, prefix + STEPINSTANCEDATA_TRG_KEY + suffix); - + result.put(CREATE_CHECKPOINTDATA_INDEX_KEY, prefix + CREATE_CHECKPOINTDATA_INDEX_KEY + suffix); - + return result; } diff --git a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/PostgresPersistenceManager.java b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/PostgresPersistenceManager.java index ac249994dfe..0cd8c1c786f 100644 --- a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/PostgresPersistenceManager.java +++ b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/PostgresPersistenceManager.java @@ -93,12 +93,12 @@ protected Map getSharedQueryMap(IBatchConfig batchConfig) throws if(schema.equals("") || schema.length() == 0){ schema = setDefaultSchema(); } - + result.put(Q_SET_SCHEMA, "set search_path to " + schema); - + return result; } - + /** * Set the schema to the default schema or the schema defined at batch * configuration time @@ -113,7 +113,7 @@ protected void setSchemaOnConnection(Connection connection) throws SQLException preparedStatement.executeUpdate(); } finally { logger.log(Level.FINEST, "Exiting {0}.setSchemaOnConnection()", CLASSNAME); - } + } } @@ -128,7 +128,7 @@ public void init(IBatchConfig batchConfig) jndiName = batchConfig.getDatabaseConfigurationBean().getJndiName(); prefix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_PREFIX_PROPERTY, ""); suffix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_SUFFIX_PROPERTY, ""); - + try { Context ctx = new InitialContext(); dataSource = (DataSource) ctx.lookup(jndiName); @@ -176,7 +176,7 @@ public void init(IBatchConfig batchConfig) /** * Check if the schema is valid. If not use the default schema - * + * * @return * @throws SQLException */ @@ -184,29 +184,22 @@ public void init(IBatchConfig batchConfig) protected boolean isSchemaValid() throws SQLException { boolean result = false; - Connection conn = null; - DatabaseMetaData dbmd = null; - ResultSet rs = null; - try { + try (Connection conn = getConnectionToDefaultSchema()) { logger.entering(CLASSNAME, "isPostgresSchemaValid"); - conn = getConnectionToDefaultSchema(); - dbmd = conn.getMetaData(); - rs = dbmd.getSchemas(); - - while (rs.next()) { - - String schemaname = rs.getString("TABLE_SCHEM"); - if (schema.equalsIgnoreCase(schemaname)) { - logger.exiting(CLASSNAME, "isSchemaValid", true); - return true; + DatabaseMetaData dbmd = conn.getMetaData(); + try (ResultSet rs = dbmd.getSchemas()) { + while (rs.next()) { + String schemaname = rs.getString("TABLE_SCHEM"); + if (schema.equalsIgnoreCase(schemaname)) { + logger.exiting(CLASSNAME, "isSchemaValid", true); + return true; + } } } } catch (SQLException e) { logger.severe(e.getLocalizedMessage()); throw e; - } finally { - cleanupConnection(conn, rs, null); } logger.exiting(CLASSNAME, "isPostgresSchemaValid", false); @@ -217,7 +210,7 @@ protected boolean isSchemaValid() throws SQLException { /** * Check the JBatch Tables exist in the relevant schema - * + * * @throws SQLException */ @Override @@ -248,11 +241,9 @@ protected void checkTables () throws SQLException { logger.exiting(CLASSNAME, "checkAllTables Postgres"); } - + @Override public boolean checkIfTableExists(DataSource dSource, String tableName, String schemaName) { - Statement statement = null; - ResultSet resultSet = null; dataSource = dSource; boolean result = true; @@ -264,24 +255,26 @@ public boolean checkIfTableExists(DataSource dSource, String tableName, String s setDefaultSchema(); } - statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - String query = "select lower(table_schema),lower(table_name) FROM information_schema.tables where lower(table_schema)= " - + "\'" - + schema - + "\'" - + " and lower(table_name)= " - + "\'" - + tableName.toLowerCase() + "\'"; - resultSet = statement.executeQuery(query); - - int rowcount = getTableRowCount(resultSet); - - if (rowcount == 0) { - if (!resultSet.next()) { - result = false; - } - } + try(Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY)) { + String query = "select lower(table_schema),lower(table_name) FROM information_schema.tables where lower(table_schema)= " + + "\'" + + schema + + "\'" + + " and lower(table_name)= " + + "\'" + + tableName.toLowerCase() + "\'"; + + try (ResultSet resultSet = statement.executeQuery(query)) { + int rowcount = getTableRowCount(resultSet); + if (rowcount == 0) { + if (!resultSet.next()) { + result = false; + } + } + } + + } } catch (SQLException ex) { logger.severe(ex.getLocalizedMessage()); } @@ -353,38 +346,31 @@ private Map setCreatePostgresStringsMap(Map tabl @Override public JobInstance createSubJobInstance(String name, String apptag) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; JobInstanceImpl jobInstance = null; - try { - conn = getConnection(); - - statement = conn.prepareStatement( - queryStrings.get(CREATE_SUB_JOB_INSTANCE), - statement.RETURN_GENERATED_KEYS); - + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement( + queryStrings.get(CREATE_SUB_JOB_INSTANCE), + Statement.RETURN_GENERATED_KEYS)) { statement.setString(1, name); statement.setString(2, apptag); statement.executeUpdate(); - rs = statement.getGeneratedKeys(); - if (rs.next()) { - long jobInstanceID = rs.getLong(1); - jobInstance = new JobInstanceImpl(jobInstanceID); - jobInstance.setJobName(name); + try(ResultSet rs = statement.getGeneratedKeys()) { + if (rs.next()) { + long jobInstanceID = rs.getLong(1); + jobInstance = new JobInstanceImpl(jobInstanceID); + jobInstance.setJobName(name); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return jobInstance; } /* * (non-Javadoc) - * + * * @see com.ibm.jbatch.container.services.IPersistenceManagerService# * createJobInstance(java.lang.String, java.lang.String, java.lang.String, * java.util.Properties) @@ -392,33 +378,24 @@ public JobInstance createSubJobInstance(String name, String apptag) { @Override public JobInstance createJobInstance(String name, String apptag, String jobXml) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; JobInstanceImpl jobInstance = null; - try { - conn = getConnection(); - - statement = conn.prepareStatement( - queryStrings.get(CREATE_JOB_INSTANCE), - statement.RETURN_GENERATED_KEYS); - + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement( + queryStrings.get(CREATE_JOB_INSTANCE), + Statement.RETURN_GENERATED_KEYS)) { statement.setString(1, name); statement.setString(2, apptag); statement.executeUpdate(); - - rs = statement.getGeneratedKeys(); - - if (rs.next()) { - long jobInstanceID = rs.getLong(1); - jobInstance = new JobInstanceImpl(jobInstanceID, jobXml); - jobInstance.setJobName(name); + try(ResultSet rs = statement.getGeneratedKeys()) { + if (rs.next()) { + long jobInstanceID = rs.getLong(1); + jobInstance = new JobInstanceImpl(jobInstanceID, jobXml); + jobInstance.setJobName(name); + } } } catch (SQLException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return jobInstance; } @@ -427,33 +404,27 @@ public JobInstance createJobInstance(String name, String apptag, protected long createRuntimeJobExecutionEntry(JobInstance jobInstance, Properties jobParameters, BatchStatus batchStatus, Timestamp timestamp) { - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; long newJobExecutionId = 0L; - try { - conn = getConnection(); - - statement = conn.prepareStatement( - queryStrings.get(CREATE_JOB_EXECUTION_ENTRY), - statement.RETURN_GENERATED_KEYS); + try ( + Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement( + queryStrings.get(CREATE_JOB_EXECUTION_ENTRY), + Statement.RETURN_GENERATED_KEYS); + ) { statement.setLong(1, jobInstance.getInstanceId()); statement.setTimestamp(2, timestamp); statement.setTimestamp(3, timestamp); statement.setString(4, batchStatus.name()); statement.setObject(5, serializeObject(jobParameters)); statement.executeUpdate(); - rs = statement.getGeneratedKeys(); - if (rs.next()) { - newJobExecutionId = rs.getLong(1); + try (ResultSet rs = statement.getGeneratedKeys()) { + if (rs.next()) { + newJobExecutionId = rs.getLong(1); + } } - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { + } catch (SQLException | IOException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, rs, statement); } return newJobExecutionId; } @@ -475,18 +446,12 @@ protected StepExecutionImpl createStepExecution(long rootJobExecId, endTime == null ? "" : endTime, persistentData == null ? "" : persistentData }); - Connection conn = null; - PreparedStatement statement = null; - ResultSet rs = null; StepExecutionImpl stepExecution = null; String query = queryStrings.get(CREATE_STEP_EXECUTION); - try { - conn = getConnection(); - - statement = conn.prepareStatement(query, - statement.RETURN_GENERATED_KEYS); - + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(query, + Statement.RETURN_GENERATED_KEYS)) { statement.setLong(1, rootJobExecId); statement.setString(2, batchStatus); statement.setString(3, exitStatus); @@ -504,83 +469,73 @@ protected StepExecutionImpl createStepExecution(long rootJobExecId, statement.setObject(15, serializeObject(persistentData)); statement.executeUpdate(); - rs = statement.getGeneratedKeys(); - if (rs.next()) { - long stepExecutionId = rs.getLong(1); - stepExecution = new StepExecutionImpl(rootJobExecId, - stepExecutionId); - stepExecution.setStepName(stepName); + + try(ResultSet rs = statement.getGeneratedKeys()) { + if (rs.next()) { + long stepExecutionId = rs.getLong(1); + stepExecution = new StepExecutionImpl(rootJobExecId, + stepExecutionId); + stepExecution.setStepName(stepName); + } } - } catch (SQLException e) { - throw new PersistenceException(e); - } catch (IOException e) { + } catch (SQLException | IOException e) { throw new PersistenceException(e); - } finally { - cleanupConnection(conn, null, statement); } logger.exiting(CLASSNAME, "createStepExecution"); return stepExecution; } - + @Override public void markJobStarted(long key, Timestamp startTS) { - - logger.entering(CLASSNAME, "markJobStarted", - new Object[] {key, startTS}); - - final int retryMax = Integer.getInteger(P_MJS_RETRY_MAX, MJS_RETRY_MAX_DEFAULT); - final int retryDelay = Integer.getInteger(P_MJS_RETRY_DELAY, MJS_RETRY_DELAY_DEFAULT); - - logger.log(Level.FINER,P_MJS_RETRY_MAX + - " = {0}" + ", " + P_MJS_RETRY_DELAY + " = {1} ms", - new Object[]{retryMax, retryDelay}); - - Connection conn = null; - PreparedStatement statement = null; - try { - conn = getConnection(); - statement = conn.prepareStatement(queryStrings - .get(MARK_JOB_STARTED)); - - statement.setString(1, BatchStatus.STARTED.name()); - statement.setTimestamp(2, startTS); - statement.setTimestamp(3, startTS); - statement.setLong(4, key); - - // Postgres use of Multi Version Concurrency (MVCC) means that - // blocking does not occur (particularly a problem in - // createStepExecution()). - // The below will check that the row has been commited by the - // initiating thread by retrying the update until at least 1 row - // is updated. - - int retryCount = 0; - while ( (statement.executeUpdate() < 1) && (retryCount++ <= retryMax) ) { - sleep(retryDelay); - } - logger.log(Level.FINER, "Marking job as started required {0} retries", retryCount); - - if (retryCount >= retryMax) { - logger.log(Level.WARNING, "Failed to mark job as started after {0} attempts", retryCount); - } + logger.entering(CLASSNAME, "markJobStarted", + new Object[] {key, startTS}); + + final int retryMax = Integer.getInteger(P_MJS_RETRY_MAX, MJS_RETRY_MAX_DEFAULT); + final int retryDelay = Integer.getInteger(P_MJS_RETRY_DELAY, MJS_RETRY_DELAY_DEFAULT); + + logger.log(Level.FINER,P_MJS_RETRY_MAX + + " = {0}" + ", " + P_MJS_RETRY_DELAY + " = {1} ms", + new Object[]{retryMax, retryDelay}); + + try (Connection conn = getConnection(); + PreparedStatement statement = conn.prepareStatement(queryStrings + .get(MARK_JOB_STARTED))) { + statement.setString(1, BatchStatus.STARTED.name()); + statement.setTimestamp(2, startTS); + statement.setTimestamp(3, startTS); + statement.setLong(4, key); + + // Postgres use of Multi Version Concurrency (MVCC) means that + // blocking does not occur (particularly a problem in + // createStepExecution()). + // The below will check that the row has been committed by the + // initiating thread by retrying the update until at least 1 row + // is updated. + + int retryCount = 0; + while ( (statement.executeUpdate() < 1) && (retryCount++ <= retryMax) ) { + sleep(retryDelay); + } + logger.log(Level.FINER, "Marking job as started required {0} retries", retryCount); - } catch (SQLException e) { - throw new PersistenceException(e); - } finally { - cleanupConnection(conn, null, statement); - } - logger.exiting(CLASSNAME, "markJobStarted"); + if (retryCount >= retryMax) { + logger.log(Level.WARNING, "Failed to mark job as started after {0} attempts", retryCount); + } + + } catch (SQLException e) { + throw new PersistenceException(e); + } + logger.exiting(CLASSNAME, "markJobStarted"); } - - private static void sleep(int duration){ - try { - Thread.sleep(duration); - } catch(InterruptedException ie) { - logger.warning("Thread interrupted"); - Thread.currentThread().interrupt(); - } + private static void sleep(int duration){ + try { + Thread.sleep(duration); + } catch(InterruptedException ie) { + logger.warning("Thread interrupted"); + Thread.currentThread().interrupt(); + } } } diff --git a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/SQLServerPersistenceManager.java b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/SQLServerPersistenceManager.java index a3465774a10..1ab272e4bcd 100644 --- a/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/SQLServerPersistenceManager.java +++ b/appserver/batch/glassfish-batch-connector/src/main/java/fish/payara/jbatch/persistence/rdbms/SQLServerPersistenceManager.java @@ -41,19 +41,12 @@ import com.ibm.jbatch.container.exception.BatchContainerServiceException; import com.ibm.jbatch.spi.services.IBatchConfig; -import static fish.payara.jbatch.persistence.rdbms.JDBCQueryConstants.CHECKPOINT_TABLE_KEY; -import static fish.payara.jbatch.persistence.rdbms.JDBCQueryConstants.EXECUTION_INSTANCE_TABLE_KEY; -import static fish.payara.jbatch.persistence.rdbms.JDBCQueryConstants.JOB_INSTANCE_TABLE_KEY; -import static fish.payara.jbatch.persistence.rdbms.JDBCQueryConstants.JOB_STATUS_TABLE_KEY; -import static fish.payara.jbatch.persistence.rdbms.JDBCQueryConstants.Q_SET_SCHEMA; -import static fish.payara.jbatch.persistence.rdbms.JDBCQueryConstants.STEP_EXECUTION_INSTANCE_TABLE_KEY; -import static fish.payara.jbatch.persistence.rdbms.JDBCQueryConstants.STEP_STATUS_TABLE_KEY; -import static fish.payara.jbatch.persistence.rdbms.SQLServerJDBCConstants.SQLSERVER_CREATE_TABLE_CHECKPOINTDATA; -import static fish.payara.jbatch.persistence.rdbms.SQLServerJDBCConstants.SQLSERVER_CREATE_TABLE_EXECUTIONINSTANCEDATA; -import static fish.payara.jbatch.persistence.rdbms.SQLServerJDBCConstants.SQLSERVER_CREATE_TABLE_JOBINSTANCEDATA; -import static fish.payara.jbatch.persistence.rdbms.SQLServerJDBCConstants.SQLSERVER_CREATE_TABLE_JOBSTATUS; -import static fish.payara.jbatch.persistence.rdbms.SQLServerJDBCConstants.SQLSERVER_CREATE_TABLE_STEPINSTANCEDATA; -import static fish.payara.jbatch.persistence.rdbms.SQLServerJDBCConstants.SQLSERVER_CREATE_TABLE_STEPSTATUS; +import org.glassfish.batch.spi.impl.BatchRuntimeConfiguration; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -62,44 +55,40 @@ import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; -import org.glassfish.batch.spi.impl.BatchRuntimeConfiguration; + import static org.glassfish.batch.spi.impl.BatchRuntimeHelper.PAYARA_TABLE_PREFIX_PROPERTY; import static org.glassfish.batch.spi.impl.BatchRuntimeHelper.PAYARA_TABLE_SUFFIX_PROPERTY; public class SQLServerPersistenceManager extends JBatchJDBCPersistenceManager implements SQLServerJDBCConstants { - - private static final String CLASSNAME = SQLServerPersistenceManager.class.getName(); + + private static final String CLASSNAME = SQLServerPersistenceManager.class.getName(); private static final Logger LOGGER = Logger.getLogger(CLASSNAME); - + // SQL Server create table strings protected Map SQLServerCreateStrings; - protected Map schemaTableNames; - + protected Map schemaTableNames; + @Override public void init(IBatchConfig batchConfig) throws BatchContainerServiceException { - - LOGGER.entering(CLASSNAME, "init", batchConfig); + + LOGGER.entering(CLASSNAME, "init", batchConfig); schema = batchConfig.getDatabaseConfigurationBean().getSchema(); jndiName = batchConfig.getDatabaseConfigurationBean().getJndiName(); prefix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_PREFIX_PROPERTY, ""); suffix = batchConfig.getConfigProperties().getProperty(PAYARA_TABLE_SUFFIX_PROPERTY, ""); - + if (null == jndiName || jndiName.isEmpty()) { throw new BatchContainerServiceException("JNDI name is not defined."); } - + Context ctx; try { ctx = new InitialContext(); dataSource = (DataSource) ctx.lookup(jndiName); } catch (NamingException e) { - LOGGER.log(Level.SEVERE, + LOGGER.log(Level.SEVERE, "Lookup failed for JNDI name: {0}. " + "One cause of this could be that the batch runtime " + "is incorrectly configured to EE mode when it " @@ -143,28 +132,19 @@ protected boolean isSchemaValid() throws SQLException { LOGGER.entering(CLASSNAME, "isSQLServerSchemaValid"); boolean result = false; - Connection conn = null; - ResultSet rs = null; - PreparedStatement ps = null; - try { - conn = getConnectionToDefaultSchema(); - ps = conn.prepareStatement( - "SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE ?" - ); - ps.setString(1, schema); - rs = ps.executeQuery(); - - if (rs.next()) { - result = true; + try (Connection conn = getConnectionToDefaultSchema(); + PreparedStatement ps = conn.prepareStatement("SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE ?")) { + ps.setString(1, schema); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + result = true; + } } } catch (SQLException e) { LOGGER.severe(e.getLocalizedMessage()); throw e; - } finally { - cleanupConnection(conn, rs, ps); } - - LOGGER.exiting(CLASSNAME, "isSQLServerSchemaValid", result); + LOGGER.exiting(CLASSNAME, "isSQLServerSchemaValid", result); return result; } @@ -173,7 +153,7 @@ protected boolean isSchemaValid() throws SQLException { * @throws SQLException */ private void checkSQLServerTables() throws SQLException { - + LOGGER.entering(CLASSNAME, "checkSQLServerTables"); setCreateSQLServerStringsMap(); createTableIfNotExists(tableNames.get(CHECKPOINT_TABLE_KEY), @@ -181,16 +161,16 @@ private void checkSQLServerTables() throws SQLException { createTableIfNotExists(tableNames.get(JOB_INSTANCE_TABLE_KEY), SQLServerCreateStrings.get(SQLSERVER_CREATE_TABLE_JOBINSTANCEDATA)); - + createTableIfNotExists(tableNames.get(EXECUTION_INSTANCE_TABLE_KEY), SQLServerCreateStrings.get(SQLSERVER_CREATE_TABLE_EXECUTIONINSTANCEDATA)); - + createTableIfNotExists(tableNames.get(STEP_EXECUTION_INSTANCE_TABLE_KEY), SQLServerCreateStrings.get(SQLSERVER_CREATE_TABLE_STEPINSTANCEDATA)); - + createTableIfNotExists(tableNames.get(JOB_STATUS_TABLE_KEY), SQLServerCreateStrings.get(SQLSERVER_CREATE_TABLE_JOBSTATUS)); - + createTableIfNotExists(tableNames.get(STEP_STATUS_TABLE_KEY), SQLServerCreateStrings.get(SQLSERVER_CREATE_TABLE_STEPSTATUS)); @@ -199,21 +179,21 @@ private void checkSQLServerTables() throws SQLException { @Override public void createTables(DataSource dataSource, BatchRuntimeConfiguration batchRuntimeConfiguration){ - this.dataSource = dataSource; - prefix = batchRuntimeConfiguration.getTablePrefix(); - suffix = batchRuntimeConfiguration.getTableSuffix(); - schema = batchRuntimeConfiguration.getSchemaName(); - tableNames = getSharedTableMap(); - schemaTableNames = getSharedSchemaTableMap(); - - try { - if (!isSchemaValid()) { - setDefaultSchema(); - } - checkSQLServerTables(); - } catch (SQLException ex) { - LOGGER.severe(ex.getLocalizedMessage()); - } + this.dataSource = dataSource; + prefix = batchRuntimeConfiguration.getTablePrefix(); + suffix = batchRuntimeConfiguration.getTableSuffix(); + schema = batchRuntimeConfiguration.getSchemaName(); + tableNames = getSharedTableMap(); + schemaTableNames = getSharedSchemaTableMap(); + + try { + if (!isSchemaValid()) { + setDefaultSchema(); + } + checkSQLServerTables(); + } catch (SQLException ex) { + LOGGER.severe(ex.getLocalizedMessage()); + } } /** * Create the jbatch tables if they do not exist. @@ -223,50 +203,43 @@ public void createTables(DataSource dataSource, BatchRuntimeConfiguration batchR */ protected void createSQLServerTableIfNotExist(String tableName, String createTableStatement) throws SQLException { - + LOGGER.entering(CLASSNAME, "createSQLServerTableIfNotExists", new Object[] { tableName, createTableStatement }); - Connection conn = null; - PreparedStatement ps = null; - ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement( + try (Connection conn = getConnection(); + PreparedStatement ps = conn.prepareStatement( "SELECT table_schema, table_name FROM information_schema.tables " + "WHERE table_schema LIKE ? AND table_name LIKE ?", ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY - ); - ps.setString(1, schema); - ps.setString(2, tableName); - rs = ps.executeQuery(); - - int rowcount = getTableRowCount(rs); - - // Create table if it does not exist - if (rowcount == 0) { - if (!rs.next()) { - LOGGER.log(Level.INFO, "{0} table does not exists. Trying to create it.", tableName); - ps = conn.prepareStatement(createTableStatement); - ps.executeUpdate(); + ResultSet.CONCUR_READ_ONLY)) { + ps.setString(1, schema); + ps.setString(2, tableName); + + try(ResultSet rs = ps.executeQuery()) { + int rowcount = getTableRowCount(rs); + // Create table if it does not exist + if (rowcount == 0) { + if (!rs.next()) { + LOGGER.log(Level.INFO, "{0} table does not exists. Trying to create it.", tableName); + try(PreparedStatement psCt = conn.prepareStatement(createTableStatement)) { + psCt.executeUpdate(); + } + } } } + } catch (SQLException e) { LOGGER.severe(e.getLocalizedMessage()); throw e; - } finally { - cleanupConnection(conn, ps); } LOGGER.exiting(CLASSNAME, "createSQLServerTableIfNotExists"); } - + @Override public boolean checkIfTableExists(DataSource dSource, String tableName, String schemaName) { - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; dataSource = dSource; boolean result = true; @@ -278,50 +251,52 @@ public boolean checkIfTableExists(DataSource dSource, String tableName, String s setDefaultSchema(); } - preparedStatement = connection.prepareStatement( + try(PreparedStatement preparedStatement = connection.prepareStatement( "SELECT table_schema, table_name FROM information_schema.tables " + "WHERE table_schema LIKE ? AND table_name LIKE ?", ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY - ); - - preparedStatement.setString(1, schema); - preparedStatement.setString(2, tableName); - resultSet = preparedStatement.executeQuery(); - - int rowcount = getTableRowCount(resultSet); - - if (rowcount == 0) { - if (!resultSet.next()) { - result = false; - } - } + ResultSet.CONCUR_READ_ONLY)) { + + preparedStatement.setString(1, schema); + preparedStatement.setString(2, tableName); + try(ResultSet resultSet = preparedStatement.executeQuery()) { + int rowcount = getTableRowCount(resultSet); + + if (rowcount == 0) { + if (!resultSet.next()) { + result = false; + } + } + } + + } + } catch (SQLException ex) { LOGGER.severe(ex.getLocalizedMessage()); } - return result; + return result; } - protected Map getSharedSchemaTableMap() { + protected Map getSharedSchemaTableMap() { String schemaPrefix; if(schema == null || schema.isEmpty()) { schemaPrefix = ""; } else { schemaPrefix = schema + "."; } - + Map result = new HashMap(6); - result.put(JOB_INSTANCE_TABLE_KEY, schemaPrefix + prefix + result.put(JOB_INSTANCE_TABLE_KEY, schemaPrefix + prefix + "JOBINSTANCEDATA" + suffix); result.put(EXECUTION_INSTANCE_TABLE_KEY, schemaPrefix + prefix + "EXECUTIONINSTANCEDATA" + suffix); result.put(STEP_EXECUTION_INSTANCE_TABLE_KEY, schemaPrefix + prefix + "STEPEXECUTIONINSTANCEDATA" + suffix); - result.put(JOB_STATUS_TABLE_KEY, schemaPrefix + prefix + result.put(JOB_STATUS_TABLE_KEY, schemaPrefix + prefix + "JOBSTATUS" + suffix); - result.put(STEP_STATUS_TABLE_KEY, schemaPrefix + prefix + result.put(STEP_STATUS_TABLE_KEY, schemaPrefix + prefix + "STEPSTATUS" + suffix); - result.put(CHECKPOINT_TABLE_KEY, schemaPrefix + prefix + result.put(CHECKPOINT_TABLE_KEY, schemaPrefix + prefix + "CHECKPOINTDATA" + suffix); return result; } @@ -330,28 +305,28 @@ protected Map getSharedSchemaTableMap() { protected void setSchemaOnConnection(Connection connection){ // SQL Server does not support setting default schema for session } - + /** * Method invoked to insert the MySql create table strings into a hashmap * @return SQLServerCreateStrings **/ private Map setCreateSQLServerStringsMap () { - + SQLServerCreateStrings = new HashMap<>(); - + SQLServerCreateStrings.put(SQLSERVER_CREATE_TABLE_CHECKPOINTDATA, "CREATE TABLE " + schemaTableNames.get(CHECKPOINT_TABLE_KEY) + "(" + "id VARCHAR(512)," + "obj VARBINARY(MAX))"); - + SQLServerCreateStrings.put(SQLSERVER_CREATE_TABLE_JOBINSTANCEDATA,"CREATE TABLE " + schemaTableNames.get(JOB_INSTANCE_TABLE_KEY) + "(" + "jobinstanceid BIGINT NOT NULL PRIMARY KEY IDENTITY(1,1)," + "name VARCHAR(512)," + "apptag VARCHAR(512))"); - + SQLServerCreateStrings.put(SQLSERVER_CREATE_TABLE_EXECUTIONINSTANCEDATA,"CREATE TABLE " + schemaTableNames.get(EXECUTION_INSTANCE_TABLE_KEY) + "(" @@ -390,7 +365,7 @@ private Map setCreateSQLServerStringsMap () { + "CONSTRAINT JOBEXEC_STEPEXEC_FK FOREIGN KEY (jobexecid) REFERENCES " + schemaTableNames.get(EXECUTION_INSTANCE_TABLE_KEY) + "(jobexecid))"); - + SQLServerCreateStrings.put(SQLSERVER_CREATE_TABLE_JOBSTATUS,"CREATE TABLE " + schemaTableNames.get(JOB_STATUS_TABLE_KEY) + "(" @@ -410,10 +385,10 @@ private Map setCreateSQLServerStringsMap () { + "(stepexecid) ON DELETE CASCADE)"); return SQLServerCreateStrings; - } - + } + protected Map getSQLServerSharedQueryMap(IBatchConfig batchConfig) throws SQLException { - + String schemaPrefix = batchConfig.getDatabaseConfigurationBean().getSchema(); if(schemaPrefix != null && !schemaPrefix.isEmpty()) { schemaPrefix += ".";