From 14844df41a609d96012bb44ac05bb8a5956491e4 Mon Sep 17 00:00:00 2001 From: Deepak Dixit Date: Mon, 28 Oct 2024 14:47:58 +0530 Subject: [PATCH] Use try-with-resources for JDBC AutoCloseable resources Refactored code to utilize try-with-resources for JDBC operations, ensuring automatic resource management (ARM) compliance. This change improves code readability and reliability by eliminating the need for explicit resource closure, reducing the risk of resource leaks. --- .../org/moqui/impl/InstanceServices.xml | 12 +- .../impl/context/TransactionCache.groovy | 12 +- .../org/moqui/impl/entity/EntityDbMeta.groovy | 152 ++++++------------ .../moqui/impl/entity/EntityFacadeImpl.groovy | 39 ++--- .../org/moqui/impl/util/JdbcExtractor.java | 13 +- 5 files changed, 68 insertions(+), 160 deletions(-) diff --git a/framework/service/org/moqui/impl/InstanceServices.xml b/framework/service/org/moqui/impl/InstanceServices.xml index dacbd18ca..6c0b6f500 100644 --- a/framework/service/org/moqui/impl/InstanceServices.xml +++ b/framework/service/org/moqui/impl/InstanceServices.xml @@ -723,15 +723,14 @@ along with this software (see the LICENSE.md file). If not, see dbUserExists = false javax.sql.XAConnection testXaCon = null - java.sql.Connection testCon = null try { testXaCon = ec.entity.getConfConnection(adminMap) - testCon = testXaCon.getConnection() - dbConnectSuccess = true + try (java.sql.Connection testCon = testXaCon.getConnection()) { + dbConnectSuccess = true + } } catch (Exception e) { logger.warn("Test connection failed", e) } finally { - if (testCon != null) testCon.close() if (testXaCon != null) testXaCon.close() } @@ -804,15 +803,14 @@ along with this software (see the LICENSE.md file). If not, see dbUserExists = false javax.sql.XAConnection testXaCon = null - java.sql.Connection testCon = null try { testXaCon = ec.entity.getConfConnection(adminMap) - testCon = testXaCon.getConnection() + try (java.sql.Connection testCon = testXaCon.getConnection()) { dbConnectSuccess = true + } } catch (Exception e) { logger.warn("Test connection to Postgres failed", e) } finally { - if (testCon != null) testCon.close() if (testXaCon != null) testXaCon.close() } diff --git a/framework/src/main/groovy/org/moqui/impl/context/TransactionCache.groovy b/framework/src/main/groovy/org/moqui/impl/context/TransactionCache.groovy index f82a1ee15..ede0a88f0 100644 --- a/framework/src/main/groovy/org/moqui/impl/context/TransactionCache.groovy +++ b/framework/src/main/groovy/org/moqui/impl/context/TransactionCache.groovy @@ -440,7 +440,6 @@ class TransactionCache implements Synchronization { } void flushCache(boolean clearRead) { - Map connectionByGroup = new HashMap<>() try { int writeInfoListSize = writeInfoList.size() if (writeInfoListSize > 0) { @@ -456,12 +455,7 @@ class TransactionCache implements Synchronization { for (int i = 0; i < writeInfoListSize; i++) { EntityWriteInfo ewi = (EntityWriteInfo) writeInfoList.get(i) String groupName = ewi.evb.getEntityDefinition().getEntityGroupName() - Connection con = connectionByGroup.get(groupName) - if (con == null) { - con = efi.getConnection(groupName) - connectionByGroup.put(groupName, con) - } - + try (Connection con = efi.getConnection(groupName)) { if (ewi.writeMode.is(WriteMode.CREATE)) { ewi.evb.basicCreate(con) createCount++ @@ -472,6 +466,7 @@ class TransactionCache implements Synchronization { ewi.evb.basicUpdate(con) updateCount++ } + } } if (logger.isDebugEnabled()) logger.debug("Flushed TransactionCache in ${System.currentTimeMillis() - startTime}ms: ${createCount} creates, ${updateCount} updates, ${deleteCount} deletes, ${readOneCache.size()} read entries, ${readListCache.size()} entities with list cache") } @@ -489,9 +484,6 @@ class TransactionCache implements Synchronization { } catch (Throwable t) { logger.error("Error writing values from TransactionCache: ${t.toString()}", t) throw new XAException("Error writing values from TransactionCache: + ${t.toString()}") - } finally { - // now close connections - for (Connection con in connectionByGroup.values()) con.close() } } diff --git a/framework/src/main/groovy/org/moqui/impl/entity/EntityDbMeta.groovy b/framework/src/main/groovy/org/moqui/impl/entity/EntityDbMeta.groovy index 4a4158ab6..6c8ef64ac 100644 --- a/framework/src/main/groovy/org/moqui/impl/entity/EntityDbMeta.groovy +++ b/framework/src/main/groovy/org/moqui/impl/entity/EntityDbMeta.groovy @@ -111,29 +111,19 @@ class EntityDbMeta { Set existingTableNames = new HashSet<>() boolean beganTx = useTxForMetaData ? efi.ecfi.transactionFacade.begin(300) : false - try { - Connection con = efi.getConnection(groupName) - - try { + try (Connection con = efi.getConnection(groupName)) { DatabaseMetaData dbData = con.getMetaData() - - ResultSet tableSet = null - try { - tableSet = dbData.getTables(con.getCatalog(), schemaName, "%", types) + try (ResultSet tableSet = dbData.getTables(con.getCatalog(), schemaName, "%", types)) { while (tableSet.next()) { String tableName = tableSet.getString('TABLE_NAME') existingTableNames.add(tableName) } } catch (Exception e) { throw new EntityException("Exception getting tables in group ${groupName}", e) - } finally { - if (tableSet != null && !tableSet.isClosed()) tableSet.close() } Map> existingColumnsByTable = new HashMap<>() - ResultSet colSet = null - try { - colSet = dbData.getColumns(con.getCatalog(), schemaName, "%", "%") + try (ResultSet colSet = dbData.getColumns(con.getCatalog(), schemaName, "%", "%")) { while (colSet.next()) { String tableName = colSet.getString("TABLE_NAME") String colName = colSet.getString("COLUMN_NAME") @@ -149,8 +139,6 @@ class EntityDbMeta { } } catch (Exception e) { throw new EntityException("Exception getting columns in group ${groupName}", e) - } finally { - if (colSet != null && !colSet.isClosed()) colSet.close() } Set remainingTableNames = new HashSet<>(existingTableNames) @@ -210,9 +198,6 @@ class EntityDbMeta { if (remainingTableNames.size() > 0) logger.warn("Found unknown tables in database for group ${groupName}: ${remainingTableNames}") - } finally { - if (con != null) con.close() - } } finally { if (beganTx) efi.ecfi.transactionFacade.commit() } @@ -222,20 +207,15 @@ class EntityDbMeta { logger.info("Tables were created, checking FKs for all entities in group ${groupName}") beganTx = useTxForMetaData ? efi.ecfi.transactionFacade.begin(300) : false - try { - Connection con = efi.getConnection(groupName) - - try { + try (Connection con = efi.getConnection(groupName)) { DatabaseMetaData dbData = con.getMetaData() // NOTE: don't need to get fresh results for existing table names as created tables are added to the Set above Map>> fkInfoByFkTable = new HashMap<>() - ResultSet ikSet = null - try { + try (ResultSet ikSet = dbData.getImportedKeys(null, schemaName, "%")) { // don't rely on constraint name, look at related table name, keys // get set of fields on main entity to match against (more unique than fields on related entity) - ikSet = dbData.getImportedKeys(null, schemaName, "%") while (ikSet.next()) { // logger.info("Existing FK col: PKTABLE_NAME [${ikSet.getString("PKTABLE_NAME")}] PKCOLUMN_NAME [${ikSet.getString("PKCOLUMN_NAME")}] FKTABLE_NAME [${ikSet.getString("FKTABLE_NAME")}] FKCOLUMN_NAME [${ikSet.getString("FKCOLUMN_NAME")}]") String pkTable = ikSet.getString("PKTABLE_NAME") @@ -250,8 +230,6 @@ class EntityDbMeta { } } catch (Exception e) { logger.error("Error getting all foreign keys for group ${groupName}", e) - } finally { - if (ikSet != null && !ikSet.isClosed()) ikSet.close() } if (fkInfoByFkTable.size() == 0) { @@ -261,8 +239,7 @@ class EntityDbMeta { if (ed.isViewEntity) continue String fkTable = ed.getTableName() boolean gotIkResults = false - try { - ikSet = dbData.getImportedKeys(null, schemaName, fkTable) + try (ResultSet ikSet = dbData.getImportedKeys(null, schemaName, fkTable)) { while (ikSet.next()) { gotIkResults = true String pkTable = ikSet.getString("PKTABLE_NAME") @@ -275,13 +252,10 @@ class EntityDbMeta { } } catch (Exception e) { logger.error("Error getting foreign keys for entity ${entityName} group ${groupName}", e) - } finally { - if (ikSet != null && !ikSet.isClosed()) ikSet.close() } if (!gotIkResults) { // no results found, try lower case table name - try { - ikSet = dbData.getImportedKeys(null, schemaName, fkTable.toLowerCase()) + try (ResultSet ikSet = dbData.getImportedKeys(null, schemaName, fkTable.toLowerCase())) { while (ikSet.next()) { String pkTable = ikSet.getString("PKTABLE_NAME") String fkCol = ikSet.getString("FKCOLUMN_NAME") @@ -293,8 +267,6 @@ class EntityDbMeta { } } catch (Exception e) { logger.error("Error getting foreign keys for entity ${entityName} group ${groupName}", e) - } finally { - if (ikSet != null && !ikSet.isClosed()) ikSet.close() } } } @@ -366,9 +338,6 @@ class EntityDbMeta { if (noRelTableCount > 0) logger.warn("In full FK check found ${noRelTableCount} type one relationships where no table exists for related entity") if (fksCreated > 0) logger.info("Created ${fksCreated} FKs out of ${relOneCount} type one relationships for entity ${entityName}") } - } finally { - if (con != null) con.close() - } } finally { if (beganTx) efi.ecfi.transactionFacade.commit() } @@ -450,39 +419,32 @@ class EntityDbMeta { dbResult = anyExist } else { String groupName = ed.getEntityGroupName() - Connection con = null - ResultSet tableSet1 = null - ResultSet tableSet2 = null boolean beganTx = useTxForMetaData ? efi.ecfi.transactionFacade.begin(5) : false - try { - try { - con = efi.getConnection(groupName) - } catch (EntityException ee) { - logger.warn("Could not get connection so treating entity ${ed.fullEntityName} in group ${groupName} as table does not exist: ${ee.toString()}") - return false - } + try (Connection con = efi.getConnection(groupName)) { DatabaseMetaData dbData = con.getMetaData() String[] types = ["TABLE", "VIEW", "ALIAS", "SYNONYM", "PARTITIONED TABLE"] - tableSet1 = dbData.getTables(con.getCatalog(), ed.getSchemaName(), ed.getTableName(), types) + try (ResultSet tableSet1 = dbData.getTables(con.getCatalog(), ed.getSchemaName(), ed.getTableName(), types)) { if (tableSet1.next()) { dbResult = true } else { // try lower case, just in case DB is case sensitive - tableSet2 = dbData.getTables(con.getCatalog(), ed.getSchemaName(), ed.getTableName().toLowerCase(), types) + try (ResultSet tableSet2 = dbData.getTables(con.getCatalog(), ed.getSchemaName(), ed.getTableName().toLowerCase(), types)) { if (tableSet2.next()) { dbResult = true } else { if (logger.isTraceEnabled()) logger.trace("Table for entity ${ed.getFullEntityName()} does NOT exist") dbResult = false } + } } + } + } catch (EntityException ee) { + logger.warn("Could not get connection so treating entity ${ed.fullEntityName} in group ${groupName} as table does not exist: ${ee.toString()}") + return false } catch (Exception e) { throw new EntityException("Exception checking to see if table ${ed.getTableName()} exists", e) } finally { - if (tableSet1 != null && !tableSet1.isClosed()) tableSet1.close() - if (tableSet2 != null && !tableSet2.isClosed()) tableSet2.close() - if (con != null) con.close() if (beganTx) efi.ecfi.transactionFacade.commit() } } @@ -565,18 +527,15 @@ class EntityDbMeta { if (ed.isViewEntity) return new ArrayList() String groupName = ed.getEntityGroupName() - Connection con = null - ResultSet colSet1 = null - ResultSet colSet2 = null + boolean beganTx = useTxForMetaData ? efi.ecfi.transactionFacade.begin(5) : false - try { - con = efi.getConnection(groupName) + try (Connection con = efi.getConnection(groupName)) { DatabaseMetaData dbData = con.getMetaData() // con.setAutoCommit(false) ArrayList fieldInfos = new ArrayList<>(ed.allFieldInfoList) int fieldCount = fieldInfos.size() - colSet1 = dbData.getColumns(con.getCatalog(), ed.getSchemaName(), ed.getTableName(), "%") + try (ResultSet colSet1 = dbData.getColumns(con.getCatalog(), ed.getSchemaName(), ed.getTableName(), "%")) { if (colSet1.isClosed()) { logger.error("Tried to get columns for entity ${ed.getFullEntityName()} but ResultSet was closed!") return new ArrayList() @@ -592,10 +551,11 @@ class EntityDbMeta { } } } + } if (fieldInfos.size() == fieldCount) { // try lower case table name - colSet2 = dbData.getColumns(con.getCatalog(), ed.getSchemaName(), ed.getTableName().toLowerCase(), "%") + try (ResultSet colSet2 = dbData.getColumns(con.getCatalog(), ed.getSchemaName(), ed.getTableName().toLowerCase(), "%")) { if (colSet2.isClosed()) { logger.error("Tried to get columns for entity ${ed.getFullEntityName()} but ResultSet was closed!") return new ArrayList() @@ -611,6 +571,7 @@ class EntityDbMeta { } } } + } if (fieldInfos.size() == fieldCount) { logger.warn("Could not find any columns to match fields for entity ${ed.getFullEntityName()}") @@ -622,9 +583,6 @@ class EntityDbMeta { logger.error("Exception checking for missing columns in table ${ed.getTableName()}", e) return new ArrayList() } finally { - if (colSet1 != null && !colSet1.isClosed()) colSet1.close() - if (colSet2 != null && !colSet2.isClosed()) colSet2.close() - if (con != null && !con.isClosed()) con.close() if (beganTx) efi.ecfi.transactionFacade.commit() } } @@ -821,15 +779,11 @@ class EntityDbMeta { } Boolean indexExists(EntityDefinition ed, String indexName, Collection indexFields) { String groupName = ed.getEntityGroupName() - Connection con = null - ResultSet ikSet1 = null - ResultSet ikSet2 = null - try { - con = efi.getConnection(groupName) + try (Connection con = efi.getConnection(groupName)) { DatabaseMetaData dbData = con.getMetaData() Set fieldNames = new HashSet(indexFields) - ikSet1 = dbData.getIndexInfo(null, ed.getSchemaName(), ed.getTableName(), false, true) + try (ResultSet ikSet1 = dbData.getIndexInfo(null, ed.getSchemaName(), ed.getTableName(), false, true)) { while (ikSet1.next()) { String idxName = ikSet1.getString("INDEX_NAME") if (idxName.toLowerCase() != indexName.toLowerCase()) continue @@ -842,9 +796,10 @@ class EntityDbMeta { } } } + } if (fieldNames.size() > 0) { // try with lower case table name - ikSet2 = dbData.getIndexInfo(null, ed.getSchemaName(), ed.getTableName().toLowerCase(), false, true) + try (ResultSet ikSet2 = dbData.getIndexInfo(null, ed.getSchemaName(), ed.getTableName().toLowerCase(), false, true)) { while (ikSet2.next()) { String idxName = ikSet2.getString("INDEX_NAME") if (idxName.toLowerCase() != indexName.toLowerCase()) continue @@ -857,6 +812,7 @@ class EntityDbMeta { } } } + } } // if we found all of the index-field field-names then fieldNames will be empty, and we have a full index @@ -864,21 +820,14 @@ class EntityDbMeta { } catch (Exception e) { logger.error("Exception checking to see if index exists for table ${ed.getTableName()}", e) return null - } finally { - if (ikSet1 != null && !ikSet1.isClosed()) ikSet1.close() - if (ikSet2 != null && !ikSet2.isClosed()) ikSet2.close() - if (con != null) con.close() } } Boolean foreignKeyExists(EntityDefinition ed, RelationshipInfo relInfo) { String groupName = ed.getEntityGroupName() EntityDefinition relEd = relInfo.relatedEd - Connection con = null - ResultSet ikSet1 = null - ResultSet ikSet2 = null - try { - con = efi.getConnection(groupName) + try (Connection con = efi.getConnection(groupName)) { + DatabaseMetaData dbData = con.getMetaData() // don't rely on constraint name, look at related table name, keys @@ -887,7 +836,7 @@ class EntityDbMeta { Set fieldNames = new HashSet(keyMap.keySet()) Set fkColsFound = new HashSet() - ikSet1 = dbData.getImportedKeys(null, ed.getSchemaName(), ed.getTableName()) + try (ResultSet ikSet1 = dbData.getImportedKeys(null, ed.getSchemaName(), ed.getTableName())) { while (ikSet1.next()) { String pkTable = ikSet1.getString("PKTABLE_NAME") // logger.info("FK exists [${ed.getFullEntityName()}] - [${relNode."@title"}${relEd.getFullEntityName()}] PKTABLE_NAME [${ikSet.getString("PKTABLE_NAME")}] PKCOLUMN_NAME [${ikSet.getString("PKCOLUMN_NAME")}] FKCOLUMN_NAME [${ikSet.getString("FKCOLUMN_NAME")}]") @@ -902,9 +851,10 @@ class EntityDbMeta { } } } + } if (fieldNames.size() > 0) { // try with lower case table name - ikSet2 = dbData.getImportedKeys(null, ed.getSchemaName(), ed.getTableName().toLowerCase()) + try (ResultSet ikSet2 = dbData.getImportedKeys(null, ed.getSchemaName(), ed.getTableName().toLowerCase())) { while (ikSet2.next()) { String pkTable = ikSet2.getString("PKTABLE_NAME") // logger.info("FK exists [${ed.getFullEntityName()}] - [${relNode."@title"}${relEd.getFullEntityName()}] PKTABLE_NAME [${ikSet.getString("PKTABLE_NAME")}] PKCOLUMN_NAME [${ikSet.getString("PKCOLUMN_NAME")}] FKCOLUMN_NAME [${ikSet.getString("FKCOLUMN_NAME")}]") @@ -919,6 +869,7 @@ class EntityDbMeta { } } } + } } // logger.info("Checking FK exists for entity [${ed.getFullEntityName()}] relationship [${relNode."@title"}${relEd.getFullEntityName()}] fields to match are [${keyMap.keySet()}] FK columns found [${fkColsFound}] final fieldNames (empty for match) [${fieldNames}]") @@ -928,20 +879,12 @@ class EntityDbMeta { } catch (Exception e) { logger.error("Exception checking to see if foreign key exists for table ${ed.getTableName()}", e) return null - } finally { - if (ikSet1 != null && !ikSet1.isClosed()) ikSet1.close() - if (ikSet2 != null && !ikSet2.isClosed()) ikSet2.close() - if (con != null) con.close() } } String getForeignKeyName(EntityDefinition ed, RelationshipInfo relInfo) { String groupName = ed.getEntityGroupName() EntityDefinition relEd = relInfo.relatedEd - Connection con = null - ResultSet ikSet1 = null - ResultSet ikSet2 = null - try { - con = efi.getConnection(groupName) + try (Connection con = efi.getConnection(groupName)) { DatabaseMetaData dbData = con.getMetaData() // don't rely on constraint name, look at related table name, keys @@ -951,7 +894,7 @@ class EntityDbMeta { List fieldNames = new ArrayList(keyMap.keySet()) Map> fieldsByFkName = new HashMap<>() - ikSet1 = dbData.getImportedKeys(null, ed.getSchemaName(), ed.getTableName()) + try (ResultSet ikSet1 = dbData.getImportedKeys(null, ed.getSchemaName(), ed.getTableName())) { while (ikSet1.next()) { String pkTable = ikSet1.getString("PKTABLE_NAME") // logger.info("FK exists [${ed.getFullEntityName()}] - [${relNode."@title"}${relEd.getFullEntityName()}] PKTABLE_NAME [${ikSet.getString("PKTABLE_NAME")}] PKCOLUMN_NAME [${ikSet.getString("PKCOLUMN_NAME")}] FKCOLUMN_NAME [${ikSet.getString("FKCOLUMN_NAME")}]") @@ -968,9 +911,10 @@ class EntityDbMeta { } } } + } if (fieldNames.size() > 0) { // try with lower case table name - ikSet2 = dbData.getImportedKeys(null, ed.getSchemaName(), ed.getTableName().toLowerCase()) + try (ResultSet ikSet2 = dbData.getImportedKeys(null, ed.getSchemaName(), ed.getTableName().toLowerCase())) { while (ikSet2.next()) { String pkTable = ikSet2.getString("PKTABLE_NAME") // logger.info("FK exists [${ed.getFullEntityName()}] - [${relNode."@title"}${relEd.getFullEntityName()}] PKTABLE_NAME [${ikSet.getString("PKTABLE_NAME")}] PKCOLUMN_NAME [${ikSet.getString("PKCOLUMN_NAME")}] FKCOLUMN_NAME [${ikSet.getString("FKCOLUMN_NAME")}]") @@ -987,6 +931,7 @@ class EntityDbMeta { } } } + } } // logger.warn("fieldNames: ${fieldNames}"); logger.warn("fieldsByFkName: ${fieldsByFkName}") @@ -997,10 +942,6 @@ class EntityDbMeta { } catch (Exception e) { logger.error("Exception getting foreign key name for table ${ed.getTableName()}", e) return null - } finally { - if (ikSet1 != null && !ikSet1.isClosed()) ikSet1.close() - if (ikSet2 != null && !ikSet2.isClosed()) ikSet2.close() - if (con != null) con.close() } } @@ -1191,16 +1132,15 @@ class EntityDbMeta { try { // use a short timeout here just in case this is in the middle of stuff going on with tables locked, may happen a lot for FK ops efi.ecfi.transactionFacade.runRequireNew(10, "Error in DB meta data change", useTxForMetaData, true, { - Connection con = null - Statement stmt = null - - try { - con = sharedCon != null ? sharedCon : efi.getConnection(groupName) - stmt = con.createStatement() - records = stmt.executeUpdate(sql.toString()) - } finally { - if (stmt != null) stmt.close() - if (con != null && sharedCon == null) con.close() + if (sharedCon != null) { + try (Statement stmt = sharedCon.createStatement()) { + records = stmt.executeUpdate(sql.toString()) + } + } else { + try (Connection con = efi.getConnection(groupName) + Statement stmt = con.createStatement()) { + records = stmt.executeUpdate(sql.toString()) + } } }) } catch (Throwable t) { diff --git a/framework/src/main/groovy/org/moqui/impl/entity/EntityFacadeImpl.groovy b/framework/src/main/groovy/org/moqui/impl/entity/EntityFacadeImpl.groovy index acd5aaf14..d9477960f 100644 --- a/framework/src/main/groovy/org/moqui/impl/entity/EntityFacadeImpl.groovy +++ b/framework/src/main/groovy/org/moqui/impl/entity/EntityFacadeImpl.groovy @@ -1276,16 +1276,13 @@ class EntityFacadeImpl implements EntityFacade { int records = 0 ecfi.transactionFacade.runRequireNew(30, "Error in DB meta data change", false, true, { XAConnection xacon = null - Connection con = null - Statement stmt = null try { xacon = getConfConnection(confMap) - con = xacon.getConnection() - stmt = con.createStatement() + try (Connection con = xacon.getConnection() + Statement stmt = con.createStatement()) { records = stmt.executeUpdate(sql.toString()) + } } finally { - if (stmt != null) stmt.close() - if (con != null) con.close() if (xacon != null) xacon.close() } }) @@ -1311,20 +1308,15 @@ class EntityFacadeImpl implements EntityFacade { long runSqlCountConf(CharSequence from, CharSequence where, Map confMap) { StringBuilder sqlSb = new StringBuilder("SELECT COUNT(*) FROM ").append(from).append(" WHERE ").append(where) XAConnection xacon = null - Connection con = null - Statement stmt = null - ResultSet rs = null try { xacon = getConfConnection(confMap) - con = xacon.getConnection() - stmt = con.createStatement() - rs = stmt.executeQuery(sqlSb.toString()) + try (Connection con = xacon.getConnection() + Statement stmt = con.createStatement() + ResultSet rs = stmt.executeQuery(sqlSb.toString())) { if (rs.next()) return rs.getLong(1) + } return 0 } finally { - if (stmt != null) stmt.close() - if (rs != null) rs.close() - if (con != null) con.close() if (xacon != null) xacon.close() } } @@ -1572,12 +1564,8 @@ class EntityFacadeImpl implements EntityFacade { // run the SQL now that it is built EntityValueBase newEntityValue = (EntityValueBase) null - Connection connection = (Connection) null - PreparedStatement ps = (PreparedStatement) null - ResultSet rs = (ResultSet) null - try { - connection = getConnection(ed.getEntityGroupName()) - ps = connection.prepareStatement(finalSql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY) + try (Connection connection = getConnection(ed.getEntityGroupName()) + PreparedStatement ps = connection.prepareStatement(finalSql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { for (int i = 0; i < pkSize; i++) { FieldInfo fi = (FieldInfo) pkFieldInfoArray[i] Object fieldValue = values[i] @@ -1586,7 +1574,7 @@ class EntityFacadeImpl implements EntityFacade { boolean queryStats = getQueryStats() long beforeQuery = queryStats ? System.nanoTime() : 0 - rs = ps.executeQuery() + try (ResultSet rs = ps.executeQuery()) { if (queryStats) saveQueryStats(ed, finalSql, System.nanoTime() - beforeQuery, false) if (rs.next()) { @@ -1599,14 +1587,9 @@ class EntityFacadeImpl implements EntityFacade { fi.getResultSetValue(rs, i + 1, valueMap, this) } } + } } catch (SQLException e) { throw new EntityException("Error finding value", e); - } finally { - try { - if (ps != null) ps.close() - if (rs != null) rs.close() - if (connection != null) connection.close(); - } catch (SQLException sqle) { throw new EntityException("Error finding value", sqle); } } return newEntityValue; diff --git a/framework/src/main/groovy/org/moqui/impl/util/JdbcExtractor.java b/framework/src/main/groovy/org/moqui/impl/util/JdbcExtractor.java index ca682a254..f15a0c524 100644 --- a/framework/src/main/groovy/org/moqui/impl/util/JdbcExtractor.java +++ b/framework/src/main/groovy/org/moqui/impl/util/JdbcExtractor.java @@ -60,14 +60,11 @@ public void extract(SimpleEtl etl) throws Exception { this.etl = etl; XAConnection xacon = null; - Connection con = null; - Statement stmt = null; - ResultSet rs = null; try { xacon = eci.getEntityFacade().getConfConnection(confMap); - con = xacon.getConnection(); - stmt = con.createStatement(); - rs = stmt.executeQuery(selectSql); + try (Connection con = xacon.getConnection(); + Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery(selectSql)) { ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String[] columnNames = new String[columnCount]; @@ -84,12 +81,10 @@ public void extract(SimpleEtl etl) throws Exception { break; } } + } } catch (Exception e) { throw new BaseException("Error in SQL query " + selectSql, e); } finally { - if (rs != null) rs.close(); - if (stmt != null) stmt.close(); - if (con != null) con.close(); if (xacon != null) xacon.close(); } }