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 1853ed84e0..b34178dbf7 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 void copyParams(Map params) { * @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(); + } } /** 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 06bc744c9b..7a136cb8bb 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 @@ public PropertiesSettings(String name) { 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); - } - } } } 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 c27e0786dd..8d36bf6612 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 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro 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(); - } } } 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 13a5c3c9d4..4d512237bf 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 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro // 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 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro 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 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro 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 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro // Flush oOutput.flush(); } - finally { - if (inputStream != null) inputStream.close(); - if (oOutput != null) oOutput.close(); - } } /** 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 e65973f879..2f92340eb6 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 @@ private File createTemporaryFile(String fileName, String location) throws IOExce */ 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; } 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 7ea1fed7fc..5a88577b90 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 void beforeResult(ActionInvocation inv, String actionResult) { 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 void beforeResult(ActionInvocation inv, String actionResult) { 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(); 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 00fb12ff22..8645df784f 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 void writeTo(JspWriter out, String encoding) throws IOException { * 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 - } - } } } 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 f32a5a6502..375a726ac5 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 @@ protected TemplateLoader createTemplateLoader(ServletContext servletContext, Str * @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 @@ protected void loadSettings(ServletContext servletContext) { 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); - } - } } } 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 7dc9bd2e3e..484c317ca4 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 @@ protected Object findValue(String expr, Class toType) { } 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() { diff --git a/core/src/test/java/org/apache/struts2/TestUtils.java b/core/src/test/java/org/apache/struts2/TestUtils.java index 001f98da3b..02fe8b5e49 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 static String readContent(URL url) } 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(); } } 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 b2fadaa666..959458a0d0 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 void testPlainText() throws Exception { 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 void testPlainText() throws Exception { readAsString("org/apache/struts2/dispatcher/someJspFile.jsp"), true); assertEquals(r, e); } - finally { - jspResourceInputStream.close(); - } } public void testPlainTextWithoutSlash() throws Exception { @@ -82,11 +77,9 @@ public void testPlainTextWithoutSlash() throws Exception { 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 void testPlainTextWithoutSlash() throws Exception { 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 void testPlainTextWithEncoding() throws Exception { 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 void testPlainTextWithEncoding() throws Exception { 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 @@ protected String readAsString(String resource) throws Exception { } return stringBuilder.toString(); } - finally { - if (is != null) - is.close(); - } - } 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 106ba5fa17..02e1f9688e 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 void verify(URL url) throws Exception { } 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. 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 d113a39d5c..56cd4b06f2 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 @@ 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.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 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro // 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 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro parameters.putAll(reportParams); } - byte[] output; + ByteArrayOutputStream output; JasperPrint jasperPrint; // Fill the report and produce a print object @@ -381,8 +382,7 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro 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,13 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro * @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()) { + output.writeTo(outputStream); 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 +445,7 @@ private void initializeProperties(ActionInvocation invocation) throws Exception * @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 +455,7 @@ private byte[] exportReportToBytes(JasperPrint jasperPrint, JRExporter exporter) } exporter.exportReport(); - - output = baos.toByteArray(); - - return output; + return baos; } } 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 76f9caa7d6..28ad3eca5d 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 @@ private void readClassDef(String className) { 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); 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 fdd8aae759..1c75d61696 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.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 @@ protected XMLConfigurer buildClassValidatorConfigs(Class aClass, boolean checkFi 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 @@ protected XMLConfigurer loadFile(String fileName, Class clazz, boolean checkFile 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); 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 accfd3b8fc..00cb7e2072 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 static void main(String[] args) throws IOException { } 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; } 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 1ac2f3cce3..37efc13bb3 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 @@ private void matchPatterns(Pattern pattern, Set targets, int type) { 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 @@ protected String readFile(File file) { buffer.append(s).append('\n'); } - in.close(); - return buffer.toString(); } catch (FileNotFoundException e) { if (LOG.isWarnEnabled()) { 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 04fe72c8fe..71c3699ed1 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 void testWebFlow() throws Exception { 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")); } } 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 90382b5c92..6959357f46 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 @@ */ public class ExceptionHolder implements Serializable { + private static final long serialVersionUID = 1L; private Exception exception; /** @@ -44,37 +45,29 @@ public ExceptionHolder(Exception exception) { } /** - * 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. } } 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 b70363954f..2e140a75d7 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 @@ private void readClassDef(String className) { 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); 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 e07503d288..c7f9fd170f 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 @@ private static void readJarDirectoryEntries(URL location, String basePath, Set 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 { 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 e039bde681..bfc306b5e7 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 void testOpenWithJarProtocol() throws IOException { 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(); - } } } 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 58b2c350c8..b900b5519e 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 void testValidatorDefinitionsWithBadClassName() { } 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 void testValidatorWithI18nMessage() throws Exception { assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getParams().get("anotherParam"), "anotherValue"); assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getType(), "requiredstring"); } - finally { - if (is != null) { - is.close(); - } - } }