This is an automated email from the ASF dual-hosted git repository.

dixitdeepak pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/ofbiz-framework.git


The following commit(s) were added to refs/heads/trunk by this push:
     new cf03391ffb Use try-with-resources for owned resources (OFBIZ-13399)
cf03391ffb is described below

commit cf03391ffbc9629dc6a34da69cfd2a9bfa45e869
Author: Deepak Dixit <[email protected]>
AuthorDate: Fri May 22 11:24:49 2026 +0530

    Use try-with-resources for owned resources (OFBIZ-13399)
    
    Replace manual resource closing with try-with-resources in utility code. 
Scope certificate, object serialization, XML URL streams, and sequence JDBC 
resources to their owning
    blocks. Keep caller-owned XML input streams open in UtilProperties.
---
 .../org/apache/ofbiz/base/util/KeyStoreUtil.java   |  43 ++++----
 .../org/apache/ofbiz/base/util/UtilObject.java     |  12 +-
 .../org/apache/ofbiz/base/util/UtilProperties.java |  26 +----
 .../java/org/apache/ofbiz/base/util/UtilXml.java   |   7 +-
 .../org/apache/ofbiz/entity/util/SequenceUtil.java | 121 ++++++++++-----------
 5 files changed, 94 insertions(+), 115 deletions(-)

diff --git 
a/framework/base/src/main/java/org/apache/ofbiz/base/util/KeyStoreUtil.java 
b/framework/base/src/main/java/org/apache/ofbiz/base/util/KeyStoreUtil.java
index 91b79239bc..196a914d38 100755
--- a/framework/base/src/main/java/org/apache/ofbiz/base/util/KeyStoreUtil.java
+++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/KeyStoreUtil.java
@@ -188,7 +188,9 @@ public final class KeyStoreUtil {
     }
 
     public static Certificate pemToCert(File certFile) throws IOException, 
CertificateException {
-        return pemToCert(new FileInputStream(certFile));
+        try (InputStream is = new FileInputStream(certFile)) {
+            return pemToCert(is);
+        }
     }
 
     public static Certificate pemToCert(InputStream is) throws IOException, 
CertificateException {
@@ -201,31 +203,30 @@ public final class KeyStoreUtil {
 
         BufferedReader reader = new BufferedReader(r);
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        PrintStream ps = new PrintStream(baos, false, 
StandardCharsets.UTF_8.toString());
-
-        String line;
+        try (PrintStream ps = new PrintStream(baos, false, 
StandardCharsets.UTF_8.toString())) {
+            String line;
 
-        // ignore up to the header
-        while ((line = reader.readLine()) != null && !line.equals(header)) {
-            Debug.logVerbose("Ignore up to the header...", MODULE);
-        }
+            // ignore up to the header
+            while ((line = reader.readLine()) != null && !line.equals(header)) 
{
+                Debug.logVerbose("Ignore up to the header...", MODULE);
+            }
 
-        // no header found
-        if (line == null) {
-            throw new IOException("Error reading certificate, missing BEGIN 
boundary");
-        }
+            // no header found
+            if (line == null) {
+                throw new IOException("Error reading certificate, missing 
BEGIN boundary");
+            }
 
-        // in between the header and footer is the actual certificate
-        while ((line = reader.readLine()) != null && !line.equals(footer)) {
-            line = line.replaceAll("\\s", "");
-            ps.print(line);
-        }
+            // in between the header and footer is the actual certificate
+            while ((line = reader.readLine()) != null && !line.equals(footer)) 
{
+                line = line.replaceAll("\\s", "");
+                ps.print(line);
+            }
 
-        // no footer found
-        if (line == null) {
-            throw new IOException("Error reading certificate, missing END 
boundary");
+            // no footer found
+            if (line == null) {
+                throw new IOException("Error reading certificate, missing END 
boundary");
+            }
         }
-        ps.close();
 
         // decode the buffer to a X509Certificate
 
diff --git 
a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilObject.java 
b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilObject.java
index a9b7ac2a0f..00fb095a72 100644
--- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilObject.java
+++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilObject.java
@@ -64,13 +64,11 @@ public final class UtilObject {
      * @throws IOException
      */
     public static long getByteCount(Object obj) throws IOException {
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        ObjectOutputStream oos = new ObjectOutputStream(bos);
-        oos.writeObject(obj);
-        oos.flush();
-        long size = bos.size();
-        bos.close();
-        return size;
+        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
+            oos.writeObject(obj);
+            oos.flush();
+            return bos.size();
+        }
     }
 
     /** Deserialize a byte array back to an object; if there is an error, it 
is logged, and null is returned. */
diff --git 
a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java 
b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java
index 83c99a7cad..ce9b63e742 100644
--- 
a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java
+++ 
b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilProperties.java
@@ -303,26 +303,18 @@ public final class UtilProperties implements Serializable 
{
      */
     public static Properties createProperties(String fileName) {
         Assert.notEmpty("fileName", fileName);
-        InputStream inStream = null;
         try {
             URL url = 
Thread.currentThread().getContextClassLoader().getResource(fileName);
             if (url == null) {
                 return null;
             }
-            inStream = url.openStream();
-            Properties properties = new Properties();
-            properties.load(inStream);
-            return properties;
+            try (InputStream inStream = url.openStream()) {
+                Properties properties = new Properties();
+                properties.load(inStream);
+                return properties;
+            }
         } catch (Exception e) {
             throw new IllegalStateException("Exception thrown while reading " 
+ fileName + ": " + e);
-        } finally {
-            if (inStream != null) {
-                try {
-                    inStream.close();
-                } catch (IOException e) {
-                    Debug.logError(e, "Exception thrown while closing 
InputStream", MODULE);
-                }
-            }
         }
     }
 
@@ -963,10 +955,8 @@ public final class UtilProperties implements Serializable {
         Document doc = null;
         try {
             doc = UtilXml.readXmlDocument(in, true, "XML Properties file");
-            in.close();
         } catch (Exception e) {
             Debug.logWarning(e, "XML file for locale " + locale + " could not 
be loaded.", MODULE);
-            in.close();
             return null;
         }
         Element resourceElement = doc.getDocumentElement();
@@ -1138,11 +1128,7 @@ public final class UtilProperties implements 
Serializable {
         }
         @Override
         public synchronized void loadFromXML(InputStream in) throws 
IOException, InvalidPropertiesFormatException {
-            try {
-                xmlToProperties(in, null, this);
-            } finally {
-                in.close();
-            }
+            xmlToProperties(in, null, this);
         }
     }
 }
diff --git 
a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilXml.java 
b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilXml.java
index c6e0440b01..8fff8b7727 100644
--- a/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilXml.java
+++ b/framework/base/src/main/java/org/apache/ofbiz/base/util/UtilXml.java
@@ -429,10 +429,9 @@ public final class UtilXml {
             throw new IOException("Domain " + urlHost + " not accepted to 
prevent host header injection."
                     + " You need to set host-headers-allowed property in 
security.properties file.");
         }
-        InputStream is = url.openStream();
-        Document document = readXmlDocument(is, validate, url.toString(), 
withPosition);
-        is.close();
-        return document;
+        try (InputStream is = url.openStream()) {
+            return readXmlDocument(is, validate, url.toString(), withPosition);
+        }
     }
 
     public static Document readXmlDocument(InputStream is, String 
docDescription)
diff --git 
a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/SequenceUtil.java 
b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/SequenceUtil.java
index 81b6b3802a..d77e6e8d52 100644
--- 
a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/SequenceUtil.java
+++ 
b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/SequenceUtil.java
@@ -201,76 +201,72 @@ public class SequenceUtil {
                 try {
                     beganTransaction = TransactionUtil.begin();
 
-                    Connection connection = null;
-                    Statement stmt = null;
-                    ResultSet rs = null;
-
-                    try {
-                        connection = 
TransactionFactoryLoader.getInstance().getConnection(SequenceUtil.this.helperInfo);
-                    } catch (SQLException sqle) {
-                        Debug.logWarning("Unable to establish a connection 
with the database. Error was:" + sqle.toString(), MODULE);
-                        throw sqle;
-                    } catch (GenericEntityException e) {
-                        Debug.logWarning("Unable to establish a connection 
with the database. Error was: " + e.toString(), MODULE);
-                        throw e;
-                    }
-                    if (connection == null) {
-                        throw new GenericEntityException("Unable to establish 
a connection with the database, connection was null...");
-                    }
+                    boolean committed = false;
+                    boolean connectionAvailable = false;
+                    try (Connection connection = 
TransactionFactoryLoader.getInstance().getConnection(SequenceUtil.this.helperInfo))
 {
+                        if (connection == null) {
+                            throw new GenericEntityException("Unable to 
establish a connection with the database, connection was null...");
+                        }
+                        connectionAvailable = true;
+
+                        try (Statement stmt = connection.createStatement()) {
+                            String sql = null;
+                            // 1 - run an update with no changes to get a lock 
on the record
+                            if (stmt.executeUpdate(updateForLockStatement) <= 
0) {
+                                Debug.logWarning("Lock failed; no sequence row 
was found, will try to add a new one for sequence: " + seqName,
+                                        MODULE);
+                                sql = "INSERT INTO " + 
SequenceUtil.this.tableName + " (" + SequenceUtil.this.nameColName + ", "
+                                        + SequenceUtil.this.idColName + ") 
VALUES ('" + this.seqName + "', " + START_SEQ_ID + ")";
+                                try {
+                                    stmt.executeUpdate(sql);
+                                } catch (SQLException sqle) {
+                                    // insert failed: this means that another 
thread inserted the record;
+                                    // then retry to run an update with no 
changes to
+                                    // get a lock on the record
+                                    if 
(stmt.executeUpdate(updateForLockStatement) <= 0) {
+                                        // This should never happen
+                                        throw new GenericEntityException("No 
rows changed when trying insert new sequence: " + seqName);
+                                    }
 
-                    try {
-                        stmt = connection.createStatement();
-                        String sql = null;
-                        // 1 - run an update with no changes to get a lock on 
the record
-                        if (stmt.executeUpdate(updateForLockStatement) <= 0) {
-                            Debug.logWarning("Lock failed; no sequence row was 
found, will try to add a new one for sequence: " + seqName, MODULE);
-                            sql = "INSERT INTO " + SequenceUtil.this.tableName 
+ " (" + SequenceUtil.this.nameColName + ", "
-                                    + SequenceUtil.this.idColName + ") VALUES 
('" + this.seqName + "', " + START_SEQ_ID + ")";
-                            try {
-                                stmt.executeUpdate(sql);
-                            } catch (SQLException sqle) {
-                                // insert failed: this means that another 
thread inserted the record; then retry to run an update with no changes to
-                                // get a lock on the record
-                                if (stmt.executeUpdate(updateForLockStatement) 
<= 0) {
-                                    // This should never happen
-                                    throw new GenericEntityException("No rows 
changed when trying insert new sequence: " + seqName);
                                 }
-
                             }
-                        }
-                        // 2 - select the record (now locked) to get the 
curSeqId
-                        rs = stmt.executeQuery(selectSequenceStatement);
-                        boolean sequenceFound = rs.next();
-                        if (sequenceFound) {
-                            curSeqId = rs.getLong(SequenceUtil.this.idColName);
-                        }
-                        rs.close();
-                        if (!sequenceFound) {
-                            throw new GenericEntityException("Failed to find 
the sequence record for sequence: " + seqName);
-                        }
-                        // 3 - increment the sequence
-                        sql = "UPDATE " + SequenceUtil.this.tableName + " SET 
" + SequenceUtil.this.idColName + "=" + SequenceUtil.this.idColName
-                                + "+" + bankSize + " WHERE " + 
SequenceUtil.this.nameColName + "='" + this.seqName + "'";
-                        if (stmt.executeUpdate(sql) <= 0) {
-                            throw new GenericEntityException("Update failed, 
no rows changes for seqName: " + seqName);
-                        }
+                            // 2 - select the record (now locked) to get the 
curSeqId
+                            boolean sequenceFound;
+                            try (ResultSet rs = 
stmt.executeQuery(selectSequenceStatement)) {
+                                sequenceFound = rs.next();
+                                if (sequenceFound) {
+                                    curSeqId = 
rs.getLong(SequenceUtil.this.idColName);
+                                }
+                            }
+                            if (!sequenceFound) {
+                                throw new GenericEntityException("Failed to 
find the sequence record for sequence: " + seqName);
+                            }
+                            // 3 - increment the sequence
+                            sql = "UPDATE " + SequenceUtil.this.tableName + " 
SET " + SequenceUtil.this.idColName + "=" + SequenceUtil.this.idColName
+                                    + "+" + bankSize + " WHERE " + 
SequenceUtil.this.nameColName + "='" + this.seqName + "'";
+                            if (stmt.executeUpdate(sql) <= 0) {
+                                throw new GenericEntityException("Update 
failed, no rows changes for seqName: " + seqName);
+                            }
 
-                        TransactionUtil.commit(beganTransaction);
+                            TransactionUtil.commit(beganTransaction);
+                            committed = true;
+                        }
 
                     } catch (SQLException sqle) {
-                        Debug.logWarning(sqle, "SQL Exception:" + 
sqle.getMessage(), MODULE);
-                        throw sqle;
-                    } finally {
-                        try {
-                            if (stmt != null) stmt.close();
-                        } catch (SQLException sqle) {
-                            Debug.logWarning(sqle, "Error closing statement in 
sequence util", MODULE);
+                        if (committed) {
+                            Debug.logWarning(sqle, "Error closing database 
resources in sequence util", MODULE);
+                        } else if (!connectionAvailable) {
+                            Debug.logWarning("Unable to establish a connection 
with the database. Error was:" + sqle.toString(), MODULE);
+                            throw sqle;
+                        } else {
+                            Debug.logWarning(sqle, "SQL Exception:" + 
sqle.getMessage(), MODULE);
+                            throw sqle;
                         }
-                        try {
-                            connection.close();
-                        } catch (SQLException sqle) {
-                            Debug.logWarning(sqle, "Error closing connection 
in sequence util", MODULE);
+                    } catch (GenericEntityException e) {
+                        if (!connectionAvailable) {
+                            Debug.logWarning("Unable to establish a connection 
with the database. Error was: " + e.toString(), MODULE);
                         }
+                        throw e;
                     }
                 } catch (SQLException | GenericEntityException e) {
                     // reset the sequence fields and return (note: it would be 
better to throw an exception)
@@ -313,4 +309,3 @@ public class SequenceUtil {
         }
     }
 }
-

Reply via email to