[Bug 415999] Fix some of FindBugs warnings

Mostly not closed streams/DB resources are fixed. But also less
important things.

Signed-off-by: Mikhail Mazursky <mikhail.mazursky@gmail.com>
This commit is contained in:
Mikhail Mazursky 2013-08-28 09:58:56 +06:00 committed by Gerrit Code Review @ Eclipse.org
parent cdd95bb551
commit 767faece5c
63 changed files with 805 additions and 811 deletions

View File

@ -33,7 +33,7 @@ public class TaskLog
private static Task task; private static Task task;
private static SimpleDateFormat format = new SimpleDateFormat( private static final SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS"); "yyyy-MM-dd HH:mm:ss.SSS");
public static void setTask(Task task) public static void setTask(Task task)
@ -48,6 +48,11 @@ public class TaskLog
public static void logWithTimestamp(String message) 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);
} }
} }

View File

@ -155,7 +155,7 @@ public class InputStreamResponseListener extends Response.Listener.Empty
{ {
synchronized (this) synchronized (this)
{ {
if (length.get() >= maxBufferSize && failure == null && !closed) while (length.get() >= maxBufferSize && failure == null && !closed)
wait(); wait();
// Re-read the values as they may have changed while waiting. // Re-read the values as they may have changed while waiting.
return failure == null && !closed; return failure == null && !closed;
@ -163,6 +163,7 @@ public class InputStreamResponseListener extends Response.Listener.Empty
} }
catch (InterruptedException x) catch (InterruptedException x)
{ {
Thread.currentThread().interrupt();
return false; return false;
} }
} }

View File

@ -24,6 +24,7 @@ import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URI; import java.net.URI;
@ -123,8 +124,10 @@ public class XmlConfiguredJetty
// Write out configuration for use by ConfigurationManager. // Write out configuration for use by ConfigurationManager.
File testConfig = new File(_jettyHome, "xml-configured-jetty.properties"); File testConfig = new File(_jettyHome, "xml-configured-jetty.properties");
FileOutputStream out = new FileOutputStream(testConfig); try (OutputStream out = new FileOutputStream(testConfig))
properties.store(out,"Generated by " + XmlConfiguredJetty.class.getName()); {
properties.store(out,"Generated by " + XmlConfiguredJetty.class.getName());
}
for (Object key:properties.keySet()) for (Object key:properties.keySet())
setProperty(String.valueOf(key),String.valueOf(properties.get(key))); setProperty(String.valueOf(key),String.valueOf(properties.get(key)));
} }

View File

@ -231,7 +231,7 @@ public class HttpField
public String toString() public String toString()
{ {
String v=getValue(); String v=getValue();
return getName() + ": " + (v==null?"":v.toString()); return getName() + ": " + (v==null?"":v);
} }
public boolean isSame(HttpField field) public boolean isSame(HttpField field)

View File

@ -901,7 +901,7 @@ public class HttpFields implements Iterable<HttpField>
HttpField field=i.next(); HttpField field=i.next();
if (field.getHeader()==HttpHeader.SET_COOKIE) 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)) if (val!=null && val.startsWith(name_equals))
{ {
//existing cookie has same name, does it also match domain and path? //existing cookie has same name, does it also match domain and path?

View File

@ -25,6 +25,7 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.MissingResourceException; import java.util.MissingResourceException;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import java.util.Set; import java.util.Set;
@ -192,8 +193,8 @@ public class MimeTypes
_mimeMap.clear(); _mimeMap.clear();
if (mimeMap!=null) if (mimeMap!=null)
{ {
for (String ext : mimeMap.keySet()) for (Entry<String, String> ext : mimeMap.entrySet())
_mimeMap.put(StringUtil.asciiToLowerCase(ext),normalizeMimeType(mimeMap.get(ext))); _mimeMap.put(StringUtil.asciiToLowerCase(ext.getKey()),normalizeMimeType(ext.getValue()));
} }
} }

View File

@ -1246,7 +1246,7 @@ public class HttpParserTest
request=false; request=false;
_methodOrVersion = version.asString(); _methodOrVersion = version.asString();
_uriOrStatus = Integer.toString(status); _uriOrStatus = Integer.toString(status);
_versionOrReason = reason==null?null:reason.toString(); _versionOrReason = reason;
fields=new HttpFields(); fields=new HttpFields();
_hdr= new String[9]; _hdr= new String[9];

View File

@ -57,8 +57,8 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService
{ {
private static final Logger LOG = Log.getLogger(JAASLoginService.class); private static final Logger LOG = Log.getLogger(JAASLoginService.class);
public static String DEFAULT_ROLE_CLASS_NAME = "org.eclipse.jetty.jaas.JAASRole"; public static final 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_NAMES = {DEFAULT_ROLE_CLASS_NAME};
protected String[] _roleClassNames = DEFAULT_ROLE_CLASS_NAMES; protected String[] _roleClassNames = DEFAULT_ROLE_CLASS_NAMES;
protected String _callbackHandlerClass; protected String _callbackHandlerClass;

View File

@ -73,45 +73,44 @@ public abstract class AbstractDatabaseLoginModule extends AbstractLoginModule
public UserInfo getUserInfo (String userName) public UserInfo getUserInfo (String userName)
throws Exception throws Exception
{ {
Connection connection = null; try (Connection connection = getConnection())
try
{ {
connection = getConnection();
//query for credential //query for credential
PreparedStatement statement = connection.prepareStatement (userQuery);
statement.setString (1, userName);
ResultSet results = statement.executeQuery();
String dbCredential = null; String dbCredential = null;
if (results.next()) try (PreparedStatement statement = connection.prepareStatement (userQuery))
{ {
dbCredential = results.getString(1); statement.setString (1, userName);
try (ResultSet results = statement.executeQuery())
{
if (results.next())
{
dbCredential = results.getString(1);
}
}
}
if (dbCredential==null)
{
return null;
} }
results.close();
statement.close();
//query for role names //query for role names
statement = connection.prepareStatement (rolesQuery);
statement.setString (1, userName);
results = statement.executeQuery();
List<String> roles = new ArrayList<String>(); List<String> roles = new ArrayList<String>();
try (PreparedStatement statement = connection.prepareStatement (rolesQuery))
while (results.next())
{ {
String roleName = results.getString (1); statement.setString (1, userName);
roles.add (roleName); try (ResultSet results = statement.executeQuery())
{
while (results.next())
{
String roleName = results.getString (1);
roles.add (roleName);
}
}
} }
results.close(); return new UserInfo (userName, Credential.getCredential(dbCredential), roles);
statement.close();
return dbCredential==null ? null : new UserInfo (userName,
Credential.getCredential(dbCredential), roles);
}
finally
{
if (connection != null) connection.close();
} }
} }

View File

@ -19,6 +19,7 @@
package org.eclipse.jetty.jndi; package org.eclipse.jetty.jndi;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.Statement; import java.sql.Statement;
import javax.sql.DataSource; import javax.sql.DataSource;
@ -66,9 +67,11 @@ public class DataSourceCloser implements Destroyable
if (_shutdown!=null) if (_shutdown!=null)
{ {
LOG.info("Shutdown datasource {}",_datasource); LOG.info("Shutdown datasource {}",_datasource);
Statement stmt = _datasource.getConnection().createStatement(); try (Connection connection = _datasource.getConnection();
stmt.executeUpdate(_shutdown); Statement stmt = connection.createStatement())
stmt.close(); {
stmt.executeUpdate(_shutdown);
}
} }
} }
catch (Exception e) catch (Exception e)

View File

@ -433,13 +433,15 @@ public class JspcMojo extends AbstractMojo
static void delete(File dir, FileFilter filter) static void delete(File dir, FileFilter filter)
{ {
File[] files = dir.listFiles(filter); File[] files = dir.listFiles(filter);
for(int i=0; i<files.length; i++) if (files != null)
{ {
File f = files[i]; for(File f: files)
if(f.isDirectory()) {
delete(f, filter); if(f.isDirectory())
else delete(f, filter);
f.delete(); else
f.delete();
}
} }
} }
@ -474,47 +476,45 @@ public class JspcMojo extends AbstractMojo
} }
File mergedWebXml = new File(fragmentWebXml.getParentFile(), File mergedWebXml = new File(fragmentWebXml.getParentFile(),
"web.xml"); "web.xml");
BufferedReader webXmlReader = new BufferedReader(new FileReader( try (BufferedReader webXmlReader = new BufferedReader(new FileReader(
webXml)); webXml));
PrintWriter mergedWebXmlWriter = new PrintWriter(new FileWriter( PrintWriter mergedWebXmlWriter = new PrintWriter(new FileWriter(
mergedWebXml)); mergedWebXml))) {
// read up to the insertion marker or the </webapp> if there is no // read up to the insertion marker or the </webapp> if there is no
// marker // marker
boolean atInsertPoint = false; boolean atInsertPoint = false;
boolean atEOF = false; boolean atEOF = false;
String marker = (insertionMarker == null String marker = (insertionMarker == null
|| insertionMarker.equals("") ? END_OF_WEBAPP : insertionMarker); || insertionMarker.equals("") ? END_OF_WEBAPP : insertionMarker);
while (!atInsertPoint && !atEOF) while (!atInsertPoint && !atEOF)
{
String line = webXmlReader.readLine();
if (line == null)
atEOF = true;
else if (line.indexOf(marker) >= 0)
{ {
atInsertPoint = true; String line = webXmlReader.readLine();
if (line == null)
atEOF = true;
else if (line.indexOf(marker) >= 0)
{
atInsertPoint = true;
}
else
{
mergedWebXmlWriter.println(line);
}
} }
else
{ // put in the generated fragment
mergedWebXmlWriter.println(line); try (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);
// copy in the rest of the original web.xml file
IO.copy(webXmlReader, mergedWebXmlWriter);
} }
} }
// put in the generated fragment
BufferedReader fragmentWebXmlReader = new BufferedReader(
new FileReader(fragmentWebXml));
IO.copy(fragmentWebXmlReader, mergedWebXmlWriter);
// if we inserted just before the </web-app>, put it back in
if (marker.equals(END_OF_WEBAPP))
mergedWebXmlWriter.println(END_OF_WEBAPP);
// copy in the rest of the original web.xml file
IO.copy(webXmlReader, mergedWebXmlWriter);
webXmlReader.close();
mergedWebXmlWriter.close();
fragmentWebXmlReader.close();
} }
} }

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.maven.plugin;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
@ -758,14 +759,15 @@ public abstract class AbstractJettyMojo extends AbstractMojo
public void setSystemPropertiesFile(File file) throws Exception public void setSystemPropertiesFile(File file) throws Exception
{ {
this.systemPropertiesFile = file; this.systemPropertiesFile = file;
FileInputStream propFile = new FileInputStream(systemPropertiesFile);
Properties properties = new Properties(); Properties properties = new Properties();
properties.load(propFile); try (InputStream propFile = new FileInputStream(systemPropertiesFile))
{
properties.load(propFile);
}
if (this.systemProperties == null ) if (this.systemProperties == null )
this.systemProperties = new SystemProperties(); this.systemProperties = new SystemProperties();
for (Enumeration keys = properties.keys(); keys.hasMoreElements(); ) for (Enumeration<?> keys = properties.keys(); keys.hasMoreElements(); )
{ {
String key = (String)keys.nextElement(); String key = (String)keys.nextElement();
if ( ! systemProperties.containsSystemProperty(key) ) if ( ! systemProperties.containsSystemProperty(key) )
@ -791,10 +793,8 @@ public abstract class AbstractJettyMojo extends AbstractMojo
this.systemProperties = systemProperties; this.systemProperties = systemProperties;
else else
{ {
Iterator itor = systemProperties.getSystemProperties().iterator(); for (SystemProperty prop: systemProperties.getSystemProperties())
while (itor.hasNext())
{ {
SystemProperty prop = (SystemProperty)itor.next();
this.systemProperties.setSystemProperty(prop); this.systemProperties.setSystemProperty(prop);
} }
} }

View File

@ -26,6 +26,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.LineNumberReader; import java.io.LineNumberReader;
import java.io.OutputStream;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -504,7 +505,10 @@ public class JettyRunForkedMojo extends AbstractMojo
props.put("maven.war.overlay."+(i++), c.toString()); 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; return propsFile;
} }
catch (Exception e) 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 //child indicates it has finished starting by printing on stdout the token passed to it
try try
{ {
LineNumberReader reader = new LineNumberReader(new InputStreamReader(forkedProcess.getInputStream()));
String line = ""; String line = "";
int attempts = maxStartupLines; //max lines we'll read trying to get token try (InputStream is = forkedProcess.getInputStream();
while (attempts>0 && line != null) LineNumberReader reader = new LineNumberReader(new InputStreamReader(is)))
{ {
--attempts; int attempts = maxStartupLines; //max lines we'll read trying to get token
line = reader.readLine(); while (attempts>0 && line != null)
if (line != null && line.startsWith(token)) {
break; --attempts;
} line = reader.readLine();
if (line != null && line.startsWith(token))
break;
}
reader.close(); }
if (line != null && line.trim().equals(token)) if (line != null && line.trim().equals(token))
PluginLog.getLog().info("Forked process started."); PluginLog.getLog().info("Forked process started.");

View File

@ -47,9 +47,9 @@ import org.eclipse.jetty.util.thread.Scheduler;
*/ */
public class MavenServerConnector extends AbstractLifeCycle implements Connector public class MavenServerConnector extends AbstractLifeCycle implements Connector
{ {
public static int DEFAULT_PORT = 8080; public static final int DEFAULT_PORT = 8080;
public static String DEFAULT_PORT_STR = String.valueOf(DEFAULT_PORT); public static final String DEFAULT_PORT_STR = String.valueOf(DEFAULT_PORT);
public static int DEFAULT_MAX_IDLE_TIME = 30000; public static final int DEFAULT_MAX_IDLE_TIME = 30000;
private Server server; private Server server;
private ServerConnector delegate; private ServerConnector delegate;
@ -206,7 +206,7 @@ public class MavenServerConnector extends AbstractLifeCycle implements Connector
public ConnectionFactory getDefaultConnectionFactory() public ConnectionFactory getDefaultConnectionFactory()
{ {
checkDelegate(); checkDelegate();
return getDefaultConnectionFactory(); return this.delegate.getDefaultConnectionFactory();
} }
/** /**

View File

@ -22,6 +22,7 @@ import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL; import java.net.URL;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@ -145,91 +146,87 @@ public class SelectiveJarResource extends JarResource
URL jarFileURL = new URL(urlString.substring(startOfJarUrl, endOfJarUrl)); URL jarFileURL = new URL(urlString.substring(startOfJarUrl, endOfJarUrl));
InputStream is = jarFileURL.openConnection().getInputStream(); try (InputStream is = jarFileURL.openConnection().getInputStream();
JarInputStream jin = new JarInputStream(is); JarInputStream jin = new JarInputStream(is))
JarEntry entry;
while((entry=jin.getNextJarEntry())!=null)
{ {
String entryName = entry.getName(); JarEntry entry;
LOG.debug("Looking at "+entryName); while((entry=jin.getNextJarEntry())!=null)
String dotCheck = entryName.replace('\\', '/');
dotCheck = URIUtil.canonicalPath(dotCheck);
if (dotCheck == null)
{ {
LOG.info("Invalid entry: "+entryName); String entryName = entry.getName();
continue;
}
File file=new File(directory,entryName); LOG.debug("Looking at "+entryName);
String dotCheck = entryName.replace('\\', '/');
if (entry.isDirectory()) dotCheck = URIUtil.canonicalPath(dotCheck);
{ if (dotCheck == null)
if (isIncluded(entryName))
{ {
if (!isExcluded(entryName)) LOG.info("Invalid entry: "+entryName);
continue;
}
File file=new File(directory,entryName);
if (entry.isDirectory())
{
if (isIncluded(entryName))
{ {
// Make directory if (!isExcluded(entryName))
if (!file.exists()) {
file.mkdirs(); // Make directory
if (!file.exists())
file.mkdirs();
}
else
LOG.debug("{} dir is excluded", entryName);
} }
else else
LOG.debug("{} dir is excluded", entryName); LOG.debug("{} dir is NOT included", entryName);
} }
else 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) if (!isExcluded(entryName))
File dir = new File(file.getParent());
if (!dir.exists())
dir.mkdirs();
// Make file
FileOutputStream fout = null;
try
{ {
fout = new FileOutputStream(file); // make directory (some jars don't list dirs)
IO.copy(jin,fout); File dir = new File(file.getParent());
} if (!dir.exists())
finally dir.mkdirs();
{
IO.close(fout);
}
// touch the file. // Make file
if (entry.getTime()>=0) try (OutputStream fout = new FileOutputStream(file))
file.setLastModified(entry.getTime()); {
IO.copy(jin,fout);
}
// touch the file.
if (entry.getTime()>=0)
file.setLastModified(entry.getTime());
}
else
LOG.debug("{} file is excluded", entryName);
} }
else 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();
Manifest manifest = jin.getManifest(); if (manifest != null)
if (manifest != null)
{
if (isIncluded("META-INF") && !isExcluded("META-INF"))
{ {
File metaInf = new File (directory, "META-INF"); if (isIncluded("META-INF") && !isExcluded("META-INF"))
metaInf.mkdir(); {
File f = new File(metaInf, "MANIFEST.MF"); File metaInf = new File (directory, "META-INF");
FileOutputStream fout = new FileOutputStream(f); metaInf.mkdir();
manifest.write(fout); File f = new File(metaInf, "MANIFEST.MF");
fout.close(); try (OutputStream fout = new FileOutputStream(f))
{
manifest.write(fout);
}
}
} }
} }
IO.close(jin);
} }
} }

View File

@ -20,6 +20,7 @@ package org.eclipse.jetty.maven.plugin;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration; import java.util.Enumeration;
@ -360,7 +361,10 @@ public class Starter
{ {
File f = new File(args[++i].trim()); File f = new File(args[++i].trim());
props = new Properties(); props = new Properties();
props.load(new FileInputStream(f)); try (InputStream in = new FileInputStream(f))
{
props.load(in);
}
} }
//--token //--token

View File

@ -34,12 +34,12 @@ import java.util.Map;
*/ */
public class SystemProperties public class SystemProperties
{ {
Map properties; private final Map<String, SystemProperty> properties;
boolean force; private boolean force;
public SystemProperties() public SystemProperties()
{ {
properties = new HashMap(); properties = new HashMap<>();
} }
public void setForce (boolean force) public void setForce (boolean force)
@ -64,7 +64,7 @@ public class SystemProperties
public SystemProperty getSystemProperty(String name) public SystemProperty getSystemProperty(String name)
{ {
return (SystemProperty)properties.get(name); return properties.get(name);
} }
public boolean containsSystemProperty(String name) public boolean containsSystemProperty(String name)
@ -72,8 +72,8 @@ public class SystemProperties
return properties.containsKey(name); return properties.containsKey(name);
} }
public List getSystemProperties () public List<SystemProperty> getSystemProperties ()
{ {
return new ArrayList(properties.values()); return new ArrayList<>(properties.values());
} }
} }

View File

@ -53,7 +53,7 @@ public class BundleWatcher implements BundleTrackerCustomizer
{ {
private static final Logger LOG = Log.getLogger(BundleWatcher.class); 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() + ")"; public static final String FILTER = "(objectclass=" + BundleProvider.class.getName() + ")";

View File

@ -73,7 +73,7 @@ public class LibExtClassLoaderHelper
public static Set<IFilesInJettyHomeResourcesProcessor> registeredFilesInJettyHomeResourcesProcessors = new HashSet<IFilesInJettyHomeResourcesProcessor>(); public static final Set<IFilesInJettyHomeResourcesProcessor> registeredFilesInJettyHomeResourcesProcessors = new HashSet<IFilesInJettyHomeResourcesProcessor>();
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */

View File

@ -51,13 +51,13 @@ import org.osgi.framework.BundleReference;
public class OSGiWebappClassLoader extends WebAppClassLoader implements 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 * 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. * 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) public static void addClassThatIdentifiesAJarThatMustBeRejected(Class<?> zclass)
{ {

View File

@ -20,6 +20,7 @@ package org.eclipse.jetty.overlays;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Set; import java.util.Set;
@ -577,9 +578,10 @@ public class OverlayedAppProviderTest
try try
{ {
IO.delete(file); IO.delete(file);
FileOutputStream out = new FileOutputStream(file,false); try (OutputStream out = new FileOutputStream(file,false))
out.write("<h1>Hello</h1>".getBytes()); {
out.close(); out.write("<h1>Hello</h1>".getBytes());
}
} }
catch(Exception e) catch(Exception e)
{ {

View File

@ -24,6 +24,7 @@ import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -290,30 +291,32 @@ public class DataSourceLoginService extends MappedLoginService
@Override @Override
protected UserIdentity loadUser (String userName) protected UserIdentity loadUser (String userName)
{ {
Connection connection = null;
try try
{ {
initDb(); initDb();
connection = getConnection(); try (Connection connection = getConnection();
PreparedStatement statement1 = connection.prepareStatement(_userSql))
PreparedStatement statement = connection.prepareStatement(_userSql);
statement.setObject(1, userName);
ResultSet rs = statement.executeQuery();
if (rs.next())
{ {
int key = rs.getInt(_userTableKey); statement1.setObject(1, userName);
String credentials = rs.getString(_userTablePasswordField); try (ResultSet rs1 = statement1.executeQuery())
statement.close(); {
if (rs1.next())
statement = connection.prepareStatement(_roleSql); {
statement.setInt(1, key); int key = rs1.getInt(_userTableKey);
rs = statement.executeQuery(); String credentials = rs1.getString(_userTablePasswordField);
List<String> roles = new ArrayList<String>(); List<String> roles = new ArrayList<String>();
while (rs.next()) try (PreparedStatement statement2 = connection.prepareStatement(_roleSql))
roles.add(rs.getString(_roleTableRoleField)); {
statement.close(); statement2.setInt(1, key);
return putUser(userName,new Password(credentials), roles.toArray(new String[roles.size()])); 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) catch (NamingException e)
@ -324,24 +327,6 @@ public class DataSourceLoginService extends MappedLoginService
{ {
LOG.warn("Problem loading user info for "+userName, e); 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; return null;
} }
@ -402,93 +387,94 @@ public class DataSourceLoginService extends MappedLoginService
private void prepareTables() private void prepareTables()
throws NamingException, SQLException throws NamingException, SQLException
{ {
Connection connection = null;
boolean autocommit = true;
if (_createTables) if (_createTables)
{ {
try boolean autocommit = true;
Connection connection = getConnection();
try (Statement stmt = connection.createStatement())
{ {
connection = getConnection();
autocommit = connection.getAutoCommit(); autocommit = connection.getAutoCommit();
connection.setAutoCommit(false); connection.setAutoCommit(false);
DatabaseMetaData metaData = connection.getMetaData(); DatabaseMetaData metaData = connection.getMetaData();
//check if tables exist //check if tables exist
String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName));
ResultSet result = metaData.getTables(null, null, tableName, null); try (ResultSet result = metaData.getTables(null, null, tableName, null))
if (!result.next())
{ {
//user table default if (!result.next())
/* {
* create table _userTableName (_userTableKey integer, //user table default
* _userTableUserField varchar(100) not null unique, /*
* _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); * create table _userTableName (_userTableKey integer,
*/ * _userTableUserField varchar(100) not null unique,
connection.createStatement().executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ * _userTablePasswordField varchar(20) not null, primary key(_userTableKey));
_userTableUserField+" varchar(100) not null unique,"+ */
_userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+
if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); _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)); tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName));
result = metaData.getTables(null, null, tableName, null); try (ResultSet result = metaData.getTables(null, null, tableName, null))
if (!result.next())
{ {
//role table default if (!result.next())
/* {
* create table _roleTableName (_roleTableKey integer, //role table default
* _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); /*
*/ * create table _roleTableName (_roleTableKey integer,
String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey));
_roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; */
connection.createStatement().executeUpdate(str); String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+
if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); _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)); tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName));
result = metaData.getTables(null, null, tableName, null); try (ResultSet result = metaData.getTables(null, null, tableName, null))
if (!result.next())
{ {
//user-role table if (!result.next())
/* {
* create table _userRoleTableName (_userRoleTableUserKey integer, //user-role table
* _userRoleTableRoleKey integer, /*
* primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * create table _userRoleTableName (_userRoleTableUserKey integer,
* * _userRoleTableRoleKey integer,
* create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); * primary key (_userRoleTableUserKey, _userRoleTableRoleKey));
*/ *
connection.createStatement().executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey);
_userRoleTableRoleKey+" integer, "+ */
"primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+
connection.createStatement().executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); _userRoleTableRoleKey+" integer, "+
if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); "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(); connection.commit();
} }
finally finally
{ {
if (connection != null) try
{
connection.setAutoCommit(autocommit);
}
catch (SQLException e)
{
if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e);
}
finally
{ {
try try
{ {
connection.setAutoCommit(autocommit);
connection.close(); connection.close();
} }
catch (SQLException e) catch (SQLException e)
{ {
if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e);
} }
finally
{
connection = null;
}
} }
} }
} }

View File

@ -19,6 +19,7 @@
package org.eclipse.jetty.security; package org.eclipse.jetty.security;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager; import java.sql.DriverManager;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -116,8 +117,10 @@ public class JDBCLoginService extends MappedLoginService
{ {
Properties properties = new Properties(); Properties properties = new Properties();
Resource resource = Resource.newResource(_config); Resource resource = Resource.newResource(_config);
properties.load(resource.getInputStream()); try (InputStream in = resource.getInputStream())
{
properties.load(in);
}
_jdbcDriver = properties.getProperty("jdbcdriver"); _jdbcDriver = properties.getProperty("jdbcdriver");
_url = properties.getProperty("url"); _url = properties.getProperty("url");
_userName = properties.getProperty("username"); _userName = properties.getProperty("username");
@ -238,25 +241,29 @@ public class JDBCLoginService extends MappedLoginService
if (null == _con) if (null == _con)
throw new SQLException("Can't connect to database"); throw new SQLException("Can't connect to database");
PreparedStatement stat = _con.prepareStatement(_userSql); try (PreparedStatement stat1 = _con.prepareStatement(_userSql))
stat.setObject(1, username);
ResultSet rs = stat.executeQuery();
if (rs.next())
{ {
int key = rs.getInt(_userTableKey); stat1.setObject(1, username);
String credentials = rs.getString(_userTablePasswordField); try (ResultSet rs1 = stat1.executeQuery())
stat.close(); {
if (rs1.next())
{
int key = rs1.getInt(_userTableKey);
String credentials = rs1.getString(_userTablePasswordField);
List<String> roles = new ArrayList<String>();
stat = _con.prepareStatement(_roleSql); try (PreparedStatement stat2 = _con.prepareStatement(_roleSql))
stat.setInt(1, key); {
rs = stat.executeQuery(); stat2.setInt(1, key);
List<String> roles = new ArrayList<String>(); try (ResultSet rs2 = stat2.executeQuery())
while (rs.next()) {
roles.add(rs.getString(_roleTableRoleField)); while (rs2.next())
roles.add(rs2.getString(_roleTableRoleField));
stat.close(); }
return putUser(username, Credential.getCredential(credentials),roles.toArray(new String[roles.size()])); }
return putUser(username, Credential.getCredential(credentials),roles.toArray(new String[roles.size()]));
}
}
} }
} }
catch (SQLException e) catch (SQLException e)

View File

@ -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() 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 * FormAuthenticator to allow access to logon and error pages within an
* authenticated URI tree. * authenticated URI tree.
*/ */
public static Principal __NOBODY = new Principal() public static final Principal __NOBODY = new Principal()
{ {
public String getName() public String getName()
{ {

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.security;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@ -55,19 +56,21 @@ public class PropertyUserStoreTest
private void writeInitialUsers(String testFile) throws Exception private void writeInitialUsers(String testFile) throws Exception
{ {
BufferedWriter writer = new BufferedWriter(new FileWriter(testFile)); try (Writer writer = new BufferedWriter(new FileWriter(testFile)))
writer.append("tom: tom, roleA\n"); {
writer.append("dick: dick, roleB\n"); writer.append("tom: tom, roleA\n");
writer.append("harry: harry, roleA, roleB\n"); writer.append("dick: dick, roleB\n");
writer.close(); writer.append("harry: harry, roleA, roleB\n");
}
} }
private void writeAdditionalUser(String testFile) throws Exception private void writeAdditionalUser(String testFile) throws Exception
{ {
Thread.sleep(1001); Thread.sleep(1001);
BufferedWriter writer = new BufferedWriter(new FileWriter(testFile,true)); try (Writer writer = new BufferedWriter(new FileWriter(testFile,true)))
writer.append("skip: skip, roleA\n"); {
writer.close(); writer.append("skip: skip, roleA\n");
}
} }
@Test @Test

View File

@ -208,7 +208,7 @@ public class NCSARequestLog extends AbstractNCSARequestLog implements RequestLog
{ {
if (_writer==null) if (_writer==null)
return; return;
_writer.write(requestEntry.toString()); _writer.write(requestEntry);
_writer.write(StringUtil.__LINE_SEPARATOR); _writer.write(StringUtil.__LINE_SEPARATOR);
_writer.flush(); _writer.flush();
} }

View File

@ -423,8 +423,11 @@ public class Response implements HttpServletResponse
writer.flush(); writer.flush();
setContentLength(writer.size()); setContentLength(writer.size());
writer.writeTo(getOutputStream()); try (ServletOutputStream outputStream = getOutputStream())
writer.destroy(); {
writer.writeTo(outputStream);
writer.destroy();
}
} }
} }
else if (code!=SC_PARTIAL_CONTENT) else if (code!=SC_PARTIAL_CONTENT)

View File

@ -169,9 +169,10 @@ public class DefaultHandler extends AbstractHandler
writer.write("\n</BODY>\n</HTML>\n"); writer.write("\n</BODY>\n</HTML>\n");
writer.flush(); writer.flush();
response.setContentLength(writer.size()); response.setContentLength(writer.size());
OutputStream out=response.getOutputStream(); try (OutputStream out=response.getOutputStream())
writer.writeTo(out); {
out.close(); writer.writeTo(out);
}
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */

View File

@ -281,7 +281,7 @@ public class ResourceHandler extends HandlerWrapper
{ {
LOG.warn(e.toString()); LOG.warn(e.toString());
LOG.debug(e); LOG.debug(e);
throw new IllegalArgumentException(stylesheet.toString()); throw new IllegalArgumentException(stylesheet);
} }
} }
@ -291,7 +291,7 @@ public class ResourceHandler extends HandlerWrapper
*/ */
public String getCacheControl() public String getCacheControl()
{ {
return _cacheControl.toString(); return _cacheControl;
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@ -484,7 +484,7 @@ public class ResourceHandler extends HandlerWrapper
String mime=_mimeTypes.getMimeByExtension(resource.toString()); String mime=_mimeTypes.getMimeByExtension(resource.toString());
if (mime==null) if (mime==null)
mime=_mimeTypes.getMimeByExtension(request.getPathInfo()); mime=_mimeTypes.getMimeByExtension(request.getPathInfo());
doResponseHeaders(response,resource,mime!=null?mime.toString():null); doResponseHeaders(response,resource,mime);
if (_etags) if (_etags)
baseRequest.getResponse().getHttpFields().put(HttpHeader.ETAG,etag); baseRequest.getResponse().getHttpFields().put(HttpHeader.ETAG,etag);
@ -615,7 +615,7 @@ public class ResourceHandler extends HandlerWrapper
response.setContentLength((int)length); response.setContentLength((int)length);
if (_cacheControl!=null) if (_cacheControl!=null)
response.setHeader(HttpHeader.CACHE_CONTROL.asString(),_cacheControl.toString()); response.setHeader(HttpHeader.CACHE_CONTROL.asString(),_cacheControl);
} }
} }
} }

View File

@ -623,11 +623,10 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
_deleteId = "delete from "+_sessionIdTable+" where id = ?"; _deleteId = "delete from "+_sessionIdTable+" where id = ?";
_queryId = "select * from "+_sessionIdTable+" where id = ?"; _queryId = "select * from "+_sessionIdTable+" where id = ?";
Connection connection = null; try (Connection connection = getConnection();
try Statement statement = connection.createStatement())
{ {
//make the id table //make the id table
connection = getConnection();
connection.setAutoCommit(true); connection.setAutoCommit(true);
DatabaseMetaData metaData = connection.getMetaData(); DatabaseMetaData metaData = connection.getMetaData();
_dbAdaptor = new DatabaseAdaptor(metaData); _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 //checking for table existence is case-sensitive, but table creation is not
String tableName = _dbAdaptor.convertIdentifier(_sessionIdTable); String tableName = _dbAdaptor.convertIdentifier(_sessionIdTable);
ResultSet result = metaData.getTables(null, null, tableName, null); try (ResultSet result = metaData.getTables(null, null, tableName, null))
if (!result.next())
{ {
//table does not exist, so create it if (!result.next())
connection.createStatement().executeUpdate(_createSessionIdTable); {
//table does not exist, so create it
statement.executeUpdate(_createSessionIdTable);
}
} }
//make the session table if necessary //make the session table if necessary
tableName = _dbAdaptor.convertIdentifier(_sessionTable); tableName = _dbAdaptor.convertIdentifier(_sessionTable);
result = metaData.getTables(null, null, tableName, null); try (ResultSet result = metaData.getTables(null, null, tableName, null))
if (!result.next())
{ {
//table does not exist, so create it if (!result.next())
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")); //table does not exist, so create it
String blobType = _dbAdaptor.getBlobType();
String longType = _dbAdaptor.getLongType();
_createSessionTable = "create table "+_sessionTable+" ("+_sessionTableRowId+" varchar(120), sessionId varchar(120), "+
" contextPath varchar(60), virtualHost varchar(60), lastNode varchar(60), accessTime "+longType+", "+
" lastAccessTime "+longType+", createTime "+longType+", cookieTime "+longType+", "+
" lastSavedTime "+longType+", expiryTime "+longType+", maxInterval "+longType+", map "+blobType+", primary key("+_sessionTableRowId+"))";
statement.executeUpdate(_createSessionTable);
} }
catch (SQLException s) else
{
LOG.warn("Problem checking if "+_sessionTable+" table contains maxInterval column. Ensure table contains column definition: \"maxInterval long not null default -999\"");
throw s;
}
if (!colResult.next())
{ {
//session table exists, check it has maxinterval column
ResultSet colResult = null;
try try
{ {
//add the maxinterval column colResult = metaData.getColumns(null, null,_dbAdaptor.convertIdentifier(_sessionTable), _dbAdaptor.convertIdentifier("maxInterval"));
String longType = _dbAdaptor.getLongType();
connection.createStatement().executeUpdate("alter table "+_sessionTable+" add maxInterval "+longType+" not null default "+MAX_INTERVAL_NOT_SET);
} }
catch (SQLException s) 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; 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 //make some indexes on the JettySessions table
String index1 = "idx_"+_sessionTable+"_expiry"; String index1 = "idx_"+_sessionTable+"_expiry";
String index2 = "idx_"+_sessionTable+"_session"; String index2 = "idx_"+_sessionTable+"_session";
result = metaData.getIndexInfo(null, null, tableName, false, false);
boolean index1Exists = false; boolean index1Exists = false;
boolean index2Exists = false; boolean index2Exists = false;
while (result.next()) try (ResultSet result = metaData.getIndexInfo(null, null, tableName, false, false))
{ {
String idxName = result.getString("INDEX_NAME"); while (result.next())
if (index1.equalsIgnoreCase(idxName)) {
index1Exists = true; String idxName = result.getString("INDEX_NAME");
else if (index2.equalsIgnoreCase(idxName)) if (index1.equalsIgnoreCase(idxName))
index2Exists = true; index1Exists = true;
} else if (index2.equalsIgnoreCase(idxName))
if (!(index1Exists && index2Exists)) index2Exists = true;
{ }
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)");
} }
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 //set up some strings representing the statements for session manipulation
_insertSession = "insert into "+_sessionTable+ _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) private void insert (String id)
throws SQLException throws SQLException
{ {
Connection connection = null; try (Connection connection = getConnection();
try PreparedStatement query = connection.prepareStatement(_queryId))
{ {
connection = getConnection();
connection.setAutoCommit(true); connection.setAutoCommit(true);
PreparedStatement query = connection.prepareStatement(_queryId);
query.setString(1, id); query.setString(1, id);
ResultSet result = query.executeQuery(); try (ResultSet result = query.executeQuery())
//only insert the id if it isn't in the db already
if (!result.next())
{ {
PreparedStatement statement = connection.prepareStatement(_insertId); //only insert the id if it isn't in the db already
statement.setString(1, id); if (!result.next())
statement.executeUpdate(); {
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) private void delete (String id)
throws SQLException throws SQLException
{ {
Connection connection = null; try (Connection connection = getConnection();
try PreparedStatement statement = connection.prepareStatement(_deleteId))
{ {
connection = getConnection();
connection.setAutoCommit(true); connection.setAutoCommit(true);
PreparedStatement statement = connection.prepareStatement(_deleteId);
statement.setString(1, id); statement.setString(1, id);
statement.executeUpdate(); statement.executeUpdate();
} }
finally
{
if (connection != null)
connection.close();
}
} }
@ -804,20 +794,15 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
private boolean exists (String id) private boolean exists (String id)
throws SQLException throws SQLException
{ {
Connection connection = null; try (Connection connection = getConnection();
try PreparedStatement statement = connection.prepareStatement(_queryId))
{ {
connection = getConnection();
connection.setAutoCommit(true); connection.setAutoCommit(true);
PreparedStatement statement = connection.prepareStatement(_queryId);
statement.setString(1, id); statement.setString(1, id);
ResultSet result = statement.executeQuery(); try (ResultSet result = statement.executeQuery())
return result.next(); {
} return result.next();
finally }
{
if (connection != null)
connection.close();
} }
} }
@ -835,7 +820,6 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
private void scavenge () private void scavenge ()
{ {
Connection connection = null; Connection connection = null;
Set<String> expiredSessionIds = new HashSet<String>();
try try
{ {
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled())
@ -844,70 +828,78 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
{ {
connection = getConnection(); connection = getConnection();
connection.setAutoCommit(true); 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 //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 lowerBound = (_lastScavengeTime - _scavengeIntervalMs);
long upperBound = _lastScavengeTime; long upperBound = _lastScavengeTime;
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled())
LOG.debug (getWorkerName()+"- Pass 1: Searching for sessions expired between "+lowerBound + " and "+upperBound); LOG.debug (getWorkerName()+"- Pass 1: Searching for sessions expired between "+lowerBound + " and "+upperBound);
statement.setString(1, getWorkerName()); try (PreparedStatement statement = connection.prepareStatement(_selectBoundedExpiredSessions))
statement.setLong(2, lowerBound);
statement.setLong(3, upperBound);
ResultSet result = statement.executeQuery();
while (result.next())
{ {
String sessionId = result.getString("sessionId"); statement.setString(1, getWorkerName());
expiredSessionIds.add(sessionId); statement.setLong(2, lowerBound);
if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId); 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); scavengeSessions(expiredSessionIds, false);
//Pass 2: find sessions that have expired a while ago for which this node was their last manager //Pass 2: find sessions that have expired a while ago for which this node was their last manager
PreparedStatement selectExpiredSessions = connection.prepareStatement(_selectExpiredSessions); try (PreparedStatement selectExpiredSessions = connection.prepareStatement(_selectExpiredSessions))
expiredSessionIds.clear();
upperBound = _lastScavengeTime - (2 * _scavengeIntervalMs);
if (upperBound > 0)
{
if (LOG.isDebugEnabled()) LOG.debug(getWorkerName()+"- Pass 2: Searching for sessions expired before "+upperBound);
selectExpiredSessions.setLong(1, upperBound);
result = selectExpiredSessions.executeQuery();
while (result.next())
{
String sessionId = result.getString("sessionId");
String lastNode = result.getString("lastNode");
if ((getWorkerName() == null && lastNode == null) || (getWorkerName() != null && getWorkerName().equals(lastNode)))
expiredSessionIds.add(sessionId);
if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId+" last managed by "+getWorkerName());
}
result.close();
scavengeSessions(expiredSessionIds, false);
}
//Pass 3:
//find all sessions that have expired at least a couple of scanIntervals ago
//if we did not succeed in loading them (eg their related context no longer exists, can't be loaded etc) then
//they are simply deleted
upperBound = _lastScavengeTime - (3 * _scavengeIntervalMs);
expiredSessionIds.clear();
if (upperBound > 0)
{ {
if (LOG.isDebugEnabled()) LOG.debug(getWorkerName()+"- Pass 3: searching for sessions expired before "+upperBound); expiredSessionIds.clear();
selectExpiredSessions.setLong(1, upperBound); upperBound = _lastScavengeTime - (2 * _scavengeIntervalMs);
result = selectExpiredSessions.executeQuery(); if (upperBound > 0)
while (result.next())
{ {
String sessionId = result.getString("sessionId"); if (LOG.isDebugEnabled()) LOG.debug(getWorkerName()+"- Pass 2: Searching for sessions expired before "+upperBound);
expiredSessionIds.add(sessionId); selectExpiredSessions.setLong(1, upperBound);
if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId); try (ResultSet result = selectExpiredSessions.executeQuery())
} {
result.close(); while (result.next())
scavengeSessions(expiredSessionIds, true); {
String sessionId = result.getString("sessionId");
String lastNode = result.getString("lastNode");
if ((getWorkerName() == null && lastNode == null) || (getWorkerName() != null && getWorkerName().equals(lastNode)))
expiredSessionIds.add(sessionId);
if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId+" last managed by "+getWorkerName());
}
}
scavengeSessions(expiredSessionIds, false);
}
//Pass 3:
//find all sessions that have expired at least a couple of scanIntervals ago
//if we did not succeed in loading them (eg their related context no longer exists, can't be loaded etc) then
//they are simply deleted
upperBound = _lastScavengeTime - (3 * _scavengeIntervalMs);
expiredSessionIds.clear();
if (upperBound > 0)
{
if (LOG.isDebugEnabled()) LOG.debug(getWorkerName()+"- Pass 3: searching for sessions expired before "+upperBound);
selectExpiredSessions.setLong(1, upperBound);
try (ResultSet result = selectExpiredSessions.executeQuery())
{
while (result.next())
{
String sessionId = result.getString("sessionId");
expiredSessionIds.add(sessionId);
if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId);
}
}
scavengeSessions(expiredSessionIds, true);
}
} }
} }
} }
@ -990,10 +982,8 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
return; return;
String[] ids = expiredIds.toArray(new String[expiredIds.size()]); String[] ids = expiredIds.toArray(new String[expiredIds.size()]);
Connection con = null; try (Connection con = getConnection())
try
{ {
con = getConnection();
con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
con.setAutoCommit(false); con.setAutoCommit(false);
@ -1002,38 +992,29 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
int blocksize = _deleteBlockSize; int blocksize = _deleteBlockSize;
int block = 0; int block = 0;
while (end < ids.length) try (Statement statement = con.createStatement())
{ {
start = block*blocksize; while (end < ids.length)
if ((ids.length - start) >= blocksize) {
end = start + blocksize; start = block*blocksize;
else if ((ids.length - start) >= blocksize)
end = ids.length; end = start + blocksize;
else
Statement statement = con.createStatement(); 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();
} //take them out of the sessionIds table
catch (Exception e) statement.executeUpdate(fillInClause("delete from "+_sessionIdTable+" where id in ", ids, start, end));
{ //take them out of the sessions table
if (con != null) statement.executeUpdate(fillInClause("delete from "+_sessionTable+" where sessionId in ", ids, start, end));
block++;
}
}
catch (Exception e)
{ {
con.rollback(); con.rollback();
throw e; throw e;
} }
} con.commit();
finally
{
if (con != null)
{
con.close();
}
} }
} }

View File

@ -874,14 +874,11 @@ public class JDBCSessionManager extends AbstractSessionManager
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void run() public void run()
{ {
Session session = null; try (Connection connection = getConnection();
Connection connection=null; PreparedStatement statement = _jdbcSessionIdMgr._dbAdaptor.getLoadStatement(connection, id, canonicalContextPath, vhost);
PreparedStatement statement = null; ResultSet result = statement.executeQuery())
try
{ {
connection = getConnection(); Session session = null;
statement = _jdbcSessionIdMgr._dbAdaptor.getLoadStatement(connection, id, canonicalContextPath, vhost);
ResultSet result = statement.executeQuery();
if (result.next()) if (result.next())
{ {
long maxInterval = result.getLong("maxInterval"); long maxInterval = result.getLong("maxInterval");
@ -901,11 +898,12 @@ public class JDBCSessionManager extends AbstractSessionManager
session.setCanonicalContext(result.getString("contextPath")); session.setCanonicalContext(result.getString("contextPath"));
session.setVirtualHost(result.getString("virtualHost")); session.setVirtualHost(result.getString("virtualHost"));
InputStream is = ((JDBCSessionIdManager)getSessionIdManager())._dbAdaptor.getBlobInputStream(result, "map"); try (InputStream is = ((JDBCSessionIdManager)getSessionIdManager())._dbAdaptor.getBlobInputStream(result, "map");
ClassLoadingObjectInputStream ois = new ClassLoadingObjectInputStream (is); ClassLoadingObjectInputStream ois = new ClassLoadingObjectInputStream(is))
Object o = ois.readObject(); {
session.addAttributes((Map<String,Object>)o); Object o = ois.readObject();
ois.close(); session.addAttributes((Map<String,Object>)o);
}
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled())
LOG.debug("LOADED session "+session); LOG.debug("LOADED session "+session);
@ -919,14 +917,6 @@ public class JDBCSessionManager extends AbstractSessionManager
{ {
_exception.set(e); _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; return;
//put into the database //put into the database
Connection connection = getConnection(); try (Connection connection = getConnection();
PreparedStatement statement = null; PreparedStatement statement = connection.prepareStatement(_jdbcSessionIdMgr._insertSession))
try
{ {
String rowId = calculateRowId(session); String rowId = calculateRowId(session);
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
connection.setAutoCommit(true); connection.setAutoCommit(true);
statement = connection.prepareStatement(_jdbcSessionIdMgr._insertSession);
statement.setString(1, rowId); //rowId statement.setString(1, rowId); //rowId
statement.setString(2, session.getId()); //session id statement.setString(2, session.getId()); //session id
statement.setString(3, session.getCanonicalContext()); //context path statement.setString(3, session.getCanonicalContext()); //context path
@ -984,6 +972,7 @@ public class JDBCSessionManager extends AbstractSessionManager
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos); ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(session.getAttributeMap()); oos.writeObject(session.getAttributeMap());
oos.flush();
byte[] bytes = baos.toByteArray(); byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
@ -993,16 +982,9 @@ public class JDBCSessionManager extends AbstractSessionManager
statement.executeUpdate(); statement.executeUpdate();
session.setRowId(rowId); //set it on the in-memory data as well as in db session.setRowId(rowId); //set it on the in-memory data as well as in db
session.setLastSaved(now); 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) if (data==null)
return; return;
Connection connection = getConnection(); try (Connection connection = getConnection();
PreparedStatement statement = null; PreparedStatement statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSession))
try
{ {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
connection.setAutoCommit(true); connection.setAutoCommit(true);
statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSession);
statement.setString(1, data.getId()); statement.setString(1, data.getId());
statement.setString(2, getSessionIdManager().getWorkerName());//my node id statement.setString(2, getSessionIdManager().getWorkerName());//my node id
statement.setLong(3, data.getAccessed());//accessTime statement.setLong(3, data.getAccessed());//accessTime
@ -1036,6 +1016,7 @@ public class JDBCSessionManager extends AbstractSessionManager
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos); ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(data.getAttributeMap()); oos.writeObject(data.getAttributeMap());
oos.flush();
byte[] bytes = baos.toByteArray(); byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
@ -1044,14 +1025,9 @@ public class JDBCSessionManager extends AbstractSessionManager
statement.executeUpdate(); statement.executeUpdate();
data.setLastSaved(now); 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 throws Exception
{ {
String nodeId = getSessionIdManager().getWorkerName(); String nodeId = getSessionIdManager().getWorkerName();
Connection connection = getConnection(); try (Connection connection = getConnection();
PreparedStatement statement = null; PreparedStatement statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSessionNode))
try
{ {
connection.setAutoCommit(true); connection.setAutoCommit(true);
statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSessionNode);
statement.setString(1, nodeId); statement.setString(1, nodeId);
statement.setString(2, data.getRowId()); statement.setString(2, data.getRowId());
statement.executeUpdate(); 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) private void updateSessionAccessTime (Session data)
throws Exception throws Exception
{ {
Connection connection = getConnection(); try (Connection connection = getConnection();
PreparedStatement statement = null; PreparedStatement statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSessionAccessTime))
try
{ {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
connection.setAutoCommit(true); connection.setAutoCommit(true);
statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSessionAccessTime);
statement.setString(1, getSessionIdManager().getWorkerName()); statement.setString(1, getSessionIdManager().getWorkerName());
statement.setLong(2, data.getAccessed()); statement.setLong(2, data.getAccessed());
statement.setLong(3, data.getLastAccessedTime()); statement.setLong(3, data.getLastAccessedTime());
@ -1111,15 +1077,9 @@ public class JDBCSessionManager extends AbstractSessionManager
statement.executeUpdate(); statement.executeUpdate();
data.setLastSaved(now); 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) protected void deleteSession (Session data)
throws Exception throws Exception
{ {
Connection connection = getConnection(); try (Connection connection = getConnection();
PreparedStatement statement = null; PreparedStatement statement = connection.prepareStatement(_jdbcSessionIdMgr._deleteSession))
try
{ {
connection.setAutoCommit(true); connection.setAutoCommit(true);
statement = connection.prepareStatement(_jdbcSessionIdMgr._deleteSession);
statement.setString(1, data.getRowId()); statement.setString(1, data.getRowId());
statement.executeUpdate(); statement.executeUpdate();
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled())
LOG.debug("Deleted Session "+data); LOG.debug("Deleted Session "+data);
} }
finally
{
if (connection!=null)
connection.close();
}
} }

View File

@ -117,7 +117,7 @@ public class DumpHandler extends AbstractHandler
Enumeration<String> names=request.getParameterNames(); Enumeration<String> names=request.getParameterNames();
while(names.hasMoreElements()) while(names.hasMoreElements())
{ {
String name=names.nextElement().toString(); String name=names.nextElement();
String[] values=request.getParameterValues(name); String[] values=request.getParameterValues(name);
if (values==null || values.length==0) if (values==null || values.length==0)
{ {

View File

@ -988,10 +988,12 @@ public class RequestTest
if (evil_keys.exists()) if (evil_keys.exists())
{ {
LOG.info("Using real evil keys!"); LOG.info("Using real evil keys!");
BufferedReader in = new BufferedReader(new FileReader(evil_keys)); try (BufferedReader in = new BufferedReader(new FileReader(evil_keys)))
String key=null; {
while((key=in.readLine())!=null) String key=null;
buf.append("&").append(key).append("=").append("x"); while((key=in.readLine())!=null)
buf.append("&").append(key).append("=").append("x");
}
} }
else else
{ {

View File

@ -25,6 +25,7 @@ import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream;
import org.eclipse.jetty.http.HttpContent; import org.eclipse.jetty.http.HttpContent;
import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.http.MimeTypes;
@ -117,11 +118,12 @@ public class ResourceCacheTest
files[i]=File.createTempFile("R-"+i+"-",".txt"); files[i]=File.createTempFile("R-"+i+"-",".txt");
files[i].deleteOnExit(); files[i].deleteOnExit();
names[i]=files[i].getName(); names[i]=files[i].getName();
FileOutputStream out = new FileOutputStream(files[i]); try (OutputStream out = new FileOutputStream(files[i]))
for (int j=0;j<(i*10-1);j++) {
out.write(' '); for (int j=0;j<(i*10-1);j++)
out.write('\n'); out.write(' ');
out.close(); out.write('\n');
}
} }
directory=Resource.newResource(files[0].getParentFile().getAbsolutePath()); directory=Resource.newResource(files[0].getParentFile().getAbsolutePath());
@ -182,9 +184,10 @@ public class ResourceCacheTest
Thread.sleep(200); Thread.sleep(200);
FileOutputStream out = new FileOutputStream(files[6]); try (OutputStream out = new FileOutputStream(files[6]))
out.write(' '); {
out.close(); out.write(' ');
}
content=cache.lookup(names[7]); content=cache.lookup(names[7]);
assertEquals(70,cache.getCachedSize()); assertEquals(70,cache.getCachedSize());
assertEquals(1,cache.getCachedFiles()); assertEquals(1,cache.getCachedFiles());
@ -250,10 +253,11 @@ public class ResourceCacheTest
{ {
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
String line = null; String line = null;
BufferedReader br = new BufferedReader(new InputStreamReader(r.addPath(path).getURL().openStream())); try (BufferedReader br = new BufferedReader(new InputStreamReader(r.addPath(path).getURL().openStream())))
while((line=br.readLine())!=null) {
buffer.append(line); while((line=br.readLine())!=null)
br.close(); buffer.append(line);
}
return buffer.toString(); return buffer.toString();
} }

View File

@ -21,6 +21,8 @@ package org.eclipse.jetty.server.handler;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket; import java.net.Socket;
import java.net.URI; import java.net.URI;
@ -58,11 +60,14 @@ public class ResourceHandlerTest
File dir = MavenTestingUtils.getTargetFile("test-classes/simple"); File dir = MavenTestingUtils.getTargetFile("test-classes/simple");
File huge = new File(dir,"huge.txt"); File huge = new File(dir,"huge.txt");
File big=new File(dir,"big.txt"); File big=new File(dir,"big.txt");
FileOutputStream out = new FileOutputStream(huge); try (OutputStream out = new FileOutputStream(huge)) {
for (int i=0;i<100;i++) for (int i=0;i<100;i++)
{ {
FileInputStream in=new FileInputStream(big); try (InputStream in=new FileInputStream(big))
IO.copy(in,out); {
IO.copy(in,out);
}
}
} }
huge.deleteOnExit(); huge.deleteOnExit();

View File

@ -75,7 +75,10 @@ public class SSLSelectChannelConnectorLoadTest
server.start(); server.start();
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); 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 trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore); trustManagerFactory.init(keystore);
sslContext = SSLContext.getInstance("SSL"); sslContext = SSLContext.getInstance("SSL");

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.server.ssl;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.Socket; import java.net.Socket;
import java.net.SocketException; import java.net.SocketException;
@ -111,7 +112,10 @@ public class SelectChannelServerSslTest extends HttpServerTestBase
startServer(connector); startServer(connector);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); 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 trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore); trustManagerFactory.init(keystore);
__sslContext = SSLContext.getInstance("TLS"); __sslContext = SSLContext.getInstance("TLS");

View File

@ -19,6 +19,7 @@
package org.eclipse.jetty.server.ssl; package org.eclipse.jetty.server.ssl;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream;
import java.net.Socket; import java.net.Socket;
import java.security.KeyStore; import java.security.KeyStore;
@ -55,7 +56,10 @@ public class SslSelectChannelTimeoutTest extends ConnectorTimeoutTest
startServer(connector); startServer(connector);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); 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 trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore); trustManagerFactory.init(keystore);
__sslContext = SSLContext.getInstance("SSL"); __sslContext = SSLContext.getInstance("SSL");

View File

@ -88,7 +88,10 @@ public class SslUploadTest
{ {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
SslContextFactory ctx=connector.getConnectionFactory(SslConnectionFactory.class).getSslContextFactory(); 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 trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore); trustManagerFactory.init(keystore);
SSLContext sslContext = SSLContext.getInstance("SSL"); SSLContext sslContext = SSLContext.getInstance("SSL");

View File

@ -664,7 +664,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
while (!match && quoted.hasMoreTokens()) while (!match && quoted.hasMoreTokens())
{ {
String tag = quoted.nextToken(); String tag = quoted.nextToken();
if (content.getETag().toString().equals(tag)) if (content.getETag().equals(tag))
match=true; match=true;
} }
} }
@ -680,7 +680,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
if (if_non_match_etag!=null && content.getETag()!=null) if (if_non_match_etag!=null && content.getETag()!=null)
{ {
// Look for GzipFiltered version of etag // 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.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader(HttpHeader.ETAG.asString(),if_non_match_etag); 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. // 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.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader(HttpHeader.ETAG.asString(),content.getETag()); response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
@ -700,7 +700,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
while (quoted.hasMoreTokens()) while (quoted.hasMoreTokens())
{ {
String tag = quoted.nextToken(); String tag = quoted.nextToken();
if (content.getETag().toString().equals(tag)) if (content.getETag().equals(tag))
{ {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader(HttpHeader.ETAG.asString(),content.getETag()); response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
@ -923,7 +923,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
// content-length header // content-length header
// //
writeHeaders(response,content,-1); 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) if (mimetype==null)
LOG.warn("Unknown mimetype for "+request.getRequestURI()); LOG.warn("Unknown mimetype for "+request.getRequestURI());
MultiPartOutputStream multi = new MultiPartOutputStream(out); MultiPartOutputStream multi = new MultiPartOutputStream(out);
@ -1041,7 +1041,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
writeOptionHeaders(response); writeOptionHeaders(response);
if (_etags) if (_etags)
response.setHeader(HttpHeader.ETAG.asString(),content.getETag().toString()); response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
} }
} }

View File

@ -409,9 +409,10 @@ public class CGI extends HttpServlet
{ {
try try
{ {
Writer outToCgi = new OutputStreamWriter(p.getOutputStream()); try (Writer outToCgi = new OutputStreamWriter(p.getOutputStream()))
outToCgi.write(input); {
outToCgi.close(); outToCgi.write(input);
}
} }
catch (IOException e) catch (IOException e)
{ {

View File

@ -219,24 +219,26 @@ public class PutFilter implements Filter
if (_putAtomic) if (_putAtomic)
{ {
File tmp=File.createTempFile(file.getName(),null,_tmpdir); File tmp=File.createTempFile(file.getName(),null,_tmpdir);
OutputStream out = new FileOutputStream(tmp,false); try (OutputStream out = new FileOutputStream(tmp,false))
if (toRead >= 0) {
IO.copy(in, out, toRead); if (toRead >= 0)
else IO.copy(in, out, toRead);
IO.copy(in, out); else
out.close(); IO.copy(in, out);
}
if (!tmp.renameTo(file)) if (!tmp.renameTo(file))
throw new IOException("rename from "+tmp+" to "+file+" failed"); throw new IOException("rename from "+tmp+" to "+file+" failed");
} }
else else
{ {
OutputStream out = new FileOutputStream(file,false); try (OutputStream out = new FileOutputStream(file,false))
if (toRead >= 0) {
IO.copy(in, out, toRead); if (toRead >= 0)
else IO.copy(in, out, toRead);
IO.copy(in, out); else
out.close(); IO.copy(in, out);
}
} }
response.setStatus(exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED); response.setStatus(exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED);

View File

@ -26,6 +26,7 @@ import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@ -95,10 +96,11 @@ public class IncludableGzipFilterTest
testdir.ensureEmpty(); testdir.ensureEmpty();
File testFile = testdir.getFile("file.txt"); File testFile = testdir.getFile("file.txt");
BufferedOutputStream testOut = new BufferedOutputStream(new FileOutputStream(testFile)); try (OutputStream testOut = new BufferedOutputStream(new FileOutputStream(testFile)))
ByteArrayInputStream testIn = new ByteArrayInputStream(__content.getBytes("ISO8859_1")); {
IO.copy(testIn,testOut); ByteArrayInputStream testIn = new ByteArrayInputStream(__content.getBytes("ISO8859_1"));
testOut.close(); IO.copy(testIn,testOut);
}
tester=new ServletTester("/context"); tester=new ServletTester("/context");
tester.getContext().setResourceBase(testdir.getDir().getCanonicalPath()); tester.getContext().setResourceBase(testdir.getDir().getCanonicalPath());

View File

@ -23,6 +23,7 @@ import static org.junit.Assert.assertTrue;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.Socket; import java.net.Socket;
import java.net.URL; import java.net.URL;
@ -193,9 +194,10 @@ public class PutFilterTest
File file=new File(_dir,"file.txt"); File file=new File(_dir,"file.txt");
assertTrue(file.exists()); assertTrue(file.exists());
FileInputStream fis = new FileInputStream(file); try (InputStream fis = new FileInputStream(file))
assertEquals(data1,IO.toString(fis)); {
fis.close(); assertEquals(data1,IO.toString(fis));
}
request.setMethod("DELETE"); request.setMethod("DELETE");
request.setURI("/context/file.txt"); request.setURI("/context/file.txt");
@ -231,9 +233,10 @@ public class PutFilterTest
File file=new File(_dir,"file.txt"); File file=new File(_dir,"file.txt");
assertTrue(file.exists()); assertTrue(file.exists());
FileInputStream fis = new FileInputStream(file); try (InputStream fis = new FileInputStream(file))
assertEquals(data1,IO.toString(fis)); {
fis.close(); assertEquals(data1,IO.toString(fis));
}
request.setMethod("MOVE"); request.setMethod("MOVE");
request.setURI("/context/file.txt"); request.setURI("/context/file.txt");

View File

@ -25,10 +25,11 @@ import java.util.Map;
public class Settings implements Iterable<Settings.Setting> public class Settings implements Iterable<Settings.Setting>
{ {
private Map<ID, Settings.Setting> settings = new HashMap<>(); private final Map<ID, Settings.Setting> settings;
public Settings() public Settings()
{ {
settings = new HashMap<>();
} }
public Settings(Settings original, boolean immutable) public Settings(Settings original, boolean immutable)
@ -94,13 +95,13 @@ public class Settings implements Iterable<Settings.Setting>
public static final class ID public static final class ID
{ {
public static ID UPLOAD_BANDWIDTH = new ID(1); public static final ID UPLOAD_BANDWIDTH = new ID(1);
public static ID DOWNLOAD_BANDWIDTH = new ID(2); public static final ID DOWNLOAD_BANDWIDTH = new ID(2);
public static ID ROUND_TRIP_TIME = new ID(3); public static final ID ROUND_TRIP_TIME = new ID(3);
public static ID MAX_CONCURRENT_STREAMS = new ID(4); public static final ID MAX_CONCURRENT_STREAMS = new ID(4);
public static ID CURRENT_CONGESTION_WINDOW = new ID(5); public static final ID CURRENT_CONGESTION_WINDOW = new ID(5);
public static ID DOWNLOAD_RETRANSMISSION_RATE = new ID(6); public static final ID DOWNLOAD_RETRANSMISSION_RATE = new ID(6);
public static ID INITIAL_WINDOW_SIZE = new ID(7); public static final ID INITIAL_WINDOW_SIZE = new ID(7);
public synchronized static ID from(int code) public synchronized static ID from(int code)
{ {

View File

@ -19,7 +19,7 @@
package org.eclipse.jetty.spdy.generator; package org.eclipse.jetty.spdy.generator;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.Random; import java.util.concurrent.ThreadLocalRandom;
import org.eclipse.jetty.io.ArrayByteBufferPool; import org.eclipse.jetty.io.ArrayByteBufferPool;
import org.eclipse.jetty.spdy.api.ByteBufferDataInfo; import org.eclipse.jetty.spdy.api.ByteBufferDataInfo;
@ -93,7 +93,7 @@ public class DataFrameGeneratorTest
private ByteBuffer createByteBuffer(int bufferSize) private ByteBuffer createByteBuffer(int bufferSize)
{ {
byte[] bytes = new byte[bufferSize]; byte[] bytes = new byte[bufferSize];
new Random().nextBytes(bytes); ThreadLocalRandom.current().nextBytes(bytes);
ByteBuffer byteBuffer = bufferPool.acquire(bufferSize, false); ByteBuffer byteBuffer = bufferPool.acquire(bufferSize, false);
BufferUtil.flipToFill(byteBuffer); BufferUtil.flipToFill(byteBuffer);
byteBuffer.put(bytes); byteBuffer.put(bytes);

View File

@ -24,11 +24,11 @@ import java.net.InetSocketAddress;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier; import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Exchanger; import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@ -349,7 +349,7 @@ public class PushStreamTest extends AbstractTest
private byte[] createHugeByteArray(int sizeInBytes) private byte[] createHugeByteArray(int sizeInBytes)
{ {
byte[] bytes = new byte[sizeInBytes]; byte[] bytes = new byte[sizeInBytes];
new Random().nextBytes(bytes); ThreadLocalRandom.current().nextBytes(bytes);
return bytes; return bytes;
} }

View File

@ -742,7 +742,10 @@ public class Main
File prop_file = File.createTempFile("start",".properties"); File prop_file = File.createTempFile("start",".properties");
if (!_dryRun) if (!_dryRun)
prop_file.deleteOnExit(); 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()); cmd.addArg(prop_file.getAbsolutePath());
} }

View File

@ -46,9 +46,9 @@ import java.util.TimerTask;
public class DateCache 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 String _tzFormatString;
private SimpleDateFormat _tzFormat; private SimpleDateFormat _tzFormat;

View File

@ -52,7 +52,7 @@ public class IO
CRLF_BYTES = {(byte)'\015',(byte)'\012'}; 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! // TODO get rid of this singleton!
@ -298,11 +298,11 @@ public class IO
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public static void copyFile(File from,File to) throws IOException public static void copyFile(File from,File to) throws IOException
{ {
FileInputStream in=new FileInputStream(from); try (InputStream in=new FileInputStream(from);
FileOutputStream out=new FileOutputStream(to); OutputStream out=new FileOutputStream(to))
copy(in,out); {
in.close(); copy(in,out);
out.close(); }
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */

View File

@ -35,8 +35,8 @@ public class MultiPartWriter extends FilterWriter
private final static String __CRLF="\015\012"; private final static String __CRLF="\015\012";
private final static String __DASHDASH="--"; private final static String __DASHDASH="--";
public static String MULTIPART_MIXED=MultiPartOutputStream.MULTIPART_MIXED; public static final String MULTIPART_MIXED=MultiPartOutputStream.MULTIPART_MIXED;
public static String MULTIPART_X_MIXED_REPLACE=MultiPartOutputStream.MULTIPART_X_MIXED_REPLACE; public static final String MULTIPART_X_MIXED_REPLACE=MultiPartOutputStream.MULTIPART_X_MIXED_REPLACE;
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
private String boundary; private String boundary;
@ -63,14 +63,20 @@ public class MultiPartWriter extends FilterWriter
public void close() public void close()
throws IOException throws IOException
{ {
if (inPart) try
{
if (inPart)
out.write(__CRLF);
out.write(__DASHDASH);
out.write(boundary);
out.write(__DASHDASH);
out.write(__CRLF); out.write(__CRLF);
out.write(__DASHDASH); inPart=false;
out.write(boundary); }
out.write(__DASHDASH); finally
out.write(__CRLF); {
inPart=false; super.close();
super.close(); }
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */

View File

@ -92,7 +92,7 @@ public class StringUtil
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public static char[] lowercases = { public static final char[] lowercases = {
'\000','\001','\002','\003','\004','\005','\006','\007', '\000','\001','\002','\003','\004','\005','\006','\007',
'\010','\011','\012','\013','\014','\015','\016','\017', '\010','\011','\012','\013','\014','\015','\016','\017',
'\020','\021','\022','\023','\024','\025','\026','\027', '\020','\021','\022','\023','\024','\025','\026','\027',

View File

@ -47,8 +47,8 @@ public class TypeUtil
{ {
private static final Logger LOG = Log.getLogger(TypeUtil.class); private static final Logger LOG = Log.getLogger(TypeUtil.class);
public static final Class<?>[] NO_ARGS = new Class[]{}; public static final Class<?>[] NO_ARGS = new Class[]{};
public static int CR = '\015'; public static final int CR = '\015';
public static int LF = '\012'; public static final int LF = '\012';
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
private static final HashMap<String, Class<?>> name2Class=new HashMap<>(); private static final HashMap<String, Class<?>> name2Class=new HashMap<>();

View File

@ -19,6 +19,7 @@
package org.eclipse.jetty.util.component; package org.eclipse.jetty.util.component;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.Writer;
import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.Logger;
@ -30,7 +31,7 @@ import org.eclipse.jetty.util.log.Logger;
*/ */
public class FileNoticeLifeCycleListener implements LifeCycle.Listener 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; private final String _filename;
@ -41,11 +42,9 @@ public class FileNoticeLifeCycleListener implements LifeCycle.Listener
private void writeState(String action, LifeCycle lifecycle) 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.append(action).append(" ").append(lifecycle.toString()).append("\n");
out.close();
} }
catch(Exception e) catch(Exception e)
{ {

View File

@ -58,7 +58,7 @@ public class Log
/** /**
* Logging Configuration Properties * Logging Configuration Properties
*/ */
protected static Properties __props; protected static final Properties __props;
/** /**
* The {@link Logger} implementation class name * The {@link Logger} implementation class name
*/ */

View File

@ -23,6 +23,7 @@ import java.io.FileOutputStream;
import java.io.FilterInputStream; import java.io.FilterInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.net.JarURLConnection; import java.net.JarURLConnection;
import java.net.URL; import java.net.URL;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
@ -153,115 +154,110 @@ public class JarResource extends URLResource
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled())
LOG.debug("Extracting entry = "+subEntryName+" from jar "+jarFileURL); LOG.debug("Extracting entry = "+subEntryName+" from jar "+jarFileURL);
InputStream is = jarFileURL.openConnection().getInputStream(); try (InputStream is = jarFileURL.openConnection().getInputStream();
JarInputStream jin = new JarInputStream(is); JarInputStream jin = new JarInputStream(is))
JarEntry entry;
boolean shouldExtract;
while((entry=jin.getNextJarEntry())!=null)
{ {
String entryName = entry.getName(); JarEntry entry;
if ((subEntryName != null) && (entryName.startsWith(subEntryName))) boolean shouldExtract;
{ while((entry=jin.getNextJarEntry())!=null)
// is the subentry really a dir? {
if (!subEntryIsDir && subEntryName.length()+1==entryName.length() && entryName.endsWith("/")) String entryName = entry.getName();
subEntryIsDir=true; if ((subEntryName != null) && (entryName.startsWith(subEntryName)))
//if there is a particular subEntry that we are looking for, only
//extract it.
if (subEntryIsDir)
{ {
//if it is a subdirectory we are looking for, then we // is the subentry really a dir?
//are looking to extract its contents into the target if (!subEntryIsDir && subEntryName.length()+1==entryName.length() && entryName.endsWith("/"))
//directory. Remove the name of the subdirectory so subEntryIsDir=true;
//that we don't wind up creating it too.
entryName = entryName.substring(subEntryName.length()); //if there is a particular subEntry that we are looking for, only
if (!entryName.equals("")) //extract it.
if (subEntryIsDir)
{ {
//the entry is //if it is a subdirectory we are looking for, then we
shouldExtract = true; //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 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 else
shouldExtract = true;
}
else if ((subEntryName != null) && (!entryName.startsWith(subEntryName)))
{
//there is a particular entry we are looking for, and this one
//isn't it
shouldExtract = false;
}
else
{
//we are extracting everything
shouldExtract = true;
}
if (!shouldExtract)
{
if (LOG.isDebugEnabled())
LOG.debug("Skipping entry: "+entryName);
continue;
}
String dotCheck = entryName.replace('\\', '/');
dotCheck = URIUtil.canonicalPath(dotCheck);
if (dotCheck == null)
{
if (LOG.isDebugEnabled())
LOG.debug("Invalid entry: "+entryName);
continue;
}
File file=new File(directory,entryName);
if (entry.isDirectory())
{
// Make directory
if (!file.exists())
file.mkdirs();
}
else
{
// make directory (some jars don't list dirs)
File dir = new File(file.getParent());
if (!dir.exists())
dir.mkdirs();
// Make file
FileOutputStream fout = null;
try
{ {
fout = new FileOutputStream(file); //we are extracting everything
IO.copy(jin,fout); shouldExtract = true;
}
finally
{
IO.close(fout);
} }
// touch the file. if (!shouldExtract)
if (entry.getTime()>=0) {
file.setLastModified(entry.getTime()); if (LOG.isDebugEnabled())
LOG.debug("Skipping entry: "+entryName);
continue;
}
String dotCheck = entryName.replace('\\', '/');
dotCheck = URIUtil.canonicalPath(dotCheck);
if (dotCheck == null)
{
if (LOG.isDebugEnabled())
LOG.debug("Invalid entry: "+entryName);
continue;
}
File file=new File(directory,entryName);
if (entry.isDirectory())
{
// Make directory
if (!file.exists())
file.mkdirs();
}
else
{
// make directory (some jars don't list dirs)
File dir = new File(file.getParent());
if (!dir.exists())
dir.mkdirs();
// Make file
try (OutputStream fout = new FileOutputStream(file))
{
IO.copy(jin,fout);
}
// touch the file.
if (entry.getTime()>=0)
file.setLastModified(entry.getTime());
}
} }
}
if ((subEntryName == null) || (subEntryName != null && subEntryName.equalsIgnoreCase("META-INF/MANIFEST.MF")))
if ((subEntryName == null) || (subEntryName != null && subEntryName.equalsIgnoreCase("META-INF/MANIFEST.MF")))
{
Manifest manifest = jin.getManifest();
if (manifest != null)
{ {
File metaInf = new File (directory, "META-INF"); Manifest manifest = jin.getManifest();
metaInf.mkdir(); if (manifest != null)
File f = new File(metaInf, "MANIFEST.MF"); {
FileOutputStream fout = new FileOutputStream(f); File metaInf = new File (directory, "META-INF");
manifest.write(fout); metaInf.mkdir();
fout.close(); 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 public static Resource newJarResource(Resource resource) throws IOException

View File

@ -615,8 +615,7 @@ public abstract class Resource implements ResourceFactory, Closeable
public void writeTo(OutputStream out,long start,long count) public void writeTo(OutputStream out,long start,long count)
throws IOException throws IOException
{ {
InputStream in = getInputStream(); try (InputStream in = getInputStream())
try
{ {
in.skip(start); in.skip(start);
if (count<0) if (count<0)
@ -624,10 +623,6 @@ public abstract class Resource implements ResourceFactory, Closeable
else else
IO.copy(in,out,count); IO.copy(in,out,count);
} }
finally
{
in.close();
}
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@ -636,7 +631,10 @@ public abstract class Resource implements ResourceFactory, Closeable
{ {
if (destination.exists()) if (destination.exists())
throw new IllegalArgumentException(destination+" exists"); throw new IllegalArgumentException(destination+" exists");
writeTo(new FileOutputStream(destination),0,-1); try (OutputStream out = new FileOutputStream(destination))
{
writeTo(out,0,-1);
}
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */

View File

@ -24,7 +24,7 @@ import java.io.IOException;
import java.nio.BufferOverflowException; import java.nio.BufferOverflowException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.Arrays; 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.Log;
import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.Logger;
@ -245,7 +245,7 @@ public class BufferUtilTest
int iterations = 100; int iterations = 100;
int testRuns = 10; int testRuns = 10;
byte[] bytes = new byte[capacity]; byte[] bytes = new byte[capacity];
new Random().nextBytes(bytes); ThreadLocalRandom.current().nextBytes(bytes);
ByteBuffer buffer = BufferUtil.allocate(capacity); ByteBuffer buffer = BufferUtil.allocate(capacity);
BufferUtil.append(buffer, bytes, 0, capacity); BufferUtil.append(buffer, bytes, 0, capacity);
long startTest = System.nanoTime(); long startTest = System.nanoTime();
@ -294,7 +294,7 @@ public class BufferUtilTest
{ {
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] bytes = new byte[capacity]; byte[] bytes = new byte[capacity];
new Random().nextBytes(bytes); ThreadLocalRandom.current().nextBytes(bytes);
ByteBuffer buffer = BufferUtil.allocate(capacity); ByteBuffer buffer = BufferUtil.allocate(capacity);
BufferUtil.append(buffer, bytes, 0, capacity); BufferUtil.append(buffer, bytes, 0, capacity);
BufferUtil.writeTo(buffer.asReadOnlyBuffer(), out); BufferUtil.writeTo(buffer.asReadOnlyBuffer(), out);

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.util;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import java.util.List; import java.util.List;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
@ -236,51 +237,52 @@ public class ScannerTest
// Create a new file by writing to it. // Create a new file by writing to it.
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
File file = new File(_directory,"st"); File file = new File(_directory,"st");
FileOutputStream out = new FileOutputStream(file,true); try (OutputStream out = new FileOutputStream(file,true))
out.write('x'); {
out.flush(); out.write('x');
file.setLastModified(now); out.flush();
file.setLastModified(now);
// Not stable yet so no notification. // Not stable yet so no notification.
_scanner.scan(); _scanner.scan();
event = _queue.poll(); event = _queue.poll();
Assert.assertTrue(event==null); Assert.assertTrue(event==null);
// Modify size only // Modify size only
out.write('x'); out.write('x');
out.flush(); out.flush();
file.setLastModified(now); file.setLastModified(now);
// Still not stable yet so no notification. // Still not stable yet so no notification.
_scanner.scan(); _scanner.scan();
event = _queue.poll(); event = _queue.poll();
Assert.assertTrue(event==null); Assert.assertTrue(event==null);
// now stable so finally see the ADDED // now stable so finally see the ADDED
_scanner.scan(); _scanner.scan();
event = _queue.poll(); event = _queue.poll();
Assert.assertTrue(event!=null); Assert.assertTrue(event!=null);
Assert.assertEquals(_directory+"/st",event._filename); Assert.assertEquals(_directory+"/st",event._filename);
Assert.assertEquals(Notification.ADDED,event._notification); Assert.assertEquals(Notification.ADDED,event._notification);
// Modify size only // Modify size only
out.write('x'); out.write('x');
out.flush(); out.flush();
file.setLastModified(now); file.setLastModified(now);
// Still not stable yet so no notification. // Still not stable yet so no notification.
_scanner.scan(); _scanner.scan();
event = _queue.poll(); event = _queue.poll();
Assert.assertTrue(event==null); 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);
// 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 private void delete(String string) throws IOException

View File

@ -104,10 +104,11 @@ public class ResourceCollectionTest
{ {
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
String line = null; String line = null;
BufferedReader br = new BufferedReader(new InputStreamReader(r.addPath(path).getURL().openStream())); try (BufferedReader br = new BufferedReader(new InputStreamReader(r.addPath(path).getURL().openStream())))
while((line=br.readLine())!=null) {
buffer.append(line); while((line=br.readLine())!=null)
br.close(); buffer.append(line);
}
return buffer.toString(); return buffer.toString();
} }

View File

@ -65,11 +65,11 @@ public class SslContextFactoryTest
@Test @Test
public void testNoTsSetKs() throws Exception public void testNoTsSetKs() throws Exception
{ {
InputStream keystoreInputStream = this.getClass().getResourceAsStream("keystore");
KeyStore ks = KeyStore.getInstance("JKS"); 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.setKeyStore(ks);
cf.setKeyManagerPassword("keypwd"); cf.setKeyManagerPassword("keypwd");

View File

@ -94,7 +94,7 @@ public class WebAppContext extends ServletContextHandler implements WebAppClassL
private String[] __dftProtectedTargets = {"/web-inf", "/meta-inf"}; 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.WebInfConfiguration",
"org.eclipse.jetty.webapp.WebXmlConfiguration", "org.eclipse.jetty.webapp.WebXmlConfiguration",

View File

@ -25,8 +25,8 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Random;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import org.eclipse.jetty.util.B64Code; import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.MultiMap; import org.eclipse.jetty.util.MultiMap;
@ -190,7 +190,7 @@ public class ClientUpgradeRequest extends UpgradeRequest
private final String genRandomKey() private final String genRandomKey()
{ {
byte[] bytes = new byte[16]; byte[] bytes = new byte[16];
new Random().nextBytes(bytes); ThreadLocalRandom.current().nextBytes(bytes);
return new String(B64Code.encode(bytes)); return new String(B64Code.encode(bytes));
} }