Skip to content

Commit

Permalink
Use try-with-resources for stream classes
Browse files Browse the repository at this point in the history
    Refactored code to utilize try-with-resources for stream, 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.
  • Loading branch information
dixitdeepak committed Oct 28, 2024
1 parent 8950361 commit b52180b
Show file tree
Hide file tree
Showing 19 changed files with 89 additions and 179 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ class ExecutionContextFactoryImpl implements ExecutionContextFactory {
// get the MoquiInit.properties file
Properties moquiInitProperties = new Properties()
URL initProps = this.class.getClassLoader().getResource("MoquiInit.properties")
if (initProps != null) { InputStream is = initProps.openStream(); moquiInitProperties.load(is); is.close() }
if (initProps != null) { try(InputStream is = initProps.openStream()) { moquiInitProperties.load(is);} }

// if there is a system property use that, otherwise from the properties file
runtimePath = System.getProperty("moqui.runtime")
Expand Down Expand Up @@ -517,9 +517,10 @@ class ExecutionContextFactoryImpl implements ExecutionContextFactory {
try {
if (confSaveFile.exists()) confSaveFile.delete()
if (!confSaveFile.parentFile.exists()) confSaveFile.parentFile.mkdirs()
FileWriter fw = new FileWriter(confSaveFile)
try (FileWriter fw = new FileWriter(confSaveFile)) {
fw.write(confXmlRoot.toString())
fw.close()
}

} catch (Exception e) {
logger.warn("Could not save ${confSaveFile.absolutePath} file: ${e.toString()}")
}
Expand Down Expand Up @@ -1346,8 +1347,7 @@ class ExecutionContextFactoryImpl implements ExecutionContextFactory {
String targetDirLocation = zipFile.getParent()
logger.info("Expanding component archive ${zipRr.getFileName()} to ${targetDirLocation}")

ZipInputStream zipIn = new ZipInputStream(zipRr.openStream())
try {
try (ZipInputStream zipIn = new ZipInputStream(zipRr.openStream())) {
ZipEntry entry = zipIn.getNextEntry()
// iterates over entries in the zip file
while (entry != null) {
Expand All @@ -1357,14 +1357,13 @@ class ExecutionContextFactoryImpl implements ExecutionContextFactory {
File dir = new File(filePath)
dir.mkdir()
} else {
OutputStream os = new FileOutputStream(filePath)
try (OutputStream os = new FileOutputStream(filePath)) {
ObjectUtilities.copyStream(zipIn, os)
}
}
zipIn.closeEntry()
entry = zipIn.getNextEntry()
}
} finally {
zipIn.close()
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -827,23 +827,17 @@ class WebFacadeImpl implements WebFacade {
response.setHeader("Content-Disposition", "attachment; filename=\"${rr.getFileName()}\"; filename*=utf-8''${StringUtilities.encodeAsciiFilename(rr.getFileName())}")
}
if (contentType == null || contentType.isEmpty() || ResourceReference.isBinaryContentType(contentType)) {
InputStream is = rr.openStream()
try (InputStream is = rr.openStream()) {
if (is == null) {
logger.warn("Sending not found response, openStream returned null for location: ${location}")
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found at ${location}")
return
}

try {
OutputStream os = response.outputStream
try {
try (OutputStream os = response.outputStream) {
int totalLen = ObjectUtilities.copyStream(is, os)
logger.info("Streamed ${totalLen} bytes from location ${location}")
} finally {
os.close()
}
} finally {
is.close()
}
}
} else {
String rrText = rr.getText()
Expand Down Expand Up @@ -1386,8 +1380,7 @@ class WebFacadeImpl implements WebFacade {
// first send the empty image
response.setContentType('image/png')
response.setHeader("Content-Disposition", "inline")
OutputStream os = response.outputStream
try { os.write(trackingPng) } finally { os.close() }
try (OutputStream os = response.outputStream) { os.write(trackingPng) }
// mark the message viewed
try {
String emailMessageId = (String) eci.contextStack.get("emailMessageId")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,21 +94,17 @@ private Template makeTemplate(final String location, boolean hasVersion) {
}

Template newTemplate;
Reader templateReader = null;

InputStream is = ecfi.resourceFacade.getLocationStream(location);
try (InputStream is = ecfi.resourceFacade.getLocationStream(location)) {
if (is == null) throw new BaseArtifactException("Template not found at " + location);

try {
templateReader = new InputStreamReader(is, StandardCharsets.UTF_8);
try (Reader templateReader = new InputStreamReader(is, StandardCharsets.UTF_8);) {
newTemplate = new Template(location, templateReader, getFtlConfiguration());
} catch (Exception e) {
throw new BaseArtifactException("Error while initializing template at " + location, e);
} finally {
if (templateReader != null) {
try { templateReader.close(); }
catch (Exception e) { logger.error("Error closing template reader", e); }
}
}
} catch (IOException e) {
throw new BaseArtifactException("Template not found at " + location);
}

if (!hasVersion) templateFtlLocationCache.put(location, newTemplate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,11 @@ class GStringTemplateRenderer implements TemplateRenderer {
if (theTemplate) return theTemplate

Template newTemplate = null
Reader templateReader = null
try {
templateReader = new InputStreamReader(ecfi.resourceFacade.getLocationStream(location))
try (Reader templateReader = new InputStreamReader(ecfi.resourceFacade.getLocationStream(location))) {
GStringTemplateEngine gste = new GStringTemplateEngine()
newTemplate = gste.createTemplate(templateReader)
} catch (Exception e) {
throw new BaseArtifactException("Error while initializing template at [${location}]", e)
} finally {
if (templateReader != null) templateReader.close()
}

if (newTemplate) templateGStringLocationCache.put(location, newTemplate)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,11 @@ class XmlActionsScriptRunner implements ScriptRunner {

String templateLocation = ecfi.confXmlRoot.first("resource-facade").attribute("xml-actions-template-location")
Template newTemplate = null
Reader templateReader = null
try {
templateReader = new InputStreamReader(ecfi.resourceFacade.getLocationStream(templateLocation))
try (Reader templateReader = new InputStreamReader(ecfi.resourceFacade.getLocationStream(templateLocation))) {
newTemplate = new Template(templateLocation, templateReader,
ecfi.resourceFacade.ftlTemplateRenderer.getFtlConfiguration())
} catch (Exception e) {
logger.error("Error while initializing XMLActions template at [${templateLocation}]", e)
} finally {
if (templateReader != null) templateReader.close()
}
xmlActionsTemplate = newTemplate
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,12 @@ class EntityDataDocument {
efi.ecfi.getEci().message.addError(efi.ecfi.resource.expand('File ${filename} already exists.','',[filename:filename]))
return 0
}

PrintWriter pw = new PrintWriter(outFile)

int valuesWritten
try (PrintWriter pw = new PrintWriter(outFile)) {
pw.write("[\n")
int valuesWritten = writeDocumentsToWriter(pw, dataDocumentIds, condition, fromUpdateStamp, thruUpdatedStamp, prettyPrint)
valuesWritten = writeDocumentsToWriter(pw, dataDocumentIds, condition, fromUpdateStamp, thruUpdatedStamp, prettyPrint)
pw.write("{}\n]\n")
pw.close()
}
efi.ecfi.getEci().message.addMessage(efi.ecfi.resource.expand('Wrote ${valuesWritten} documents to file ${filename}','',[valuesWritten:valuesWritten,filename:filename]))
return valuesWritten
}
Expand All @@ -85,11 +84,11 @@ class EntityDataDocument {
}
outFile.createNewFile()

PrintWriter pw = new PrintWriter(outFile)
try (PrintWriter pw = new PrintWriter(outFile)) {
pw.write("[\n")
valuesWritten += writeDocumentsToWriter(pw, [dataDocumentId], condition, fromUpdateStamp, thruUpdatedStamp, prettyPrint)
pw.write("{}\n]\n")
pw.close()
}
efi.ecfi.getEci().message.addMessage(efi.ecfi.resource.expand('Wrote ${valuesWritten} records to file ${filename}','',[valuesWritten:valuesWritten, filename:filename]))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,21 +295,15 @@ class EntityDataLoaderImpl implements EntityDataLoader {

// load the CSV text in its own transaction
if (this.csvText) {
InputStream csvInputStream = new ByteArrayInputStream(csvText.getBytes("UTF-8"))
try {
try (InputStream csvInputStream = new ByteArrayInputStream(csvText.getBytes("UTF-8"))) {
tf.runUseOrBegin(transactionTimeout, "Error loading CSV entity data", { ech.loadFile("csvText", csvInputStream) })
} finally {
if (csvInputStream != null) csvInputStream.close()
}
}

// load the JSON text in its own transaction
if (this.jsonText) {
InputStream jsonInputStream = new ByteArrayInputStream(jsonText.getBytes("UTF-8"))
try {
try (InputStream jsonInputStream = new ByteArrayInputStream(jsonText.getBytes("UTF-8"))) {
tf.runUseOrBegin(transactionTimeout, "Error loading JSON entity data", { ejh.loadFile("jsonText", jsonInputStream) })
} finally {
if (jsonInputStream != null) jsonInputStream.close()
}
}

Expand All @@ -336,12 +330,11 @@ class EntityDataLoaderImpl implements EntityDataLoader {
TransactionFacade tf = efi.ecfi.transactionFacade
boolean beganTransaction = tf.begin(transactionTimeout)
try {
InputStream inputStream = null
try {

try (InputStream inputStream = efi.ecfi.resourceFacade.getLocationStream(location)) {
logger.info("Loading entity data from ${location}")
long beforeTime = System.currentTimeMillis()

inputStream = efi.ecfi.resourceFacade.getLocationStream(location)
if (inputStream == null) throw new BaseException("Data file not found at ${location}")

long recordsLoaded = 0
Expand Down Expand Up @@ -421,8 +414,6 @@ class EntityDataLoaderImpl implements EntityDataLoader {
}
} catch (TypeToSkipException e) {
// nothing to do, this just stops the parsing when we know the file is not in the types we want
} finally {
if (inputStream != null) inputStream.close()
}
} catch (Throwable t) {
tf.rollback(beganTransaction, "Error loading entity data", t)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,11 @@ class EntityDataWriterImpl implements EntityDataWriter {
efi.ecfi.executionContext.message.addError('Cannot write to single CSV file with multiple entity names')
return 0
}

PrintWriter pw = new PrintWriter(outFile)
int valuesWritten
try (PrintWriter pw = new PrintWriter(outFile)) {
// NOTE: don't have to do anything different here for different file types, writer() method will handle that
int valuesWritten = this.writer(pw)
pw.close()
valuesWritten = this.writer(pw)
}
efi.ecfi.executionContext.message.addMessage(efi.ecfi.resource.expand('Wrote ${valuesWritten} records to file ${filename}', '', [valuesWritten:valuesWritten, filename:filename]))
return valuesWritten
}
Expand All @@ -130,9 +130,9 @@ class EntityDataWriterImpl implements EntityDataWriter {
return 0
}

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))
try {
PrintWriter pw = new PrintWriter(out)

try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))
PrintWriter pw = new PrintWriter(out)) {
ZipEntry e = new ZipEntry(filenameWithinZip)
out.putNextEntry(e)
try {
Expand All @@ -143,8 +143,6 @@ class EntityDataWriterImpl implements EntityDataWriter {
} finally {
out.closeEntry()
}
} finally {
out.close()
}
}

Expand Down Expand Up @@ -185,8 +183,7 @@ class EntityDataWriterImpl implements EntityDataWriter {
}
outFile.createNewFile()

PrintWriter pw = new PrintWriter(outFile)
try {
try (PrintWriter pw = new PrintWriter(outFile)) {
startFile(pw, ed)

int curValuesWritten = 0
Expand All @@ -199,8 +196,6 @@ class EntityDataWriterImpl implements EntityDataWriter {

efi.ecfi.getEci().message.addMessage(efi.ecfi.resource.expand('Wrote ${curValuesWritten} records to file ${filename}','',[curValuesWritten:curValuesWritten,filename:filename]))
valuesWritten += curValuesWritten
} finally {
pw.close()
}
}
}
Expand Down Expand Up @@ -240,9 +235,10 @@ class EntityDataWriterImpl implements EntityDataWriter {
if (dependentLevels > 0) efi.createAllAutoReverseManyRelationships()

int valuesWritten = 0
ZipOutputStream out = new ZipOutputStream(outputStream)
try {
PrintWriter pw = new PrintWriter(out)

try (ZipOutputStream out = new ZipOutputStream(outputStream)
PrintWriter pw = new PrintWriter(out)) {

for (String en in entityNames) {
if (skipEntityNames.contains(en)) continue
EntityDefinition ed = efi.getEntityDefinition(en)
Expand Down Expand Up @@ -275,8 +271,6 @@ class EntityDataWriterImpl implements EntityDataWriter {
}
}
}
} finally {
out.close()
}
return valuesWritten
}
Expand Down
21 changes: 6 additions & 15 deletions framework/src/main/groovy/org/moqui/impl/entity/FieldInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -354,19 +354,13 @@ void getResultSetValue(ResultSet rs, int index, LiteStringMap<Object> valueMap,
logger.warn("Got byte array back empty for serialized Object with length [" + originalBytes.length + "] for field [" + name + "] (" + index + ")");
}
if (binaryInput != null) {
ObjectInputStream inStream = null;
try {
inStream = new ObjectInputStream(binaryInput);

try (ObjectInputStream inStream = new ObjectInputStream(binaryInput)) {
obj = inStream.readObject();
} catch (IOException ex) {
if (logger.isTraceEnabled()) logger.trace("Unable to read BLOB from input stream for field [" + name + "] (" + index + "): " + ex.toString());
} catch (ClassNotFoundException ex) {
if (logger.isTraceEnabled()) logger.trace("Class not found: Unable to cast BLOB data to an Java object for field [" + name + "] (" + index + "); most likely because it is a straight byte[], so just using the raw bytes: " + ex.toString());
} finally {
if (inStream != null) {
try { inStream.close(); }
catch (IOException e) { logger.error("Unable to close binary input stream for field [" + name + "] (" + index + "): " + e.toString(), e); }
}
}
}
if (obj != null) {
Expand Down Expand Up @@ -548,17 +542,14 @@ private void setPreparedStatementValue(PreparedStatement ps, int index, Object v
case 10: if (value != null) { ps.setBoolean(index, (Boolean) value); } else { ps.setNull(index, Types.BOOLEAN); } break;
case 11:
if (value != null) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
try (ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);) {
oos.writeObject(value);
oos.close();
byte[] buf = os.toByteArray();
os.close();

ByteArrayInputStream is = new ByteArrayInputStream(buf);
try (ByteArrayInputStream is = new ByteArrayInputStream(buf)) {
ps.setBinaryStream(index, is, buf.length);
is.close();
}
} catch (IOException ex) {
throw new EntityException("Error setting serialized object, for field " + entityName + "." + name, ex);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1215,13 +1215,10 @@ class ScreenForm {
} else if ("list-options".equals(childNode.name)) {
Object listObject = ec.resource.expression(childNode.attribute('list'), null)
if (listObject instanceof EntityListIterator) {
EntityListIterator eli
try {
eli = (EntityListIterator) listObject

try (EntityListIterator eli = (EntityListIterator) listObject) {
EntityValue ev
while ((ev = eli.next()) != null) addFieldOption(options, fieldNode, childNode, ev, ec)
} finally {
eli.close()
}
} else {
String keyAttr = childNode.attribute("key")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -635,9 +635,8 @@ class ScreenRenderImpl implements ScreenRender {
response.setHeader("Cache-Control", "max-age=86400, must-revalidate, public")
}

InputStream is
try {
is = fileResourceRef.openStream()

try (InputStream is = fileResourceRef.openStream()) {
OutputStream os = response.outputStream
int totalLen = ObjectUtilities.copyStream(is, os)

Expand All @@ -647,8 +646,6 @@ class ScreenRenderImpl implements ScreenRender {
resourceStartTime, (System.nanoTime() - startTimeNanos)/1000000.0D, (long) totalLen)
}
if (isTraceEnabled) logger.trace("Sent binary response of length ${totalLen} from file ${fileResourceRef.location} for request to ${screenUrlInstance.url}")
} finally {
if (is != null) is.close()
}
} else {
throw new BaseArtifactException("Tried to get binary content at ${screenUrlInfo.fileResourcePathList} under screen ${screenUrlInfo.targetScreen.location}, but there is no HTTP response available")
Expand Down
Loading

0 comments on commit b52180b

Please sign in to comment.