WW-4515 Convert try blocks to try-with-resources

Project: http://git-wip-us.apache.org/repos/asf/struts/repo
Commit: http://git-wip-us.apache.org/repos/asf/struts/commit/3fab155b
Tree: http://git-wip-us.apache.org/repos/asf/struts/tree/3fab155b
Diff: http://git-wip-us.apache.org/repos/asf/struts/diff/3fab155b

Branch: refs/heads/master
Commit: 3fab155b4cc530ca3ca0b69299ddcb348eb5f26d
Parents: bf15ad2
Author: Aaron Johnson <[email protected]>
Authored: Wed Jun 17 09:24:08 2015 -0500
Committer: Aaron Johnson <[email protected]>
Committed: Wed Jun 17 09:24:08 2015 -0500

----------------------------------------------------------------------
 .../apache/struts2/components/Component.java    | 11 +++---
 .../struts2/config/PropertiesSettings.java      | 12 +-----
 .../struts2/dispatcher/PlainTextResult.java     | 19 ++--------
 .../apache/struts2/dispatcher/StreamResult.java | 16 ++------
 .../JakartaStreamMultiPartRequest.java          | 21 +---------
 .../debugging/DebuggingInterceptor.java         |  9 ++---
 .../struts2/util/FastByteArrayOutputStream.java | 12 +-----
 .../views/freemarker/FreemarkerManager.java     | 15 +-------
 .../struts2/views/jsp/StrutsBodyTagSupport.java | 10 ++---
 .../test/java/org/apache/struts2/TestUtils.java | 13 +++----
 .../struts2/dispatcher/PlainTextResultTest.java | 40 +++++---------------
 .../struts2/views/jsp/AbstractUITagTest.java    | 15 ++++----
 .../jasperreports/JasperReportsResult.java      | 38 ++++++-------------
 .../struts2/convention/Java8ClassFinder.java    |  5 +--
 .../DefaultOValValidationManager.java           | 20 ++++------
 .../org/apache/struts2/sitegraph/SiteGraph.java | 21 +++++-----
 .../sitegraph/entities/FileBasedView.java       |  6 +--
 .../apache/struts2/sitegraph/SiteGraphTest.java | 15 ++++----
 .../xwork2/interceptor/ExceptionHolder.java     | 25 +++++-------
 .../xwork2/util/finder/DefaultClassFinder.java  |  5 +--
 .../xwork2/util/finder/ResourceFinder.java      | 21 +---------
 .../validator/DefaultValidatorFactory.java      |  3 +-
 .../opensymphony/xwork2/util/UrlUtilTest2.java  |  8 +---
 .../DefaultValidatorFileParserTest.java         |  9 +----
 24 files changed, 99 insertions(+), 270 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/main/java/org/apache/struts2/components/Component.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/struts2/components/Component.java 
b/core/src/main/java/org/apache/struts2/components/Component.java
index 1853ed8..b34178d 100644
--- a/core/src/main/java/org/apache/struts2/components/Component.java
+++ b/core/src/main/java/org/apache/struts2/components/Component.java
@@ -465,12 +465,11 @@ public class Component {
      * @return the exception as a string.
      */
     protected String toString(Throwable t) {
-        FastByteArrayOutputStream bout = new FastByteArrayOutputStream();
-        PrintWriter wrt = new PrintWriter(bout);
-        t.printStackTrace(wrt);
-        wrt.close();
-
-        return bout.toString();
+        try (FastByteArrayOutputStream bout = new FastByteArrayOutputStream();
+                PrintWriter wrt = new PrintWriter(bout)) {
+            t.printStackTrace(wrt);
+            return bout.toString();
+        }
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/main/java/org/apache/struts2/config/PropertiesSettings.java
----------------------------------------------------------------------
diff --git 
a/core/src/main/java/org/apache/struts2/config/PropertiesSettings.java 
b/core/src/main/java/org/apache/struts2/config/PropertiesSettings.java
index 06bc744..7a136cb 100644
--- a/core/src/main/java/org/apache/struts2/config/PropertiesSettings.java
+++ b/core/src/main/java/org/apache/struts2/config/PropertiesSettings.java
@@ -64,20 +64,10 @@ class PropertiesSettings implements Settings {
         settings = new LocatableProperties(new LocationImpl(null, 
settingsUrl.toString()));
 
         // Load settings
-        InputStream in = null;
-        try {
-            in = settingsUrl.openStream();
+        try (InputStream in = settingsUrl.openStream()) {
             settings.load(in);
         } catch (IOException e) {
             throw new StrutsException("Could not load " + name + ".properties: 
" + e, e);
-        } finally {
-            if(in != null) {
-                try {
-                    in.close();
-                } catch(IOException io) {
-                       LOG.warn("Unable to close input stream", io);
-                }
-            }
         }
     }
 

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/main/java/org/apache/struts2/dispatcher/PlainTextResult.java
----------------------------------------------------------------------
diff --git 
a/core/src/main/java/org/apache/struts2/dispatcher/PlainTextResult.java 
b/core/src/main/java/org/apache/struts2/dispatcher/PlainTextResult.java
index c27e078..8d36bf6 100644
--- a/core/src/main/java/org/apache/struts2/dispatcher/PlainTextResult.java
+++ b/core/src/main/java/org/apache/struts2/dispatcher/PlainTextResult.java
@@ -122,24 +122,11 @@ public class PlainTextResult extends StrutsResultSupport {
         applyAdditionalHeaders(response);
         String location = adjustLocation(finalLocation);
 
-        PrintWriter writer = response.getWriter();
-        InputStreamReader reader = null;
-        try {
-            InputStream resourceAsStream = readStream(invocation, location);
+        try (PrintWriter writer = response.getWriter();
+                InputStream resourceAsStream = readStream(invocation, 
location);
+                InputStreamReader reader = new 
InputStreamReader(resourceAsStream, charset == null ? Charset.defaultCharset() 
: charset)) {
             logWrongStream(finalLocation, resourceAsStream);
-            if (charset != null) {
-                reader = new InputStreamReader(resourceAsStream, charset);
-            } else {
-                reader = new InputStreamReader(resourceAsStream);
-            }
             sendStream(writer, reader);
-        } finally {
-            if (reader != null)
-                reader.close();
-            if (writer != null) {
-                writer.flush();
-                writer.close();
-            }
         }
     }
 

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/main/java/org/apache/struts2/dispatcher/StreamResult.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/struts2/dispatcher/StreamResult.java 
b/core/src/main/java/org/apache/struts2/dispatcher/StreamResult.java
index 13a5c3c..4d51223 100644
--- a/core/src/main/java/org/apache/struts2/dispatcher/StreamResult.java
+++ b/core/src/main/java/org/apache/struts2/dispatcher/StreamResult.java
@@ -221,9 +221,9 @@ public class StreamResult extends StrutsResultSupport {
         // Override any parameters using values on the stack
         resolveParamsFromStack(invocation.getStack(), invocation);
 
-        OutputStream oOutput = null;
-
-        try {
+        // Find the Response in context
+        HttpServletResponse oResponse = (HttpServletResponse) 
invocation.getInvocationContext().get(HTTP_RESPONSE);
+        try (OutputStream oOutput = oResponse.getOutputStream()) {
             if (inputStream == null) {
                 // Find the inputstream from the invocation variable stack
                 inputStream = (InputStream) 
invocation.getStack().findValue(conditionalParse(inputName, invocation));
@@ -236,9 +236,6 @@ public class StreamResult extends StrutsResultSupport {
                 throw new IllegalArgumentException(msg);
             }
 
-            // Find the Response in context
-            HttpServletResponse oResponse = (HttpServletResponse) 
invocation.getInvocationContext().get(HTTP_RESPONSE);
-
             // Set the content type
             if (contentCharSet != null && ! contentCharSet.equals("")) {
                 oResponse.setContentType(conditionalParse(contentType, 
invocation)+";charset="+contentCharSet);
@@ -273,9 +270,6 @@ public class StreamResult extends StrutsResultSupport {
                 oResponse.addHeader("Cache-Control", "no-cache");
             }
 
-            // Get the outputstream
-            oOutput = oResponse.getOutputStream();
-
             LOG.debug("Streaming result [{}] type=[{}] length=[{}] 
content-disposition=[{}] charset=[{}]",
                     inputName, contentType, contentLength, contentDisposition, 
contentCharSet);
 
@@ -291,10 +285,6 @@ public class StreamResult extends StrutsResultSupport {
             // Flush
             oOutput.flush();
         }
-        finally {
-            if (inputStream != null) inputStream.close();
-            if (oOutput != null) oOutput.close();
-        }
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/main/java/org/apache/struts2/dispatcher/multipart/JakartaStreamMultiPartRequest.java
----------------------------------------------------------------------
diff --git 
a/core/src/main/java/org/apache/struts2/dispatcher/multipart/JakartaStreamMultiPartRequest.java
 
b/core/src/main/java/org/apache/struts2/dispatcher/multipart/JakartaStreamMultiPartRequest.java
index e65973f..2f92340 100644
--- 
a/core/src/main/java/org/apache/struts2/dispatcher/multipart/JakartaStreamMultiPartRequest.java
+++ 
b/core/src/main/java/org/apache/struts2/dispatcher/multipart/JakartaStreamMultiPartRequest.java
@@ -449,31 +449,14 @@ public class JakartaStreamMultiPartRequest implements 
MultiPartRequest {
      */
     private boolean streamFileToDisk(FileItemStream itemStream, File file) 
throws IOException {
         boolean result = false;
-        InputStream input = itemStream.openStream();
-        OutputStream output = null;
-        try {
-            output = new BufferedOutputStream(new FileOutputStream(file), 
bufferSize);
+        try (InputStream input = itemStream.openStream();
+                OutputStream output = new BufferedOutputStream(new 
FileOutputStream(file), bufferSize)) {
             byte[] buffer = new byte[bufferSize];
             LOG.debug("Streaming file using buffer size {}.", bufferSize);
             for (int length = 0; ((length = input.read(buffer)) > 0); ) {
                 output.write(buffer, 0, length);
             }
             result = true;
-        } finally {
-            if (output != null) {
-                try {
-                    output.close();
-                } catch (IOException e) {
-                    LOG.warn("Error occurred during closing of OutputStream.", 
e);
-                }
-            }
-            if (input != null) {
-                try {
-                    input.close();
-                } catch (IOException e) {
-                    LOG.warn("Error occurred during closing of InputStream.", 
e);
-                }
-            }
         }
         return result;
     }

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/main/java/org/apache/struts2/interceptor/debugging/DebuggingInterceptor.java
----------------------------------------------------------------------
diff --git 
a/core/src/main/java/org/apache/struts2/interceptor/debugging/DebuggingInterceptor.java
 
b/core/src/main/java/org/apache/struts2/interceptor/debugging/DebuggingInterceptor.java
index 7ea1fed..5a88577 100644
--- 
a/core/src/main/java/org/apache/struts2/interceptor/debugging/DebuggingInterceptor.java
+++ 
b/core/src/main/java/org/apache/struts2/interceptor/debugging/DebuggingInterceptor.java
@@ -192,11 +192,9 @@ public class DebuggingInterceptor extends 
AbstractInterceptor {
                 HttpServletResponse res = ServletActionContext.getResponse();
                 res.setContentType("text/plain");
 
-                try {
-                    PrintWriter writer =
-                            ServletActionContext.getResponse().getWriter();
+                try (PrintWriter writer =
+                            ServletActionContext.getResponse().getWriter()) {
                     writer.print(stack.findValue(cmd));
-                    writer.close();
                 } catch (IOException ex) {
                     ex.printStackTrace();
                 }
@@ -213,8 +211,7 @@ public class DebuggingInterceptor extends 
AbstractInterceptor {
                             ValueStack stack = (ValueStack) 
ctx.get(ActionContext.VALUE_STACK);
                             Object rootObject = 
stack.findValue(rootObjectExpression);
                             
-                            try {
-                                StringWriter writer = new StringWriter();
+                            try (StringWriter writer = new StringWriter()) {
                                 ObjectToHTMLWriter htmlWriter = new 
ObjectToHTMLWriter(writer);
                                 htmlWriter.write(reflectionProvider, 
rootObject, rootObjectExpression);
                                 String html = writer.toString();

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/main/java/org/apache/struts2/util/FastByteArrayOutputStream.java
----------------------------------------------------------------------
diff --git 
a/core/src/main/java/org/apache/struts2/util/FastByteArrayOutputStream.java 
b/core/src/main/java/org/apache/struts2/util/FastByteArrayOutputStream.java
index 00fb12f..8645df7 100644
--- a/core/src/main/java/org/apache/struts2/util/FastByteArrayOutputStream.java
+++ b/core/src/main/java/org/apache/struts2/util/FastByteArrayOutputStream.java
@@ -133,20 +133,10 @@ public class FastByteArrayOutputStream extends 
OutputStream {
      * This method is need only for debug. And needed for tests generated 
files.
      */
     private void writeToFile() {
-        FileOutputStream fileOutputStream = null;
-        try {
-            fileOutputStream = new 
FileOutputStream(File.createTempFile(getClass().getName() + 
System.currentTimeMillis(), ".log"));
+        try (FileOutputStream fileOutputStream = new 
FileOutputStream(File.createTempFile(getClass().getName() + 
System.currentTimeMillis(), ".log"))){
             writeTo(fileOutputStream);
         } catch (IOException e) {
             // Ignore
-        } finally {
-            if (fileOutputStream != null) {
-                try {
-                    fileOutputStream.close();
-                } catch (IOException e) {
-                    // Ignore
-                }
-            }
         }
     }
 

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/main/java/org/apache/struts2/views/freemarker/FreemarkerManager.java
----------------------------------------------------------------------
diff --git 
a/core/src/main/java/org/apache/struts2/views/freemarker/FreemarkerManager.java 
b/core/src/main/java/org/apache/struts2/views/freemarker/FreemarkerManager.java
index f32a5a6..375a726 100644
--- 
a/core/src/main/java/org/apache/struts2/views/freemarker/FreemarkerManager.java
+++ 
b/core/src/main/java/org/apache/struts2/views/freemarker/FreemarkerManager.java
@@ -436,12 +436,7 @@ public class FreemarkerManager {
      * @see freemarker.template.Configuration#setSettings for the definition 
of valid settings
      */
     protected void loadSettings(ServletContext servletContext) {
-        InputStream in = null;
-
-        try {
-
-            in = 
fileManager.loadFile(ClassLoaderUtil.getResource("freemarker.properties", 
getClass()));
-
+        try (InputStream in = 
fileManager.loadFile(ClassLoaderUtil.getResource("freemarker.properties", 
getClass()))){
             if (in != null) {
                 Properties p = new Properties();
                 p.load(in);
@@ -465,14 +460,6 @@ public class FreemarkerManager {
             LOG.error("Error while loading freemarker settings from 
/freemarker.properties", e);
         } catch (TemplateException e) {
             LOG.error("Error while loading freemarker settings from 
/freemarker.properties", e);
-        } finally {
-            if (in != null) {
-                try {
-                    in.close();
-                } catch(IOException io) {
-                    LOG.warn("Unable to close input stream", io);
-                }
-            }
         }
     }
 

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/main/java/org/apache/struts2/views/jsp/StrutsBodyTagSupport.java
----------------------------------------------------------------------
diff --git 
a/core/src/main/java/org/apache/struts2/views/jsp/StrutsBodyTagSupport.java 
b/core/src/main/java/org/apache/struts2/views/jsp/StrutsBodyTagSupport.java
index 7dc9bd2..484c317 100644
--- a/core/src/main/java/org/apache/struts2/views/jsp/StrutsBodyTagSupport.java
+++ b/core/src/main/java/org/apache/struts2/views/jsp/StrutsBodyTagSupport.java
@@ -66,12 +66,12 @@ public class StrutsBodyTagSupport extends BodyTagSupport {
     }
 
     protected String toString(Throwable t) {
-        FastByteArrayOutputStream bout = new FastByteArrayOutputStream();
-        PrintWriter wrt = new PrintWriter(bout);
-        t.printStackTrace(wrt);
-        wrt.close();
+        try (FastByteArrayOutputStream bout = new FastByteArrayOutputStream();
+                PrintWriter wrt = new PrintWriter(bout)) {
+            t.printStackTrace(wrt);
 
-        return bout.toString();
+            return bout.toString();
+        }
     }
 
     protected String getBody() {

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/test/java/org/apache/struts2/TestUtils.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/struts2/TestUtils.java 
b/core/src/test/java/org/apache/struts2/TestUtils.java
index 001f98d..02fe8b5 100644
--- a/core/src/test/java/org/apache/struts2/TestUtils.java
+++ b/core/src/test/java/org/apache/struts2/TestUtils.java
@@ -82,16 +82,15 @@ public class TestUtils {
         }
 
         StringBuilder buffer = new StringBuilder(128);
-        InputStream in = url.openStream();
-        byte[] buf = new byte[4096];
-        int nbytes;
+        try (InputStream in = url.openStream()) {
+            byte[] buf = new byte[4096];
+            int nbytes;
 
-        while((nbytes = in.read(buf)) > 0) {
-            buffer.append(new String(buf, 0, nbytes));
+            while ((nbytes = in.read(buf)) > 0) {
+                buffer.append(new String(buf, 0, nbytes));
+            }
         }
 
-        in.close();
-
         return buffer.toString();
     }
 }

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/test/java/org/apache/struts2/dispatcher/PlainTextResultTest.java
----------------------------------------------------------------------
diff --git 
a/core/src/test/java/org/apache/struts2/dispatcher/PlainTextResultTest.java 
b/core/src/test/java/org/apache/struts2/dispatcher/PlainTextResultTest.java
index b2fadaa..959458a 100644
--- a/core/src/test/java/org/apache/struts2/dispatcher/PlainTextResultTest.java
+++ b/core/src/test/java/org/apache/struts2/dispatcher/PlainTextResultTest.java
@@ -56,13 +56,11 @@ public class PlainTextResultTest extends 
StrutsInternalTestCase {
 
         response.setExpectedContentType("text/plain");
         response.setExpectedHeader("Content-Disposition", "inline");
-        InputStream jspResourceInputStream =
+
+        try (InputStream jspResourceInputStream =
             ClassLoaderUtil.getResourceAsStream(
                 "org/apache/struts2/dispatcher/someJspFile.jsp",
-                PlainTextResultTest.class);
-
-
-        try {
+                PlainTextResultTest.class)) {
             servletContext.setResourceAsStream(jspResourceInputStream);
             result.execute(invocation);
 
@@ -71,9 +69,6 @@ public class PlainTextResultTest extends 
StrutsInternalTestCase {
                     
readAsString("org/apache/struts2/dispatcher/someJspFile.jsp"), true);
             assertEquals(r, e);
         }
-        finally {
-            jspResourceInputStream.close();
-        }
     }
 
     public void testPlainTextWithoutSlash() throws Exception {
@@ -82,11 +77,9 @@ public class PlainTextResultTest extends 
StrutsInternalTestCase {
 
         response.setExpectedContentType("text/plain");
         response.setExpectedHeader("Content-Disposition", "inline");
-        InputStream jspResourceInputStream =
-            
ClassLoaderUtil.getResourceAsStream("org/apache/struts2/dispatcher/someJspFile.jsp",
 PlainTextResultTest.class);
-
 
-        try {
+        try (InputStream jspResourceInputStream =
+            
ClassLoaderUtil.getResourceAsStream("org/apache/struts2/dispatcher/someJspFile.jsp",
 PlainTextResultTest.class)) {
             servletContext.setResourceAsStream(jspResourceInputStream);
             result.execute(invocation);
 
@@ -94,9 +87,6 @@ public class PlainTextResultTest extends 
StrutsInternalTestCase {
             String e = 
AbstractUITagTest.normalize(readAsString("org/apache/struts2/dispatcher/someJspFile.jsp"),
 true);
             assertEquals(r, e);
         }
-        finally {
-            jspResourceInputStream.close();
-        }
     }
 
     public void testPlainTextWithEncoding() throws Exception {
@@ -106,13 +96,11 @@ public class PlainTextResultTest extends 
StrutsInternalTestCase {
 
         response.setExpectedContentType("text/plain; charset=UTF-8");
         response.setExpectedHeader("Content-Disposition", "inline");
-        InputStream jspResourceInputStream =
+
+        try (InputStream jspResourceInputStream =
             ClassLoaderUtil.getResourceAsStream(
                 "org/apache/struts2/dispatcher/someJspFile.jsp",
-                PlainTextResultTest.class);
-
-
-        try {
+                PlainTextResultTest.class)) {
             servletContext.setResourceAsStream(jspResourceInputStream);
             result.execute(invocation);
 
@@ -121,15 +109,10 @@ public class PlainTextResultTest extends 
StrutsInternalTestCase {
                     
readAsString("org/apache/struts2/dispatcher/someJspFile.jsp"), true);
             assertEquals(r, e);
         }
-        finally {
-            jspResourceInputStream.close();
-        }
     }
 
     protected String readAsString(String resource) throws Exception {
-        InputStream is = null;
-        try {
-            is = ClassLoaderUtil.getResourceAsStream(resource, 
PlainTextResultTest.class);
+        try (InputStream is = ClassLoaderUtil.getResourceAsStream(resource, 
PlainTextResultTest.class)) {
             int sizeRead = 0;
             byte[] buffer = new byte[1024];
             StringBuilder stringBuilder = new StringBuilder();
@@ -138,11 +121,6 @@ public class PlainTextResultTest extends 
StrutsInternalTestCase {
             }
             return stringBuilder.toString();
         }
-        finally {
-            if (is != null)
-                is.close();
-        }
-
     }
 
 

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/core/src/test/java/org/apache/struts2/views/jsp/AbstractUITagTest.java
----------------------------------------------------------------------
diff --git 
a/core/src/test/java/org/apache/struts2/views/jsp/AbstractUITagTest.java 
b/core/src/test/java/org/apache/struts2/views/jsp/AbstractUITagTest.java
index 106ba5f..02e1f96 100644
--- a/core/src/test/java/org/apache/struts2/views/jsp/AbstractUITagTest.java
+++ b/core/src/test/java/org/apache/struts2/views/jsp/AbstractUITagTest.java
@@ -251,16 +251,15 @@ public abstract class AbstractUITagTest extends 
AbstractTagTest {
         }
 
         StringBuilder buffer = new StringBuilder(128);
-        InputStream in = url.openStream();
-        byte[] buf = new byte[4096];
-        int nbytes;
-
-        while ((nbytes = in.read(buf)) > 0) {
-            buffer.append(new String(buf, 0, nbytes));
+        try (InputStream in = url.openStream()) {
+               byte[] buf = new byte[4096];
+               int nbytes;
+       
+               while ((nbytes = in.read(buf)) > 0) {
+                   buffer.append(new String(buf, 0, nbytes));
+               }
         }
 
-        in.close();
-
         /**
          * compare the trimmed values of each buffer and make sure they're 
equivalent.  however, let's make sure to
          * normalize the strings first to account for line termination 
differences between platforms.

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/plugins/jasperreports/src/main/java/org/apache/struts2/views/jasperreports/JasperReportsResult.java
----------------------------------------------------------------------
diff --git 
a/plugins/jasperreports/src/main/java/org/apache/struts2/views/jasperreports/JasperReportsResult.java
 
b/plugins/jasperreports/src/main/java/org/apache/struts2/views/jasperreports/JasperReportsResult.java
index d113a39..a64a48a 100644
--- 
a/plugins/jasperreports/src/main/java/org/apache/struts2/views/jasperreports/JasperReportsResult.java
+++ 
b/plugins/jasperreports/src/main/java/org/apache/struts2/views/jasperreports/JasperReportsResult.java
@@ -23,9 +23,11 @@ package org.apache.struts2.views.jasperreports;
 
 import com.opensymphony.xwork2.ActionInvocation;
 import com.opensymphony.xwork2.util.ValueStack;
+
 import net.sf.jasperreports.engine.*;
 import net.sf.jasperreports.engine.export.*;
 import net.sf.jasperreports.engine.util.JRLoader;
+
 import org.apache.commons.lang3.StringUtils;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
@@ -37,9 +39,11 @@ import javax.servlet.ServletException;
 import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.sql.Connection;
 import java.util.HashMap;
 import java.util.Map;
@@ -244,12 +248,9 @@ public class JasperReportsResult extends 
StrutsResultSupport implements JasperRe
         // Handle IE special case: it sends a "contype" request first.
         // TODO Set content type to config settings?
         if ("contype".equals(request.getHeader("User-Agent"))) {
-            try {
+            try (OutputStream outputStream = response.getOutputStream()) {
                 response.setContentType("application/pdf");
                 response.setContentLength(0);
-
-                ServletOutputStream outputStream = response.getOutputStream();
-                outputStream.close();
             } catch (IOException e) {
                 LOG.error("Error writing report output", e);
                 throw new ServletException(e.getMessage(), e);
@@ -300,7 +301,7 @@ public class JasperReportsResult extends 
StrutsResultSupport implements JasperRe
             parameters.putAll(reportParams);
         }
 
-        byte[] output;
+        ByteArrayOutputStream output;
         JasperPrint jasperPrint;
 
         // Fill the report and produce a print object
@@ -381,8 +382,7 @@ public class JasperReportsResult extends 
StrutsResultSupport implements JasperRe
             throw new ServletException(e.getMessage(), e);
         }
 
-        response.setContentLength(output.length);
-
+        response.setContentLength(output.size());
         // Will throw ServletException on IOException.
         writeReport(response, output);
     }
@@ -394,24 +394,12 @@ public class JasperReportsResult extends 
StrutsResultSupport implements JasperRe
      * @param output   Report bytes to write.
      * @throws ServletException on stream IOException.
      */
-    private void writeReport(HttpServletResponse response, byte[] output) 
throws ServletException {
-        ServletOutputStream outputStream = null;
-        try {
-            outputStream = response.getOutputStream();
-            outputStream.write(output);
+    private void writeReport(HttpServletResponse response, 
ByteArrayOutputStream output) throws ServletException {
+        try (OutputStream outputStream = response.getOutputStream()) {
             outputStream.flush();
         } catch (IOException e) {
             LOG.error("Error writing report output", e);
             throw new ServletException(e.getMessage(), e);
-        } finally {
-            try {
-                if (outputStream != null) {
-                    outputStream.close();
-                }
-            } catch (IOException e) {
-                LOG.error("Error closing report output stream", e);
-                throw new ServletException(e.getMessage(), e);
-            }
         }
     }
 
@@ -456,8 +444,7 @@ public class JasperReportsResult extends 
StrutsResultSupport implements JasperRe
      * @throws net.sf.jasperreports.engine.JRException
      *          If there is a problem running the report
      */
-    private byte[] exportReportToBytes(JasperPrint jasperPrint, JRExporter 
exporter) throws JRException {
-        byte[] output;
+    private ByteArrayOutputStream exportReportToBytes(JasperPrint jasperPrint, 
JRExporter exporter) throws JRException {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
         exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
@@ -467,10 +454,7 @@ public class JasperReportsResult extends 
StrutsResultSupport implements JasperRe
         }
 
         exporter.exportReport();
-
-        output = baos.toByteArray();
-
-        return output;
+        return baos;
     }
 
 }

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/plugins/java8-support/src/main/java/org/apache/struts2/convention/Java8ClassFinder.java
----------------------------------------------------------------------
diff --git 
a/plugins/java8-support/src/main/java/org/apache/struts2/convention/Java8ClassFinder.java
 
b/plugins/java8-support/src/main/java/org/apache/struts2/convention/Java8ClassFinder.java
index 76f9caa..28ad3ec 100644
--- 
a/plugins/java8-support/src/main/java/org/apache/struts2/convention/Java8ClassFinder.java
+++ 
b/plugins/java8-support/src/main/java/org/apache/struts2/convention/Java8ClassFinder.java
@@ -438,12 +438,9 @@ public class Java8ClassFinder implements ClassFinder {
         try {
             URL resource = classLoaderInterface.getResource(className);
             if (resource != null) {
-                InputStream in = resource.openStream();
-                try {
+                try (InputStream in = resource.openStream()) {
                     ClassReader classReader = new ClassReader(in);
                     classReader.accept(new InfoBuildingClassVisitor(this), 
ClassReader.SKIP_DEBUG);
-                } finally {
-                    in.close();
                 }
             } else {
                 throw new XWorkException("Could not load " + className);

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/plugins/oval/src/main/java/org/apache/struts2/oval/interceptor/DefaultOValValidationManager.java
----------------------------------------------------------------------
diff --git 
a/plugins/oval/src/main/java/org/apache/struts2/oval/interceptor/DefaultOValValidationManager.java
 
b/plugins/oval/src/main/java/org/apache/struts2/oval/interceptor/DefaultOValValidationManager.java
index fdd8aae..1c75d61 100644
--- 
a/plugins/oval/src/main/java/org/apache/struts2/oval/interceptor/DefaultOValValidationManager.java
+++ 
b/plugins/oval/src/main/java/org/apache/struts2/oval/interceptor/DefaultOValValidationManager.java
@@ -4,14 +4,19 @@ import com.opensymphony.xwork2.FileManager;
 import com.opensymphony.xwork2.FileManagerFactory;
 import com.opensymphony.xwork2.inject.Inject;
 import com.opensymphony.xwork2.util.ClassLoaderUtil;
+
 import org.apache.logging.log4j.Logger;
 import org.apache.logging.log4j.LogManager;
+
 import net.sf.oval.configuration.Configurer;
 import net.sf.oval.configuration.annotation.AnnotationsConfigurer;
 import net.sf.oval.configuration.annotation.JPAAnnotationsConfigurer;
 import net.sf.oval.configuration.xml.XMLConfigurer;
+
 import org.apache.struts2.StrutsConstants;
 
+import java.io.IOException;
+import java.io.InputStream;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -152,11 +157,8 @@ public class DefaultOValValidationManager implements 
OValValidationManager {
     protected XMLConfigurer loadFile(String fileName, Class clazz, boolean 
checkFile) {
         URL fileUrl = ClassLoaderUtil.getResource(fileName, clazz);
         if ((checkFile && fileManager.fileNeedsReloading(fileUrl)) || 
!validatorFileCache.containsKey(fileName)) {
-            java.io.InputStream is = null;
-
-            try {
-                is = fileManager.loadFile(fileUrl);
 
+            try (InputStream is = fileManager.loadFile(fileUrl)) {
                 if (is != null) {
                     LOG.debug("Loading validation xml file [{}]", fileName);
                     XMLConfigurer configurer = new XMLConfigurer();
@@ -164,14 +166,8 @@ public class DefaultOValValidationManager implements 
OValValidationManager {
                     validatorFileCache.put(fileName, configurer);
                     return configurer;
                 }
-            } finally {
-                if (is != null) {
-                    try {
-                        is.close();
-                    } catch (java.io.IOException e) {
-                        LOG.error("Unable to close input stream for [{}] ", 
fileName, e);
-                    }
-                }
+            } catch (IOException e) {
+                LOG.error("Unable to close input stream for [{}] ", fileName, 
e);
             }
         } else {
             return (XMLConfigurer) validatorFileCache.get(fileName);

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/plugins/sitegraph/src/main/java/org/apache/struts2/sitegraph/SiteGraph.java
----------------------------------------------------------------------
diff --git 
a/plugins/sitegraph/src/main/java/org/apache/struts2/sitegraph/SiteGraph.java 
b/plugins/sitegraph/src/main/java/org/apache/struts2/sitegraph/SiteGraph.java
index accfd3b..00cb7e2 100644
--- 
a/plugins/sitegraph/src/main/java/org/apache/struts2/sitegraph/SiteGraph.java
+++ 
b/plugins/sitegraph/src/main/java/org/apache/struts2/sitegraph/SiteGraph.java
@@ -66,18 +66,17 @@ public class SiteGraph {
         }
 
         if (args.length != 8 && args.length != 6) {
-            InputStream is = 
SiteGraph.class.getResourceAsStream("sitegraph-usage.txt");
-            byte[] buffer = new byte[2048];
-            int length;
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            while ((length = is.read(buffer)) != -1) {
-                baos.write(buffer, 0, length);
+            try (InputStream is = 
SiteGraph.class.getResourceAsStream("sitegraph-usage.txt");
+                    ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+                byte[] buffer = new byte[2048];
+                int length;
+                while ((length = is.read(buffer)) != -1) {
+                    baos.write(buffer, 0, length);
+                }
+            
+                String usage = baos.toString();
+                System.out.println(usage.replaceAll("//.*", ""));
             }
-            is.close();
-            baos.close();
-
-            String usage = baos.toString();
-            System.out.println(usage.replaceAll("//.*", ""));
             return;
         }
 

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/plugins/sitegraph/src/main/java/org/apache/struts2/sitegraph/entities/FileBasedView.java
----------------------------------------------------------------------
diff --git 
a/plugins/sitegraph/src/main/java/org/apache/struts2/sitegraph/entities/FileBasedView.java
 
b/plugins/sitegraph/src/main/java/org/apache/struts2/sitegraph/entities/FileBasedView.java
index 1ac2f3c..37efc13 100644
--- 
a/plugins/sitegraph/src/main/java/org/apache/struts2/sitegraph/entities/FileBasedView.java
+++ 
b/plugins/sitegraph/src/main/java/org/apache/struts2/sitegraph/entities/FileBasedView.java
@@ -85,9 +85,7 @@ public abstract class FileBasedView implements View {
     protected abstract Pattern getFormPattern();
 
     protected String readFile(File file) {
-        try {
-            BufferedReader in = new BufferedReader(new FileReader(file));
-
+        try (BufferedReader in = new BufferedReader(new FileReader(file))) {
             String s;
             StringBuilder buffer = new StringBuilder();
 
@@ -95,8 +93,6 @@ public abstract class FileBasedView implements View {
                 buffer.append(s).append('\n');
             }
 
-            in.close();
-
             return buffer.toString();
         } catch (FileNotFoundException e) {
             if (LOG.isWarnEnabled()) {

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/plugins/sitegraph/src/test/java/org/apache/struts2/sitegraph/SiteGraphTest.java
----------------------------------------------------------------------
diff --git 
a/plugins/sitegraph/src/test/java/org/apache/struts2/sitegraph/SiteGraphTest.java
 
b/plugins/sitegraph/src/test/java/org/apache/struts2/sitegraph/SiteGraphTest.java
index 04fe72c..71c3699 100644
--- 
a/plugins/sitegraph/src/test/java/org/apache/struts2/sitegraph/SiteGraphTest.java
+++ 
b/plugins/sitegraph/src/test/java/org/apache/struts2/sitegraph/SiteGraphTest.java
@@ -47,15 +47,14 @@ public class SiteGraphTest extends StrutsTestCase {
 
         URL compare = SiteGraphTest.class.getResource("out.txt");
         StringBuilder buffer = new StringBuilder(128);
-        InputStream in = compare.openStream();
-        byte[] buf = new byte[4096];
-        int nbytes;
-
-        while ((nbytes = in.read(buf)) > 0) {
-            buffer.append(new String(buf, 0, nbytes));
+        try (InputStream in = compare.openStream()){
+               byte[] buf = new byte[4096];
+               int nbytes;
+       
+               while ((nbytes = in.read(buf)) > 0) {
+                   buffer.append(new String(buf, 0, nbytes));
+               }
         }
-
-        in.close();
         assertEquals(buffer.toString().replaceAll("\r\n", "\n"), 
writer.toString().replaceAll("\r\n", "\n"));
     }
 }

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ExceptionHolder.java
----------------------------------------------------------------------
diff --git 
a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ExceptionHolder.java
 
b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ExceptionHolder.java
index 90382b5..6959357 100644
--- 
a/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ExceptionHolder.java
+++ 
b/xwork-core/src/main/java/com/opensymphony/xwork2/interceptor/ExceptionHolder.java
@@ -32,6 +32,7 @@ import java.io.Serializable;
  */
 public class ExceptionHolder implements Serializable {
 
+    private static final long serialVersionUID = 1L;
     private Exception exception;
 
     /**
@@ -44,37 +45,29 @@ public class ExceptionHolder implements Serializable {
     }
 
     /**
-     * Gets the holded exception
+     * Gets the held exception
      *
-     * @return  the holded exception
+     * @return the held exception
      */
     public Exception getException() {
         return this.exception;
     }
 
     /**
-     * Gets the holded exception stacktrace using {@link 
Exception#printStackTrace()}.
+     * Gets the held exception stack trace using {@link 
Exception#printStackTrace()}.
      *
-     * @return  stacktrace
+     * @return stack trace
      */
     public String getExceptionStack() {
         String exceptionStack = null;
 
         if (getException() != null) {
-            StringWriter sw = new StringWriter();
-            PrintWriter pw = new PrintWriter(sw);
-
-            try {
+            try (StringWriter sw = new StringWriter();
+                    PrintWriter pw = new PrintWriter(sw)) {
                 getException().printStackTrace(pw);
                 exceptionStack = sw.toString();
-            }
-            finally {
-                try {
-                    sw.close();
-                    pw.close();
-                } catch (IOException e) {
-                    // ignore
-                }
+            } catch (IOException e) {
+                // Ignore exception generating stack trace.
             }
         }
 

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java
----------------------------------------------------------------------
diff --git 
a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java
 
b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java
index b703639..2e140a7 100644
--- 
a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java
+++ 
b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java
@@ -450,12 +450,9 @@ public class DefaultClassFinder implements ClassFinder {
         try {
             URL resource = classLoaderInterface.getResource(className);
             if (resource != null) {
-                InputStream in = resource.openStream();
-                try {
+                try (InputStream in = resource.openStream()) {
                     ClassReader classReader = new ClassReader(in);
                     classReader.accept(new InfoBuildingVisitor(this), 
ClassReader.SKIP_DEBUG);
-                } finally {
-                    in.close();
                 }
             } else {
                 throw new XWorkException("Could not load " + className);

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java
----------------------------------------------------------------------
diff --git 
a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java
 
b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java
index e07503d..c7f9fd1 100644
--- 
a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java
+++ 
b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java
@@ -969,29 +969,18 @@ public class ResourceFinder {
     }
 
     private Properties loadProperties(URL resource) throws IOException {
-        InputStream in = resource.openStream();
-
-        BufferedInputStream reader = new BufferedInputStream(in);
-        try {
+        try (InputStream reader = new 
BufferedInputStream(resource.openStream())) {
             Properties properties = new Properties();
             properties.load(reader);
 
             return properties;
-        } finally {
-            try {
-                in.close();
-                reader.close();
-            } catch (Exception e) {
-            }
         }
     }
 
     private String readContents(URL resource) throws IOException {
-        InputStream in = resource.openStream();
         StringBuilder sb = new StringBuilder();
 
-        BufferedInputStream reader = new BufferedInputStream(in);
-        try {
+        try (InputStream reader = new 
BufferedInputStream(resource.openStream())) {
             int b = reader.read();
             while (b != -1) {
                 sb.append((char) b);
@@ -999,12 +988,6 @@ public class ResourceFinder {
             }
 
             return sb.toString().trim();
-        } finally {
-            try {
-                in.close();
-                reader.close();
-            } catch (Exception e) {
-            }
         }
     }
 

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultValidatorFactory.java
----------------------------------------------------------------------
diff --git 
a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultValidatorFactory.java
 
b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultValidatorFactory.java
index 9f8a1b9..d4d7ff7 100644
--- 
a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultValidatorFactory.java
+++ 
b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/DefaultValidatorFactory.java
@@ -138,8 +138,7 @@ public class DefaultValidatorFactory implements 
ValidatorFactory {
                             // Ex: struts-app.jar -> MyApp.jar -> 
Login-validators.xml should be
                             // parsed and loaded.
                             ZipInputStream zipInputStream = null;
-                            try {
-                                InputStream inputStream = u.openStream();
+                            try (InputStream inputStream = u.openStream()) {
                                 if (inputStream instanceof ZipInputStream) {
                                     zipInputStream = (ZipInputStream) 
inputStream;
                                 } else {

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/xwork-core/src/test/java/com/opensymphony/xwork2/util/UrlUtilTest2.java
----------------------------------------------------------------------
diff --git 
a/xwork-core/src/test/java/com/opensymphony/xwork2/util/UrlUtilTest2.java 
b/xwork-core/src/test/java/com/opensymphony/xwork2/util/UrlUtilTest2.java
index e039bde..bfc306b 100644
--- a/xwork-core/src/test/java/com/opensymphony/xwork2/util/UrlUtilTest2.java
+++ b/xwork-core/src/test/java/com/opensymphony/xwork2/util/UrlUtilTest2.java
@@ -28,14 +28,8 @@ public class UrlUtilTest2 extends TestCase {
 
     private void assertUrlCanBeOpened(URL url) throws IOException {
         InputStream is = url.openStream();
-        JarInputStream jarStream = null;
-        try {
-            jarStream = new JarInputStream(is);
+        try (JarInputStream jarStream = new JarInputStream(is)) {
             assertNotNull(jarStream);
-        } finally {
-            if (jarStream != null)
-                jarStream.close();
-
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/struts/blob/3fab155b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DefaultValidatorFileParserTest.java
----------------------------------------------------------------------
diff --git 
a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DefaultValidatorFileParserTest.java
 
b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DefaultValidatorFileParserTest.java
index 58b2c35..b900b55 100644
--- 
a/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DefaultValidatorFileParserTest.java
+++ 
b/xwork-core/src/test/java/com/opensymphony/xwork2/validator/DefaultValidatorFileParserTest.java
@@ -171,9 +171,7 @@ public class DefaultValidatorFileParserTest extends 
TestCase {
     }
 
     public void testValidatorWithI18nMessage() throws Exception {
-        InputStream is = null;
-        try {
-            is = ClassLoaderUtil.getResourceAsStream(testFileName6, 
this.getClass());
+        try (InputStream is = 
ClassLoaderUtil.getResourceAsStream(testFileName6, this.getClass())) {
             
mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", 
C.args(C.eq("requiredstring")), RequiredStringValidator.class.getName());
             
mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", 
C.args(C.eq("requiredstring")), RequiredStringValidator.class.getName());
 
@@ -203,11 +201,6 @@ public class DefaultValidatorFileParserTest extends 
TestCase {
             
assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getParams().get("anotherParam"),
 "anotherValue");
             assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getType(), 
"requiredstring");
         }
-        finally {
-            if (is != null) {
-                is.close();
-            }
-        }
     }
 
     

Reply via email to