From e262854e2a1b7548efa0a1eb50d350ecd215231b Mon Sep 17 00:00:00 2001 From: Aaron Johnson Date: Fri, 22 May 2015 09:28:08 -0500 Subject: [PATCH 1/6] WW-4503 Build Struts with JDK 7 --- pom.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index b99e47e2d7..83582ec329 100644 --- a/pom.xml +++ b/pom.xml @@ -146,9 +146,10 @@ maven-compiler-plugin + 3.3 - 1.5 - 1.5 + 1.7 + 1.7 From 08fad71aafb1215438d65f817412a04b3584f5bb Mon Sep 17 00:00:00 2001 From: Aaron Johnson Date: Tue, 26 May 2015 09:36:33 -0500 Subject: [PATCH 2/6] WW-4402 JDK 8: build fails due to missing apt tool --- core/pom.xml | 47 +++++++++++++++++------------------------------ pom.xml | 2 +- 2 files changed, 18 insertions(+), 31 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 6eed44f489..6d63119103 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -40,38 +40,25 @@ - org.apache.myfaces.tobago - maven-apt-plugin - 1.0.15 + org.apache.maven.plugins + maven-compiler-plugin - uri=/struts-tags,tlibVersion=${tlib.version},jspVersion=2.0,shortName=s,displayName=Struts Tags, - outFile=${basedir}/target/classes/META-INF/struts-tags.tld, - description="To make it easier to access dynamic data; - the Apache Struts framework includes a library of custom tags. - The tags interact with the framework's validation and internationalization features; - to ensure that input is correct and output is localized. - The Struts Tags can be used with JSP FreeMarker or Velocity.", - outTemplatesDir=${basedir}/src/site/resources/tags - - target - false - true - true - true - org.apache.struts.annotations.taglib.apt.TLDAnnotationProcessorFactory - 1.5 - - **/*.java - + + -Auri=/struts-tags + -AtlibVersion=${tlib.version} + -AjspVersion=2.0 + -AshortName=s + -AdisplayName=Struts Tags + -AoutFile=${basedir}/target/classes/META-INF/struts-tags.tld + -Adescription="To make it easier to access dynamic data; + the Apache Struts framework includes a library of custom tags. + The tags interact with the framework's validation and + internationalization features; + to ensure that input is correct and output is localized. + The Struts Tags can be used with JSP FreeMarker or Velocity." + -AoutTemplatesDir=${basedir}/src/site/resources/tags + - - - compile - - execute - - - diff --git a/pom.xml b/pom.xml index 83582ec329..08e0d54549 100644 --- a/pom.xml +++ b/pom.xml @@ -353,7 +353,7 @@ org.apache.struts struts-annotations - 1.0.5 + 1.0.6-SNAPSHOT From 3fab155b4cc530ca3ca0b69299ddcb348eb5f26d Mon Sep 17 00:00:00 2001 From: Aaron Johnson Date: Wed, 17 Jun 2015 09:24:08 -0500 Subject: [PATCH 3/6] WW-4515 Convert try blocks to try-with-resources --- .../apache/struts2/components/Component.java | 11 +++-- .../struts2/config/PropertiesSettings.java | 12 +----- .../struts2/dispatcher/PlainTextResult.java | 19 ++------- .../struts2/dispatcher/StreamResult.java | 16 ++------ .../JakartaStreamMultiPartRequest.java | 21 +--------- .../debugging/DebuggingInterceptor.java | 9 ++--- .../util/FastByteArrayOutputStream.java | 12 +----- .../views/freemarker/FreemarkerManager.java | 15 +------ .../views/jsp/StrutsBodyTagSupport.java | 10 ++--- .../java/org/apache/struts2/TestUtils.java | 13 +++--- .../dispatcher/PlainTextResultTest.java | 40 +++++-------------- .../struts2/views/jsp/AbstractUITagTest.java | 15 ++++--- .../jasperreports/JasperReportsResult.java | 38 +++++------------- .../struts2/convention/Java8ClassFinder.java | 5 +-- .../DefaultOValValidationManager.java | 20 ++++------ .../apache/struts2/sitegraph/SiteGraph.java | 21 +++++----- .../sitegraph/entities/FileBasedView.java | 6 +-- .../struts2/sitegraph/SiteGraphTest.java | 15 ++++--- .../xwork2/interceptor/ExceptionHolder.java | 25 +++++------- .../util/finder/DefaultClassFinder.java | 5 +-- .../xwork2/util/finder/ResourceFinder.java | 21 +--------- .../validator/DefaultValidatorFactory.java | 3 +- .../xwork2/util/UrlUtilTest2.java | 8 +--- .../DefaultValidatorFileParserTest.java | 9 +---- 24 files changed, 99 insertions(+), 270 deletions(-) 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..a64a48a091 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,12 @@ 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()) { 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 @@ 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 +454,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(); - } - } } From c71c3def74aae42ad205bd1ec839044c220b7ac0 Mon Sep 17 00:00:00 2001 From: Aaron Johnson Date: Wed, 17 Jun 2015 09:32:57 -0500 Subject: [PATCH 4/6] WW-4515 Convert try blocks to try-with-resources --- core/pom.xml | 47 ++++++++++++++++++++++++++++++----------------- pom.xml | 3 +-- 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index dd91ca1626..be09a0bffb 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -40,25 +40,38 @@ - org.apache.maven.plugins - maven-compiler-plugin + org.apache.myfaces.tobago + maven-apt-plugin + 1.0.15 - - -Auri=/struts-tags - -AtlibVersion=${tlib.version} - -AjspVersion=2.0 - -AshortName=s - -AdisplayName=Struts Tags - -AoutFile=${basedir}/target/classes/META-INF/struts-tags.tld - -Adescription="To make it easier to access dynamic data; - the Apache Struts framework includes a library of custom tags. - The tags interact with the framework's validation and - internationalization features; - to ensure that input is correct and output is localized. - The Struts Tags can be used with JSP FreeMarker or Velocity." - -AoutTemplatesDir=${basedir}/src/site/resources/tags - + uri=/struts-tags,tlibVersion=${tlib.version},jspVersion=2.0,shortName=s,displayName=Struts Tags, + outFile=${basedir}/target/classes/META-INF/struts-tags.tld, + description="To make it easier to access dynamic data; + the Apache Struts framework includes a library of custom tags. + The tags interact with the framework's validation and internationalization features; + to ensure that input is correct and output is localized. + The Struts Tags can be used with JSP FreeMarker or Velocity.", + outTemplatesDir=${basedir}/src/site/resources/tags + + target + false + true + true + true + org.apache.struts.annotations.taglib.apt.TLDAnnotationProcessorFactory + 1.5 + + **/*.java + + + + compile + + execute + + + diff --git a/pom.xml b/pom.xml index 32e16c93ef..73d959939e 100644 --- a/pom.xml +++ b/pom.xml @@ -146,7 +146,6 @@ maven-compiler-plugin - 3.3 1.7 1.7 @@ -354,7 +353,7 @@ org.apache.struts struts-annotations - 1.0.6-SNAPSHOT + 1.0.5 From 0b19499ffd78f44a6dd8b767e9995c980efeb01f Mon Sep 17 00:00:00 2001 From: Aaron Johnson Date: Wed, 17 Jun 2015 09:49:26 -0500 Subject: [PATCH 5/6] WW-4515 Convert try blocks to try-with-resources --- .../apache/struts2/views/jasperreports/JasperReportsResult.java | 1 + 1 file changed, 1 insertion(+) 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 a64a48a091..1beffbc07a 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 @@ -396,6 +396,7 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro */ private void writeReport(HttpServletResponse response, ByteArrayOutputStream output) throws ServletException { try (OutputStream outputStream = response.getOutputStream()) { + output.writeTo(output); outputStream.flush(); } catch (IOException e) { LOG.error("Error writing report output", e); From 86da1ea8c2fec919bb3c94ceeb9c29f1acf04276 Mon Sep 17 00:00:00 2001 From: Aaron Johnson Date: Wed, 17 Jun 2015 09:51:25 -0500 Subject: [PATCH 6/6] WW-4515 Convert try blocks to try-with-resources --- .../apache/struts2/views/jasperreports/JasperReportsResult.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 1beffbc07a..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 @@ -396,7 +396,7 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro */ private void writeReport(HttpServletResponse response, ByteArrayOutputStream output) throws ServletException { try (OutputStream outputStream = response.getOutputStream()) { - output.writeTo(output); + output.writeTo(outputStream); outputStream.flush(); } catch (IOException e) { LOG.error("Error writing report output", e);