aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMikhail Mazursky2013-08-27 23:58:56 (EDT)
committerGerrit Code Review @ Eclipse.org2013-09-09 00:24:31 (EDT)
commit767faece5c4692748d1ac8e130b2e4c5faa1ff20 (patch)
tree787e93c5bf452b69d28d737a04d57cddae0b7ede
parentcdd95bb5515f35af090bcbcf6f9af03d5c6762c9 (diff)
downloadorg.eclipse.jetty.project-767faece5c4692748d1ac8e130b2e4c5faa1ff20.zip
org.eclipse.jetty.project-767faece5c4692748d1ac8e130b2e4c5faa1ff20.tar.gz
org.eclipse.jetty.project-767faece5c4692748d1ac8e130b2e4c5faa1ff20.tar.bz2
[Bug 415999] Fix some of FindBugs warningsrefs/changes/20/15920/2
Mostly not closed streams/DB resources are fixed. But also less important things. Signed-off-by: Mikhail Mazursky <mikhail.mazursky@gmail.com>
-rw-r--r--jetty-ant/src/main/java/org/eclipse/jetty/ant/utils/TaskLog.java9
-rw-r--r--jetty-client/src/main/java/org/eclipse/jetty/client/util/InputStreamResponseListener.java3
-rw-r--r--jetty-deploy/src/test/java/org/eclipse/jetty/deploy/test/XmlConfiguredJetty.java7
-rw-r--r--jetty-http/src/main/java/org/eclipse/jetty/http/HttpField.java2
-rw-r--r--jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java2
-rw-r--r--jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java5
-rw-r--r--jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java2
-rw-r--r--jetty-jaas/src/main/java/org/eclipse/jetty/jaas/JAASLoginService.java4
-rw-r--r--jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractDatabaseLoginModule.java53
-rw-r--r--jetty-jndi/src/main/java/org/eclipse/jetty/jndi/DataSourceCloser.java9
-rw-r--r--jetty-jspc-maven-plugin/src/main/java/org/eclipse/jetty/jspc/plugin/JspcMojo.java82
-rw-r--r--jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/AbstractJettyMojo.java14
-rw-r--r--jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyRunForkedMojo.java26
-rw-r--r--jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/MavenServerConnector.java8
-rw-r--r--jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SelectiveJarResource.java123
-rw-r--r--jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/Starter.java6
-rw-r--r--jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/SystemProperties.java12
-rw-r--r--jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/BundleWatcher.java2
-rw-r--r--jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/LibExtClassLoaderHelper.java2
-rw-r--r--jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/OSGiWebappClassLoader.java4
-rw-r--r--jetty-overlay-deployer/src/test/java/org/eclipse/jetty/overlays/OverlayedAppProviderTest.java8
-rw-r--r--jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java172
-rw-r--r--jetty-security/src/main/java/org/eclipse/jetty/security/JDBCLoginService.java45
-rw-r--r--jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java4
-rw-r--r--jetty-security/src/test/java/org/eclipse/jetty/security/PropertyUserStoreTest.java19
-rw-r--r--jetty-server/src/main/java/org/eclipse/jetty/server/NCSARequestLog.java2
-rw-r--r--jetty-server/src/main/java/org/eclipse/jetty/server/Response.java7
-rw-r--r--jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java7
-rw-r--r--jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java8
-rw-r--r--jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionIdManager.java319
-rw-r--r--jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionManager.java107
-rw-r--r--jetty-server/src/test/java/org/eclipse/jetty/server/DumpHandler.java2
-rw-r--r--jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java10
-rw-r--r--jetty-server/src/test/java/org/eclipse/jetty/server/ResourceCacheTest.java28
-rw-r--r--jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerTest.java15
-rw-r--r--jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLSelectChannelConnectorLoadTest.java5
-rw-r--r--jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SelectChannelServerSslTest.java6
-rw-r--r--jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslSelectChannelTimeoutTest.java6
-rw-r--r--jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslUploadTest.java5
-rw-r--r--jetty-servlet/src/main/java/org/eclipse/jetty/servlet/DefaultServlet.java12
-rw-r--r--jetty-servlets/src/main/java/org/eclipse/jetty/servlets/CGI.java7
-rw-r--r--jetty-servlets/src/main/java/org/eclipse/jetty/servlets/PutFilter.java26
-rw-r--r--jetty-servlets/src/test/java/org/eclipse/jetty/servlets/IncludableGzipFilterTest.java10
-rw-r--r--jetty-servlets/src/test/java/org/eclipse/jetty/servlets/PutFilterTest.java15
-rw-r--r--jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/api/Settings.java17
-rw-r--r--jetty-spdy/spdy-core/src/test/java/org/eclipse/jetty/spdy/generator/DataFrameGeneratorTest.java4
-rw-r--r--jetty-spdy/spdy-server/src/test/java/org/eclipse/jetty/spdy/server/PushStreamTest.java4
-rw-r--r--jetty-start/src/main/java/org/eclipse/jetty/start/Main.java5
-rw-r--r--jetty-util/src/main/java/org/eclipse/jetty/util/DateCache.java4
-rw-r--r--jetty-util/src/main/java/org/eclipse/jetty/util/IO.java12
-rw-r--r--jetty-util/src/main/java/org/eclipse/jetty/util/MultiPartWriter.java24
-rw-r--r--jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java2
-rw-r--r--jetty-util/src/main/java/org/eclipse/jetty/util/TypeUtil.java4
-rw-r--r--jetty-util/src/main/java/org/eclipse/jetty/util/component/FileNoticeLifeCycleListener.java7
-rw-r--r--jetty-util/src/main/java/org/eclipse/jetty/util/log/Log.java2
-rw-r--r--jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java178
-rw-r--r--jetty-util/src/main/java/org/eclipse/jetty/util/resource/Resource.java12
-rw-r--r--jetty-util/src/test/java/org/eclipse/jetty/util/BufferUtilTest.java6
-rw-r--r--jetty-util/src/test/java/org/eclipse/jetty/util/ScannerTest.java92
-rw-r--r--jetty-util/src/test/java/org/eclipse/jetty/util/resource/ResourceCollectionTest.java9
-rw-r--r--jetty-util/src/test/java/org/eclipse/jetty/util/ssl/SslContextFactoryTest.java8
-rw-r--r--jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebAppContext.java2
-rw-r--r--jetty-websocket/websocket-client/src/main/java/org/eclipse/jetty/websocket/client/ClientUpgradeRequest.java4
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 29fc10b..e9aad1d 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 6ac55e6..d59943a 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 a14facc..6f9790e 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 6d835dc..8241d1d 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 c6b6762..3f2c12d 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>
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 5bd40b2..311a688 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<String, String> 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 654474d..d4ee8d7 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 d50c385..412ee5e 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 fc2726f..55c60af 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))
+ {
+ statement.setString (1, userName);
+ try (ResultSet results = statement.executeQuery())
+ {
+ if (results.next())
+ {
+ dbCredential = results.getString(1);
+ }
+ }
+ }
+
+ if (dbCredential==null)
{
- dbCredential = results.getString(1);
+ return null;
}
- results.close();
- statement.close();
//query for role names
- statement = connection.prepareStatement (rolesQuery);
- statement.setString (1, userName);
- results = statement.executeQuery();
List<String> roles = new ArrayList<String>();
-
- 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 61dae6f..a41174d 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 d5645c4..224a7e9 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<files.length; i++)
+ if (files != null)
{
- File f = files[i];
- if(f.isDirectory())
- delete(f, filter);
- else
- f.delete();
+ for(File f: files)
+ {
+ if(f.isDirectory())
+ delete(f, filter);
+ else
+ f.delete();
+ }
}
}
@@ -474,47 +476,45 @@ public class JspcMojo extends AbstractMojo
}
File mergedWebXml = new File(fragmentWebXml.getParentFile(),
"web.xml");
- BufferedReader webXmlReader = new BufferedReader(new FileReader(
+ try (BufferedReader webXmlReader = new BufferedReader(new FileReader(
webXml));
- PrintWriter mergedWebXmlWriter = new PrintWriter(new FileWriter(
- mergedWebXml));
-
- // read up to the insertion marker or the </webapp> 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)
+ PrintWriter mergedWebXmlWriter = new PrintWriter(new FileWriter(
+ mergedWebXml))) {
+
+ // read up to the insertion marker or the </webapp> 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;
- }
- else
- {
- mergedWebXmlWriter.println(line);
+ String line = webXmlReader.readLine();
+ if (line == null)
+ atEOF = true;
+ else if (line.indexOf(marker) >= 0)
+ {
+ atInsertPoint = true;
+ }
+ else
+ {
+ mergedWebXmlWriter.println(line);
+ }
}
- }
-
- // put in the generated fragment
- BufferedReader fragmentWebXmlReader = new BufferedReader(
- new FileReader(fragmentWebXml));
- IO.copy(fragmentWebXmlReader, mergedWebXmlWriter);
- // if we inserted just before the </web-app>, put it back in
- if (marker.equals(END_OF_WEBAPP))
- mergedWebXmlWriter.println(END_OF_WEBAPP);
+ // put in the generated fragment
+ try (BufferedReader fragmentWebXmlReader = new BufferedReader(
+ new FileReader(fragmentWebXml))) {
+ IO.copy(fragmentWebXmlReader, mergedWebXmlWriter);
- // copy in the rest of the original web.xml file
- IO.copy(webXmlReader, mergedWebXmlWriter);
+ // if we inserted just before the </web-app>, put it back in
+ if (marker.equals(END_OF_WEBAPP))
+ mergedWebXmlWriter.println(END_OF_WEBAPP);
- webXmlReader.close();
- mergedWebXmlWriter.close();
- fragmentWebXmlReader.close();
+ // copy in the rest of the original web.xml file
+ IO.copy(webXmlReader, mergedWebXmlWriter);
+ }
+ }
}
}
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 50643d5..02eeba5 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 1e7e9fe..77d5009 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 54aedb1..9d343b4 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 11c8d47..d253ca8 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();
+
+ LOG.debug("Looking at "+entryName);
+ String dotCheck = entryName.replace('\\', '/');
+ dotCheck = URIUtil.canonicalPath(dotCheck);
+ if (dotCheck == null)
+ {
+ LOG.info("Invalid entry: "+entryName);
+ continue;
+ }
- File file=new File(directory,entryName);
+ File file=new File(directory,entryName);
- if (entry.isDirectory())
- {
- if (isIncluded(entryName))
+ if (entry.isDirectory())
{
- if (!isExcluded(entryName))
+ 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
- {
- fout = new FileOutputStream(file);
- IO.copy(jin,fout);
- }
- finally
+ if (!isExcluded(entryName))
{
- IO.close(fout);
+ // 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());
}
-
- // 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 dcd8959..87f7fe6 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 590a32f..19b716d 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<String, SystemProperty> 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<SystemProperty> 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 74622c3..9bb9a02 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<TldBundleDiscoverer> JSP_REGISTRATION_HELPERS = new ArrayList<TldBundleDiscoverer>();
+ public static final Collection<TldBundleDiscoverer> JSP_REGISTRATION_HELPERS = new ArrayList<TldBundleDiscoverer>();
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 b728d21..5d67290 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<IFilesInJettyHomeResourcesProcessor> registeredFilesInJettyHomeResourcesProcessors = new HashSet<IFilesInJettyHomeResourcesProcessor>();
+ public static final Set<IFilesInJettyHomeResourcesProcessor> registeredFilesInJettyHomeResourcesProcessors = new HashSet<IFilesInJettyHomeResourcesProcessor>();
/* ------------------------------------------------------------ */
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 e963b91..10ba5d1 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<String> JAR_WITH_SUCH_CLASS_MUST_BE_EXCLUDED = new HashSet<String>();
+ public static final Set<String> JAR_WITH_SUCH_CLASS_MUST_BE_EXCLUDED = new HashSet<String>();
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 9a5ed71..bdb9add 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("<h1>Hello</h1>".getBytes());
- out.close();
+ try (OutputStream out = new FileOutputStream(file,false))
+ {
+ out.write("<h1>Hello</h1>".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 8ef3ba5..96e9ae0 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<String> roles = new ArrayList<String>();
- 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<String> roles = new ArrayList<String>();
+ 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 58db6e4..5373161 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();
-
- stat = _con.prepareStatement(_roleSql);
- stat.setInt(1, key);
- rs = stat.executeQuery();
- List<String> roles = new ArrayList<String>();
- while (rs.next())
- roles.add(rs.getString(_roleTableRoleField));
+ stat1.setObject(1, username);
+ try (ResultSet rs1 = stat1.executeQuery())
+ {
+ if (rs1.next())
+ {
+ int key = rs1.getInt(_userTableKey);
+ String credentials = rs1.getString(_userTablePasswordField);
+ List<String> roles = new ArrayList<String>();
- 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 edb5f91..df8a4eb 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 a25ee63..6b68b9b 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 ef11b3e..33e6b6f 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 b1fa612..16c331c 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 3cccf31..2d8d6ea 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</BODY>\n</HTML>\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 d1e13ce..07b289d 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 6590e24..c57188d 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
- {
- colResult = metaData.getColumns(null, null,_dbAdaptor.convertIdentifier(_sessionTable), _dbAdaptor.convertIdentifier("maxInterval"));
- }
- catch (SQLException s)
+ if (!result.next())
{
- LOG.warn("Problem checking if "+_sessionTable+" table contains maxInterval column. Ensure table contains column definition: \"maxInterval long not null default -999\"");
- throw s;
+ //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);
}
-
- 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<String> expiredSessionIds = new HashSet<String>();
try
{
if (LOG.isDebugEnabled())
@@ -844,70 +828,78 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
{
connection = getConnection();
connection.setAutoCommit(true);
+ Set<String> expiredSessionIds = new HashSet<String>();
//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())
+ try (PreparedStatement selectExpiredSessions = connection.prepareStatement(_selectExpiredSessions))
+ {
+ expiredSessionIds.clear();
+ upperBound = _lastScavengeTime - (2 * _scavengeIntervalMs);
+ if (upperBound > 0)
{
- 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());
+ 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);
}
- 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)
- {
- if (LOG.isDebugEnabled()) LOG.debug(getWorkerName()+"- Pass 3: searching for sessions expired before "+upperBound);
- selectExpiredSessions.setLong(1, upperBound);
- result = selectExpiredSessions.executeQuery();
- while (result.next())
+ //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)
{
- 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 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++;
+ while (end < ids.length)
+ {
+ start = block*blocksize;
+ if ((ids.length - start) >= blocksize)
+ end = start + blocksize;
+ else
+ end = ids.length;
+
+ //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();
-
- }
- catch (Exception e)
- {
- if (con != null)
+ 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 bf595d1..9931455 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<String,Object>)o);
- ois.close();
+ try (InputStream is = ((JDBCSessionIdManager)getSessionIdManager())._dbAdaptor.getBlobInputStream(result, "map");
+ ClassLoadingObjectInputStream ois = new ClassLoadingObjectInputStream(is))
+ {
+ Object o = ois.readObject();
+ session.addAttributes((Map<String,Object>)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 27440fa..0f86e01 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<String> 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 e2d94bf..a731c42 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 09ebcf4..3383b59 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 1a63f0a..8e65b66 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 e160c45..322f274 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 94b8bcf..6c37535 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 6d1551b..7e40aec 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 fbda4c5..d4ef124 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 97f69b2..8743cd7 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 9a34873..1ef2cf3 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 6673168..f96d29d 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 10ec3f6..6292fa7 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 266601b..132db2e 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 010267e..234cfe7 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<Settings.Setting>
{
- private Map<ID, Settings.Setting> settings = new HashMap<>();
+ private final Map<ID, Settings.Setting> settings;
public Settings()
{
+ settings = new HashMap<>();
}
public Settings(Settings original, boolean immutable)
@@ -94,13 +95,13 @@ public class Settings implements Iterable<Settings.Setting>
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 42e3d5d..e87b286 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 344667e..243bd84 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 3ea743a..4a5ed83 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 c070fcc..e5dbf1f 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 f0a3d9e..0194edd 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 bf14057..55a8e29 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 58ede8b..03e8b2c 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 d63fe37..f7371e4 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<String, Class<?>> 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 b514a58..e40a1d7 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 558ac07..6a26c73 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 fe9dbb4..c0cfc28 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;
- }
+ {
+ //we are extracting everything
+ shouldExtract = true;
+ }
- 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();
+ if (!shouldExtract)
+ {
+ if (LOG.isDebugEnabled())
+ LOG.debug("Skipping entry: "+entryName);
+ continue;
+ }
- // Make file
- FileOutputStream fout = null;
- try
+ String dotCheck = entryName.replace('\\', '/');
+ dotCheck = URIUtil.canonicalPath(dotCheck);
+ if (dotCheck == null)
{
- fout = new FileOutputStream(file);
- IO.copy(jin,fout);
+ if (LOG.isDebugEnabled())
+ LOG.debug("Invalid entry: "+entryName);
+ continue;
}
- finally
+
+ File file=new File(directory,entryName);
+
+ if (entry.isDirectory())
{
- IO.close(fout);
+ // 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());
+ // 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 3523105..f4b11a9 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 886474e..b6c85f3 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 09d5ed1..43f58f9 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);
-
- // 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);
-
- // 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);
-
- // 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);
-
+ 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);
+
+ // 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.ADDED,event._notification);
+
+ // 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);
+ }
}
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 ff3e341..f9da94b 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 980640c..bd92209 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 c52b7bc..8daa1c6 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 5c662d6..282ef1e 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));
}