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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -433,15 +433,17 @@ public class JspcMojo extends AbstractMojo
static void delete(File dir, FileFilter filter)
{
File[] files = dir.listFiles(filter);
for(int i=0; i<files.length; i++)
if (files != null)
{
for(File f: files)
{
File f = files[i];
if(f.isDirectory())
delete(f, filter);
else
f.delete();
}
}
}
/**
* Take the web fragment and put it inside a copy of the web.xml.
@ -474,10 +476,10 @@ public class JspcMojo extends AbstractMojo
}
File mergedWebXml = new File(fragmentWebXml.getParentFile(),
"web.xml");
BufferedReader webXmlReader = new BufferedReader(new FileReader(
try (BufferedReader webXmlReader = new BufferedReader(new FileReader(
webXml));
PrintWriter mergedWebXmlWriter = new PrintWriter(new FileWriter(
mergedWebXml));
mergedWebXml))) {
// read up to the insertion marker or the </webapp> if there is no
// marker
@ -501,8 +503,8 @@ public class JspcMojo extends AbstractMojo
}
// put in the generated fragment
BufferedReader fragmentWebXmlReader = new BufferedReader(
new FileReader(fragmentWebXml));
try (BufferedReader fragmentWebXmlReader = new BufferedReader(
new FileReader(fragmentWebXml))) {
IO.copy(fragmentWebXmlReader, mergedWebXmlWriter);
// if we inserted just before the </web-app>, put it back in
@ -511,10 +513,8 @@ public class JspcMojo extends AbstractMojo
// 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.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
@ -758,14 +759,15 @@ public abstract class AbstractJettyMojo extends AbstractMojo
public void setSystemPropertiesFile(File file) throws Exception
{
this.systemPropertiesFile = file;
FileInputStream propFile = new FileInputStream(systemPropertiesFile);
Properties properties = new Properties();
try (InputStream propFile = new FileInputStream(systemPropertiesFile))
{
properties.load(propFile);
}
if (this.systemProperties == null )
this.systemProperties = new SystemProperties();
for (Enumeration keys = properties.keys(); keys.hasMoreElements(); )
for (Enumeration<?> keys = properties.keys(); keys.hasMoreElements(); )
{
String key = (String)keys.nextElement();
if ( ! systemProperties.containsSystemProperty(key) )
@ -791,10 +793,8 @@ public abstract class AbstractJettyMojo extends AbstractMojo
this.systemProperties = systemProperties;
else
{
Iterator itor = systemProperties.getSystemProperties().iterator();
while (itor.hasNext())
for (SystemProperty prop: systemProperties.getSystemProperties())
{
SystemProperty prop = (SystemProperty)itor.next();
this.systemProperties.setSystemProperty(prop);
}
}

View File

@ -26,6 +26,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
@ -504,7 +505,10 @@ public class JettyRunForkedMojo extends AbstractMojo
props.put("maven.war.overlay."+(i++), c.toString());
}
props.store(new BufferedOutputStream(new FileOutputStream(propsFile)), "properties for forked webapp");
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(propsFile)))
{
props.store(out, "properties for forked webapp");
}
return propsFile;
}
catch (Exception e)
@ -723,8 +727,10 @@ public class JettyRunForkedMojo extends AbstractMojo
//child indicates it has finished starting by printing on stdout the token passed to it
try
{
LineNumberReader reader = new LineNumberReader(new InputStreamReader(forkedProcess.getInputStream()));
String line = "";
try (InputStream is = forkedProcess.getInputStream();
LineNumberReader reader = new LineNumberReader(new InputStreamReader(is)))
{
int attempts = maxStartupLines; //max lines we'll read trying to get token
while (attempts>0 && line != null)
{
@ -734,7 +740,7 @@ public class JettyRunForkedMojo extends AbstractMojo
break;
}
reader.close();
}
if (line != null && line.trim().equals(token))
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 static int DEFAULT_PORT = 8080;
public static String DEFAULT_PORT_STR = String.valueOf(DEFAULT_PORT);
public static int DEFAULT_MAX_IDLE_TIME = 30000;
public static final int DEFAULT_PORT = 8080;
public static final String DEFAULT_PORT_STR = String.valueOf(DEFAULT_PORT);
public static final int DEFAULT_MAX_IDLE_TIME = 30000;
private Server server;
private ServerConnector delegate;
@ -206,7 +206,7 @@ public class MavenServerConnector extends AbstractLifeCycle implements Connector
public ConnectionFactory getDefaultConnectionFactory()
{
checkDelegate();
return getDefaultConnectionFactory();
return this.delegate.getDefaultConnectionFactory();
}
/**

View File

@ -22,6 +22,7 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
@ -145,8 +146,9 @@ public class SelectiveJarResource extends JarResource
URL jarFileURL = new URL(urlString.substring(startOfJarUrl, endOfJarUrl));
InputStream is = jarFileURL.openConnection().getInputStream();
JarInputStream jin = new JarInputStream(is);
try (InputStream is = jarFileURL.openConnection().getInputStream();
JarInputStream jin = new JarInputStream(is))
{
JarEntry entry;
while((entry=jin.getNextJarEntry())!=null)
@ -193,16 +195,10 @@ public class SelectiveJarResource extends JarResource
dir.mkdirs();
// Make file
FileOutputStream fout = null;
try
try (OutputStream fout = new FileOutputStream(file))
{
fout = new FileOutputStream(file);
IO.copy(jin,fout);
}
finally
{
IO.close(fout);
}
// touch the file.
if (entry.getTime()>=0)
@ -224,12 +220,13 @@ public class SelectiveJarResource extends JarResource
File metaInf = new File (directory, "META-INF");
metaInf.mkdir();
File f = new File(metaInf, "MANIFEST.MF");
FileOutputStream fout = new FileOutputStream(f);
try (OutputStream fout = new FileOutputStream(f))
{
manifest.write(fout);
fout.close();
}
}
IO.close(jin);
}
}
}
}

View File

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

View File

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

View File

@ -53,7 +53,7 @@ public class BundleWatcher implements BundleTrackerCustomizer
{
private static final Logger LOG = Log.getLogger(BundleWatcher.class);
public static Collection<TldBundleDiscoverer> JSP_REGISTRATION_HELPERS = new ArrayList<TldBundleDiscoverer>();
public static final Collection<TldBundleDiscoverer> JSP_REGISTRATION_HELPERS = new ArrayList<TldBundleDiscoverer>();
public static final String FILTER = "(objectclass=" + BundleProvider.class.getName() + ")";

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
{
private Logger __logger = Log.getLogger(OSGiWebappClassLoader.class.getName().toString());
private static final Logger __logger = Log.getLogger(OSGiWebappClassLoader.class.getName());
/**
* when a logging framework is setup in the osgi classloaders, it can access
* this and register the classes that must not be found in the jar.
*/
public static Set<String> JAR_WITH_SUCH_CLASS_MUST_BE_EXCLUDED = new HashSet<String>();
public static final Set<String> JAR_WITH_SUCH_CLASS_MUST_BE_EXCLUDED = new HashSet<String>();
public static void addClassThatIdentifiesAJarThatMustBeRejected(Class<?> zclass)
{

View File

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

View File

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

View File

@ -19,6 +19,7 @@
package org.eclipse.jetty.security;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@ -116,8 +117,10 @@ public class JDBCLoginService extends MappedLoginService
{
Properties properties = new Properties();
Resource resource = Resource.newResource(_config);
properties.load(resource.getInputStream());
try (InputStream in = resource.getInputStream())
{
properties.load(in);
}
_jdbcDriver = properties.getProperty("jdbcdriver");
_url = properties.getProperty("url");
_userName = properties.getProperty("username");
@ -238,27 +241,31 @@ public class JDBCLoginService extends MappedLoginService
if (null == _con)
throw new SQLException("Can't connect to database");
PreparedStatement stat = _con.prepareStatement(_userSql);
stat.setObject(1, username);
ResultSet rs = stat.executeQuery();
if (rs.next())
try (PreparedStatement stat1 = _con.prepareStatement(_userSql))
{
int key = rs.getInt(_userTableKey);
String credentials = rs.getString(_userTablePasswordField);
stat.close();
stat = _con.prepareStatement(_roleSql);
stat.setInt(1, key);
rs = stat.executeQuery();
stat1.setObject(1, username);
try (ResultSet rs1 = stat1.executeQuery())
{
if (rs1.next())
{
int key = rs1.getInt(_userTableKey);
String credentials = rs1.getString(_userTablePasswordField);
List<String> roles = new ArrayList<String>();
while (rs.next())
roles.add(rs.getString(_roleTableRoleField));
stat.close();
try (PreparedStatement stat2 = _con.prepareStatement(_roleSql))
{
stat2.setInt(1, key);
try (ResultSet rs2 = stat2.executeQuery())
{
while (rs2.next())
roles.add(rs2.getString(_roleTableRoleField));
}
}
return putUser(username, Credential.getCredential(credentials),roles.toArray(new String[roles.size()]));
}
}
}
}
catch (SQLException e)
{
LOG.warn("UserRealm " + getName() + " could not load user information from database", 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()
{
@ -674,7 +674,7 @@ public abstract class SecurityHandler extends HandlerWrapper implements Authenti
* FormAuthenticator to allow access to logon and error pages within an
* authenticated URI tree.
*/
public static Principal __NOBODY = new Principal()
public static final Principal __NOBODY = new Principal()
{
public String getName()
{

View File

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

View File

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

View File

@ -423,10 +423,13 @@ public class Response implements HttpServletResponse
writer.flush();
setContentLength(writer.size());
writer.writeTo(getOutputStream());
try (ServletOutputStream outputStream = getOutputStream())
{
writer.writeTo(outputStream);
writer.destroy();
}
}
}
else if (code!=SC_PARTIAL_CONTENT)
{
// TODO work out why this is required?

View File

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

View File

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

View File

@ -623,11 +623,10 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
_deleteId = "delete from "+_sessionIdTable+" where id = ?";
_queryId = "select * from "+_sessionIdTable+" where id = ?";
Connection connection = null;
try
try (Connection connection = getConnection();
Statement statement = connection.createStatement())
{
//make the id table
connection = getConnection();
connection.setAutoCommit(true);
DatabaseMetaData metaData = connection.getMetaData();
_dbAdaptor = new DatabaseAdaptor(metaData);
@ -635,16 +634,18 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
//checking for table existence is case-sensitive, but table creation is not
String tableName = _dbAdaptor.convertIdentifier(_sessionIdTable);
ResultSet result = metaData.getTables(null, null, tableName, null);
try (ResultSet result = metaData.getTables(null, null, tableName, null))
{
if (!result.next())
{
//table does not exist, so create it
connection.createStatement().executeUpdate(_createSessionIdTable);
statement.executeUpdate(_createSessionIdTable);
}
}
//make the session table if necessary
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
@ -654,7 +655,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
" 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);
statement.executeUpdate(_createSessionTable);
}
else
{
@ -669,14 +670,15 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
LOG.warn("Problem checking if "+_sessionTable+" table contains maxInterval column. Ensure table contains column definition: \"maxInterval long not null default -999\"");
throw s;
}
try
{
if (!colResult.next())
{
try
{
//add the maxinterval column
String longType = _dbAdaptor.getLongType();
connection.createStatement().executeUpdate("alter table "+_sessionTable+" add maxInterval "+longType+" not null default "+MAX_INTERVAL_NOT_SET);
statement.executeUpdate("alter table "+_sessionTable+" add maxInterval "+longType+" not null default "+MAX_INTERVAL_NOT_SET);
}
catch (SQLException s)
{
@ -685,14 +687,20 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
}
}
}
finally
{
colResult.close();
}
}
}
//make some indexes on the JettySessions table
String index1 = "idx_"+_sessionTable+"_expiry";
String index2 = "idx_"+_sessionTable+"_session";
result = metaData.getIndexInfo(null, null, tableName, false, false);
boolean index1Exists = false;
boolean index2Exists = false;
try (ResultSet result = metaData.getIndexInfo(null, null, tableName, false, false))
{
while (result.next())
{
String idxName = result.getString("INDEX_NAME");
@ -701,14 +709,11 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
else if (index2.equalsIgnoreCase(idxName))
index2Exists = true;
}
if (!(index1Exists && index2Exists))
{
Statement statement = connection.createStatement();
}
if (!index1Exists)
statement.executeUpdate("create index "+index1+" on "+_sessionTable+" (expiryTime)");
if (!index2Exists)
statement.executeUpdate("create index "+index2+" on "+_sessionTable+" (sessionId, contextPath)");
}
//set up some strings representing the statements for session manipulation
_insertSession = "insert into "+_sessionTable+
@ -729,11 +734,6 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
}
finally
{
if (connection != null)
connection.close();
}
}
/**
@ -745,26 +745,23 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
private void insert (String id)
throws SQLException
{
Connection connection = null;
try
try (Connection connection = getConnection();
PreparedStatement query = connection.prepareStatement(_queryId))
{
connection = getConnection();
connection.setAutoCommit(true);
PreparedStatement query = connection.prepareStatement(_queryId);
query.setString(1, id);
ResultSet result = query.executeQuery();
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);
try (PreparedStatement statement = connection.prepareStatement(_insertId))
{
statement.setString(1, id);
statement.executeUpdate();
}
}
finally
{
if (connection != null)
connection.close();
}
}
}
@ -777,20 +774,13 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
private void delete (String id)
throws SQLException
{
Connection connection = null;
try
try (Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement(_deleteId))
{
connection = getConnection();
connection.setAutoCommit(true);
PreparedStatement statement = connection.prepareStatement(_deleteId);
statement.setString(1, id);
statement.executeUpdate();
}
finally
{
if (connection != null)
connection.close();
}
}
@ -804,20 +794,15 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
private boolean exists (String id)
throws SQLException
{
Connection connection = null;
try
try (Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement(_queryId))
{
connection = getConnection();
connection.setAutoCommit(true);
PreparedStatement statement = connection.prepareStatement(_queryId);
statement.setString(1, id);
ResultSet result = statement.executeQuery();
try (ResultSet result = statement.executeQuery())
{
return result.next();
}
finally
{
if (connection != null)
connection.close();
}
}
@ -835,7 +820,6 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
private void scavenge ()
{
Connection connection = null;
Set<String> expiredSessionIds = new HashSet<String>();
try
{
if (LOG.isDebugEnabled())
@ -844,38 +828,44 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
{
connection = getConnection();
connection.setAutoCommit(true);
Set<String> expiredSessionIds = new HashSet<String>();
//Pass 1: find sessions for which we were last managing node that have just expired since last pass
PreparedStatement statement = connection.prepareStatement(_selectBoundedExpiredSessions);
long lowerBound = (_lastScavengeTime - _scavengeIntervalMs);
long upperBound = _lastScavengeTime;
if (LOG.isDebugEnabled())
LOG.debug (getWorkerName()+"- Pass 1: Searching for sessions expired between "+lowerBound + " and "+upperBound);
try (PreparedStatement statement = connection.prepareStatement(_selectBoundedExpiredSessions))
{
statement.setString(1, getWorkerName());
statement.setLong(2, lowerBound);
statement.setLong(3, upperBound);
ResultSet result = statement.executeQuery();
try (ResultSet result = statement.executeQuery())
{
while (result.next())
{
String sessionId = result.getString("sessionId");
expiredSessionIds.add(sessionId);
if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId);
}
result.close();
}
}
scavengeSessions(expiredSessionIds, false);
//Pass 2: find sessions that have expired a while ago for which this node was their last manager
PreparedStatement selectExpiredSessions = connection.prepareStatement(_selectExpiredSessions);
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();
try (ResultSet result = selectExpiredSessions.executeQuery())
{
while (result.next())
{
String sessionId = result.getString("sessionId");
@ -884,7 +874,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
expiredSessionIds.add(sessionId);
if (LOG.isDebugEnabled()) LOG.debug ("Found expired sessionId="+sessionId+" last managed by "+getWorkerName());
}
result.close();
}
scavengeSessions(expiredSessionIds, false);
}
@ -899,18 +889,20 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
{
if (LOG.isDebugEnabled()) LOG.debug(getWorkerName()+"- Pass 3: searching for sessions expired before "+upperBound);
selectExpiredSessions.setLong(1, upperBound);
result = selectExpiredSessions.executeQuery();
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);
}
result.close();
}
scavengeSessions(expiredSessionIds, true);
}
}
}
}
catch (Exception e)
{
if (isRunning())
@ -990,10 +982,8 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
return;
String[] ids = expiredIds.toArray(new String[expiredIds.size()]);
Connection con = null;
try
try (Connection con = getConnection())
{
con = getConnection();
con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
con.setAutoCommit(false);
@ -1002,6 +992,8 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
int blocksize = _deleteBlockSize;
int block = 0;
try (Statement statement = con.createStatement())
{
while (end < ids.length)
{
start = block*blocksize;
@ -1010,30 +1002,19 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
else
end = ids.length;
Statement statement = con.createStatement();
//take them out of the sessionIds table
statement.executeUpdate(fillInClause("delete from "+_sessionIdTable+" where id in ", ids, start, end));
//take them out of the sessions table
statement.executeUpdate(fillInClause("delete from "+_sessionTable+" where sessionId in ", ids, start, end));
block++;
}
con.commit();
}
catch (Exception e)
{
if (con != null)
{
con.rollback();
throw e;
}
}
finally
{
if (con != null)
{
con.close();
}
con.commit();
}
}

View File

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

View File

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

View File

@ -988,11 +988,13 @@ public class RequestTest
if (evil_keys.exists())
{
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)
buf.append("&").append(key).append("=").append("x");
}
}
else
{
// we will just create a lot of keys and make sure the limit is applied

View File

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

View File

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

View File

@ -75,7 +75,10 @@ public class SSLSelectChannelConnectorLoadTest
server.start();
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(new FileInputStream(keystorePath), "storepwd".toCharArray());
try (InputStream stream = new FileInputStream(keystorePath))
{
keystore.load(stream, "storepwd".toCharArray());
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
sslContext = SSLContext.getInstance("SSL");

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.server.ssl;
import static org.junit.Assert.assertEquals;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
@ -111,7 +112,10 @@ public class SelectChannelServerSslTest extends HttpServerTestBase
startServer(connector);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(new FileInputStream(sslContextFactory.getKeyStorePath()), "storepwd".toCharArray());
try (InputStream stream = new FileInputStream(sslContextFactory.getKeyStorePath()))
{
keystore.load(stream, "storepwd".toCharArray());
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
__sslContext = SSLContext.getInstance("TLS");

View File

@ -19,6 +19,7 @@
package org.eclipse.jetty.server.ssl;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.Socket;
import java.security.KeyStore;
@ -55,7 +56,10 @@ public class SslSelectChannelTimeoutTest extends ConnectorTimeoutTest
startServer(connector);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(new FileInputStream(keystorePath), "storepwd".toCharArray());
try (InputStream stream = new FileInputStream(keystorePath))
{
keystore.load(stream, "storepwd".toCharArray());
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
__sslContext = SSLContext.getInstance("SSL");

View File

@ -88,7 +88,10 @@ public class SslUploadTest
{
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
SslContextFactory ctx=connector.getConnectionFactory(SslConnectionFactory.class).getSslContextFactory();
keystore.load(new FileInputStream(ctx.getKeyStorePath()), "storepwd".toCharArray());
try (InputStream stream = new FileInputStream(ctx.getKeyStorePath()))
{
keystore.load(stream, "storepwd".toCharArray());
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
SSLContext sslContext = SSLContext.getInstance("SSL");

View File

@ -664,7 +664,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
while (!match && quoted.hasMoreTokens())
{
String tag = quoted.nextToken();
if (content.getETag().toString().equals(tag))
if (content.getETag().equals(tag))
match=true;
}
}
@ -680,7 +680,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
if (if_non_match_etag!=null && content.getETag()!=null)
{
// Look for GzipFiltered version of etag
if (content.getETag().toString().equals(request.getAttribute("o.e.j.s.GzipFilter.ETag")))
if (content.getETag().equals(request.getAttribute("o.e.j.s.GzipFilter.ETag")))
{
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader(HttpHeader.ETAG.asString(),if_non_match_etag);
@ -688,7 +688,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
// Handle special case of exact match.
if (content.getETag().toString().equals(if_non_match_etag))
if (content.getETag().equals(if_non_match_etag))
{
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
@ -700,7 +700,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
while (quoted.hasMoreTokens())
{
String tag = quoted.nextToken();
if (content.getETag().toString().equals(tag))
if (content.getETag().equals(tag))
{
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
@ -923,7 +923,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
// content-length header
//
writeHeaders(response,content,-1);
String mimetype=(content==null||content.getContentType()==null?null:content.getContentType().toString());
String mimetype=(content==null?null:content.getContentType());
if (mimetype==null)
LOG.warn("Unknown mimetype for "+request.getRequestURI());
MultiPartOutputStream multi = new MultiPartOutputStream(out);
@ -1041,7 +1041,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
writeOptionHeaders(response);
if (_etags)
response.setHeader(HttpHeader.ETAG.asString(),content.getETag().toString());
response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
}
}

View File

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

View File

@ -219,24 +219,26 @@ public class PutFilter implements Filter
if (_putAtomic)
{
File tmp=File.createTempFile(file.getName(),null,_tmpdir);
OutputStream out = new FileOutputStream(tmp,false);
try (OutputStream out = new FileOutputStream(tmp,false))
{
if (toRead >= 0)
IO.copy(in, out, toRead);
else
IO.copy(in, out);
out.close();
}
if (!tmp.renameTo(file))
throw new IOException("rename from "+tmp+" to "+file+" failed");
}
else
{
OutputStream out = new FileOutputStream(file,false);
try (OutputStream out = new FileOutputStream(file,false))
{
if (toRead >= 0)
IO.copy(in, out, toRead);
else
IO.copy(in, out);
out.close();
}
}
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.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
@ -95,10 +96,11 @@ public class IncludableGzipFilterTest
testdir.ensureEmpty();
File testFile = testdir.getFile("file.txt");
BufferedOutputStream testOut = new BufferedOutputStream(new FileOutputStream(testFile));
try (OutputStream testOut = new BufferedOutputStream(new FileOutputStream(testFile)))
{
ByteArrayInputStream testIn = new ByteArrayInputStream(__content.getBytes("ISO8859_1"));
IO.copy(testIn,testOut);
testOut.close();
}
tester=new ServletTester("/context");
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.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
@ -193,9 +194,10 @@ public class PutFilterTest
File file=new File(_dir,"file.txt");
assertTrue(file.exists());
FileInputStream fis = new FileInputStream(file);
try (InputStream fis = new FileInputStream(file))
{
assertEquals(data1,IO.toString(fis));
fis.close();
}
request.setMethod("DELETE");
request.setURI("/context/file.txt");
@ -231,9 +233,10 @@ public class PutFilterTest
File file=new File(_dir,"file.txt");
assertTrue(file.exists());
FileInputStream fis = new FileInputStream(file);
try (InputStream fis = new FileInputStream(file))
{
assertEquals(data1,IO.toString(fis));
fis.close();
}
request.setMethod("MOVE");
request.setURI("/context/file.txt");

View File

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

View File

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

View File

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

View File

@ -742,7 +742,10 @@ public class Main
File prop_file = File.createTempFile("start",".properties");
if (!_dryRun)
prop_file.deleteOnExit();
properties.store(new FileOutputStream(prop_file),"start.jar properties");
try (OutputStream out = new FileOutputStream(prop_file))
{
properties.store(out,"start.jar properties");
}
cmd.addArg(prop_file.getAbsolutePath());
}

View File

@ -46,9 +46,9 @@ import java.util.TimerTask;
public class DateCache
{
public static String DEFAULT_FORMAT="EEE MMM dd HH:mm:ss zzz yyyy";
public static final String DEFAULT_FORMAT="EEE MMM dd HH:mm:ss zzz yyyy";
private String _formatString;
private final String _formatString;
private String _tzFormatString;
private SimpleDateFormat _tzFormat;

View File

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

View File

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

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',
'\010','\011','\012','\013','\014','\015','\016','\017',
'\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);
public static final Class<?>[] NO_ARGS = new Class[]{};
public static int CR = '\015';
public static int LF = '\012';
public static final int CR = '\015';
public static final int LF = '\012';
/* ------------------------------------------------------------ */
private static final HashMap<String, Class<?>> name2Class=new HashMap<>();

View File

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

View File

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

View File

@ -23,6 +23,7 @@ import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.jar.JarEntry;
@ -153,8 +154,9 @@ public class JarResource extends URLResource
if (LOG.isDebugEnabled())
LOG.debug("Extracting entry = "+subEntryName+" from jar "+jarFileURL);
InputStream is = jarFileURL.openConnection().getInputStream();
JarInputStream jin = new JarInputStream(is);
try (InputStream is = jarFileURL.openConnection().getInputStream();
JarInputStream jin = new JarInputStream(is))
{
JarEntry entry;
boolean shouldExtract;
while((entry=jin.getNextJarEntry())!=null)
@ -198,7 +200,6 @@ public class JarResource extends URLResource
shouldExtract = true;
}
if (!shouldExtract)
{
if (LOG.isDebugEnabled())
@ -231,16 +232,10 @@ public class JarResource extends URLResource
dir.mkdirs();
// Make file
FileOutputStream fout = null;
try
try (OutputStream fout = new FileOutputStream(file))
{
fout = new FileOutputStream(file);
IO.copy(jin,fout);
}
finally
{
IO.close(fout);
}
// touch the file.
if (entry.getTime()>=0)
@ -256,12 +251,13 @@ public class JarResource extends URLResource
File metaInf = new File (directory, "META-INF");
metaInf.mkdir();
File f = new File(metaInf, "MANIFEST.MF");
FileOutputStream fout = new FileOutputStream(f);
try (OutputStream fout = new FileOutputStream(f))
{
manifest.write(fout);
fout.close();
}
}
IO.close(jin);
}
}
}
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)
throws IOException
{
InputStream in = getInputStream();
try
try (InputStream in = getInputStream())
{
in.skip(start);
if (count<0)
@ -624,10 +623,6 @@ public abstract class Resource implements ResourceFactory, Closeable
else
IO.copy(in,out,count);
}
finally
{
in.close();
}
}
/* ------------------------------------------------------------ */
@ -636,7 +631,10 @@ public abstract class Resource implements ResourceFactory, Closeable
{
if (destination.exists())
throw new IllegalArgumentException(destination+" exists");
writeTo(new FileOutputStream(destination),0,-1);
try (OutputStream out = new FileOutputStream(destination))
{
writeTo(out,0,-1);
}
}
/* ------------------------------------------------------------ */

View File

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

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
@ -236,7 +237,8 @@ public class ScannerTest
// Create a new file by writing to it.
long now = System.currentTimeMillis();
File file = new File(_directory,"st");
FileOutputStream out = new FileOutputStream(file,true);
try (OutputStream out = new FileOutputStream(file,true))
{
out.write('x');
out.flush();
file.setLastModified(now);
@ -280,7 +282,7 @@ public class ScannerTest
Assert.assertTrue(event!=null);
Assert.assertEquals(_directory+"/st",event._filename);
Assert.assertEquals(Notification.CHANGED,event._notification);
}
}
private void delete(String string) throws IOException

View File

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

View File

@ -65,11 +65,11 @@ public class SslContextFactoryTest
@Test
public void testNoTsSetKs() throws Exception
{
InputStream keystoreInputStream = this.getClass().getResourceAsStream("keystore");
KeyStore ks = KeyStore.getInstance("JKS");
try (InputStream keystoreInputStream = this.getClass().getResourceAsStream("keystore"))
{
ks.load(keystoreInputStream, "storepwd".toCharArray());
}
cf.setKeyStore(ks);
cf.setKeyManagerPassword("keypwd");

View File

@ -94,7 +94,7 @@ public class WebAppContext extends ServletContextHandler implements WebAppClassL
private String[] __dftProtectedTargets = {"/web-inf", "/meta-inf"};
public static String[] DEFAULT_CONFIGURATION_CLASSES =
public static final String[] DEFAULT_CONFIGURATION_CLASSES =
{
"org.eclipse.jetty.webapp.WebInfConfiguration",
"org.eclipse.jetty.webapp.WebXmlConfiguration",

View File

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