From 767faece5c4692748d1ac8e130b2e4c5faa1ff20 Mon Sep 17 00:00:00 2001 From: Mikhail Mazursky Date: Wed, 28 Aug 2013 09:58:56 +0600 Subject: [PATCH] [Bug 415999] Fix some of FindBugs warnings Mostly not closed streams/DB resources are fixed. But also less important things. Signed-off-by: Mikhail Mazursky --- .../org/eclipse/jetty/ant/utils/TaskLog.java | 9 +- .../util/InputStreamResponseListener.java | 3 +- .../jetty/deploy/test/XmlConfiguredJetty.java | 7 +- .../org/eclipse/jetty/http/HttpField.java | 2 +- .../org/eclipse/jetty/http/HttpFields.java | 2 +- .../org/eclipse/jetty/http/MimeTypes.java | 5 +- .../eclipse/jetty/http/HttpParserTest.java | 2 +- .../eclipse/jetty/jaas/JAASLoginService.java | 4 +- .../jaas/spi/AbstractDatabaseLoginModule.java | 53 ++- .../eclipse/jetty/jndi/DataSourceCloser.java | 9 +- .../eclipse/jetty/jspc/plugin/JspcMojo.java | 82 ++--- .../jetty/maven/plugin/AbstractJettyMojo.java | 14 +- .../maven/plugin/JettyRunForkedMojo.java | 26 +- .../maven/plugin/MavenServerConnector.java | 8 +- .../maven/plugin/SelectiveJarResource.java | 125 ++++--- .../eclipse/jetty/maven/plugin/Starter.java | 6 +- .../jetty/maven/plugin/SystemProperties.java | 12 +- .../boot/internal/webapp/BundleWatcher.java | 2 +- .../webapp/LibExtClassLoaderHelper.java | 2 +- .../webapp/OSGiWebappClassLoader.java | 4 +- .../overlays/OverlayedAppProviderTest.java | 8 +- .../plus/security/DataSourceLoginService.java | 172 +++++---- .../jetty/security/JDBCLoginService.java | 45 ++- .../jetty/security/SecurityHandler.java | 4 +- .../jetty/security/PropertyUserStoreTest.java | 19 +- .../eclipse/jetty/server/NCSARequestLog.java | 2 +- .../org/eclipse/jetty/server/Response.java | 7 +- .../jetty/server/handler/DefaultHandler.java | 7 +- .../jetty/server/handler/ResourceHandler.java | 8 +- .../server/session/JDBCSessionIdManager.java | 325 +++++++++--------- .../server/session/JDBCSessionManager.java | 107 ++---- .../org/eclipse/jetty/server/DumpHandler.java | 2 +- .../org/eclipse/jetty/server/RequestTest.java | 10 +- .../jetty/server/ResourceCacheTest.java | 28 +- .../server/handler/ResourceHandlerTest.java | 15 +- .../SSLSelectChannelConnectorLoadTest.java | 5 +- .../ssl/SelectChannelServerSslTest.java | 6 +- .../ssl/SslSelectChannelTimeoutTest.java | 6 +- .../jetty/server/ssl/SslUploadTest.java | 5 +- .../eclipse/jetty/servlet/DefaultServlet.java | 12 +- .../java/org/eclipse/jetty/servlets/CGI.java | 7 +- .../org/eclipse/jetty/servlets/PutFilter.java | 26 +- .../servlets/IncludableGzipFilterTest.java | 10 +- .../eclipse/jetty/servlets/PutFilterTest.java | 15 +- .../org/eclipse/jetty/spdy/api/Settings.java | 17 +- .../generator/DataFrameGeneratorTest.java | 4 +- .../jetty/spdy/server/PushStreamTest.java | 4 +- .../java/org/eclipse/jetty/start/Main.java | 5 +- .../org/eclipse/jetty/util/DateCache.java | 4 +- .../main/java/org/eclipse/jetty/util/IO.java | 12 +- .../eclipse/jetty/util/MultiPartWriter.java | 24 +- .../org/eclipse/jetty/util/StringUtil.java | 2 +- .../java/org/eclipse/jetty/util/TypeUtil.java | 4 +- .../FileNoticeLifeCycleListener.java | 7 +- .../java/org/eclipse/jetty/util/log/Log.java | 2 +- .../jetty/util/resource/JarResource.java | 186 +++++----- .../eclipse/jetty/util/resource/Resource.java | 12 +- .../eclipse/jetty/util/BufferUtilTest.java | 6 +- .../org/eclipse/jetty/util/ScannerTest.java | 76 ++-- .../util/resource/ResourceCollectionTest.java | 9 +- .../jetty/util/ssl/SslContextFactoryTest.java | 8 +- .../eclipse/jetty/webapp/WebAppContext.java | 2 +- .../client/ClientUpgradeRequest.java | 4 +- 63 files changed, 805 insertions(+), 811 deletions(-) diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/TaskLog.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/TaskLog.java index 29fc10b31b7..e9aad1d017d 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/TaskLog.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/TaskLog.java @@ -33,7 +33,7 @@ public class TaskLog private static Task task; - private static SimpleDateFormat format = new SimpleDateFormat( + private static final SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS"); public static void setTask(Task task) @@ -48,6 +48,11 @@ public class TaskLog public static void logWithTimestamp(String message) { - task.log(format.format(new Date()) + ": " + message); + String date; + synchronized (format) + { + date = format.format(new Date()); + } + task.log(date + ": " + message); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/InputStreamResponseListener.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/InputStreamResponseListener.java index 6ac55e6f65e..d59943a4670 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/InputStreamResponseListener.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/InputStreamResponseListener.java @@ -155,7 +155,7 @@ public class InputStreamResponseListener extends Response.Listener.Empty { synchronized (this) { - if (length.get() >= maxBufferSize && failure == null && !closed) + while (length.get() >= maxBufferSize && failure == null && !closed) wait(); // Re-read the values as they may have changed while waiting. return failure == null && !closed; @@ -163,6 +163,7 @@ public class InputStreamResponseListener extends Response.Listener.Empty } catch (InterruptedException x) { + Thread.currentThread().interrupt(); return false; } } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/test/XmlConfiguredJetty.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/test/XmlConfiguredJetty.java index a14facc8e70..6f9790ec713 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/test/XmlConfiguredJetty.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/test/XmlConfiguredJetty.java @@ -24,6 +24,7 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URI; @@ -123,8 +124,10 @@ public class XmlConfiguredJetty // Write out configuration for use by ConfigurationManager. File testConfig = new File(_jettyHome, "xml-configured-jetty.properties"); - FileOutputStream out = new FileOutputStream(testConfig); - properties.store(out,"Generated by " + XmlConfiguredJetty.class.getName()); + try (OutputStream out = new FileOutputStream(testConfig)) + { + properties.store(out,"Generated by " + XmlConfiguredJetty.class.getName()); + } for (Object key:properties.keySet()) setProperty(String.valueOf(key),String.valueOf(properties.get(key))); } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpField.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpField.java index 6d835dc2d54..8241d1d62f4 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpField.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpField.java @@ -231,7 +231,7 @@ public class HttpField public String toString() { String v=getValue(); - return getName() + ": " + (v==null?"":v.toString()); + return getName() + ": " + (v==null?"":v); } public boolean isSame(HttpField field) diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java index c6b6762aa07..3f2c12d80a0 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java @@ -901,7 +901,7 @@ public class HttpFields implements Iterable HttpField field=i.next(); if (field.getHeader()==HttpHeader.SET_COOKIE) { - String val = (field.getValue() == null ? null : field.getValue().toString()); + String val = field.getValue(); if (val!=null && val.startsWith(name_equals)) { //existing cookie has same name, does it also match domain and path? diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java b/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java index 5bd40b22d7f..311a68827ef 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java @@ -25,6 +25,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; +import java.util.Map.Entry; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; @@ -192,8 +193,8 @@ public class MimeTypes _mimeMap.clear(); if (mimeMap!=null) { - for (String ext : mimeMap.keySet()) - _mimeMap.put(StringUtil.asciiToLowerCase(ext),normalizeMimeType(mimeMap.get(ext))); + for (Entry ext : mimeMap.entrySet()) + _mimeMap.put(StringUtil.asciiToLowerCase(ext.getKey()),normalizeMimeType(ext.getValue())); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java index 654474d726c..d4ee8d75cf5 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java @@ -1246,7 +1246,7 @@ public class HttpParserTest request=false; _methodOrVersion = version.asString(); _uriOrStatus = Integer.toString(status); - _versionOrReason = reason==null?null:reason.toString(); + _versionOrReason = reason; fields=new HttpFields(); _hdr= new String[9]; diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASLoginService.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASLoginService.java index d50c3859aa9..412ee5ec1a7 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASLoginService.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASLoginService.java @@ -57,8 +57,8 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService { private static final Logger LOG = Log.getLogger(JAASLoginService.class); - public static String DEFAULT_ROLE_CLASS_NAME = "org.eclipse.jetty.jaas.JAASRole"; - public static String[] DEFAULT_ROLE_CLASS_NAMES = {DEFAULT_ROLE_CLASS_NAME}; + public static final String DEFAULT_ROLE_CLASS_NAME = "org.eclipse.jetty.jaas.JAASRole"; + public static final String[] DEFAULT_ROLE_CLASS_NAMES = {DEFAULT_ROLE_CLASS_NAME}; protected String[] _roleClassNames = DEFAULT_ROLE_CLASS_NAMES; protected String _callbackHandlerClass; diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractDatabaseLoginModule.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractDatabaseLoginModule.java index fc2726ff894..55c60aff081 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractDatabaseLoginModule.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractDatabaseLoginModule.java @@ -73,45 +73,44 @@ public abstract class AbstractDatabaseLoginModule extends AbstractLoginModule public UserInfo getUserInfo (String userName) throws Exception { - Connection connection = null; - - try + try (Connection connection = getConnection()) { - connection = getConnection(); //query for credential - PreparedStatement statement = connection.prepareStatement (userQuery); - statement.setString (1, userName); - ResultSet results = statement.executeQuery(); String dbCredential = null; - if (results.next()) + try (PreparedStatement statement = connection.prepareStatement (userQuery)) { - dbCredential = results.getString(1); + statement.setString (1, userName); + try (ResultSet results = statement.executeQuery()) + { + if (results.next()) + { + dbCredential = results.getString(1); + } + } + } + + if (dbCredential==null) + { + return null; } - results.close(); - statement.close(); //query for role names - statement = connection.prepareStatement (rolesQuery); - statement.setString (1, userName); - results = statement.executeQuery(); List roles = new ArrayList(); - - while (results.next()) + try (PreparedStatement statement = connection.prepareStatement (rolesQuery)) { - String roleName = results.getString (1); - roles.add (roleName); + statement.setString (1, userName); + try (ResultSet results = statement.executeQuery()) + { + while (results.next()) + { + String roleName = results.getString (1); + roles.add (roleName); + } + } } - results.close(); - statement.close(); - - return dbCredential==null ? null : new UserInfo (userName, - Credential.getCredential(dbCredential), roles); - } - finally - { - if (connection != null) connection.close(); + return new UserInfo (userName, Credential.getCredential(dbCredential), roles); } } diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/DataSourceCloser.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/DataSourceCloser.java index 61dae6f3cd3..a41174d75ca 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/DataSourceCloser.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/DataSourceCloser.java @@ -19,6 +19,7 @@ package org.eclipse.jetty.jndi; import java.lang.reflect.Method; +import java.sql.Connection; import java.sql.Statement; import javax.sql.DataSource; @@ -66,9 +67,11 @@ public class DataSourceCloser implements Destroyable if (_shutdown!=null) { LOG.info("Shutdown datasource {}",_datasource); - Statement stmt = _datasource.getConnection().createStatement(); - stmt.executeUpdate(_shutdown); - stmt.close(); + try (Connection connection = _datasource.getConnection(); + Statement stmt = connection.createStatement()) + { + stmt.executeUpdate(_shutdown); + } } } catch (Exception e) diff --git a/jetty-jspc-maven-plugin/src/main/java/org/eclipse/jetty/jspc/plugin/JspcMojo.java b/jetty-jspc-maven-plugin/src/main/java/org/eclipse/jetty/jspc/plugin/JspcMojo.java index d5645c459f2..224a7e99d81 100644 --- a/jetty-jspc-maven-plugin/src/main/java/org/eclipse/jetty/jspc/plugin/JspcMojo.java +++ b/jetty-jspc-maven-plugin/src/main/java/org/eclipse/jetty/jspc/plugin/JspcMojo.java @@ -433,13 +433,15 @@ public class JspcMojo extends AbstractMojo static void delete(File dir, FileFilter filter) { File[] files = dir.listFiles(filter); - for(int i=0; i if there is no - // marker - boolean atInsertPoint = false; - boolean atEOF = false; - String marker = (insertionMarker == null - || insertionMarker.equals("") ? END_OF_WEBAPP : insertionMarker); - while (!atInsertPoint && !atEOF) - { - String line = webXmlReader.readLine(); - if (line == null) - atEOF = true; - else if (line.indexOf(marker) >= 0) + // read up to the insertion marker or the if there is no + // marker + boolean atInsertPoint = false; + boolean atEOF = false; + String marker = (insertionMarker == null + || insertionMarker.equals("") ? END_OF_WEBAPP : insertionMarker); + while (!atInsertPoint && !atEOF) { - atInsertPoint = true; + String line = webXmlReader.readLine(); + if (line == null) + atEOF = true; + else if (line.indexOf(marker) >= 0) + { + atInsertPoint = true; + } + else + { + mergedWebXmlWriter.println(line); + } } - else - { - mergedWebXmlWriter.println(line); + + // put in the generated fragment + try (BufferedReader fragmentWebXmlReader = new BufferedReader( + new FileReader(fragmentWebXml))) { + IO.copy(fragmentWebXmlReader, mergedWebXmlWriter); + + // if we inserted just before the , put it back in + if (marker.equals(END_OF_WEBAPP)) + mergedWebXmlWriter.println(END_OF_WEBAPP); + + // copy in the rest of the original web.xml file + IO.copy(webXmlReader, mergedWebXmlWriter); } } - - // put in the generated fragment - BufferedReader fragmentWebXmlReader = new BufferedReader( - new FileReader(fragmentWebXml)); - IO.copy(fragmentWebXmlReader, mergedWebXmlWriter); - - // if we inserted just before the , put it back in - if (marker.equals(END_OF_WEBAPP)) - mergedWebXmlWriter.println(END_OF_WEBAPP); - - // copy in the rest of the original web.xml file - IO.copy(webXmlReader, mergedWebXmlWriter); - - webXmlReader.close(); - mergedWebXmlWriter.close(); - fragmentWebXmlReader.close(); } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/AbstractJettyMojo.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/AbstractJettyMojo.java index 50643d50e38..02eeba5d802 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/AbstractJettyMojo.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/AbstractJettyMojo.java @@ -21,6 +21,7 @@ package org.eclipse.jetty.maven.plugin; import java.io.File; import java.io.FileInputStream; +import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; @@ -758,14 +759,15 @@ public abstract class AbstractJettyMojo extends AbstractMojo public void setSystemPropertiesFile(File file) throws Exception { this.systemPropertiesFile = file; - FileInputStream propFile = new FileInputStream(systemPropertiesFile); Properties properties = new Properties(); - properties.load(propFile); - + try (InputStream propFile = new FileInputStream(systemPropertiesFile)) + { + properties.load(propFile); + } if (this.systemProperties == null ) this.systemProperties = new SystemProperties(); - for (Enumeration keys = properties.keys(); keys.hasMoreElements(); ) + for (Enumeration keys = properties.keys(); keys.hasMoreElements(); ) { String key = (String)keys.nextElement(); if ( ! systemProperties.containsSystemProperty(key) ) @@ -791,10 +793,8 @@ public abstract class AbstractJettyMojo extends AbstractMojo this.systemProperties = systemProperties; else { - Iterator itor = systemProperties.getSystemProperties().iterator(); - while (itor.hasNext()) + for (SystemProperty prop: systemProperties.getSystemProperties()) { - SystemProperty prop = (SystemProperty)itor.next(); this.systemProperties.setSystemProperty(prop); } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunForkedMojo.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunForkedMojo.java index 1e7e9feeefc..77d500993b7 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunForkedMojo.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunForkedMojo.java @@ -26,6 +26,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; +import java.io.OutputStream; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; @@ -504,7 +505,10 @@ public class JettyRunForkedMojo extends AbstractMojo props.put("maven.war.overlay."+(i++), c.toString()); } - props.store(new BufferedOutputStream(new FileOutputStream(propsFile)), "properties for forked webapp"); + try (OutputStream out = new BufferedOutputStream(new FileOutputStream(propsFile))) + { + props.store(out, "properties for forked webapp"); + } return propsFile; } catch (Exception e) @@ -723,18 +727,20 @@ public class JettyRunForkedMojo extends AbstractMojo //child indicates it has finished starting by printing on stdout the token passed to it try { - LineNumberReader reader = new LineNumberReader(new InputStreamReader(forkedProcess.getInputStream())); String line = ""; - int attempts = maxStartupLines; //max lines we'll read trying to get token - while (attempts>0 && line != null) + try (InputStream is = forkedProcess.getInputStream(); + LineNumberReader reader = new LineNumberReader(new InputStreamReader(is))) { - --attempts; - line = reader.readLine(); - if (line != null && line.startsWith(token)) - break; - } + int attempts = maxStartupLines; //max lines we'll read trying to get token + while (attempts>0 && line != null) + { + --attempts; + line = reader.readLine(); + if (line != null && line.startsWith(token)) + break; + } - reader.close(); + } if (line != null && line.trim().equals(token)) PluginLog.getLog().info("Forked process started."); diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenServerConnector.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenServerConnector.java index 54aedb1303e..9d343b48af9 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenServerConnector.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenServerConnector.java @@ -47,9 +47,9 @@ import org.eclipse.jetty.util.thread.Scheduler; */ public class MavenServerConnector extends AbstractLifeCycle implements Connector { - public static int DEFAULT_PORT = 8080; - public static String DEFAULT_PORT_STR = String.valueOf(DEFAULT_PORT); - public static int DEFAULT_MAX_IDLE_TIME = 30000; + public static final int DEFAULT_PORT = 8080; + public static final String DEFAULT_PORT_STR = String.valueOf(DEFAULT_PORT); + public static final int DEFAULT_MAX_IDLE_TIME = 30000; private Server server; private ServerConnector delegate; @@ -206,7 +206,7 @@ public class MavenServerConnector extends AbstractLifeCycle implements Connector public ConnectionFactory getDefaultConnectionFactory() { checkDelegate(); - return getDefaultConnectionFactory(); + return this.delegate.getDefaultConnectionFactory(); } /** diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SelectiveJarResource.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SelectiveJarResource.java index 11c8d479d05..d253ca81a27 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SelectiveJarResource.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SelectiveJarResource.java @@ -22,6 +22,7 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.net.URL; import java.util.Arrays; import java.util.Collections; @@ -145,91 +146,87 @@ public class SelectiveJarResource extends JarResource URL jarFileURL = new URL(urlString.substring(startOfJarUrl, endOfJarUrl)); - InputStream is = jarFileURL.openConnection().getInputStream(); - JarInputStream jin = new JarInputStream(is); - JarEntry entry; - - while((entry=jin.getNextJarEntry())!=null) + try (InputStream is = jarFileURL.openConnection().getInputStream(); + JarInputStream jin = new JarInputStream(is)) { - String entryName = entry.getName(); + JarEntry entry; - LOG.debug("Looking at "+entryName); - String dotCheck = entryName.replace('\\', '/'); - dotCheck = URIUtil.canonicalPath(dotCheck); - if (dotCheck == null) + while((entry=jin.getNextJarEntry())!=null) { - LOG.info("Invalid entry: "+entryName); - continue; - } + String entryName = entry.getName(); - File file=new File(directory,entryName); - - if (entry.isDirectory()) - { - if (isIncluded(entryName)) + LOG.debug("Looking at "+entryName); + String dotCheck = entryName.replace('\\', '/'); + dotCheck = URIUtil.canonicalPath(dotCheck); + if (dotCheck == null) { - if (!isExcluded(entryName)) + LOG.info("Invalid entry: "+entryName); + continue; + } + + File file=new File(directory,entryName); + + if (entry.isDirectory()) + { + if (isIncluded(entryName)) { - // Make directory - if (!file.exists()) - file.mkdirs(); + if (!isExcluded(entryName)) + { + // Make directory + if (!file.exists()) + file.mkdirs(); + } + else + LOG.debug("{} dir is excluded", entryName); } else - LOG.debug("{} dir is excluded", entryName); + LOG.debug("{} dir is NOT included", entryName); } else - LOG.debug("{} dir is NOT included", entryName); - } - else - { - //entry is a file, is it included? - if (isIncluded(entryName)) { - if (!isExcluded(entryName)) + //entry is a file, is it included? + if (isIncluded(entryName)) { - // make directory (some jars don't list dirs) - File dir = new File(file.getParent()); - if (!dir.exists()) - dir.mkdirs(); - - // Make file - FileOutputStream fout = null; - try + if (!isExcluded(entryName)) { - fout = new FileOutputStream(file); - IO.copy(jin,fout); - } - finally - { - IO.close(fout); - } + // make directory (some jars don't list dirs) + File dir = new File(file.getParent()); + if (!dir.exists()) + dir.mkdirs(); - // touch the file. - if (entry.getTime()>=0) - file.setLastModified(entry.getTime()); + // Make file + try (OutputStream fout = new FileOutputStream(file)) + { + IO.copy(jin,fout); + } + + // touch the file. + if (entry.getTime()>=0) + file.setLastModified(entry.getTime()); + } + else + LOG.debug("{} file is excluded", entryName); } else - LOG.debug("{} file is excluded", entryName); + LOG.debug("{} file is NOT included", entryName); } - else - LOG.debug("{} file is NOT included", entryName); } - } - - Manifest manifest = jin.getManifest(); - if (manifest != null) - { - if (isIncluded("META-INF") && !isExcluded("META-INF")) + + Manifest manifest = jin.getManifest(); + if (manifest != null) { - File metaInf = new File (directory, "META-INF"); - metaInf.mkdir(); - File f = new File(metaInf, "MANIFEST.MF"); - FileOutputStream fout = new FileOutputStream(f); - manifest.write(fout); - fout.close(); + if (isIncluded("META-INF") && !isExcluded("META-INF")) + { + File metaInf = new File (directory, "META-INF"); + metaInf.mkdir(); + File f = new File(metaInf, "MANIFEST.MF"); + try (OutputStream fout = new FileOutputStream(f)) + { + manifest.write(fout); + } + } } } - IO.close(jin); } } diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Starter.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Starter.java index dcd89597fc1..87f7fe61ba1 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Starter.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Starter.java @@ -20,6 +20,7 @@ package org.eclipse.jetty.maven.plugin; import java.io.File; import java.io.FileInputStream; +import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; @@ -360,7 +361,10 @@ public class Starter { File f = new File(args[++i].trim()); props = new Properties(); - props.load(new FileInputStream(f)); + try (InputStream in = new FileInputStream(f)) + { + props.load(in); + } } //--token diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperties.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperties.java index 590a32f9eff..19b716dfbf6 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperties.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperties.java @@ -34,12 +34,12 @@ import java.util.Map; */ public class SystemProperties { - Map properties; - boolean force; + private final Map properties; + private boolean force; public SystemProperties() { - properties = new HashMap(); + properties = new HashMap<>(); } public void setForce (boolean force) @@ -64,7 +64,7 @@ public class SystemProperties public SystemProperty getSystemProperty(String name) { - return (SystemProperty)properties.get(name); + return properties.get(name); } public boolean containsSystemProperty(String name) @@ -72,8 +72,8 @@ public class SystemProperties return properties.containsKey(name); } - public List getSystemProperties () + public List getSystemProperties () { - return new ArrayList(properties.values()); + return new ArrayList<>(properties.values()); } } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/BundleWatcher.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/BundleWatcher.java index 74622c36b12..9bb9a0210e9 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/BundleWatcher.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/BundleWatcher.java @@ -53,7 +53,7 @@ public class BundleWatcher implements BundleTrackerCustomizer { private static final Logger LOG = Log.getLogger(BundleWatcher.class); - public static Collection JSP_REGISTRATION_HELPERS = new ArrayList(); + public static final Collection JSP_REGISTRATION_HELPERS = new ArrayList(); public static final String FILTER = "(objectclass=" + BundleProvider.class.getName() + ")"; diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/LibExtClassLoaderHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/LibExtClassLoaderHelper.java index b728d214326..5d67290f88c 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/LibExtClassLoaderHelper.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/LibExtClassLoaderHelper.java @@ -73,7 +73,7 @@ public class LibExtClassLoaderHelper - public static Set registeredFilesInJettyHomeResourcesProcessors = new HashSet(); + public static final Set registeredFilesInJettyHomeResourcesProcessors = new HashSet(); /* ------------------------------------------------------------ */ diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/OSGiWebappClassLoader.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/OSGiWebappClassLoader.java index e963b91344a..10ba5d1997d 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/OSGiWebappClassLoader.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/OSGiWebappClassLoader.java @@ -51,13 +51,13 @@ import org.osgi.framework.BundleReference; public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleReference { - private Logger __logger = Log.getLogger(OSGiWebappClassLoader.class.getName().toString()); + private static final Logger __logger = Log.getLogger(OSGiWebappClassLoader.class.getName()); /** * when a logging framework is setup in the osgi classloaders, it can access * this and register the classes that must not be found in the jar. */ - public static Set JAR_WITH_SUCH_CLASS_MUST_BE_EXCLUDED = new HashSet(); + public static final Set JAR_WITH_SUCH_CLASS_MUST_BE_EXCLUDED = new HashSet(); public static void addClassThatIdentifiesAJarThatMustBeRejected(Class zclass) { diff --git a/jetty-overlay-deployer/src/test/java/org/eclipse/jetty/overlays/OverlayedAppProviderTest.java b/jetty-overlay-deployer/src/test/java/org/eclipse/jetty/overlays/OverlayedAppProviderTest.java index 9a5ed717935..bdb9addb133 100644 --- a/jetty-overlay-deployer/src/test/java/org/eclipse/jetty/overlays/OverlayedAppProviderTest.java +++ b/jetty-overlay-deployer/src/test/java/org/eclipse/jetty/overlays/OverlayedAppProviderTest.java @@ -20,6 +20,7 @@ package org.eclipse.jetty.overlays; import java.io.File; import java.io.FileOutputStream; +import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Set; @@ -577,9 +578,10 @@ public class OverlayedAppProviderTest try { IO.delete(file); - FileOutputStream out = new FileOutputStream(file,false); - out.write("

Hello

".getBytes()); - out.close(); + try (OutputStream out = new FileOutputStream(file,false)) + { + out.write("

Hello

".getBytes()); + } } catch(Exception e) { diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java index 8ef3ba53eeb..96e9ae0e1d9 100644 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java +++ b/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java @@ -24,6 +24,7 @@ import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -290,30 +291,32 @@ public class DataSourceLoginService extends MappedLoginService @Override protected UserIdentity loadUser (String userName) { - Connection connection = null; try { initDb(); - connection = getConnection(); - - PreparedStatement statement = connection.prepareStatement(_userSql); - statement.setObject(1, userName); - ResultSet rs = statement.executeQuery(); - - if (rs.next()) + try (Connection connection = getConnection(); + PreparedStatement statement1 = connection.prepareStatement(_userSql)) { - int key = rs.getInt(_userTableKey); - String credentials = rs.getString(_userTablePasswordField); - statement.close(); - - statement = connection.prepareStatement(_roleSql); - statement.setInt(1, key); - rs = statement.executeQuery(); - List roles = new ArrayList(); - while (rs.next()) - roles.add(rs.getString(_roleTableRoleField)); - statement.close(); - return putUser(userName,new Password(credentials), roles.toArray(new String[roles.size()])); + statement1.setObject(1, userName); + try (ResultSet rs1 = statement1.executeQuery()) + { + if (rs1.next()) + { + int key = rs1.getInt(_userTableKey); + String credentials = rs1.getString(_userTablePasswordField); + List roles = new ArrayList(); + try (PreparedStatement statement2 = connection.prepareStatement(_roleSql)) + { + statement2.setInt(1, key); + try (ResultSet rs2 = statement2.executeQuery()) + { + while (rs2.next()) + roles.add(rs2.getString(_roleTableRoleField)); + } + } + return putUser(userName,new Password(credentials), roles.toArray(new String[roles.size()])); + } + } } } catch (NamingException e) @@ -324,24 +327,6 @@ public class DataSourceLoginService extends MappedLoginService { LOG.warn("Problem loading user info for "+userName, e); } - finally - { - if (connection != null) - { - try - { - connection.close(); - } - catch (SQLException x) - { - LOG.warn("Problem closing connection", x); - } - finally - { - connection = null; - } - } - } return null; } @@ -402,93 +387,94 @@ public class DataSourceLoginService extends MappedLoginService private void prepareTables() throws NamingException, SQLException { - Connection connection = null; - boolean autocommit = true; - if (_createTables) { - try + boolean autocommit = true; + Connection connection = getConnection(); + try (Statement stmt = connection.createStatement()) { - connection = getConnection(); autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); - ResultSet result = metaData.getTables(null, null, tableName, null); - if (!result.next()) + try (ResultSet result = metaData.getTables(null, null, tableName, null)) { - //user table default - /* - * create table _userTableName (_userTableKey integer, - * _userTableUserField varchar(100) not null unique, - * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); - */ - connection.createStatement().executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ - _userTableUserField+" varchar(100) not null unique,"+ - _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); - if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); + if (!result.next()) + { + //user table default + /* + * create table _userTableName (_userTableKey integer, + * _userTableUserField varchar(100) not null unique, + * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); + */ + stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ + _userTableUserField+" varchar(100) not null unique,"+ + _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); + if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); + } } - result.close(); - tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); - result = metaData.getTables(null, null, tableName, null); - if (!result.next()) + try (ResultSet result = metaData.getTables(null, null, tableName, null)) { - //role table default - /* - * create table _roleTableName (_roleTableKey integer, - * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); - */ - String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ - _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; - connection.createStatement().executeUpdate(str); - if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); + if (!result.next()) + { + //role table default + /* + * create table _roleTableName (_roleTableKey integer, + * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); + */ + String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ + _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; + stmt.executeUpdate(str); + if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); + } } - result.close(); - tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); - result = metaData.getTables(null, null, tableName, null); - if (!result.next()) + try (ResultSet result = metaData.getTables(null, null, tableName, null)) { - //user-role table - /* - * create table _userRoleTableName (_userRoleTableUserKey integer, - * _userRoleTableRoleKey integer, - * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); - * - * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); - */ - connection.createStatement().executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ - _userRoleTableRoleKey+" integer, "+ - "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); - connection.createStatement().executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); - if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); + if (!result.next()) + { + //user-role table + /* + * create table _userRoleTableName (_userRoleTableUserKey integer, + * _userRoleTableRoleKey integer, + * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); + * + * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); + */ + stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ + _userRoleTableRoleKey+" integer, "+ + "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); + stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); + if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); + } } - - result.close(); connection.commit(); } finally { - if (connection != null) + try + { + connection.setAutoCommit(autocommit); + } + catch (SQLException e) + { + if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); + } + finally { try { - connection.setAutoCommit(autocommit); connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } - finally - { - connection = null; - } } } } diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/JDBCLoginService.java b/jetty-security/src/main/java/org/eclipse/jetty/security/JDBCLoginService.java index 58db6e47274..5373161801c 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/JDBCLoginService.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/JDBCLoginService.java @@ -19,6 +19,7 @@ package org.eclipse.jetty.security; import java.io.IOException; +import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; @@ -116,8 +117,10 @@ public class JDBCLoginService extends MappedLoginService { Properties properties = new Properties(); Resource resource = Resource.newResource(_config); - properties.load(resource.getInputStream()); - + try (InputStream in = resource.getInputStream()) + { + properties.load(in); + } _jdbcDriver = properties.getProperty("jdbcdriver"); _url = properties.getProperty("url"); _userName = properties.getProperty("username"); @@ -238,25 +241,29 @@ public class JDBCLoginService extends MappedLoginService if (null == _con) throw new SQLException("Can't connect to database"); - PreparedStatement stat = _con.prepareStatement(_userSql); - stat.setObject(1, username); - ResultSet rs = stat.executeQuery(); - - if (rs.next()) + try (PreparedStatement stat1 = _con.prepareStatement(_userSql)) { - int key = rs.getInt(_userTableKey); - String credentials = rs.getString(_userTablePasswordField); - stat.close(); + stat1.setObject(1, username); + try (ResultSet rs1 = stat1.executeQuery()) + { + if (rs1.next()) + { + int key = rs1.getInt(_userTableKey); + String credentials = rs1.getString(_userTablePasswordField); + List roles = new ArrayList(); - stat = _con.prepareStatement(_roleSql); - stat.setInt(1, key); - rs = stat.executeQuery(); - List roles = new ArrayList(); - while (rs.next()) - roles.add(rs.getString(_roleTableRoleField)); - - stat.close(); - return putUser(username, Credential.getCredential(credentials),roles.toArray(new String[roles.size()])); + try (PreparedStatement stat2 = _con.prepareStatement(_roleSql)) + { + stat2.setInt(1, key); + try (ResultSet rs2 = stat2.executeQuery()) + { + while (rs2.next()) + roles.add(rs2.getString(_roleTableRoleField)); + } + } + return putUser(username, Credential.getCredential(credentials),roles.toArray(new String[roles.size()])); + } + } } } catch (SQLException e) diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java b/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java index edb5f9156d3..df8a4eb12c6 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java @@ -650,7 +650,7 @@ public abstract class SecurityHandler extends HandlerWrapper implements Authenti /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ - public static Principal __NO_USER = new Principal() + public static final Principal __NO_USER = new Principal() { public String getName() { @@ -674,7 +674,7 @@ public abstract class SecurityHandler extends HandlerWrapper implements Authenti * FormAuthenticator to allow access to logon and error pages within an * authenticated URI tree. */ - public static Principal __NOBODY = new Principal() + public static final Principal __NOBODY = new Principal() { public String getName() { diff --git a/jetty-security/src/test/java/org/eclipse/jetty/security/PropertyUserStoreTest.java b/jetty-security/src/test/java/org/eclipse/jetty/security/PropertyUserStoreTest.java index a25ee6384ec..6b68b9b36ba 100644 --- a/jetty-security/src/test/java/org/eclipse/jetty/security/PropertyUserStoreTest.java +++ b/jetty-security/src/test/java/org/eclipse/jetty/security/PropertyUserStoreTest.java @@ -21,6 +21,7 @@ package org.eclipse.jetty.security; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; +import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; @@ -55,19 +56,21 @@ public class PropertyUserStoreTest private void writeInitialUsers(String testFile) throws Exception { - BufferedWriter writer = new BufferedWriter(new FileWriter(testFile)); - writer.append("tom: tom, roleA\n"); - writer.append("dick: dick, roleB\n"); - writer.append("harry: harry, roleA, roleB\n"); - writer.close(); + try (Writer writer = new BufferedWriter(new FileWriter(testFile))) + { + writer.append("tom: tom, roleA\n"); + writer.append("dick: dick, roleB\n"); + writer.append("harry: harry, roleA, roleB\n"); + } } private void writeAdditionalUser(String testFile) throws Exception { Thread.sleep(1001); - BufferedWriter writer = new BufferedWriter(new FileWriter(testFile,true)); - writer.append("skip: skip, roleA\n"); - writer.close(); + try (Writer writer = new BufferedWriter(new FileWriter(testFile,true))) + { + writer.append("skip: skip, roleA\n"); + } } @Test diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/NCSARequestLog.java b/jetty-server/src/main/java/org/eclipse/jetty/server/NCSARequestLog.java index ef11b3e0c78..33e6b6f7eb2 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/NCSARequestLog.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/NCSARequestLog.java @@ -208,7 +208,7 @@ public class NCSARequestLog extends AbstractNCSARequestLog implements RequestLog { if (_writer==null) return; - _writer.write(requestEntry.toString()); + _writer.write(requestEntry); _writer.write(StringUtil.__LINE_SEPARATOR); _writer.flush(); } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Response.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Response.java index b1fa612447d..16c331cb945 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/Response.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Response.java @@ -423,8 +423,11 @@ public class Response implements HttpServletResponse writer.flush(); setContentLength(writer.size()); - writer.writeTo(getOutputStream()); - writer.destroy(); + try (ServletOutputStream outputStream = getOutputStream()) + { + writer.writeTo(outputStream); + writer.destroy(); + } } } else if (code!=SC_PARTIAL_CONTENT) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java index 3cccf319767..2d8d6ea9a19 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java @@ -169,9 +169,10 @@ public class DefaultHandler extends AbstractHandler writer.write("\n\n\n"); writer.flush(); response.setContentLength(writer.size()); - OutputStream out=response.getOutputStream(); - writer.writeTo(out); - out.close(); + try (OutputStream out=response.getOutputStream()) + { + writer.writeTo(out); + } } /* ------------------------------------------------------------ */ diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java index d1e13ce35b5..07b289d8d66 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java @@ -281,7 +281,7 @@ public class ResourceHandler extends HandlerWrapper { LOG.warn(e.toString()); LOG.debug(e); - throw new IllegalArgumentException(stylesheet.toString()); + throw new IllegalArgumentException(stylesheet); } } @@ -291,7 +291,7 @@ public class ResourceHandler extends HandlerWrapper */ public String getCacheControl() { - return _cacheControl.toString(); + return _cacheControl; } /* ------------------------------------------------------------ */ @@ -484,7 +484,7 @@ public class ResourceHandler extends HandlerWrapper String mime=_mimeTypes.getMimeByExtension(resource.toString()); if (mime==null) mime=_mimeTypes.getMimeByExtension(request.getPathInfo()); - doResponseHeaders(response,resource,mime!=null?mime.toString():null); + doResponseHeaders(response,resource,mime); if (_etags) baseRequest.getResponse().getHttpFields().put(HttpHeader.ETAG,etag); @@ -615,7 +615,7 @@ public class ResourceHandler extends HandlerWrapper response.setContentLength((int)length); if (_cacheControl!=null) - response.setHeader(HttpHeader.CACHE_CONTROL.asString(),_cacheControl.toString()); + response.setHeader(HttpHeader.CACHE_CONTROL.asString(),_cacheControl); } } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionIdManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionIdManager.java index 6590e2420e2..c57188d5d64 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionIdManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionIdManager.java @@ -623,11 +623,10 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager _deleteId = "delete from "+_sessionIdTable+" where id = ?"; _queryId = "select * from "+_sessionIdTable+" where id = ?"; - Connection connection = null; - try + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { //make the id table - connection = getConnection(); connection.setAutoCommit(true); DatabaseMetaData metaData = connection.getMetaData(); _dbAdaptor = new DatabaseAdaptor(metaData); @@ -635,80 +634,86 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager //checking for table existence is case-sensitive, but table creation is not String tableName = _dbAdaptor.convertIdentifier(_sessionIdTable); - ResultSet result = metaData.getTables(null, null, tableName, null); - if (!result.next()) + try (ResultSet result = metaData.getTables(null, null, tableName, null)) { - //table does not exist, so create it - connection.createStatement().executeUpdate(_createSessionIdTable); + if (!result.next()) + { + //table does not exist, so create it + statement.executeUpdate(_createSessionIdTable); + } } - //make the session table if necessary tableName = _dbAdaptor.convertIdentifier(_sessionTable); - result = metaData.getTables(null, null, tableName, null); - if (!result.next()) + try (ResultSet result = metaData.getTables(null, null, tableName, null)) { - //table does not exist, so create it - String blobType = _dbAdaptor.getBlobType(); - String longType = _dbAdaptor.getLongType(); - _createSessionTable = "create table "+_sessionTable+" ("+_sessionTableRowId+" varchar(120), sessionId varchar(120), "+ - " contextPath varchar(60), virtualHost varchar(60), lastNode varchar(60), accessTime "+longType+", "+ - " lastAccessTime "+longType+", createTime "+longType+", cookieTime "+longType+", "+ - " lastSavedTime "+longType+", expiryTime "+longType+", maxInterval "+longType+", map "+blobType+", primary key("+_sessionTableRowId+"))"; - connection.createStatement().executeUpdate(_createSessionTable); - } - else - { - //session table exists, check it has maxinterval column - ResultSet colResult = null; - try + if (!result.next()) { - colResult = metaData.getColumns(null, null,_dbAdaptor.convertIdentifier(_sessionTable), _dbAdaptor.convertIdentifier("maxInterval")); + //table does not exist, so create it + String blobType = _dbAdaptor.getBlobType(); + String longType = _dbAdaptor.getLongType(); + _createSessionTable = "create table "+_sessionTable+" ("+_sessionTableRowId+" varchar(120), sessionId varchar(120), "+ + " contextPath varchar(60), virtualHost varchar(60), lastNode varchar(60), accessTime "+longType+", "+ + " lastAccessTime "+longType+", createTime "+longType+", cookieTime "+longType+", "+ + " lastSavedTime "+longType+", expiryTime "+longType+", maxInterval "+longType+", map "+blobType+", primary key("+_sessionTableRowId+"))"; + statement.executeUpdate(_createSessionTable); } - catch (SQLException s) - { - LOG.warn("Problem checking if "+_sessionTable+" table contains maxInterval column. Ensure table contains column definition: \"maxInterval long not null default -999\""); - throw s; - } - - if (!colResult.next()) + else { + //session table exists, check it has maxinterval column + ResultSet colResult = null; try { - //add the maxinterval column - String longType = _dbAdaptor.getLongType(); - connection.createStatement().executeUpdate("alter table "+_sessionTable+" add maxInterval "+longType+" not null default "+MAX_INTERVAL_NOT_SET); + colResult = metaData.getColumns(null, null,_dbAdaptor.convertIdentifier(_sessionTable), _dbAdaptor.convertIdentifier("maxInterval")); } catch (SQLException s) { - LOG.warn("Problem adding maxInterval column. Ensure table contains column definition: \"maxInterval long not null default -999\""); + LOG.warn("Problem checking if "+_sessionTable+" table contains maxInterval column. Ensure table contains column definition: \"maxInterval long not null default -999\""); throw s; } - } + try + { + if (!colResult.next()) + { + try + { + //add the maxinterval column + String longType = _dbAdaptor.getLongType(); + statement.executeUpdate("alter table "+_sessionTable+" add maxInterval "+longType+" not null default "+MAX_INTERVAL_NOT_SET); + } + catch (SQLException s) + { + LOG.warn("Problem adding maxInterval column. Ensure table contains column definition: \"maxInterval long not null default -999\""); + throw s; + } + } + } + finally + { + colResult.close(); + } + } } - //make some indexes on the JettySessions table String index1 = "idx_"+_sessionTable+"_expiry"; String index2 = "idx_"+_sessionTable+"_session"; - result = metaData.getIndexInfo(null, null, tableName, false, false); boolean index1Exists = false; boolean index2Exists = false; - while (result.next()) + try (ResultSet result = metaData.getIndexInfo(null, null, tableName, false, false)) { - String idxName = result.getString("INDEX_NAME"); - if (index1.equalsIgnoreCase(idxName)) - index1Exists = true; - else if (index2.equalsIgnoreCase(idxName)) - index2Exists = true; - } - if (!(index1Exists && index2Exists)) - { - Statement statement = connection.createStatement(); - if (!index1Exists) - statement.executeUpdate("create index "+index1+" on "+_sessionTable+" (expiryTime)"); - if (!index2Exists) - statement.executeUpdate("create index "+index2+" on "+_sessionTable+" (sessionId, contextPath)"); + while (result.next()) + { + String idxName = result.getString("INDEX_NAME"); + if (index1.equalsIgnoreCase(idxName)) + index1Exists = true; + else if (index2.equalsIgnoreCase(idxName)) + index2Exists = true; + } } + if (!index1Exists) + statement.executeUpdate("create index "+index1+" on "+_sessionTable+" (expiryTime)"); + if (!index2Exists) + statement.executeUpdate("create index "+index2+" on "+_sessionTable+" (sessionId, contextPath)"); //set up some strings representing the statements for session manipulation _insertSession = "insert into "+_sessionTable+ @@ -729,11 +734,6 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager } - finally - { - if (connection != null) - connection.close(); - } } /** @@ -745,27 +745,24 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager private void insert (String id) throws SQLException { - Connection connection = null; - try + try (Connection connection = getConnection(); + PreparedStatement query = connection.prepareStatement(_queryId)) { - connection = getConnection(); connection.setAutoCommit(true); - PreparedStatement query = connection.prepareStatement(_queryId); query.setString(1, id); - ResultSet result = query.executeQuery(); - //only insert the id if it isn't in the db already - if (!result.next()) + try (ResultSet result = query.executeQuery()) { - PreparedStatement statement = connection.prepareStatement(_insertId); - statement.setString(1, id); - statement.executeUpdate(); + //only insert the id if it isn't in the db already + if (!result.next()) + { + try (PreparedStatement statement = connection.prepareStatement(_insertId)) + { + statement.setString(1, id); + statement.executeUpdate(); + } + } } } - finally - { - if (connection != null) - connection.close(); - } } /** @@ -777,20 +774,13 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager private void delete (String id) throws SQLException { - Connection connection = null; - try + try (Connection connection = getConnection(); + PreparedStatement statement = connection.prepareStatement(_deleteId)) { - connection = getConnection(); connection.setAutoCommit(true); - PreparedStatement statement = connection.prepareStatement(_deleteId); statement.setString(1, id); statement.executeUpdate(); } - finally - { - if (connection != null) - connection.close(); - } } @@ -804,20 +794,15 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager private boolean exists (String id) throws SQLException { - Connection connection = null; - try + try (Connection connection = getConnection(); + PreparedStatement statement = connection.prepareStatement(_queryId)) { - connection = getConnection(); connection.setAutoCommit(true); - PreparedStatement statement = connection.prepareStatement(_queryId); statement.setString(1, id); - ResultSet result = statement.executeQuery(); - return result.next(); - } - finally - { - if (connection != null) - connection.close(); + try (ResultSet result = statement.executeQuery()) + { + return result.next(); + } } } @@ -835,7 +820,6 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager private void scavenge () { Connection connection = null; - Set expiredSessionIds = new HashSet(); try { if (LOG.isDebugEnabled()) @@ -844,70 +828,78 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager { connection = getConnection(); connection.setAutoCommit(true); + Set expiredSessionIds = new HashSet(); //Pass 1: find sessions for which we were last managing node that have just expired since last pass - PreparedStatement statement = connection.prepareStatement(_selectBoundedExpiredSessions); long lowerBound = (_lastScavengeTime - _scavengeIntervalMs); long upperBound = _lastScavengeTime; if (LOG.isDebugEnabled()) LOG.debug (getWorkerName()+"- Pass 1: Searching for sessions expired between "+lowerBound + " and "+upperBound); - statement.setString(1, getWorkerName()); - statement.setLong(2, lowerBound); - statement.setLong(3, upperBound); - ResultSet result = statement.executeQuery(); - while (result.next()) + try (PreparedStatement statement = connection.prepareStatement(_selectBoundedExpiredSessions)) { - String sessionId = result.getString("sessionId"); - expiredSessionIds.add(sessionId); - if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId); + statement.setString(1, getWorkerName()); + statement.setLong(2, lowerBound); + statement.setLong(3, upperBound); + try (ResultSet result = statement.executeQuery()) + { + while (result.next()) + { + String sessionId = result.getString("sessionId"); + expiredSessionIds.add(sessionId); + if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId); + } + } } - result.close(); scavengeSessions(expiredSessionIds, false); - + //Pass 2: find sessions that have expired a while ago for which this node was their last manager - PreparedStatement selectExpiredSessions = connection.prepareStatement(_selectExpiredSessions); - expiredSessionIds.clear(); - upperBound = _lastScavengeTime - (2 * _scavengeIntervalMs); - if (upperBound > 0) - { - if (LOG.isDebugEnabled()) LOG.debug(getWorkerName()+"- Pass 2: Searching for sessions expired before "+upperBound); - selectExpiredSessions.setLong(1, upperBound); - result = selectExpiredSessions.executeQuery(); - while (result.next()) - { - String sessionId = result.getString("sessionId"); - String lastNode = result.getString("lastNode"); - if ((getWorkerName() == null && lastNode == null) || (getWorkerName() != null && getWorkerName().equals(lastNode))) - expiredSessionIds.add(sessionId); - if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId+" last managed by "+getWorkerName()); - } - result.close(); - scavengeSessions(expiredSessionIds, false); - } - - - //Pass 3: - //find all sessions that have expired at least a couple of scanIntervals ago - //if we did not succeed in loading them (eg their related context no longer exists, can't be loaded etc) then - //they are simply deleted - upperBound = _lastScavengeTime - (3 * _scavengeIntervalMs); - expiredSessionIds.clear(); - if (upperBound > 0) + try (PreparedStatement selectExpiredSessions = connection.prepareStatement(_selectExpiredSessions)) { - if (LOG.isDebugEnabled()) LOG.debug(getWorkerName()+"- Pass 3: searching for sessions expired before "+upperBound); - selectExpiredSessions.setLong(1, upperBound); - result = selectExpiredSessions.executeQuery(); - while (result.next()) + expiredSessionIds.clear(); + upperBound = _lastScavengeTime - (2 * _scavengeIntervalMs); + if (upperBound > 0) { - String sessionId = result.getString("sessionId"); - expiredSessionIds.add(sessionId); - if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId); - } - result.close(); - scavengeSessions(expiredSessionIds, true); + if (LOG.isDebugEnabled()) LOG.debug(getWorkerName()+"- Pass 2: Searching for sessions expired before "+upperBound); + selectExpiredSessions.setLong(1, upperBound); + try (ResultSet result = selectExpiredSessions.executeQuery()) + { + while (result.next()) + { + String sessionId = result.getString("sessionId"); + String lastNode = result.getString("lastNode"); + if ((getWorkerName() == null && lastNode == null) || (getWorkerName() != null && getWorkerName().equals(lastNode))) + expiredSessionIds.add(sessionId); + if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId+" last managed by "+getWorkerName()); + } + } + scavengeSessions(expiredSessionIds, false); + } + + + //Pass 3: + //find all sessions that have expired at least a couple of scanIntervals ago + //if we did not succeed in loading them (eg their related context no longer exists, can't be loaded etc) then + //they are simply deleted + upperBound = _lastScavengeTime - (3 * _scavengeIntervalMs); + expiredSessionIds.clear(); + if (upperBound > 0) + { + if (LOG.isDebugEnabled()) LOG.debug(getWorkerName()+"- Pass 3: searching for sessions expired before "+upperBound); + selectExpiredSessions.setLong(1, upperBound); + try (ResultSet result = selectExpiredSessions.executeQuery()) + { + while (result.next()) + { + String sessionId = result.getString("sessionId"); + expiredSessionIds.add(sessionId); + if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId); + } + } + scavengeSessions(expiredSessionIds, true); + } } } } @@ -990,10 +982,8 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager return; String[] ids = expiredIds.toArray(new String[expiredIds.size()]); - Connection con = null; - try + try (Connection con = getConnection()) { - con = getConnection(); con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); con.setAutoCommit(false); @@ -1002,38 +992,29 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager int blocksize = _deleteBlockSize; int block = 0; - while (end < ids.length) + try (Statement statement = con.createStatement()) { - start = block*blocksize; - if ((ids.length - start) >= blocksize) - end = start + blocksize; - else - end = ids.length; - - Statement statement = con.createStatement(); - //take them out of the sessionIds table - statement.executeUpdate(fillInClause("delete from "+_sessionIdTable+" where id in ", ids, start, end)); - //take them out of the sessions table - statement.executeUpdate(fillInClause("delete from "+_sessionTable+" where sessionId in ", ids, start, end)); - block++; - } - con.commit(); + while (end < ids.length) + { + start = block*blocksize; + if ((ids.length - start) >= blocksize) + end = start + blocksize; + else + end = ids.length; - } - catch (Exception e) - { - if (con != null) + //take them out of the sessionIds table + statement.executeUpdate(fillInClause("delete from "+_sessionIdTable+" where id in ", ids, start, end)); + //take them out of the sessions table + statement.executeUpdate(fillInClause("delete from "+_sessionTable+" where sessionId in ", ids, start, end)); + block++; + } + } + catch (Exception e) { con.rollback(); throw e; } - } - finally - { - if (con != null) - { - con.close(); - } + con.commit(); } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionManager.java index bf595d15bb2..99314557ee3 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionManager.java @@ -874,14 +874,11 @@ public class JDBCSessionManager extends AbstractSessionManager @SuppressWarnings("unchecked") public void run() { - Session session = null; - Connection connection=null; - PreparedStatement statement = null; - try + try (Connection connection = getConnection(); + PreparedStatement statement = _jdbcSessionIdMgr._dbAdaptor.getLoadStatement(connection, id, canonicalContextPath, vhost); + ResultSet result = statement.executeQuery()) { - connection = getConnection(); - statement = _jdbcSessionIdMgr._dbAdaptor.getLoadStatement(connection, id, canonicalContextPath, vhost); - ResultSet result = statement.executeQuery(); + Session session = null; if (result.next()) { long maxInterval = result.getLong("maxInterval"); @@ -901,11 +898,12 @@ public class JDBCSessionManager extends AbstractSessionManager session.setCanonicalContext(result.getString("contextPath")); session.setVirtualHost(result.getString("virtualHost")); - InputStream is = ((JDBCSessionIdManager)getSessionIdManager())._dbAdaptor.getBlobInputStream(result, "map"); - ClassLoadingObjectInputStream ois = new ClassLoadingObjectInputStream (is); - Object o = ois.readObject(); - session.addAttributes((Map)o); - ois.close(); + try (InputStream is = ((JDBCSessionIdManager)getSessionIdManager())._dbAdaptor.getBlobInputStream(result, "map"); + ClassLoadingObjectInputStream ois = new ClassLoadingObjectInputStream(is)) + { + Object o = ois.readObject(); + session.addAttributes((Map)o); + } if (LOG.isDebugEnabled()) LOG.debug("LOADED session "+session); @@ -919,14 +917,6 @@ public class JDBCSessionManager extends AbstractSessionManager { _exception.set(e); } - finally - { - if (connection!=null) - { - try { connection.close();} - catch(Exception e) { LOG.warn(e); } - } - } } }; @@ -959,15 +949,13 @@ public class JDBCSessionManager extends AbstractSessionManager return; //put into the database - Connection connection = getConnection(); - PreparedStatement statement = null; - try + try (Connection connection = getConnection(); + PreparedStatement statement = connection.prepareStatement(_jdbcSessionIdMgr._insertSession)) { String rowId = calculateRowId(session); long now = System.currentTimeMillis(); connection.setAutoCommit(true); - statement = connection.prepareStatement(_jdbcSessionIdMgr._insertSession); statement.setString(1, rowId); //rowId statement.setString(2, session.getId()); //session id statement.setString(3, session.getCanonicalContext()); //context path @@ -984,6 +972,7 @@ public class JDBCSessionManager extends AbstractSessionManager ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(session.getAttributeMap()); + oos.flush(); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); @@ -993,16 +982,9 @@ public class JDBCSessionManager extends AbstractSessionManager statement.executeUpdate(); session.setRowId(rowId); //set it on the in-memory data as well as in db session.setLastSaved(now); - - - if (LOG.isDebugEnabled()) - LOG.debug("Stored session "+session); - } - finally - { - if (connection!=null) - connection.close(); } + if (LOG.isDebugEnabled()) + LOG.debug("Stored session "+session); } @@ -1018,13 +1000,11 @@ public class JDBCSessionManager extends AbstractSessionManager if (data==null) return; - Connection connection = getConnection(); - PreparedStatement statement = null; - try + try (Connection connection = getConnection(); + PreparedStatement statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSession)) { long now = System.currentTimeMillis(); connection.setAutoCommit(true); - statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSession); statement.setString(1, data.getId()); statement.setString(2, getSessionIdManager().getWorkerName());//my node id statement.setLong(3, data.getAccessed());//accessTime @@ -1036,6 +1016,7 @@ public class JDBCSessionManager extends AbstractSessionManager ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(data.getAttributeMap()); + oos.flush(); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); @@ -1044,14 +1025,9 @@ public class JDBCSessionManager extends AbstractSessionManager statement.executeUpdate(); data.setLastSaved(now); - if (LOG.isDebugEnabled()) - LOG.debug("Updated session "+data); - } - finally - { - if (connection!=null) - connection.close(); } + if (LOG.isDebugEnabled()) + LOG.debug("Updated session "+data); } @@ -1065,24 +1041,16 @@ public class JDBCSessionManager extends AbstractSessionManager throws Exception { String nodeId = getSessionIdManager().getWorkerName(); - Connection connection = getConnection(); - PreparedStatement statement = null; - try + try (Connection connection = getConnection(); + PreparedStatement statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSessionNode)) { connection.setAutoCommit(true); - statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSessionNode); statement.setString(1, nodeId); statement.setString(2, data.getRowId()); statement.executeUpdate(); - statement.close(); - if (LOG.isDebugEnabled()) - LOG.debug("Updated last node for session id="+data.getId()+", lastNode = "+nodeId); - } - finally - { - if (connection!=null) - connection.close(); } + if (LOG.isDebugEnabled()) + LOG.debug("Updated last node for session id="+data.getId()+", lastNode = "+nodeId); } /** @@ -1094,13 +1062,11 @@ public class JDBCSessionManager extends AbstractSessionManager private void updateSessionAccessTime (Session data) throws Exception { - Connection connection = getConnection(); - PreparedStatement statement = null; - try + try (Connection connection = getConnection(); + PreparedStatement statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSessionAccessTime)) { long now = System.currentTimeMillis(); connection.setAutoCommit(true); - statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSessionAccessTime); statement.setString(1, getSessionIdManager().getWorkerName()); statement.setLong(2, data.getAccessed()); statement.setLong(3, data.getLastAccessedTime()); @@ -1111,15 +1077,9 @@ public class JDBCSessionManager extends AbstractSessionManager statement.executeUpdate(); data.setLastSaved(now); - statement.close(); - if (LOG.isDebugEnabled()) - LOG.debug("Updated access time session id="+data.getId()); - } - finally - { - if (connection!=null) - connection.close(); } + if (LOG.isDebugEnabled()) + LOG.debug("Updated access time session id="+data.getId()); } @@ -1135,22 +1095,15 @@ public class JDBCSessionManager extends AbstractSessionManager protected void deleteSession (Session data) throws Exception { - Connection connection = getConnection(); - PreparedStatement statement = null; - try + try (Connection connection = getConnection(); + PreparedStatement statement = connection.prepareStatement(_jdbcSessionIdMgr._deleteSession)) { connection.setAutoCommit(true); - statement = connection.prepareStatement(_jdbcSessionIdMgr._deleteSession); statement.setString(1, data.getRowId()); statement.executeUpdate(); if (LOG.isDebugEnabled()) LOG.debug("Deleted Session "+data); } - finally - { - if (connection!=null) - connection.close(); - } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/DumpHandler.java b/jetty-server/src/test/java/org/eclipse/jetty/server/DumpHandler.java index 27440fa815b..0f86e01f5e6 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/DumpHandler.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/DumpHandler.java @@ -117,7 +117,7 @@ public class DumpHandler extends AbstractHandler Enumeration names=request.getParameterNames(); while(names.hasMoreElements()) { - String name=names.nextElement().toString(); + String name=names.nextElement(); String[] values=request.getParameterValues(name); if (values==null || values.length==0) { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java index e2d94bfbbf4..a731c421143 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java @@ -988,10 +988,12 @@ public class RequestTest if (evil_keys.exists()) { LOG.info("Using real evil keys!"); - BufferedReader in = new BufferedReader(new FileReader(evil_keys)); - String key=null; - while((key=in.readLine())!=null) - buf.append("&").append(key).append("=").append("x"); + try (BufferedReader in = new BufferedReader(new FileReader(evil_keys))) + { + String key=null; + while((key=in.readLine())!=null) + buf.append("&").append(key).append("=").append("x"); + } } else { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ResourceCacheTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ResourceCacheTest.java index 09ebcf4acab..3383b596b59 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ResourceCacheTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ResourceCacheTest.java @@ -25,6 +25,7 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.InputStreamReader; +import java.io.OutputStream; import org.eclipse.jetty.http.HttpContent; import org.eclipse.jetty.http.MimeTypes; @@ -117,11 +118,12 @@ public class ResourceCacheTest files[i]=File.createTempFile("R-"+i+"-",".txt"); files[i].deleteOnExit(); names[i]=files[i].getName(); - FileOutputStream out = new FileOutputStream(files[i]); - for (int j=0;j<(i*10-1);j++) - out.write(' '); - out.write('\n'); - out.close(); + try (OutputStream out = new FileOutputStream(files[i])) + { + for (int j=0;j<(i*10-1);j++) + out.write(' '); + out.write('\n'); + } } directory=Resource.newResource(files[0].getParentFile().getAbsolutePath()); @@ -182,9 +184,10 @@ public class ResourceCacheTest Thread.sleep(200); - FileOutputStream out = new FileOutputStream(files[6]); - out.write(' '); - out.close(); + try (OutputStream out = new FileOutputStream(files[6])) + { + out.write(' '); + } content=cache.lookup(names[7]); assertEquals(70,cache.getCachedSize()); assertEquals(1,cache.getCachedFiles()); @@ -250,10 +253,11 @@ public class ResourceCacheTest { StringBuilder buffer = new StringBuilder(); String line = null; - BufferedReader br = new BufferedReader(new InputStreamReader(r.addPath(path).getURL().openStream())); - while((line=br.readLine())!=null) - buffer.append(line); - br.close(); + try (BufferedReader br = new BufferedReader(new InputStreamReader(r.addPath(path).getURL().openStream()))) + { + while((line=br.readLine())!=null) + buffer.append(line); + } return buffer.toString(); } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerTest.java index 1a63f0a6c53..8e65b661412 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerTest.java @@ -21,6 +21,8 @@ package org.eclipse.jetty.server.handler; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; import java.net.Socket; import java.net.URI; @@ -58,11 +60,14 @@ public class ResourceHandlerTest File dir = MavenTestingUtils.getTargetFile("test-classes/simple"); File huge = new File(dir,"huge.txt"); File big=new File(dir,"big.txt"); - FileOutputStream out = new FileOutputStream(huge); - for (int i=0;i<100;i++) - { - FileInputStream in=new FileInputStream(big); - IO.copy(in,out); + try (OutputStream out = new FileOutputStream(huge)) { + for (int i=0;i<100;i++) + { + try (InputStream in=new FileInputStream(big)) + { + IO.copy(in,out); + } + } } huge.deleteOnExit(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLSelectChannelConnectorLoadTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLSelectChannelConnectorLoadTest.java index e160c45cbdb..322f274e00c 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLSelectChannelConnectorLoadTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLSelectChannelConnectorLoadTest.java @@ -75,7 +75,10 @@ public class SSLSelectChannelConnectorLoadTest server.start(); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(new FileInputStream(keystorePath), "storepwd".toCharArray()); + try (InputStream stream = new FileInputStream(keystorePath)) + { + keystore.load(stream, "storepwd".toCharArray()); + } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keystore); sslContext = SSLContext.getInstance("SSL"); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SelectChannelServerSslTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SelectChannelServerSslTest.java index 94b8bcfb4fb..6c37535b862 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SelectChannelServerSslTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SelectChannelServerSslTest.java @@ -21,6 +21,7 @@ package org.eclipse.jetty.server.ssl; import static org.junit.Assert.assertEquals; import java.io.FileInputStream; +import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; @@ -111,7 +112,10 @@ public class SelectChannelServerSslTest extends HttpServerTestBase startServer(connector); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(new FileInputStream(sslContextFactory.getKeyStorePath()), "storepwd".toCharArray()); + try (InputStream stream = new FileInputStream(sslContextFactory.getKeyStorePath())) + { + keystore.load(stream, "storepwd".toCharArray()); + } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keystore); __sslContext = SSLContext.getInstance("TLS"); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslSelectChannelTimeoutTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslSelectChannelTimeoutTest.java index 6d1551b6edc..7e40aecee09 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslSelectChannelTimeoutTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslSelectChannelTimeoutTest.java @@ -19,6 +19,7 @@ package org.eclipse.jetty.server.ssl; import java.io.FileInputStream; +import java.io.InputStream; import java.net.Socket; import java.security.KeyStore; @@ -55,7 +56,10 @@ public class SslSelectChannelTimeoutTest extends ConnectorTimeoutTest startServer(connector); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(new FileInputStream(keystorePath), "storepwd".toCharArray()); + try (InputStream stream = new FileInputStream(keystorePath)) + { + keystore.load(stream, "storepwd".toCharArray()); + } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keystore); __sslContext = SSLContext.getInstance("SSL"); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslUploadTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslUploadTest.java index fbda4c59055..d4ef124138e 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslUploadTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslUploadTest.java @@ -88,7 +88,10 @@ public class SslUploadTest { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); SslContextFactory ctx=connector.getConnectionFactory(SslConnectionFactory.class).getSslContextFactory(); - keystore.load(new FileInputStream(ctx.getKeyStorePath()), "storepwd".toCharArray()); + try (InputStream stream = new FileInputStream(ctx.getKeyStorePath())) + { + keystore.load(stream, "storepwd".toCharArray()); + } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keystore); SSLContext sslContext = SSLContext.getInstance("SSL"); diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/DefaultServlet.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/DefaultServlet.java index 97f69b295ac..8743cd79485 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/DefaultServlet.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/DefaultServlet.java @@ -664,7 +664,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory while (!match && quoted.hasMoreTokens()) { String tag = quoted.nextToken(); - if (content.getETag().toString().equals(tag)) + if (content.getETag().equals(tag)) match=true; } } @@ -680,7 +680,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory if (if_non_match_etag!=null && content.getETag()!=null) { // Look for GzipFiltered version of etag - if (content.getETag().toString().equals(request.getAttribute("o.e.j.s.GzipFilter.ETag"))) + if (content.getETag().equals(request.getAttribute("o.e.j.s.GzipFilter.ETag"))) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader(HttpHeader.ETAG.asString(),if_non_match_etag); @@ -688,7 +688,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory } // Handle special case of exact match. - if (content.getETag().toString().equals(if_non_match_etag)) + if (content.getETag().equals(if_non_match_etag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader(HttpHeader.ETAG.asString(),content.getETag()); @@ -700,7 +700,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory while (quoted.hasMoreTokens()) { String tag = quoted.nextToken(); - if (content.getETag().toString().equals(tag)) + if (content.getETag().equals(tag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader(HttpHeader.ETAG.asString(),content.getETag()); @@ -923,7 +923,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory // content-length header // writeHeaders(response,content,-1); - String mimetype=(content==null||content.getContentType()==null?null:content.getContentType().toString()); + String mimetype=(content==null?null:content.getContentType()); if (mimetype==null) LOG.warn("Unknown mimetype for "+request.getRequestURI()); MultiPartOutputStream multi = new MultiPartOutputStream(out); @@ -1041,7 +1041,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory writeOptionHeaders(response); if (_etags) - response.setHeader(HttpHeader.ETAG.asString(),content.getETag().toString()); + response.setHeader(HttpHeader.ETAG.asString(),content.getETag()); } } diff --git a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/CGI.java b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/CGI.java index 9a34873f4ef..1ef2cf3f7b6 100644 --- a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/CGI.java +++ b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/CGI.java @@ -409,9 +409,10 @@ public class CGI extends HttpServlet { try { - Writer outToCgi = new OutputStreamWriter(p.getOutputStream()); - outToCgi.write(input); - outToCgi.close(); + try (Writer outToCgi = new OutputStreamWriter(p.getOutputStream())) + { + outToCgi.write(input); + } } catch (IOException e) { diff --git a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/PutFilter.java b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/PutFilter.java index 66731684202..f96d29dbec2 100644 --- a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/PutFilter.java +++ b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/PutFilter.java @@ -219,24 +219,26 @@ public class PutFilter implements Filter if (_putAtomic) { File tmp=File.createTempFile(file.getName(),null,_tmpdir); - OutputStream out = new FileOutputStream(tmp,false); - if (toRead >= 0) - IO.copy(in, out, toRead); - else - IO.copy(in, out); - out.close(); + try (OutputStream out = new FileOutputStream(tmp,false)) + { + if (toRead >= 0) + IO.copy(in, out, toRead); + else + IO.copy(in, out); + } if (!tmp.renameTo(file)) throw new IOException("rename from "+tmp+" to "+file+" failed"); } else { - OutputStream out = new FileOutputStream(file,false); - if (toRead >= 0) - IO.copy(in, out, toRead); - else - IO.copy(in, out); - out.close(); + try (OutputStream out = new FileOutputStream(file,false)) + { + if (toRead >= 0) + IO.copy(in, out, toRead); + else + IO.copy(in, out); + } } response.setStatus(exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED); diff --git a/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/IncludableGzipFilterTest.java b/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/IncludableGzipFilterTest.java index 10ec3f62f14..6292fa77a68 100644 --- a/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/IncludableGzipFilterTest.java +++ b/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/IncludableGzipFilterTest.java @@ -26,6 +26,7 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; +import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; @@ -95,10 +96,11 @@ public class IncludableGzipFilterTest testdir.ensureEmpty(); File testFile = testdir.getFile("file.txt"); - BufferedOutputStream testOut = new BufferedOutputStream(new FileOutputStream(testFile)); - ByteArrayInputStream testIn = new ByteArrayInputStream(__content.getBytes("ISO8859_1")); - IO.copy(testIn,testOut); - testOut.close(); + try (OutputStream testOut = new BufferedOutputStream(new FileOutputStream(testFile))) + { + ByteArrayInputStream testIn = new ByteArrayInputStream(__content.getBytes("ISO8859_1")); + IO.copy(testIn,testOut); + } tester=new ServletTester("/context"); tester.getContext().setResourceBase(testdir.getDir().getCanonicalPath()); diff --git a/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/PutFilterTest.java b/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/PutFilterTest.java index 266601b6d6b..132db2effd6 100644 --- a/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/PutFilterTest.java +++ b/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/PutFilterTest.java @@ -23,6 +23,7 @@ import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; +import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.URL; @@ -193,9 +194,10 @@ public class PutFilterTest File file=new File(_dir,"file.txt"); assertTrue(file.exists()); - FileInputStream fis = new FileInputStream(file); - assertEquals(data1,IO.toString(fis)); - fis.close(); + try (InputStream fis = new FileInputStream(file)) + { + assertEquals(data1,IO.toString(fis)); + } request.setMethod("DELETE"); request.setURI("/context/file.txt"); @@ -231,9 +233,10 @@ public class PutFilterTest File file=new File(_dir,"file.txt"); assertTrue(file.exists()); - FileInputStream fis = new FileInputStream(file); - assertEquals(data1,IO.toString(fis)); - fis.close(); + try (InputStream fis = new FileInputStream(file)) + { + assertEquals(data1,IO.toString(fis)); + } request.setMethod("MOVE"); request.setURI("/context/file.txt"); diff --git a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/api/Settings.java b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/api/Settings.java index 010267ed698..234cfe75e93 100644 --- a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/api/Settings.java +++ b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/api/Settings.java @@ -25,10 +25,11 @@ import java.util.Map; public class Settings implements Iterable { - private Map settings = new HashMap<>(); + private final Map settings; public Settings() { + settings = new HashMap<>(); } public Settings(Settings original, boolean immutable) @@ -94,13 +95,13 @@ public class Settings implements Iterable public static final class ID { - public static ID UPLOAD_BANDWIDTH = new ID(1); - public static ID DOWNLOAD_BANDWIDTH = new ID(2); - public static ID ROUND_TRIP_TIME = new ID(3); - public static ID MAX_CONCURRENT_STREAMS = new ID(4); - public static ID CURRENT_CONGESTION_WINDOW = new ID(5); - public static ID DOWNLOAD_RETRANSMISSION_RATE = new ID(6); - public static ID INITIAL_WINDOW_SIZE = new ID(7); + public static final ID UPLOAD_BANDWIDTH = new ID(1); + public static final ID DOWNLOAD_BANDWIDTH = new ID(2); + public static final ID ROUND_TRIP_TIME = new ID(3); + public static final ID MAX_CONCURRENT_STREAMS = new ID(4); + public static final ID CURRENT_CONGESTION_WINDOW = new ID(5); + public static final ID DOWNLOAD_RETRANSMISSION_RATE = new ID(6); + public static final ID INITIAL_WINDOW_SIZE = new ID(7); public synchronized static ID from(int code) { diff --git a/jetty-spdy/spdy-core/src/test/java/org/eclipse/jetty/spdy/generator/DataFrameGeneratorTest.java b/jetty-spdy/spdy-core/src/test/java/org/eclipse/jetty/spdy/generator/DataFrameGeneratorTest.java index 42e3d5d8acc..e87b2865009 100644 --- a/jetty-spdy/spdy-core/src/test/java/org/eclipse/jetty/spdy/generator/DataFrameGeneratorTest.java +++ b/jetty-spdy/spdy-core/src/test/java/org/eclipse/jetty/spdy/generator/DataFrameGeneratorTest.java @@ -19,7 +19,7 @@ package org.eclipse.jetty.spdy.generator; import java.nio.ByteBuffer; -import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; import org.eclipse.jetty.io.ArrayByteBufferPool; import org.eclipse.jetty.spdy.api.ByteBufferDataInfo; @@ -93,7 +93,7 @@ public class DataFrameGeneratorTest private ByteBuffer createByteBuffer(int bufferSize) { byte[] bytes = new byte[bufferSize]; - new Random().nextBytes(bytes); + ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer byteBuffer = bufferPool.acquire(bufferSize, false); BufferUtil.flipToFill(byteBuffer); byteBuffer.put(bytes); diff --git a/jetty-spdy/spdy-server/src/test/java/org/eclipse/jetty/spdy/server/PushStreamTest.java b/jetty-spdy/spdy-server/src/test/java/org/eclipse/jetty/spdy/server/PushStreamTest.java index 344667e8c95..243bd843513 100644 --- a/jetty-spdy/spdy-server/src/test/java/org/eclipse/jetty/spdy/server/PushStreamTest.java +++ b/jetty-spdy/spdy-server/src/test/java/org/eclipse/jetty/spdy/server/PushStreamTest.java @@ -24,11 +24,11 @@ import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Arrays; -import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; @@ -349,7 +349,7 @@ public class PushStreamTest extends AbstractTest private byte[] createHugeByteArray(int sizeInBytes) { byte[] bytes = new byte[sizeInBytes]; - new Random().nextBytes(bytes); + ThreadLocalRandom.current().nextBytes(bytes); return bytes; } diff --git a/jetty-start/src/main/java/org/eclipse/jetty/start/Main.java b/jetty-start/src/main/java/org/eclipse/jetty/start/Main.java index 3ea743ad778..4a5ed837792 100644 --- a/jetty-start/src/main/java/org/eclipse/jetty/start/Main.java +++ b/jetty-start/src/main/java/org/eclipse/jetty/start/Main.java @@ -742,7 +742,10 @@ public class Main File prop_file = File.createTempFile("start",".properties"); if (!_dryRun) prop_file.deleteOnExit(); - properties.store(new FileOutputStream(prop_file),"start.jar properties"); + try (OutputStream out = new FileOutputStream(prop_file)) + { + properties.store(out,"start.jar properties"); + } cmd.addArg(prop_file.getAbsolutePath()); } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/DateCache.java b/jetty-util/src/main/java/org/eclipse/jetty/util/DateCache.java index c070fcc32d8..e5dbf1f4be4 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/DateCache.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/DateCache.java @@ -46,9 +46,9 @@ import java.util.TimerTask; public class DateCache { - public static String DEFAULT_FORMAT="EEE MMM dd HH:mm:ss zzz yyyy"; + public static final String DEFAULT_FORMAT="EEE MMM dd HH:mm:ss zzz yyyy"; - private String _formatString; + private final String _formatString; private String _tzFormatString; private SimpleDateFormat _tzFormat; diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/IO.java b/jetty-util/src/main/java/org/eclipse/jetty/util/IO.java index f0a3d9ed1c9..0194edd8499 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/IO.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/IO.java @@ -52,7 +52,7 @@ public class IO CRLF_BYTES = {(byte)'\015',(byte)'\012'}; /* ------------------------------------------------------------------- */ - public static int bufferSize = 64*1024; + public static final int bufferSize = 64*1024; /* ------------------------------------------------------------------- */ // TODO get rid of this singleton! @@ -298,11 +298,11 @@ public class IO /* ------------------------------------------------------------ */ public static void copyFile(File from,File to) throws IOException { - FileInputStream in=new FileInputStream(from); - FileOutputStream out=new FileOutputStream(to); - copy(in,out); - in.close(); - out.close(); + try (InputStream in=new FileInputStream(from); + OutputStream out=new FileOutputStream(to)) + { + copy(in,out); + } } /* ------------------------------------------------------------ */ diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/MultiPartWriter.java b/jetty-util/src/main/java/org/eclipse/jetty/util/MultiPartWriter.java index bf140575811..55a8e29afd3 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/MultiPartWriter.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/MultiPartWriter.java @@ -35,8 +35,8 @@ public class MultiPartWriter extends FilterWriter private final static String __CRLF="\015\012"; private final static String __DASHDASH="--"; - public static String MULTIPART_MIXED=MultiPartOutputStream.MULTIPART_MIXED; - public static String MULTIPART_X_MIXED_REPLACE=MultiPartOutputStream.MULTIPART_X_MIXED_REPLACE; + public static final String MULTIPART_MIXED=MultiPartOutputStream.MULTIPART_MIXED; + public static final String MULTIPART_X_MIXED_REPLACE=MultiPartOutputStream.MULTIPART_X_MIXED_REPLACE; /* ------------------------------------------------------------ */ private String boundary; @@ -63,14 +63,20 @@ public class MultiPartWriter extends FilterWriter public void close() throws IOException { - if (inPart) + try + { + if (inPart) + out.write(__CRLF); + out.write(__DASHDASH); + out.write(boundary); + out.write(__DASHDASH); out.write(__CRLF); - out.write(__DASHDASH); - out.write(boundary); - out.write(__DASHDASH); - out.write(__CRLF); - inPart=false; - super.close(); + inPart=false; + } + finally + { + super.close(); + } } /* ------------------------------------------------------------ */ diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java b/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java index 58ede8b0b13..03e8b2c480f 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java @@ -92,7 +92,7 @@ public class StringUtil /* ------------------------------------------------------------ */ - public static char[] lowercases = { + public static final char[] lowercases = { '\000','\001','\002','\003','\004','\005','\006','\007', '\010','\011','\012','\013','\014','\015','\016','\017', '\020','\021','\022','\023','\024','\025','\026','\027', diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/TypeUtil.java b/jetty-util/src/main/java/org/eclipse/jetty/util/TypeUtil.java index d63fe379c47..f7371e493c4 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/TypeUtil.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/TypeUtil.java @@ -47,8 +47,8 @@ public class TypeUtil { private static final Logger LOG = Log.getLogger(TypeUtil.class); public static final Class[] NO_ARGS = new Class[]{}; - public static int CR = '\015'; - public static int LF = '\012'; + public static final int CR = '\015'; + public static final int LF = '\012'; /* ------------------------------------------------------------ */ private static final HashMap> name2Class=new HashMap<>(); diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/component/FileNoticeLifeCycleListener.java b/jetty-util/src/main/java/org/eclipse/jetty/util/component/FileNoticeLifeCycleListener.java index b514a5855dd..e40a1d7277c 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/component/FileNoticeLifeCycleListener.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/component/FileNoticeLifeCycleListener.java @@ -19,6 +19,7 @@ package org.eclipse.jetty.util.component; import java.io.FileWriter; +import java.io.Writer; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; @@ -30,7 +31,7 @@ import org.eclipse.jetty.util.log.Logger; */ public class FileNoticeLifeCycleListener implements LifeCycle.Listener { - Logger LOG = Log.getLogger(FileNoticeLifeCycleListener.class); + private static final Logger LOG = Log.getLogger(FileNoticeLifeCycleListener.class); private final String _filename; @@ -41,11 +42,9 @@ public class FileNoticeLifeCycleListener implements LifeCycle.Listener private void writeState(String action, LifeCycle lifecycle) { - try + try (Writer out = new FileWriter(_filename,true)) { - FileWriter out = new FileWriter(_filename,true); out.append(action).append(" ").append(lifecycle.toString()).append("\n"); - out.close(); } catch(Exception e) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/log/Log.java b/jetty-util/src/main/java/org/eclipse/jetty/util/log/Log.java index 558ac07b5e3..6a26c734f09 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/log/Log.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/log/Log.java @@ -58,7 +58,7 @@ public class Log /** * Logging Configuration Properties */ - protected static Properties __props; + protected static final Properties __props; /** * The {@link Logger} implementation class name */ diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java index fe9dbb44e27..c0cfc281e0d 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java @@ -23,6 +23,7 @@ import java.io.FileOutputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.net.JarURLConnection; import java.net.URL; import java.util.jar.JarEntry; @@ -153,115 +154,110 @@ public class JarResource extends URLResource if (LOG.isDebugEnabled()) LOG.debug("Extracting entry = "+subEntryName+" from jar "+jarFileURL); - InputStream is = jarFileURL.openConnection().getInputStream(); - JarInputStream jin = new JarInputStream(is); - JarEntry entry; - boolean shouldExtract; - while((entry=jin.getNextJarEntry())!=null) + try (InputStream is = jarFileURL.openConnection().getInputStream(); + JarInputStream jin = new JarInputStream(is)) { - String entryName = entry.getName(); - if ((subEntryName != null) && (entryName.startsWith(subEntryName))) - { - // is the subentry really a dir? - if (!subEntryIsDir && subEntryName.length()+1==entryName.length() && entryName.endsWith("/")) - subEntryIsDir=true; - - //if there is a particular subEntry that we are looking for, only - //extract it. - if (subEntryIsDir) + JarEntry entry; + boolean shouldExtract; + while((entry=jin.getNextJarEntry())!=null) + { + String entryName = entry.getName(); + if ((subEntryName != null) && (entryName.startsWith(subEntryName))) { - //if it is a subdirectory we are looking for, then we - //are looking to extract its contents into the target - //directory. Remove the name of the subdirectory so - //that we don't wind up creating it too. - entryName = entryName.substring(subEntryName.length()); - if (!entryName.equals("")) + // is the subentry really a dir? + if (!subEntryIsDir && subEntryName.length()+1==entryName.length() && entryName.endsWith("/")) + subEntryIsDir=true; + + //if there is a particular subEntry that we are looking for, only + //extract it. + if (subEntryIsDir) { - //the entry is - shouldExtract = true; + //if it is a subdirectory we are looking for, then we + //are looking to extract its contents into the target + //directory. Remove the name of the subdirectory so + //that we don't wind up creating it too. + entryName = entryName.substring(subEntryName.length()); + if (!entryName.equals("")) + { + //the entry is + shouldExtract = true; + } + else + shouldExtract = false; } else - shouldExtract = false; + shouldExtract = true; + } + else if ((subEntryName != null) && (!entryName.startsWith(subEntryName))) + { + //there is a particular entry we are looking for, and this one + //isn't it + shouldExtract = false; } else - shouldExtract = true; - } - else if ((subEntryName != null) && (!entryName.startsWith(subEntryName))) - { - //there is a particular entry we are looking for, and this one - //isn't it - shouldExtract = false; - } - else - { - //we are extracting everything - shouldExtract = true; - } - - - if (!shouldExtract) - { - if (LOG.isDebugEnabled()) - LOG.debug("Skipping entry: "+entryName); - continue; - } - - String dotCheck = entryName.replace('\\', '/'); - dotCheck = URIUtil.canonicalPath(dotCheck); - if (dotCheck == null) - { - if (LOG.isDebugEnabled()) - LOG.debug("Invalid entry: "+entryName); - continue; - } - - File file=new File(directory,entryName); - - if (entry.isDirectory()) - { - // Make directory - if (!file.exists()) - file.mkdirs(); - } - else - { - // make directory (some jars don't list dirs) - File dir = new File(file.getParent()); - if (!dir.exists()) - dir.mkdirs(); - - // Make file - FileOutputStream fout = null; - try { - fout = new FileOutputStream(file); - IO.copy(jin,fout); - } - finally - { - IO.close(fout); + //we are extracting everything + shouldExtract = true; } - // touch the file. - if (entry.getTime()>=0) - file.setLastModified(entry.getTime()); + if (!shouldExtract) + { + if (LOG.isDebugEnabled()) + LOG.debug("Skipping entry: "+entryName); + continue; + } + + String dotCheck = entryName.replace('\\', '/'); + dotCheck = URIUtil.canonicalPath(dotCheck); + if (dotCheck == null) + { + if (LOG.isDebugEnabled()) + LOG.debug("Invalid entry: "+entryName); + continue; + } + + File file=new File(directory,entryName); + + if (entry.isDirectory()) + { + // Make directory + if (!file.exists()) + file.mkdirs(); + } + else + { + // make directory (some jars don't list dirs) + File dir = new File(file.getParent()); + if (!dir.exists()) + dir.mkdirs(); + + // Make file + try (OutputStream fout = new FileOutputStream(file)) + { + IO.copy(jin,fout); + } + + // touch the file. + if (entry.getTime()>=0) + file.setLastModified(entry.getTime()); + } } - } - - if ((subEntryName == null) || (subEntryName != null && subEntryName.equalsIgnoreCase("META-INF/MANIFEST.MF"))) - { - Manifest manifest = jin.getManifest(); - if (manifest != null) + + if ((subEntryName == null) || (subEntryName != null && subEntryName.equalsIgnoreCase("META-INF/MANIFEST.MF"))) { - File metaInf = new File (directory, "META-INF"); - metaInf.mkdir(); - File f = new File(metaInf, "MANIFEST.MF"); - FileOutputStream fout = new FileOutputStream(f); - manifest.write(fout); - fout.close(); + Manifest manifest = jin.getManifest(); + if (manifest != null) + { + File metaInf = new File (directory, "META-INF"); + metaInf.mkdir(); + File f = new File(metaInf, "MANIFEST.MF"); + try (OutputStream fout = new FileOutputStream(f)) + { + manifest.write(fout); + } + } } } - IO.close(jin); } public static Resource newJarResource(Resource resource) throws IOException diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/Resource.java b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/Resource.java index 3523105eca2..f4b11a96e5c 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/Resource.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/Resource.java @@ -615,8 +615,7 @@ public abstract class Resource implements ResourceFactory, Closeable public void writeTo(OutputStream out,long start,long count) throws IOException { - InputStream in = getInputStream(); - try + try (InputStream in = getInputStream()) { in.skip(start); if (count<0) @@ -624,10 +623,6 @@ public abstract class Resource implements ResourceFactory, Closeable else IO.copy(in,out,count); } - finally - { - in.close(); - } } /* ------------------------------------------------------------ */ @@ -636,7 +631,10 @@ public abstract class Resource implements ResourceFactory, Closeable { if (destination.exists()) throw new IllegalArgumentException(destination+" exists"); - writeTo(new FileOutputStream(destination),0,-1); + try (OutputStream out = new FileOutputStream(destination)) + { + writeTo(out,0,-1); + } } /* ------------------------------------------------------------ */ diff --git a/jetty-util/src/test/java/org/eclipse/jetty/util/BufferUtilTest.java b/jetty-util/src/test/java/org/eclipse/jetty/util/BufferUtilTest.java index 886474e5b42..b6c85f3e9f7 100644 --- a/jetty-util/src/test/java/org/eclipse/jetty/util/BufferUtilTest.java +++ b/jetty-util/src/test/java/org/eclipse/jetty/util/BufferUtilTest.java @@ -24,7 +24,7 @@ import java.io.IOException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.util.Arrays; -import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; @@ -245,7 +245,7 @@ public class BufferUtilTest int iterations = 100; int testRuns = 10; byte[] bytes = new byte[capacity]; - new Random().nextBytes(bytes); + ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer buffer = BufferUtil.allocate(capacity); BufferUtil.append(buffer, bytes, 0, capacity); long startTest = System.nanoTime(); @@ -294,7 +294,7 @@ public class BufferUtilTest { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] bytes = new byte[capacity]; - new Random().nextBytes(bytes); + ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer buffer = BufferUtil.allocate(capacity); BufferUtil.append(buffer, bytes, 0, capacity); BufferUtil.writeTo(buffer.asReadOnlyBuffer(), out); diff --git a/jetty-util/src/test/java/org/eclipse/jetty/util/ScannerTest.java b/jetty-util/src/test/java/org/eclipse/jetty/util/ScannerTest.java index 09d5ed1c245..43f58f9a106 100644 --- a/jetty-util/src/test/java/org/eclipse/jetty/util/ScannerTest.java +++ b/jetty-util/src/test/java/org/eclipse/jetty/util/ScannerTest.java @@ -21,6 +21,7 @@ package org.eclipse.jetty.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.io.OutputStream; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; @@ -236,51 +237,52 @@ public class ScannerTest // Create a new file by writing to it. long now = System.currentTimeMillis(); File file = new File(_directory,"st"); - FileOutputStream out = new FileOutputStream(file,true); - out.write('x'); - out.flush(); - file.setLastModified(now); + try (OutputStream out = new FileOutputStream(file,true)) + { + out.write('x'); + out.flush(); + file.setLastModified(now); - // Not stable yet so no notification. - _scanner.scan(); - event = _queue.poll(); - Assert.assertTrue(event==null); + // Not stable yet so no notification. + _scanner.scan(); + event = _queue.poll(); + Assert.assertTrue(event==null); - // Modify size only - out.write('x'); - out.flush(); - file.setLastModified(now); + // Modify size only + out.write('x'); + out.flush(); + file.setLastModified(now); - // Still not stable yet so no notification. - _scanner.scan(); - event = _queue.poll(); - Assert.assertTrue(event==null); + // Still not stable yet so no notification. + _scanner.scan(); + event = _queue.poll(); + Assert.assertTrue(event==null); - // now stable so finally see the ADDED - _scanner.scan(); - event = _queue.poll(); - Assert.assertTrue(event!=null); - Assert.assertEquals(_directory+"/st",event._filename); - Assert.assertEquals(Notification.ADDED,event._notification); + // now stable so finally see the ADDED + _scanner.scan(); + event = _queue.poll(); + Assert.assertTrue(event!=null); + Assert.assertEquals(_directory+"/st",event._filename); + Assert.assertEquals(Notification.ADDED,event._notification); - // Modify size only - out.write('x'); - out.flush(); - file.setLastModified(now); + // Modify size only + out.write('x'); + out.flush(); + file.setLastModified(now); - // Still not stable yet so no notification. - _scanner.scan(); - event = _queue.poll(); - Assert.assertTrue(event==null); - - // now stable so finally see the ADDED - _scanner.scan(); - event = _queue.poll(); - Assert.assertTrue(event!=null); - Assert.assertEquals(_directory+"/st",event._filename); - Assert.assertEquals(Notification.CHANGED,event._notification); + // Still not stable yet so no notification. + _scanner.scan(); + event = _queue.poll(); + Assert.assertTrue(event==null); + // now stable so finally see the ADDED + _scanner.scan(); + event = _queue.poll(); + Assert.assertTrue(event!=null); + Assert.assertEquals(_directory+"/st",event._filename); + Assert.assertEquals(Notification.CHANGED,event._notification); + } } private void delete(String string) throws IOException diff --git a/jetty-util/src/test/java/org/eclipse/jetty/util/resource/ResourceCollectionTest.java b/jetty-util/src/test/java/org/eclipse/jetty/util/resource/ResourceCollectionTest.java index ff3e3411e9e..f9da94bcd63 100644 --- a/jetty-util/src/test/java/org/eclipse/jetty/util/resource/ResourceCollectionTest.java +++ b/jetty-util/src/test/java/org/eclipse/jetty/util/resource/ResourceCollectionTest.java @@ -104,10 +104,11 @@ public class ResourceCollectionTest { StringBuilder buffer = new StringBuilder(); String line = null; - BufferedReader br = new BufferedReader(new InputStreamReader(r.addPath(path).getURL().openStream())); - while((line=br.readLine())!=null) - buffer.append(line); - br.close(); + try (BufferedReader br = new BufferedReader(new InputStreamReader(r.addPath(path).getURL().openStream()))) + { + while((line=br.readLine())!=null) + buffer.append(line); + } return buffer.toString(); } diff --git a/jetty-util/src/test/java/org/eclipse/jetty/util/ssl/SslContextFactoryTest.java b/jetty-util/src/test/java/org/eclipse/jetty/util/ssl/SslContextFactoryTest.java index 980640c1081..bd922094572 100644 --- a/jetty-util/src/test/java/org/eclipse/jetty/util/ssl/SslContextFactoryTest.java +++ b/jetty-util/src/test/java/org/eclipse/jetty/util/ssl/SslContextFactoryTest.java @@ -65,11 +65,11 @@ public class SslContextFactoryTest @Test public void testNoTsSetKs() throws Exception { - InputStream keystoreInputStream = this.getClass().getResourceAsStream("keystore"); - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(keystoreInputStream, "storepwd".toCharArray()); - + try (InputStream keystoreInputStream = this.getClass().getResourceAsStream("keystore")) + { + ks.load(keystoreInputStream, "storepwd".toCharArray()); + } cf.setKeyStore(ks); cf.setKeyManagerPassword("keypwd"); diff --git a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebAppContext.java b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebAppContext.java index c52b7bc2066..8daa1c61c43 100644 --- a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebAppContext.java +++ b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebAppContext.java @@ -94,7 +94,7 @@ public class WebAppContext extends ServletContextHandler implements WebAppClassL private String[] __dftProtectedTargets = {"/web-inf", "/meta-inf"}; - public static String[] DEFAULT_CONFIGURATION_CLASSES = + public static final String[] DEFAULT_CONFIGURATION_CLASSES = { "org.eclipse.jetty.webapp.WebInfConfiguration", "org.eclipse.jetty.webapp.WebXmlConfiguration", diff --git a/jetty-websocket/websocket-client/src/main/java/org/eclipse/jetty/websocket/client/ClientUpgradeRequest.java b/jetty-websocket/websocket-client/src/main/java/org/eclipse/jetty/websocket/client/ClientUpgradeRequest.java index 5c662d6ee7e..282ef1e8254 100644 --- a/jetty-websocket/websocket-client/src/main/java/org/eclipse/jetty/websocket/client/ClientUpgradeRequest.java +++ b/jetty-websocket/websocket-client/src/main/java/org/eclipse/jetty/websocket/client/ClientUpgradeRequest.java @@ -25,8 +25,8 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Random; import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; import org.eclipse.jetty.util.B64Code; import org.eclipse.jetty.util.MultiMap; @@ -190,7 +190,7 @@ public class ClientUpgradeRequest extends UpgradeRequest private final String genRandomKey() { byte[] bytes = new byte[16]; - new Random().nextBytes(bytes); + ThreadLocalRandom.current().nextBytes(bytes); return new String(B64Code.encode(bytes)); }