diff --git a/pom.xml b/pom.xml index 14f015e0..c326cd9f 100644 --- a/pom.xml +++ b/pom.xml @@ -16,14 +16,6 @@ Winstone is a command line wrapper around Jetty https://github.com/jenkinsci/${project.artifactId} - - 6.20 - -SNAPSHOT - 10.0.20 - 2.0.13 - jenkinsci/winstone - - GNU Lesser General Public License version 2.1 @@ -35,6 +27,161 @@ + + scm:git:https://github.com/${gitHubRepo}.git + scm:git:git@github.com:${gitHubRepo}.git + ${scmTag} + https://github.com/${gitHubRepo} + + + + 6.20 + -SNAPSHOT + 10.0.20 + 2.0.13 + jenkinsci/winstone + true + + + + + + org.eclipse.jetty + jetty-bom + ${jetty.version} + pom + import + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-jdk14 + ${slf4j.version} + + + + + + + com.github.spotbugs + spotbugs-annotations + true + + + com.google.code.findbugs + jsr305 + + + + + io.jenkins.lib + support-log-formatter + 1.2 + + + org.eclipse.jetty + jetty-alpn-java-server + + + org.eclipse.jetty + jetty-alpn-server + + + org.eclipse.jetty + jetty-jmx + + + org.eclipse.jetty + jetty-server + + + org.eclipse.jetty + jetty-servlet + + + org.eclipse.jetty + jetty-unixdomain-server + + + org.eclipse.jetty + jetty-util + + + org.eclipse.jetty + jetty-webapp + + + org.eclipse.jetty.http2 + http2-hpack + + + org.eclipse.jetty.http2 + http2-server + + + org.eclipse.jetty.websocket + websocket-jetty-server + + + + + org.eclipse.jetty + jetty-annotations + + + + + org.slf4j + slf4j-jdk14 + + + org.awaitility + awaitility + 4.2.1 + test + + + org.eclipse.jetty + jetty-client + test + + + org.jenkins-ci + test-annotations + 1.4 + test + + + org.junit.jupiter + junit-jupiter + test + + + org.junit.vintage + junit-vintage-engine + test + + + + + + repo.jenkins-ci.org + https://repo.jenkins-ci.org/public/ + + + + + + repo.jenkins-ci.org + https://repo.jenkins-ci.org/public/ + + + @@ -43,10 +190,10 @@ prepare-testwebapp - process-test-classes run + process-test-classes @@ -70,10 +217,10 @@ false alphabetical - - - - + + + + @@ -143,10 +290,10 @@ - package shade + package true @@ -172,161 +319,17 @@ flatten - pre-integration-test + flatten + pre-integration-test - - - repo.jenkins-ci.org - https://repo.jenkins-ci.org/public/ - - - - - - repo.jenkins-ci.org - https://repo.jenkins-ci.org/public/ - - - - - scm:git:https://github.com/${gitHubRepo}.git - scm:git:git@github.com:${gitHubRepo}.git - https://github.com/${gitHubRepo} - ${scmTag} - - - - - - org.eclipse.jetty - jetty-bom - ${jetty.version} - pom - import - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - slf4j-jdk14 - ${slf4j.version} - - - - - - - com.github.spotbugs - spotbugs-annotations - true - - - com.google.code.findbugs - jsr305 - - - - - io.jenkins.lib - support-log-formatter - 1.2 - - - org.eclipse.jetty - jetty-alpn-java-server - - - org.eclipse.jetty - jetty-alpn-server - - - org.eclipse.jetty - jetty-jmx - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-servlet - - - org.eclipse.jetty - jetty-unixdomain-server - - - org.eclipse.jetty - jetty-util - - - org.eclipse.jetty - jetty-webapp - - - org.eclipse.jetty.http2 - http2-hpack - - - org.eclipse.jetty.http2 - http2-server - - - org.eclipse.jetty.websocket - websocket-jetty-server - - - - org.eclipse.jetty - jetty-annotations - - - - - org.slf4j - slf4j-jdk14 - - - org.awaitility - awaitility - 4.2.1 - test - - - org.jenkins-ci - test-annotations - 1.4 - test - - - org.junit.jupiter - junit-jupiter - test - - - org.junit.vintage - junit-vintage-engine - test - - - org.eclipse.jetty - jetty-client - test - - - enable-jacoco diff --git a/src/main/java/winstone/AbstractSecuredConnectorFactory.java b/src/main/java/winstone/AbstractSecuredConnectorFactory.java index 08fea469..a887861d 100644 --- a/src/main/java/winstone/AbstractSecuredConnectorFactory.java +++ b/src/main/java/winstone/AbstractSecuredConnectorFactory.java @@ -7,12 +7,6 @@ package winstone; -import java.util.Locale; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import winstone.cmdline.Option; - -import javax.net.ssl.KeyManagerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -22,36 +16,39 @@ import java.text.MessageFormat; import java.util.Arrays; import java.util.Enumeration; +import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.stream.Stream; +import javax.net.ssl.KeyManagerFactory; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import winstone.cmdline.Option; /** * */ -public abstract class AbstractSecuredConnectorFactory implements ConnectorFactory -{ +public abstract class AbstractSecuredConnectorFactory implements ConnectorFactory { protected static final WinstoneResourceBundle SSL_RESOURCES = new WinstoneResourceBundle("winstone.LocalStrings"); protected KeyStore keystore; protected String keystorePassword; - protected void configureSsl( Map args, Server server ) throws IOException - { + protected void configureSsl(Map args, Server server) throws IOException { try { - File keyStore = Option.HTTPS_KEY_STORE.get(args); - String pwd = Option.HTTPS_KEY_STORE_PASSWORD.get(args); + File keyStore = Option.HTTPS_KEY_STORE.get(args); + String pwd = Option.HTTPS_KEY_STORE_PASSWORD.get(args); - if (keyStore!=null) { + if (keyStore != null) { // load from default Keystore if (!keyStore.exists() || !keyStore.isFile()) - throw new WinstoneException(SSL_RESOURCES.getString( - "HttpsListener.KeyStoreNotFound", keyStore.getPath())); + throw new WinstoneException( + SSL_RESOURCES.getString("HttpsListener.KeyStoreNotFound", keyStore.getPath())); this.keystorePassword = pwd; keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - try(InputStream inputStream = new FileInputStream(keyStore)){ - keystore.load( inputStream, this.keystorePassword.toCharArray()); + try (InputStream inputStream = new FileInputStream(keyStore)) { + keystore.load(inputStream, this.keystorePassword.toCharArray()); } } else { throw new WinstoneException(MessageFormat.format("Please set --{0}", Option.HTTPS_KEY_STORE)); @@ -65,7 +62,7 @@ protected void configureSsl( Map args, Server server ) throws IO * Used to get the base ssl context in which to create the server socket. * This is basically just so we can have a custom location for key stores. */ - protected SslContextFactory.Server getSSLContext( Map args) { + protected SslContextFactory.Server getSSLContext(Map args) { try { String privateKeyPassword; @@ -82,18 +79,20 @@ protected SslContextFactory.Server getSSLContext( Map args) { // Dump the content of the keystore if log level is FULL_DEBUG // Note: The kmf is instantiated here only to access the keystore, // the SslContextFactory will instantiate its own KeyManager - KeyManagerFactory kmf = KeyManagerFactory.getInstance( Option.HTTPS_KEY_MANAGER_TYPE.get( args)); + KeyManagerFactory kmf = KeyManagerFactory.getInstance(Option.HTTPS_KEY_MANAGER_TYPE.get(args)); // In case the KeyStore password and the KeyPassword are not the same, // the KeyManagerFactory needs the KeyPassword because it will access the individual key(s) kmf.init(keystore, keystorePassword.toCharArray()); - Logger.log(Level.FINEST, SSL_RESOURCES, - "HttpsListener.KeyCount", keystore.size() + ""); - for ( Enumeration e = keystore.aliases(); e.hasMoreElements();) { + Logger.log(Level.FINEST, SSL_RESOURCES, "HttpsListener.KeyCount", keystore.size() + ""); + for (Enumeration e = keystore.aliases(); e.hasMoreElements(); ) { String alias = e.nextElement(); - Logger.log(Level.FINEST, SSL_RESOURCES, - "HttpsListener.KeyFound", alias, - keystore.getCertificate(alias) + ""); + Logger.log( + Level.FINEST, + SSL_RESOURCES, + "HttpsListener.KeyFound", + alias, + keystore.getCertificate(alias) + ""); } SslContextFactory.Server ssl = new SslContextFactory.Server(); @@ -103,21 +102,26 @@ protected SslContextFactory.Server getSSLContext( Map args) { ssl.setKeyManagerFactoryAlgorithm(Option.HTTPS_KEY_MANAGER_TYPE.get(args)); ssl.setCertAlias(Option.HTTPS_CERTIFICATE_ALIAS.get(args)); String excludeProtos = Option.HTTPS_EXCLUDE_PROTOCOLS.get(args); - if(excludeProtos!=null&&excludeProtos.length()>0) { - String[] protos = Stream.of(excludeProtos.split(",")).map(String::trim).toArray(String[]::new); + if (excludeProtos != null && excludeProtos.length() > 0) { + String[] protos = + Stream.of(excludeProtos.split(",")).map(String::trim).toArray(String[]::new); ssl.setExcludeProtocols(protos); } String excludeCiphers = Option.HTTPS_EXCLUDE_CIPHER_SUITES.get(args); - if(excludeCiphers!=null&&excludeCiphers.length()>0) { + if (excludeCiphers != null && excludeCiphers.length() > 0) { String[] cipherSuites = excludeCiphers.split(","); ssl.setExcludeCipherSuites(cipherSuites); } - Logger.log(Level.INFO, SSL_RESOURCES, // - "HttpsListener.ExcludeProtocols", // - Arrays.asList(ssl.getExcludeProtocols())); - Logger.log(Level.INFO, SSL_RESOURCES, // - "HttpsListener.ExcludeCiphers", // - Arrays.asList(ssl.getExcludeCipherSuites())); + Logger.log( + Level.INFO, + SSL_RESOURCES, // + "HttpsListener.ExcludeProtocols", // + Arrays.asList(ssl.getExcludeProtocols())); + Logger.log( + Level.INFO, + SSL_RESOURCES, // + "HttpsListener.ExcludeCiphers", // + Arrays.asList(ssl.getExcludeCipherSuites())); switch (Option.HTTPS_VERIFY_CLIENT.get(args).toLowerCase(Locale.ROOT)) { case "yes": @@ -128,14 +132,12 @@ protected SslContextFactory.Server getSSLContext( Map args) { ssl.setWantClientAuth(true); break; default: - ssl.setNeedClientAuth(false); - break; + ssl.setNeedClientAuth(false); + break; } return ssl; } catch (Throwable err) { - throw new WinstoneException(SSL_RESOURCES - .getString("HttpsListener.ErrorGettingContext"), err); + throw new WinstoneException(SSL_RESOURCES.getString("HttpsListener.ErrorGettingContext"), err); } } - } diff --git a/src/main/java/winstone/ConnectorFactory.java b/src/main/java/winstone/ConnectorFactory.java index f47bd961..3f16b321 100644 --- a/src/main/java/winstone/ConnectorFactory.java +++ b/src/main/java/winstone/ConnectorFactory.java @@ -6,16 +6,15 @@ */ package winstone; -import org.eclipse.jetty.server.Connector; -import org.eclipse.jetty.server.Server; - import java.io.IOException; import java.util.Map; +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.Server; /** * Interface that defines the necessary methods for being a connection listener * within winstone. - * + * * @author Rick Knowles */ public interface ConnectorFactory { @@ -23,6 +22,5 @@ public interface ConnectorFactory { * After the listener is loaded and initialized, this starts the thread * @return the Connector instance or null if not started */ - Connector start( Map args, Server server) throws IOException; - + Connector start(Map args, Server server) throws IOException; } diff --git a/src/main/java/winstone/HostConfiguration.java b/src/main/java/winstone/HostConfiguration.java index ddb185f1..9cc6a596 100644 --- a/src/main/java/winstone/HostConfiguration.java +++ b/src/main/java/winstone/HostConfiguration.java @@ -8,17 +8,6 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.eclipse.jetty.http.MimeTypes; -import org.eclipse.jetty.security.LoginService; -import org.eclipse.jetty.server.Handler; -import org.eclipse.jetty.server.RequestLog; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.RequestLogHandler; -import org.eclipse.jetty.webapp.WebAppContext; -import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer; -import winstone.cmdline.Option; - -import javax.servlet.SessionTrackingMode; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -40,6 +29,16 @@ import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.logging.Level; +import javax.servlet.SessionTrackingMode; +import org.eclipse.jetty.http.MimeTypes; +import org.eclipse.jetty.security.LoginService; +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.RequestLog; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.handler.RequestLogHandler; +import org.eclipse.jetty.webapp.WebAppContext; +import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer; +import winstone.cmdline.Option; /** * Manages the references to individual webapps within the container. This object handles @@ -52,7 +51,7 @@ public class HostConfiguration { private final Server server; private String hostname; private Map args; - private Map webapps; + private Map webapps; private ClassLoader commonLibCL; private MimeTypes mimeTypes = new MimeTypes(); private final LoginService loginService; @@ -67,7 +66,8 @@ public HostConfiguration(Server server, String hostname, ClassLoader commonLibCL try { // Build the realm - Class realmClass = Option.REALM_CLASS_NAME.get(this.args, LoginService.class, commonLibCL); + Class realmClass = + Option.REALM_CLASS_NAME.get(this.args, LoginService.class, commonLibCL); Constructor realmConstr = realmClass.getConstructor(Map.class); loginService = realmConstr.newInstance(this.args); } catch (Throwable err) { @@ -85,16 +85,15 @@ public HostConfiguration(Server server, String hostname, ClassLoader commonLibCL } Handler handler = configureAccessLog(create(getWebRoot(webroot, warfile), prefix), "webapp"); - {// load additional mime types + { // load additional mime types loadBuiltinMimeTypes(); String types = Option.MIME_TYPES.get(this.args); - if (types!=null) { + if (types != null) { StringTokenizer mappingST = new StringTokenizer(types, ":", false); while (mappingST.hasMoreTokens()) { String mapping = mappingST.nextToken(); int delimPos = mapping.indexOf('='); - if (delimPos == -1) - continue; + if (delimPos == -1) continue; String extension = mapping.substring(0, delimPos); String mimeType = mapping.substring(delimPos + 1); this.mimeTypes.addMimeMapping(extension.toLowerCase(), mimeType); @@ -103,8 +102,12 @@ public HostConfiguration(Server server, String hostname, ClassLoader commonLibCL } server.setHandler(handler); - Logger.log(Level.FINER, Launcher.RESOURCES, "HostConfig.InitComplete", - this.webapps.size() + "", this.webapps.keySet() + ""); + Logger.log( + Level.FINER, + Launcher.RESOURCES, + "HostConfig.InitComplete", + this.webapps.size() + "", + this.webapps.keySet() + ""); } private void loadBuiltinMimeTypes() { @@ -112,22 +115,22 @@ private void loadBuiltinMimeTypes() { Properties props = new Properties(); props.load(in); for (Entry e : props.entrySet()) { - mimeTypes.addMimeMapping(e.getKey().toString(),e.getValue().toString()); + mimeTypes.addMimeMapping(e.getKey().toString(), e.getValue().toString()); } } catch (IOException e) { throw new UncheckedIOException("Failed to load the built-in MIME types", e); } } - /** * @param webAppName * Unique name given to the access logger. */ private Handler configureAccessLog(Handler handler, String webAppName) { try { - Class loggerClass = Option.ACCESS_LOGGER_CLASSNAME.get(args, RequestLog.class, commonLibCL); - if (loggerClass!=null) { + Class loggerClass = + Option.ACCESS_LOGGER_CLASSNAME.get(args, RequestLog.class, commonLibCL); + if (loggerClass != null) { // Build the realm Constructor loggerConstr = loggerClass.getConstructor(String.class, Map.class); RequestLogHandler rlh = new RequestLogHandler(); @@ -138,14 +141,13 @@ private Handler configureAccessLog(Handler handler, String webAppName) { Logger.log(Level.FINER, Launcher.RESOURCES, "WebAppConfig.LoggerDisabled"); } } catch (Throwable err) { - Logger.log(Level.SEVERE, Launcher.RESOURCES, - "WebAppConfig.LoggerError", "", err); + Logger.log(Level.SEVERE, Launcher.RESOURCES, "WebAppConfig.LoggerError", "", err); } return handler; } private WebAppContext create(File app, String prefix) { - WebAppContext wac = new WebAppContext(app.getAbsolutePath(),prefix) { + WebAppContext wac = new WebAppContext(app.getAbsolutePath(), prefix) { @Override public void preConfigure() throws Exception { // to have WebAppClassLoader inherit from commonLibCL, @@ -171,20 +173,21 @@ public void postConfigure() throws Exception { // if specified, override the value in web.xml int sessionTimeout = Option.SESSION_TIMEOUT.get(args); - if (sessionTimeout>0) { + if (sessionTimeout > 0) { getSessionHandler().setMaxInactiveInterval(sessionTimeout * 60); } int sessionEviction = Option.SESSION_EVICTION.get(args); - getSessionHandler().getSessionCache().setEvictionPolicy( sessionEviction ); + getSessionHandler().getSessionCache().setEvictionPolicy(sessionEviction); } }; JettyWebSocketServletContainerInitializer.configure(wac, null); wac.getSecurityHandler().setLoginService(loginService); - wac.setThrowUnavailableOnStartupException(true); // if boot fails, abort the process instead of letting empty Jetty run + wac.setThrowUnavailableOnStartupException( + true); // if boot fails, abort the process instead of letting empty Jetty run wac.setMimeTypes(mimeTypes); wac.getSessionHandler().setSessionTrackingModes(Set.of(SessionTrackingMode.COOKIE)); wac.getSessionHandler().setSessionCookie(WinstoneSession.SESSION_COOKIE_NAME); - this.webapps.put(wac.getContextPath(),wac); + this.webapps.put(wac.getContextPath(), wac); return wac; } @@ -199,7 +202,7 @@ public void reloadWebApp(String prefix) { webApp.stop(); webApp.start(); } catch (Exception e) { - throw new WinstoneException("Failed to redeploy "+prefix,e); + throw new WinstoneException("Failed to redeploy " + prefix, e); } } else { throw new WinstoneException(Launcher.RESOURCES.getString("HostConfig.PrefixUnknown", prefix)); @@ -211,16 +214,16 @@ public void reloadWebApp(String prefix) { * war file is newer than. If none is supplied, use the default temp * directory. */ - @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "false positive, we're not being called from a webapp") + @SuppressFBWarnings( + value = "PATH_TRAVERSAL_IN", + justification = "false positive, we're not being called from a webapp") protected File getWebRoot(File requestedWebroot, File warfile) throws IOException { if (warfile != null) { - Logger.log(Level.INFO, Launcher.RESOURCES, - "HostConfig.BeginningWarExtraction"); + Logger.log(Level.INFO, Launcher.RESOURCES, "HostConfig.BeginningWarExtraction"); // open the war file if (!warfile.exists() || !warfile.isFile()) - throw new WinstoneException(Launcher.RESOURCES.getString( - "HostConfig.WarFileInvalid", warfile)); + throw new WinstoneException(Launcher.RESOURCES.getString("HostConfig.WarFileInvalid", warfile)); // Get the webroot folder (or a temp dir if none supplied) File unzippedDir; @@ -229,10 +232,15 @@ protected File getWebRoot(File requestedWebroot, File warfile) throws IOExceptio } else { File tempFile = File.createTempFile("dummy", "dummy"); String userName = System.getProperty("user.name"); - unzippedDir = new File(tempFile.getParent(), - (userName != null ? WinstoneResourceBundle.globalReplace(userName, - new String[][] {{"/", ""}, {"\\", ""}, {",", ""}}) + "/" : "") + - "winstone/" + warfile.getName()); + unzippedDir = new File( + tempFile.getParent(), + (userName != null + ? WinstoneResourceBundle.globalReplace( + userName, new String[][] {{"/", ""}, {"\\", ""}, {",", ""}}) + + "/" + : "") + + "winstone/" + + warfile.getName()); try { Files.delete(tempFile.toPath()); @@ -242,23 +250,27 @@ protected File getWebRoot(File requestedWebroot, File warfile) throws IOExceptio } if (unzippedDir.exists()) { if (!unzippedDir.isDirectory()) { - throw new WinstoneException(Launcher.RESOURCES.getString( - "HostConfig.WebRootNotDirectory", unzippedDir.getPath())); + throw new WinstoneException( + Launcher.RESOURCES.getString("HostConfig.WebRootNotDirectory", unzippedDir.getPath())); } else { - Logger.log(Level.FINER, Launcher.RESOURCES, - "HostConfig.WebRootExists", unzippedDir.getCanonicalPath()); + Logger.log( + Level.FINER, + Launcher.RESOURCES, + "HostConfig.WebRootExists", + unzippedDir.getCanonicalPath()); } } // check consistency and if out-of-sync, recreate - File timestampFile = new File(unzippedDir,".timestamp"); - if(!timestampFile.exists() || Math.abs(timestampFile.lastModified()- warfile.lastModified())>1000) { + File timestampFile = new File(unzippedDir, ".timestamp"); + if (!timestampFile.exists() || Math.abs(timestampFile.lastModified() - warfile.lastModified()) > 1000) { // contents of the target directory is inconsistent from the war. deleteRecursive(unzippedDir); try { Files.createDirectories(unzippedDir.toPath()); } catch (Exception ex) { - Logger.logDirectMessage(Level.WARNING, null, "Failed to recreate dirs " + unzippedDir.getAbsolutePath(), ex); + Logger.logDirectMessage( + Level.WARNING, null, "Failed to recreate dirs " + unzippedDir.getAbsolutePath(), ex); } } else { // files are up to date @@ -268,7 +280,7 @@ protected File getWebRoot(File requestedWebroot, File warfile) throws IOExceptio // Iterate through the files byte[] buffer = new byte[8192]; try (JarFile warArchive = new JarFile(warfile)) { - for (Enumeration e = warArchive.entries(); e.hasMoreElements();) { + for (Enumeration e = warArchive.entries(); e.hasMoreElements(); ) { JarEntry element = e.nextElement(); if (element.isDirectory()) { continue; @@ -295,16 +307,21 @@ protected File getWebRoot(File requestedWebroot, File warfile) throws IOExceptio Files.createDirectories(parent); } } catch (IOException | InvalidPathException | SecurityException ex) { - Logger.logDirectMessage(Level.WARNING, null, "Failed to create dirs " + outFile.getParentFile().getAbsolutePath(), null); + Logger.logDirectMessage( + Level.WARNING, + null, + "Failed to create dirs " + + outFile.getParentFile().getAbsolutePath(), + null); } // Copy out the extracted file try (InputStream inContent = warArchive.getInputStream(element); OutputStream outStream = new FileOutputStream(outFile)) { - int readBytes = inContent.read( buffer ); - while ( readBytes != -1 ) { - outStream.write( buffer, 0, readBytes ); - readBytes = inContent.read( buffer ); + int readBytes = inContent.read(buffer); + while (readBytes != -1) { + outStream.write(buffer, 0, readBytes); + readBytes = inContent.read(buffer); } } } @@ -312,8 +329,9 @@ protected File getWebRoot(File requestedWebroot, File warfile) throws IOExceptio // extraction completed new FileOutputStream(timestampFile).close(); - if(!timestampFile.setLastModified(warfile.lastModified())) { - Logger.logDirectMessage(Level.WARNING, null, "Failed to set timestamp " + timestampFile.getAbsolutePath(), null); + if (!timestampFile.setLastModified(warfile.lastModified())) { + Logger.logDirectMessage( + Level.WARNING, null, "Failed to set timestamp " + timestampFile.getAbsolutePath(), null); } // Return webroot @@ -325,7 +343,7 @@ protected File getWebRoot(File requestedWebroot, File warfile) throws IOExceptio private void deleteRecursive(File dir) { File[] children = dir.listFiles(); - if(children!=null) { + if (children != null) { for (File child : children) { deleteRecursive(child); } diff --git a/src/main/java/winstone/HostGroup.java b/src/main/java/winstone/HostGroup.java index e22f1f1d..b6511985 100644 --- a/src/main/java/winstone/HostGroup.java +++ b/src/main/java/winstone/HostGroup.java @@ -6,12 +6,11 @@ */ package winstone; -import org.eclipse.jetty.server.Server; - import java.io.IOException; import java.util.Hashtable; import java.util.Map; import java.util.logging.Level; +import org.eclipse.jetty.server.Server; /** * Manages the references to individual hosts within the container. This object handles @@ -23,24 +22,26 @@ */ public class HostGroup { - private final static String DEFAULT_HOSTNAME = "default"; + private static final String DEFAULT_HOSTNAME = "default"; private final Server server; // private Map args; private Map hostConfigs; private String defaultHostName; - public HostGroup( - Server server, ClassLoader commonLibCL, - Map args) throws IOException { + public HostGroup(Server server, ClassLoader commonLibCL, Map args) throws IOException { this.server = server; this.hostConfigs = new Hashtable<>(); // If host mode initHost(DEFAULT_HOSTNAME, commonLibCL, args); this.defaultHostName = DEFAULT_HOSTNAME; - Logger.log(Level.FINER, Launcher.RESOURCES, "HostGroup.InitSingleComplete", - this.hostConfigs.size() + "", this.hostConfigs.keySet() + ""); + Logger.log( + Level.FINER, + Launcher.RESOURCES, + "HostGroup.InitSingleComplete", + this.hostConfigs.size() + "", + this.hostConfigs.keySet() + ""); } public HostConfiguration getHostByName(String hostname) { diff --git a/src/main/java/winstone/Http2ConnectorFactory.java b/src/main/java/winstone/Http2ConnectorFactory.java index 9779a04a..552b8487 100644 --- a/src/main/java/winstone/Http2ConnectorFactory.java +++ b/src/main/java/winstone/Http2ConnectorFactory.java @@ -20,6 +20,9 @@ package winstone; +import java.io.IOException; +import java.util.Map; +import java.util.logging.Level; import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory; import org.eclipse.jetty.http.HttpCompliance; import org.eclipse.jetty.http.UriCompliance; @@ -35,10 +38,6 @@ import org.eclipse.jetty.util.ssl.SslContextFactory; import winstone.cmdline.Option; -import java.io.IOException; -import java.util.Map; -import java.util.logging.Level; - /** * This class add the HTTP/2 Listener This is the class that gets launched * by the command line, and owns the server socket, etc. @@ -46,20 +45,18 @@ */ public class Http2ConnectorFactory extends AbstractSecuredConnectorFactory implements ConnectorFactory { @Override - public Connector start( Map args, Server server ) throws IOException - { - int listenPort = Option.HTTP2_PORT.get( args ); + public Connector start(Map args, Server server) throws IOException { + int listenPort = Option.HTTP2_PORT.get(args); String listenAddress = Option.HTTP2_LISTEN_ADDRESS.get(args); - if ( listenPort < 0 ) { + if (listenPort < 0) { // not running HTTP2 listener return null; } - try { - configureSsl( args, server ); - SslContextFactory.Server sslContextFactory = getSSLContext( args ); + configureSsl(args, server); + SslContextFactory.Server sslContextFactory = getSSLContext(args); sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); // HTTPS Configuration @@ -80,20 +77,25 @@ public Connector start( Map args, Server server ) throws IOExcep alpn.setDefaultProtocol("http/1.1"); // SSL Connection Factory - SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,alpn.getProtocol()); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol()); // HTTP/2 Connector - ServerConnector http2Connector = - new ServerConnector(server,Option.JETTY_ACCEPTORS.get( args ), Option.JETTY_SELECTORS.get( args ) - ,ssl,alpn,h2,new HttpConnectionFactory(https_config)); + ServerConnector http2Connector = new ServerConnector( + server, + Option.JETTY_ACCEPTORS.get(args), + Option.JETTY_SELECTORS.get(args), + ssl, + alpn, + h2, + new HttpConnectionFactory(https_config)); http2Connector.setPort(listenPort); - http2Connector.setHost( listenAddress ); + http2Connector.setHost(listenAddress); server.addConnector(http2Connector); - server.setDumpAfterStart( Boolean.getBoolean( "dumpAfterStart" ) ); + server.setDumpAfterStart(Boolean.getBoolean("dumpAfterStart")); return http2Connector; } catch (IllegalStateException e) { - Logger.log(Level.WARNING, Launcher.RESOURCES, "Http2ConnectorFactory.FailedStart.ALPN", e ); + Logger.log(Level.WARNING, Launcher.RESOURCES, "Http2ConnectorFactory.FailedStart.ALPN", e); } return null; } diff --git a/src/main/java/winstone/HttpConnectorFactory.java b/src/main/java/winstone/HttpConnectorFactory.java index c1dc8d0e..30bd669d 100644 --- a/src/main/java/winstone/HttpConnectorFactory.java +++ b/src/main/java/winstone/HttpConnectorFactory.java @@ -8,46 +8,42 @@ import java.io.IOException; import java.util.Map; - import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; - import winstone.cmdline.Option; /** * Implements the main listener daemon thread. This is the class that gets * launched by the command line, and owns the server socket, etc. Note that this * class is also used as the base class for the HTTPS listener. - * + * * @author Rick Knowles * @version $Id: HttpConnectorFactory.java,v 1.15 2007/05/01 04:39:49 rickknowles Exp $ */ public class HttpConnectorFactory implements ConnectorFactory { @Override - public Connector start( Map args, Server server) throws IOException { + public Connector start(Map args, Server server) throws IOException { // Load resources int listenPort = Option.HTTP_PORT.get(args); String listenUnixDomainPath = Option.HTTP_UNIX_DOMAIN_PATH.get(args); if (listenPort < 0 && listenUnixDomainPath == null) { return null; - } - else { + } else { ServerConnectorBuilder scb = new ServerConnectorBuilder() - .withServer(server) - .withAcceptors(Option.JETTY_ACCEPTORS.get(args)) - .withSelectors(Option.JETTY_SELECTORS.get(args)) - .withListenerUnixDomainPath(listenUnixDomainPath) - .withListenerPort(listenPort) - .withSecureListenerPort(Option.HTTPS_PORT.get(args, -1)) - .withListenerAddress(Option.HTTP_LISTEN_ADDRESS.get(args)) - .withRequestHeaderSize(Option.REQUEST_HEADER_SIZE.get(args)) - .withResponseHeaderSize(Option.RESPONSE_HEADER_SIZE.get(args)) - .withKeepAliveTimeout(Option.HTTP_KEEP_ALIVE_TIMEOUT.get(args)); + .withServer(server) + .withAcceptors(Option.JETTY_ACCEPTORS.get(args)) + .withSelectors(Option.JETTY_SELECTORS.get(args)) + .withListenerUnixDomainPath(listenUnixDomainPath) + .withListenerPort(listenPort) + .withSecureListenerPort(Option.HTTPS_PORT.get(args, -1)) + .withListenerAddress(Option.HTTP_LISTEN_ADDRESS.get(args)) + .withRequestHeaderSize(Option.REQUEST_HEADER_SIZE.get(args)) + .withResponseHeaderSize(Option.RESPONSE_HEADER_SIZE.get(args)) + .withKeepAliveTimeout(Option.HTTP_KEEP_ALIVE_TIMEOUT.get(args)); Connector connector = scb.build(); server.addConnector(connector); return connector; - } } } diff --git a/src/main/java/winstone/HttpsConnectorFactory.java b/src/main/java/winstone/HttpsConnectorFactory.java index 5568ae98..6eacd11e 100644 --- a/src/main/java/winstone/HttpsConnectorFactory.java +++ b/src/main/java/winstone/HttpsConnectorFactory.java @@ -8,42 +8,40 @@ import java.io.IOException; import java.util.Map; - import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.SecuredRedirectHandler; - import winstone.cmdline.Option; /** * Implements the main listener daemon thread. This is the class that gets * launched by the command line, and owns the server socket, etc. - * + * * @author Rick Knowles * @version $Id: HttpsConnectorFactory.java,v 1.10 2007/06/13 15:27:35 rickknowles Exp $ */ public class HttpsConnectorFactory extends AbstractSecuredConnectorFactory implements ConnectorFactory { @Override - public Connector start( Map args, Server server) throws IOException { + public Connector start(Map args, Server server) throws IOException { int listenPort = Option.HTTPS_PORT.get(args); - if (listenPort<0) { + if (listenPort < 0) { // not running HTTPS listener return null; } - if(Option.HTTPS_REDIRECT_HTTP.get(args)) { + if (Option.HTTPS_REDIRECT_HTTP.get(args)) { // setup a redirect from http to https Handler currentHandler = server.getHandler(); - if(currentHandler == null) { + if (currentHandler == null) { server.setHandler(new SecuredRedirectHandler()); } else { - if(currentHandler instanceof HandlerList) { - ((HandlerList)currentHandler).addHandler(new SecuredRedirectHandler()); + if (currentHandler instanceof HandlerList) { + ((HandlerList) currentHandler).addHandler(new SecuredRedirectHandler()); } else { HandlerList handlers = new HandlerList(); handlers.addHandler(new SecuredRedirectHandler()); @@ -55,17 +53,17 @@ public Connector start( Map args, Server server) throws IOExcept configureSsl(args, server); ServerConnectorBuilder scb = new ServerConnectorBuilder() - .withServer(server) - .withAcceptors(Option.JETTY_ACCEPTORS.get(args)) - .withSelectors(Option.JETTY_SELECTORS.get(args)) - .withListenerPort(listenPort) - .withListenerAddress(Option.HTTPS_LISTEN_ADDRESS.get(args)) - .withRequestHeaderSize(Option.REQUEST_HEADER_SIZE.get(args)) - .withResponseHeaderSize(Option.RESPONSE_HEADER_SIZE.get(args)) - .withKeepAliveTimeout(Option.HTTPS_KEEP_ALIVE_TIMEOUT.get(args)) - .withSniHostCheck(Option.HTTPS_SNI_HOST_CHECK.get(args)) - .withSniRequired(Option.HTTPS_SNI_REQUIRED.get(args)) - .withSslContext(getSSLContext(args)); + .withServer(server) + .withAcceptors(Option.JETTY_ACCEPTORS.get(args)) + .withSelectors(Option.JETTY_SELECTORS.get(args)) + .withListenerPort(listenPort) + .withListenerAddress(Option.HTTPS_LISTEN_ADDRESS.get(args)) + .withRequestHeaderSize(Option.REQUEST_HEADER_SIZE.get(args)) + .withResponseHeaderSize(Option.RESPONSE_HEADER_SIZE.get(args)) + .withKeepAliveTimeout(Option.HTTPS_KEEP_ALIVE_TIMEOUT.get(args)) + .withSniHostCheck(Option.HTTPS_SNI_HOST_CHECK.get(args)) + .withSniRequired(Option.HTTPS_SNI_REQUIRED.get(args)) + .withSslContext(getSSLContext(args)); Connector c = scb.build(); server.addConnector(c); return c; diff --git a/src/main/java/winstone/Launcher.java b/src/main/java/winstone/Launcher.java index 98997b36..eacc53e2 100644 --- a/src/main/java/winstone/Launcher.java +++ b/src/main/java/winstone/Launcher.java @@ -9,15 +9,6 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.jenkins.lib.support_log_formatter.SupportLogFormatter; -import org.eclipse.jetty.jmx.MBeanContainer; -import org.eclipse.jetty.server.Connector; -import org.eclipse.jetty.server.LowResourceMonitor; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.util.thread.QueuedThreadPool; -import winstone.cmdline.CmdLineParser; -import winstone.cmdline.Option; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -48,6 +39,14 @@ import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; +import org.eclipse.jetty.jmx.MBeanContainer; +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.LowResourceMonitor; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.util.thread.QueuedThreadPool; +import winstone.cmdline.CmdLineParser; +import winstone.cmdline.Option; /** * Implements the main launcher daemon thread. This is the class that gets @@ -71,7 +70,7 @@ public class Launcher implements Runnable { private static int SHUTDOWN_TIMEOUT = 20000; // wait 20s for shutdown private Thread controlThread; - public final static WinstoneResourceBundle RESOURCES = new WinstoneResourceBundle("winstone.LocalStrings"); + public static final WinstoneResourceBundle RESOURCES = new WinstoneResourceBundle("winstone.LocalStrings"); private int controlPort; private HostGroup hostGroup; private Map args; @@ -84,9 +83,11 @@ public class Launcher implements Runnable { * Constructor - initialises the web app, object pools, control port and the * available protocol listeners. */ - @SuppressFBWarnings(value ="DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED", justification = "cf. https://github.com/spotbugs/spotbugs/issues/1515") + @SuppressFBWarnings( + value = "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED", + justification = "cf. https://github.com/spotbugs/spotbugs/issues/1515") public Launcher(Map args) throws IOException { - boolean success=false; + boolean success = false; /* * As described in JDK-8161253, there is no way to control the order of execution of * shutdown hooks. When LogManager#Cleaner runs before our custom shutdown hook, logging @@ -121,27 +122,25 @@ public Launcher(Map args) throws IOException { Logger.log(Level.ALL, RESOURCES, "Launcher.StartupArgs", args + ""); this.args = args; - this.controlPort =Option.CONTROL_PORT.get(args); + this.controlPort = Option.CONTROL_PORT.get(args); // Check for java home List jars = new ArrayList<>(); String defaultJavaHome = System.getProperty("java.home"); - File javaHome = Option.JAVA_HOME.get(args,new File(defaultJavaHome)); + File javaHome = Option.JAVA_HOME.get(args, new File(defaultJavaHome)); Logger.log(Level.FINER, RESOURCES, "Launcher.UsingJavaHome", javaHome.getPath()); // Set up common lib class loader - File libFolder = Option.COMMON_LIB_FOLDER.get(args,new File("lib")); + File libFolder = Option.COMMON_LIB_FOLDER.get(args, new File("lib")); if (libFolder.exists() && libFolder.isDirectory()) { - Logger.log(Level.FINER, RESOURCES, "Launcher.UsingCommonLib", - libFolder.getCanonicalPath()); + Logger.log(Level.FINER, RESOURCES, "Launcher.UsingCommonLib", libFolder.getCanonicalPath()); File[] children = libFolder.listFiles(); if (children != null) for (File aChildren : children) if (aChildren.getName().endsWith(".jar") || aChildren.getName().endsWith(".zip")) { jars.add(aChildren.toURI().toURL()); - Logger.log(Level.FINER, RESOURCES, "Launcher.AddedCommonLibJar", - aChildren.getName()); + Logger.log(Level.FINER, RESOURCES, "Launcher.AddedCommonLibJar", aChildren.getName()); } } else { Logger.log(Level.FINER, RESOURCES, "Launcher.NoCommonLib"); @@ -149,32 +148,31 @@ public Launcher(Map args) throws IOException { File extraLibFolder = Option.EXTRA_LIB_FOLDER.get(args); List extraJars = new ArrayList<>(); - if(extraLibFolder != null && extraLibFolder.exists()){ + if (extraLibFolder != null && extraLibFolder.exists()) { Logger.log(Level.WARNING, RESOURCES, "Launcher.ExtraLibFolder"); File[] children = extraLibFolder.listFiles(); if (children != null) for (File aChildren : children) if (aChildren.getName().endsWith(".jar") - || aChildren.getName().endsWith(".zip")) { + || aChildren.getName().endsWith(".zip")) { extraJars.add(aChildren.toURI().toURL()); } } - ClassLoader commonLibCL = new URLClassLoader(jars.toArray(new URL[0]), - getClass().getClassLoader()); - - Logger.log(Level.ALL, RESOURCES, "Launcher.CLClassLoader", - commonLibCL.toString()); + ClassLoader commonLibCL = + new URLClassLoader(jars.toArray(new URL[0]), getClass().getClassLoader()); + Logger.log(Level.ALL, RESOURCES, "Launcher.CLClassLoader", commonLibCL.toString()); - if(!extraJars.isEmpty()){ - ClassLoader extraClassLoader = new URLClassLoader(extraJars.toArray(new URL[0]), - getClass().getClassLoader()); - Thread.currentThread().setContextClassLoader( extraClassLoader ); + if (!extraJars.isEmpty()) { + ClassLoader extraClassLoader = new URLClassLoader( + extraJars.toArray(new URL[0]), getClass().getClassLoader()); + Thread.currentThread().setContextClassLoader(extraClassLoader); } int qtpMaxThread = Option.QTP_MAXTHREADS.get(args); - QueuedThreadPool queuedThreadPool = qtpMaxThread>0?new QueuedThreadPool(qtpMaxThread):new QueuedThreadPool(); + QueuedThreadPool queuedThreadPool = + qtpMaxThread > 0 ? new QueuedThreadPool(qtpMaxThread) : new QueuedThreadPool(); queuedThreadPool.setName("Jetty (winstone)"); this.server = new Server(queuedThreadPool); @@ -183,7 +181,6 @@ public Launcher(Map args) throws IOException { lowResourceMonitor.setMonitorThreads(true); this.server.addBean(lowResourceMonitor); - // Open the web apps this.hostGroup = new HostGroup(server, commonLibCL, args); @@ -195,9 +192,9 @@ public Launcher(Map args) throws IOException { lowResourceMonitor.setMonitoredConnectors(connectors); - if(Option.USE_JMX.get(args)) { + if (Option.USE_JMX.get(args)) { // Setup JMX if needed - MBeanContainer mbeanContainer = new MBeanContainer( ManagementFactory.getPlatformMBeanServer()); + MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); server.addBean(mbeanContainer); } @@ -206,18 +203,16 @@ public Launcher(Map args) throws IOException { writePortToFileIfNeeded(); } catch (Exception e) { - throw new IOException("Failed to start Jetty",e); + throw new IOException("Failed to start Jetty", e); } - this.controlThread = new Thread(this, RESOURCES.getString( - "Launcher.ThreadName", "" + this.controlPort)); + this.controlThread = new Thread(this, RESOURCES.getString("Launcher.ThreadName", "" + this.controlPort)); this.controlThread.setDaemon(false); this.controlThread.start(); success = true; } finally { - if (!success) - shutdown(); + if (!success) shutdown(); } try { @@ -300,7 +295,8 @@ private void writePortToFileIfNeeded() throws IOException { Path portFile = Paths.get(portFileName); Path portDir = portFile.getParent(); if (portDir == null) { - throw new IllegalArgumentException("Given port file name doesn't have a parent: " + portFileName); + throw new IllegalArgumentException( + "Given port file name doesn't have a parent: " + portFileName); } Files.createDirectories(portDir); Path fileName = portFile.getFileName(); @@ -313,7 +309,8 @@ private void writePortToFileIfNeeded() throws IOException { try { Files.move(tmpPath, portFile, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException e) { - Logger.logDirectMessage(Level.WARNING, null, "Atomic move not supported. Falling back to non-atomic move.", e); + Logger.logDirectMessage( + Level.WARNING, null, "Atomic move not supported. Falling back to non-atomic move.", e); try { Files.move(tmpPath, portFile, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e2) { @@ -338,15 +335,15 @@ private void writePortToFileIfNeeded() throws IOException { */ protected Connector spawnListener(String listenerClassName, List connectors) throws IOException { try { - ConnectorFactory connectorFactory = (ConnectorFactory) Class.forName(listenerClassName) - .getDeclaredConstructor().newInstance(); + ConnectorFactory connectorFactory = (ConnectorFactory) + Class.forName(listenerClassName).getDeclaredConstructor().newInstance(); Connector connector = connectorFactory.start(args, server); - if(connector!=null){ + if (connector != null) { connectors.add(connector); } return connector; } catch (Throwable err) { - throw new IOException("Failed to start a listener: "+listenerClassName, err); + throw new IOException("Failed to start a listener: " + listenerClassName, err); } } @@ -364,10 +361,12 @@ public void run() { controlSocket.setSoTimeout(CONTROL_TIMEOUT); } - Logger.log(Level.INFO, RESOURCES, "Launcher.StartupOK", + Logger.log( + Level.INFO, + RESOURCES, + "Launcher.StartupOK", RESOURCES.getString("ServerVersion"), - (this.controlPort > 0 ? "" + this.controlPort - : RESOURCES.getString("Launcher.ControlDisabled"))); + (this.controlPort > 0 ? "" + this.controlPort : RESOURCES.getString("Launcher.ControlDisabled"))); // Enter the main loop while (!interrupted) { @@ -387,11 +386,13 @@ public void run() { } catch (InterruptedException err) { interrupted = true; } catch (Throwable err) { - Logger.log(Level.SEVERE, RESOURCES, - "Launcher.ShutdownError", err); + Logger.log(Level.SEVERE, RESOURCES, "Launcher.ShutdownError", err); } finally { if (accepted != null) { - try {accepted.close();} catch (IOException err) {} + try { + accepted.close(); + } catch (IOException err) { + } } if (Thread.interrupted()) { interrupted = true; @@ -416,8 +417,7 @@ protected void handleControlRequest(Socket csAccepted) throws IOException { inSocket = csAccepted.getInputStream(); int reqType = inSocket.read(); if ((byte) reqType == SHUTDOWN_TYPE) { - Logger.log(Level.INFO, RESOURCES, - "Launcher.ShutdownRequestReceived"); + Logger.log(Level.INFO, RESOURCES, "Launcher.ShutdownRequestReceived"); shutdown(); } else if ((byte) reqType == RELOAD_TYPE) { inControl = new ObjectInputStream(inSocket); @@ -429,10 +429,16 @@ protected void handleControlRequest(Socket csAccepted) throws IOException { } } finally { if (inControl != null) { - try {inControl.close();} catch (IOException err) {} + try { + inControl.close(); + } catch (IOException err) { + } } if (inSocket != null) { - try {inSocket.close();} catch (IOException err) {} + try { + inSocket.close(); + } catch (IOException err) { + } } } } @@ -468,11 +474,11 @@ public static void main(String[] argv) throws IOException { Map args = getArgsFromCommandLine(argv); if (System.getProperty("java.util.logging.config.file") == null) { - for (Handler h : java.util.logging.Logger.getLogger("").getHandlers()) { - if (h instanceof ConsoleHandler) { - ((ConsoleHandler) h).setFormatter(new SupportLogFormatter()); - } - } + for (Handler h : java.util.logging.Logger.getLogger("").getHandlers()) { + if (h instanceof ConsoleHandler) { + ((ConsoleHandler) h).setFormatter(new SupportLogFormatter()); + } + } } if (Option.USAGE.isIn(args) || Option.HELP.isIn(args)) { @@ -489,7 +495,6 @@ public static void main(String[] argv) throws IOException { return; } - // Launch try { new Launcher(args); @@ -502,7 +507,7 @@ public static void main(String[] argv) throws IOException { @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "TODO needs triage") public static Map getArgsFromCommandLine(String[] argv) throws IOException { - Map args = new CmdLineParser(Option.all(Option.class)).parse(argv,"nonSwitch"); + Map args = new CmdLineParser(Option.all(Option.class)).parse(argv, "nonSwitch"); // Small hack to allow re-use of the command line parsing inside the control tool String firstNonSwitchArgument = args.get("nonSwitch"); @@ -522,11 +527,12 @@ public static Map getArgsFromCommandLine(String[] argv) throws I return args; } - @SuppressFBWarnings(value = { "NP_LOAD_OF_KNOWN_NULL_VALUE", "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE" }, justification = "false positive https://github.com/spotbugs/spotbugs/issues/1338") + @SuppressFBWarnings( + value = {"NP_LOAD_OF_KNOWN_NULL_VALUE", "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"}, + justification = "false positive https://github.com/spotbugs/spotbugs/issues/1338") protected static void deployEmbeddedWarfile(Map args) throws IOException { String embeddedWarfileName = RESOURCES.getString("Launcher.EmbeddedWarFile"); - try (InputStream embeddedWarfile = Launcher.class.getResourceAsStream( - embeddedWarfileName)) { + try (InputStream embeddedWarfile = Launcher.class.getResourceAsStream(embeddedWarfileName)) { if (embeddedWarfile == null) { return; } @@ -535,7 +541,8 @@ protected static void deployEmbeddedWarfile(Map args) throws IOE try { Files.createDirectories(parentTempWarFile.toPath()); } catch (Exception ex) { - Logger.logDirectMessage(Level.WARNING, null, "Failed to mkdirs " + parentTempWarFile.getAbsolutePath(), ex); + Logger.logDirectMessage( + Level.WARNING, null, "Failed to mkdirs " + parentTempWarFile.getAbsolutePath(), ex); } tempWarfile.deleteOnExit(); @@ -547,8 +554,7 @@ protected static void deployEmbeddedWarfile(Map args) throws IOE Logger.logDirectMessage(Level.WARNING, null, "Failed to mkdirs " + tempWebroot.getAbsolutePath(), ex); } - Logger.log(Level.FINER, RESOURCES, "Launcher.CopyingEmbeddedWarfile", - tempWarfile.getAbsolutePath()); + Logger.log(Level.FINER, RESOURCES, "Launcher.CopyingEmbeddedWarfile", tempWarfile.getAbsolutePath()); try (OutputStream out = new FileOutputStream(tempWarfile, true)) { // TODO use Files#copy(InputStream,Path,CopyOption...) int read; @@ -576,8 +582,10 @@ public static void initLogger(Map args) throws IOException { } catch (InvalidPathException e) { throw new IOException(e); } - OutputStream outputStream = Files.newOutputStream(logPath, StandardOpenOption.CREATE, StandardOpenOption.APPEND); - // TODO: Ideally, should change this to UTF-8, but this could cause problems for Windows users when appending to existing logs. + OutputStream outputStream = + Files.newOutputStream(logPath, StandardOpenOption.CREATE, StandardOpenOption.APPEND); + // TODO: Ideally, should change this to UTF-8, but this could cause problems for Windows users when + // appending to existing logs. PrintStream printStream = new PrintStream(outputStream, false, Charset.defaultCharset()); System.setOut(printStream); System.setErr(printStream); @@ -589,15 +597,16 @@ protected static void printUsage() { // if the caller overrides the usage, use that instead. String usage = USAGE; - String header = RESOURCES.getString("Launcher.UsageInstructions.Header", - RESOURCES.getString("ServerVersion")); + String header = RESOURCES.getString("Launcher.UsageInstructions.Header", RESOURCES.getString("ServerVersion")); String options = RESOURCES.getString("Launcher.UsageInstructions.Options"); String footer = RESOURCES.getString("Launcher.UsageInstructions.Options"); - if(usage==null) { - usage = header+options+footer; + if (usage == null) { + usage = header + options + footer; } else { - usage = usage.replace("{HEADER}",header).replace("{OPTIONS}",options).replace("{FOOTER}",footer); + usage = usage.replace("{HEADER}", header) + .replace("{OPTIONS}", options) + .replace("{FOOTER}", footer); } System.out.println(usage); } diff --git a/src/main/java/winstone/Logger.java b/src/main/java/winstone/Logger.java index 9da0bb99..57fdc17f 100644 --- a/src/main/java/winstone/Logger.java +++ b/src/main/java/winstone/Logger.java @@ -26,7 +26,7 @@ */ public class Logger { - private final static Object semaphore = new Object(); + private static final Object semaphore = new Object(); static boolean initialised = false; static boolean showThrowingThread; @@ -44,9 +44,7 @@ public static void init(int level) { /** * Initialize default streams */ - public static void init( - Level level, - boolean showThrowingThreadArg) { + public static void init(Level level, boolean showThrowingThreadArg) { synchronized (semaphore) { if (!initialised) { // recheck in case we were blocking on another init LOGGER.setLevel(level); @@ -59,9 +57,10 @@ public static void init( public static void setCurrentDebugLevel(int level) { if (!initialised) { init(level); - } else synchronized (semaphore) { - LOGGER.setLevel(Level.parse(String.valueOf(level))); - } + } else + synchronized (semaphore) { + LOGGER.setLevel(Level.parse(String.valueOf(level))); + } } /** @@ -75,15 +74,14 @@ private static void logInternal(Level level, String message, Throwable error) { String msg = ""; if (showThrowingThread) { - msg = "["+Thread.currentThread().getName()+"] - "; + msg = "[" + Thread.currentThread().getName() + "] - "; } msg += message; - LOGGER.log(level,msg,error); + LOGGER.log(level, msg, error); } - public static void log(Level level, WinstoneResourceBundle resources, - String messageKey) { + public static void log(Level level, WinstoneResourceBundle resources, String messageKey) { if (!LOGGER.isLoggable(level)) { return; } else { @@ -91,8 +89,7 @@ public static void log(Level level, WinstoneResourceBundle resources, } } - public static void log(Level level, WinstoneResourceBundle resources, - String messageKey, Throwable error) { + public static void log(Level level, WinstoneResourceBundle resources, String messageKey, Throwable error) { if (!LOGGER.isLoggable(level)) { return; } else { @@ -100,8 +97,7 @@ public static void log(Level level, WinstoneResourceBundle resources, } } - public static void log(Level level, WinstoneResourceBundle resources, - String messageKey, Object param) { + public static void log(Level level, WinstoneResourceBundle resources, String messageKey, Object param) { if (!LOGGER.isLoggable(level)) { return; } else { @@ -109,8 +105,7 @@ public static void log(Level level, WinstoneResourceBundle resources, } } - public static void log(Level level, WinstoneResourceBundle resources, - String messageKey, Object... params) { + public static void log(Level level, WinstoneResourceBundle resources, String messageKey, Object... params) { if (!LOGGER.isLoggable(level)) { return; } else { @@ -118,8 +113,8 @@ public static void log(Level level, WinstoneResourceBundle resources, } } - public static void log(Level level, WinstoneResourceBundle resources, - String messageKey, Object param, Throwable error) { + public static void log( + Level level, WinstoneResourceBundle resources, String messageKey, Object param, Throwable error) { if (!LOGGER.isLoggable(level)) { return; } else { @@ -127,8 +122,8 @@ public static void log(Level level, WinstoneResourceBundle resources, } } - public static void log(Level level, WinstoneResourceBundle resources, - String messageKey, Object[] params, Throwable error) { + public static void log( + Level level, WinstoneResourceBundle resources, String messageKey, Object[] params, Throwable error) { if (!LOGGER.isLoggable(level)) { return; } else { @@ -136,8 +131,13 @@ public static void log(Level level, WinstoneResourceBundle resources, } } - public static void log(Level level, WinstoneResourceBundle resources, - String streamName, String messageKey, Object[] params, Throwable error) { + public static void log( + Level level, + WinstoneResourceBundle resources, + String streamName, + String messageKey, + Object[] params, + Throwable error) { if (!LOGGER.isLoggable(level)) { return; } else { @@ -145,8 +145,7 @@ public static void log(Level level, WinstoneResourceBundle resources, } } - public static void logDirectMessage(Level level, String streamName, String message, - Throwable error) { + public static void logDirectMessage(Level level, String streamName, String message, Throwable error) { if (!LOGGER.isLoggable(level)) { return; } else { diff --git a/src/main/java/winstone/ServerConnectorBuilder.java b/src/main/java/winstone/ServerConnectorBuilder.java index a1394b9a..6d84ad2e 100644 --- a/src/main/java/winstone/ServerConnectorBuilder.java +++ b/src/main/java/winstone/ServerConnectorBuilder.java @@ -1,7 +1,6 @@ package winstone; import java.nio.file.Path; - import org.eclipse.jetty.http.HttpCompliance; import org.eclipse.jetty.http.UriCompliance; import org.eclipse.jetty.server.Connector; @@ -81,9 +80,9 @@ public ServerConnectorBuilder withRequestHeaderSize(int requestHeaderSize) { } public ServerConnectorBuilder withResponseHeaderSize(int responseHeaderSize) { - this.responseHeaderSize = responseHeaderSize; - return this; - } + this.responseHeaderSize = responseHeaderSize; + return this; + } public ServerConnectorBuilder withSniHostCheck(boolean sniHostCheck) { this.sniHostCheck = sniHostCheck; @@ -102,9 +101,8 @@ public Connector build() { if (listenerUnixDomainPath != null) { UnixDomainServerConnector usc; - - usc = new UnixDomainServerConnector(server, acceptors, selectors, - new HttpConnectionFactory()); + + usc = new UnixDomainServerConnector(server, acceptors, selectors, new HttpConnectionFactory()); usc.setUnixDomainPath(Path.of(listenerUnixDomainPath)); usc.setIdleTimeout(keepAliveTimeout); @@ -126,11 +124,11 @@ public Connector build() { sc.setIdleTimeout(keepAliveTimeout); c = sc; - } - HttpConfiguration hc = c.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration(); - if(secureListenerPort > 0) { + HttpConfiguration hc = + c.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration(); + if (secureListenerPort > 0) { hc.setSecurePort(secureListenerPort); } hc.setHttpCompliance(HttpCompliance.RFC7230); @@ -140,15 +138,13 @@ public Connector build() { hc.setResponseHeaderSize(responseHeaderSize); SecureRequestCustomizer src = hc.getCustomizer(SecureRequestCustomizer.class); - if(src!=null&&!sniHostCheck){ + if (src != null && !sniHostCheck) { src.setSniHostCheck(false); } - if(src!=null&&sniRequired){ + if (src != null && sniRequired) { src.setSniRequired(true); } return c; - } - } diff --git a/src/main/java/winstone/ShutdownHook.java b/src/main/java/winstone/ShutdownHook.java index e1b39853..81557f93 100644 --- a/src/main/java/winstone/ShutdownHook.java +++ b/src/main/java/winstone/ShutdownHook.java @@ -10,7 +10,7 @@ /** * A jvm hook to force the calling of the web-app destroy before the process terminates - * + * * @author Rick Knowles * @version $Id: ShutdownHook.java,v 1.3 2006/02/28 07:32:47 rickknowles Exp $ */ diff --git a/src/main/java/winstone/WinstoneException.java b/src/main/java/winstone/WinstoneException.java index f69e7671..6c7745eb 100644 --- a/src/main/java/winstone/WinstoneException.java +++ b/src/main/java/winstone/WinstoneException.java @@ -10,7 +10,7 @@ * Master exception within the servlet container. This is thrown whenever a * non-recoverable error occurs that we want to throw to the top of the * application. - * + * * @author Rick Knowles * @version $Id: WinstoneException.java,v 1.1 2004/03/08 15:27:21 rickknowles * Exp $ @@ -18,7 +18,7 @@ public class WinstoneException extends RuntimeException { /** * Create an exception with a useful message for the system administrator. - * + * * @param pMsg * Error message for to be used for administrative * troubleshooting @@ -30,19 +30,19 @@ public WinstoneException(String pMsg) { /** * Create an exception with a useful message for the system administrator * and a nested throwable object. - * + * * @param pMsg * Error message for administrative troubleshooting * @param pError * The actual exception that occurred */ public WinstoneException(String pMsg, Throwable pError) { - super(pMsg,pError); + super(pMsg, pError); } /** * Get the nested error or exception - * + * * @return The nested error or exception */ public Throwable getNestedError() { @@ -51,7 +51,7 @@ public Throwable getNestedError() { /** * Set the nested error or exception - * + * * @param pError * The nested error or exception */ diff --git a/src/main/java/winstone/WinstoneResourceBundle.java b/src/main/java/winstone/WinstoneResourceBundle.java index da7dc075..a21ea0d2 100644 --- a/src/main/java/winstone/WinstoneResourceBundle.java +++ b/src/main/java/winstone/WinstoneResourceBundle.java @@ -12,7 +12,7 @@ /** * A ResourceBundle that includes the ability to do string replacement on the * resources it retrieves. - * + * * @author Rick Knowles */ public class WinstoneResourceBundle { @@ -48,7 +48,7 @@ public String getString(String key, Object parameter) { } private String toString(Object s) { - return s!=null?s.toString():null; + return s != null ? s.toString() : null; } /** @@ -74,7 +74,7 @@ public static String globalReplace(String input, String fromMarker, String toVal globalReplace(out, fromMarker, toValue); return out.toString(); } - + private static void globalReplace(StringBuilder input, String fromMarker, String toValue) { if (input == null) { return; @@ -93,7 +93,7 @@ private static void globalReplace(StringBuilder input, String fromMarker, String foundAt = input.indexOf(fromMarker, index); } } - + public static String globalReplace(String input, String[][] parameters) { if (parameters != null) { StringBuilder out = new StringBuilder(input); diff --git a/src/main/java/winstone/WinstoneSession.java b/src/main/java/winstone/WinstoneSession.java index ebca811c..9709c2bf 100644 --- a/src/main/java/winstone/WinstoneSession.java +++ b/src/main/java/winstone/WinstoneSession.java @@ -11,9 +11,10 @@ public class WinstoneSession { /** * Name of the cookie that stores HTTP session ID. */ - @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "mutated by jenkinsci/jenkins/war/src/main/java/executable/Main.java") + @SuppressFBWarnings( + value = "MS_SHOULD_BE_FINAL", + justification = "mutated by jenkinsci/jenkins/war/src/main/java/executable/Main.java") public static String SESSION_COOKIE_NAME = "JSESSIONID"; private WinstoneSession() {} - } diff --git a/src/main/java/winstone/accesslog/SimpleAccessLogger.java b/src/main/java/winstone/accesslog/SimpleAccessLogger.java index adb8bb23..004f57db 100644 --- a/src/main/java/winstone/accesslog/SimpleAccessLogger.java +++ b/src/main/java/winstone/accesslog/SimpleAccessLogger.java @@ -7,15 +7,6 @@ package winstone.accesslog; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.eclipse.jetty.server.Authentication; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.RequestLog; -import org.eclipse.jetty.server.Response; -import org.eclipse.jetty.util.component.AbstractLifeCycle; -import winstone.Logger; -import winstone.WinstoneResourceBundle; -import winstone.cmdline.Option; - import java.io.File; import java.io.IOException; import java.io.OutputStream; @@ -30,6 +21,14 @@ import java.util.Date; import java.util.Map; import java.util.logging.Level; +import org.eclipse.jetty.server.Authentication; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.RequestLog; +import org.eclipse.jetty.server.Response; +import org.eclipse.jetty.util.component.AbstractLifeCycle; +import winstone.Logger; +import winstone.WinstoneResourceBundle; +import winstone.cmdline.Option; /** * Simulates an apache "combined" style logger, which logs User-Agent, Referer, etc @@ -53,9 +52,10 @@ public class SimpleAccessLogger extends AbstractLifeCycle implements RequestLog private String pattern; private String fileName; - @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "false positive, webAppName come from command line") - public SimpleAccessLogger(String webAppName, Map startupArgs) - throws IOException { + @SuppressFBWarnings( + value = "PATH_TRAVERSAL_IN", + justification = "false positive, webAppName come from command line") + public SimpleAccessLogger(String webAppName, Map startupArgs) throws IOException { // Get pattern String patternType = Option.SIMPLE_ACCESS_LOGGER_FORMAT.get(startupArgs); @@ -72,10 +72,9 @@ public SimpleAccessLogger(String webAppName, Map startupArgs) } // Get filename - String filePattern = Option.SIMPLE_ACCESS_LOGGER_FILE.get(startupArgs); - this.fileName = WinstoneResourceBundle.globalReplace(filePattern, - new String [][] { - {"###webapp###", webAppName}}); + String filePattern = Option.SIMPLE_ACCESS_LOGGER_FILE.get(startupArgs); + this.fileName = + WinstoneResourceBundle.globalReplace(filePattern, new String[][] {{"###webapp###", webAppName}}); File file = new File(this.fileName); File parentFile = file.getParentFile(); @@ -91,8 +90,7 @@ public SimpleAccessLogger(String webAppName, Map startupArgs) } this.outWriter = new PrintWriter(new OutputStreamWriter(this.outStream, StandardCharsets.UTF_8), true); - Logger.log(Level.FINER, ACCESSLOG_RESOURCES, "SimpleAccessLogger.Init", - this.fileName, patternType); + Logger.log(Level.FINER, ACCESSLOG_RESOURCES, "SimpleAccessLogger.Init", this.fileName, patternType); } @Override @@ -105,7 +103,8 @@ public void log(Request request, Response response) { date = DF.format(new Date()); } - // mimic https://github.com/eclipse/jetty.project/blob/jetty-9.4.0.v20161208/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractNCSARequestLog.java#L130 + // mimic + // https://github.com/eclipse/jetty.project/blob/jetty-9.4.0.v20161208/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractNCSARequestLog.java#L130 Authentication authentication = request.getAuthentication(); String remoteUser; if (authentication instanceof Authentication.User) { @@ -116,24 +115,24 @@ public void log(Request request, Response response) { } String logLine = WinstoneResourceBundle.globalReplace(this.pattern, new String[][] { - {"###x-forwarded-for###", nvl(request.getHeader("X-Forwarded-For"))}, - {"###x-forwarded-host###", nvl(request.getHeader("X-Forwarded-Host"))}, - {"###x-forwarded-proto###", nvl(request.getHeader("X-Forwarded-Proto"))}, - {"###x-forwarded-protocol###", nvl(request.getHeader("X-Forwarded-Protocol"))}, - {"###x-forwarded-server###", nvl(request.getHeader("X-Forwarded-Server"))}, - {"###x-forwarded-ssl###", nvl(request.getHeader("X-Forwarded-Ssl"))}, - {"###x-requested-with###", nvl(request.getHeader("X-Requested-With"))}, - {"###x-do-not-track###", nvl(request.getHeader("X-Do-Not-Track"))}, - {"###dnt###", nvl(request.getHeader("DNT"))}, - {"###via###", nvl(request.getHeader("Via"))}, - {"###ip###", request.getRemoteHost()}, - {"###user###", nvl(remoteUser)}, - {"###time###", "[" + date + "]"}, - {"###uriLine###", uriLine}, - {"###status###", "" + status}, - {"###size###", "" + size}, - {"###referer###", nvl(request.getHeader("Referer"))}, - {"###userAgent###", nvl(request.getHeader("User-Agent"))} + {"###x-forwarded-for###", nvl(request.getHeader("X-Forwarded-For"))}, + {"###x-forwarded-host###", nvl(request.getHeader("X-Forwarded-Host"))}, + {"###x-forwarded-proto###", nvl(request.getHeader("X-Forwarded-Proto"))}, + {"###x-forwarded-protocol###", nvl(request.getHeader("X-Forwarded-Protocol"))}, + {"###x-forwarded-server###", nvl(request.getHeader("X-Forwarded-Server"))}, + {"###x-forwarded-ssl###", nvl(request.getHeader("X-Forwarded-Ssl"))}, + {"###x-requested-with###", nvl(request.getHeader("X-Requested-With"))}, + {"###x-do-not-track###", nvl(request.getHeader("X-Do-Not-Track"))}, + {"###dnt###", nvl(request.getHeader("DNT"))}, + {"###via###", nvl(request.getHeader("Via"))}, + {"###ip###", request.getRemoteHost()}, + {"###user###", nvl(remoteUser)}, + {"###time###", "[" + date + "]"}, + {"###uriLine###", uriLine}, + {"###status###", "" + status}, + {"###size###", "" + size}, + {"###referer###", nvl(request.getHeader("Referer"))}, + {"###userAgent###", nvl(request.getHeader("User-Agent"))} }); this.outWriter.println(logLine); } diff --git a/src/main/java/winstone/cmdline/CmdLineParser.java b/src/main/java/winstone/cmdline/CmdLineParser.java index ea6e0e8c..4afc4f6a 100644 --- a/src/main/java/winstone/cmdline/CmdLineParser.java +++ b/src/main/java/winstone/cmdline/CmdLineParser.java @@ -1,9 +1,6 @@ package winstone.cmdline; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import winstone.Launcher; -import winstone.Logger; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -13,6 +10,8 @@ import java.util.Map; import java.util.Properties; import java.util.logging.Level; +import winstone.Launcher; +import winstone.Logger; /** * Command line argument parser, Winstone style. @@ -27,17 +26,15 @@ public CmdLineParser(List> options) { } @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "TODO needs triage") - public Map parse(String[] argv, String nonSwitchArgName) throws IOException { - Map args = new HashMap<>(); + public Map parse(String[] argv, String nonSwitchArgName) throws IOException { + Map args = new HashMap<>(); // Load embedded properties file - String embeddedPropertiesFilename = Launcher.RESOURCES.getString( - "Launcher.EmbeddedPropertiesFile"); + String embeddedPropertiesFilename = Launcher.RESOURCES.getString("Launcher.EmbeddedPropertiesFile"); - try (InputStream embeddedPropsStream = Launcher.class.getResourceAsStream( - embeddedPropertiesFilename)) { - if ( embeddedPropsStream != null ) { - loadPropsFromStream( embeddedPropsStream, args ); + try (InputStream embeddedPropsStream = Launcher.class.getResourceAsStream(embeddedPropertiesFilename)) { + if (embeddedPropsStream != null) { + loadPropsFromStream(embeddedPropsStream, args); } } @@ -46,26 +43,27 @@ public Map parse(String[] argv, String nonSwitchArgName) throws I for (String option : argv) { if (option.startsWith("--")) { int equalPos = option.indexOf('='); - String paramName = option.substring(2, - equalPos == -1 ? option.length() : equalPos); + String paramName = option.substring(2, equalPos == -1 ? option.length() : equalPos); Option opt = toOption(paramName); if (opt == null) - throw new IllegalArgumentException(Launcher.RESOURCES.getString("CmdLineParser.UnrecognizedOption", option)); + throw new IllegalArgumentException( + Launcher.RESOURCES.getString("CmdLineParser.UnrecognizedOption", option)); if (equalPos != -1) { args.put(paramName, option.substring(equalPos + 1)); } else { - if (opt.type == Boolean.class) - args.put(paramName, "true"); + if (opt.type == Boolean.class) args.put(paramName, "true"); else - throw new IllegalArgumentException(Launcher.RESOURCES.getString("CmdLineParser.OperandExpected", option)); + throw new IllegalArgumentException( + Launcher.RESOURCES.getString("CmdLineParser.OperandExpected", option)); } if (paramName.equals(Option.CONFIG.name)) { configFilename = args.get(paramName); } } else { if (args.containsKey(nonSwitchArgName)) - throw new IllegalArgumentException(Launcher.RESOURCES.getString("CmdLineParser.MultipleArgs", option)); + throw new IllegalArgumentException( + Launcher.RESOURCES.getString("CmdLineParser.MultipleArgs", option)); args.put(nonSwitchArgName, option); } } @@ -74,10 +72,10 @@ public Map parse(String[] argv, String nonSwitchArgName) throws I File configFile = new File(configFilename); if (configFile.exists() && configFile.isFile()) { try (InputStream inConfig = new FileInputStream(configFile)) { - loadPropsFromStream( inConfig, args ); + loadPropsFromStream(inConfig, args); inConfig.close(); - Launcher.initLogger( args ); - Logger.log(Level.FINER, Launcher.RESOURCES, "Launcher.UsingPropertyFile", configFilename ); + Launcher.initLogger(args); + Logger.log(Level.FINER, Launcher.RESOURCES, "Launcher.UsingPropertyFile", configFilename); } } else { Launcher.initLogger(args); @@ -85,7 +83,7 @@ public Map parse(String[] argv, String nonSwitchArgName) throws I return args; } - private static void loadPropsFromStream(InputStream inConfig, Map args) throws IOException { + private static void loadPropsFromStream(InputStream inConfig, Map args) throws IOException { Properties props = new Properties(); props.load(inConfig); for (Object o : props.keySet()) { @@ -99,10 +97,8 @@ private static void loadPropsFromStream(InputStream inConfig, Map private Option toOption(String paramName) { for (Option o : options) { - if (o.isWildcard() && paramName.startsWith(o.name)) - return o; - if (!o.isWildcard() && paramName.equals(o.name)) - return o; + if (o.isWildcard() && paramName.startsWith(o.name)) return o; + if (!o.isWildcard() && paramName.equals(o.name)) return o; } return null; } diff --git a/src/main/java/winstone/cmdline/Option.java b/src/main/java/winstone/cmdline/Option.java index eea378ac..57b593ac 100644 --- a/src/main/java/winstone/cmdline/Option.java +++ b/src/main/java/winstone/cmdline/Option.java @@ -8,13 +8,12 @@ import java.util.List; import java.util.Map; import java.util.logging.Level; - import winstone.Launcher; import winstone.realm.ArgumentsRealm; /** * Command line options used in {@link Launcher}. - * + * * @author Kohsuke Kawaguchi */ public class Option { @@ -28,85 +27,88 @@ public static List> all(Class clazz) { try { r.add((Option) f.get(null)); } catch (IllegalAccessException e) { - throw (Error)new IllegalAccessError().initCause(e); + throw (Error) new IllegalAccessError().initCause(e); } } } return r; } - - public static final OFile WEBROOT=file("webroot"); - public static final OFile WARFILE=file("warfile"); - public static final OFile JAVA_HOME=file("javaHome"); - public static final OFile CONFIG=file("config"); - public static final OString PREFIX=string("prefix",""); - public static final OFile COMMON_LIB_FOLDER=file("commonLibFolder"); - public static final OFile LOGFILE=file("logfile"); - public static final OFile EXTRA_LIB_FOLDER=file("extraLibFolder"); - public static final OBoolean LOG_THROWING_LINE_NO=bool("logThrowingLineNo",false); - public static final OBoolean LOG_THROWING_THREAD=bool("logThrowingThread",false); + + public static final OFile WEBROOT = file("webroot"); + public static final OFile WARFILE = file("warfile"); + public static final OFile JAVA_HOME = file("javaHome"); + public static final OFile CONFIG = file("config"); + public static final OString PREFIX = string("prefix", ""); + public static final OFile COMMON_LIB_FOLDER = file("commonLibFolder"); + public static final OFile LOGFILE = file("logfile"); + public static final OFile EXTRA_LIB_FOLDER = file("extraLibFolder"); + public static final OBoolean LOG_THROWING_LINE_NO = bool("logThrowingLineNo", false); + public static final OBoolean LOG_THROWING_THREAD = bool("logThrowingThread", false); public static final OInt DEBUG = new ODebugInt("debug", 5); // these are combined with protocol to form options private static final OInt _PORT = integer("Port"); private static final OString _LISTEN_ADDRESS = string("ListenAddress"); - private static final OString _UNIX_DOMAIN_PATH=string("UnixDomainPath"); + private static final OString _UNIX_DOMAIN_PATH = string("UnixDomainPath"); /** * Number of milliseconds for the HTTP keep-alive to hang around until the next request is sent. */ - private static final OInt _KEEP_ALIVE_TIMEOUT = integer("KeepAliveTimeout",30000); - - public static final OInt HTTP_PORT=integer("http"+_PORT,8080); - public static final OString HTTP_LISTEN_ADDRESS=string("http"+ _LISTEN_ADDRESS); - public static final OString HTTP_UNIX_DOMAIN_PATH=string("http"+ _UNIX_DOMAIN_PATH); - public static final OInt HTTP_KEEP_ALIVE_TIMEOUT=integer("http" + _KEEP_ALIVE_TIMEOUT, _KEEP_ALIVE_TIMEOUT.defaultValue); - - public static final OInt HTTPS_PORT=integer("https"+_PORT,-1); - public static final OString HTTPS_LISTEN_ADDRESS=string("https"+_LISTEN_ADDRESS); - public static final OInt HTTPS_KEEP_ALIVE_TIMEOUT=integer("https" + _KEEP_ALIVE_TIMEOUT, _KEEP_ALIVE_TIMEOUT.defaultValue); - public static final OFile HTTPS_KEY_STORE=file("httpsKeyStore"); - public static final OString HTTPS_KEY_STORE_PASSWORD=string("httpsKeyStorePassword"); - public static final OString HTTPS_PRIVATE_KEY_PASSWORD=string("httpsPrivateKeyPassword"); - public static final OString HTTPS_KEY_MANAGER_TYPE=string("httpsKeyManagerType","SunX509"); - public static final OString HTTPS_VERIFY_CLIENT=string("httpsVerifyClient","false"); - public static final OString HTTPS_CERTIFICATE_ALIAS=string("httpsCertificateAlias"); - public static final OString HTTPS_EXCLUDE_PROTOCOLS=string("excludeProtocols", "SSL, SSLv2, SSLv2Hello, SSLv3"); - public static final OString HTTPS_EXCLUDE_CIPHER_SUITES=string("excludeCipherSuites"); - public static final OBoolean HTTPS_REDIRECT_HTTP=bool("httpsRedirectHttp", false); - public static final OBoolean HTTPS_SNI_HOST_CHECK=bool("httpsSniHostCheck", false); - public static final OBoolean HTTPS_SNI_REQUIRED=bool("httpsSniRequired", false); - - public static final OString HTTP2_LISTEN_ADDRESS=string("http2"+_LISTEN_ADDRESS); - public static final OInt HTTP2_PORT=integer("http2"+_PORT,-1); - - public static final OInt CONTROL_PORT=integer("controlPort",-1); - - public static final OBoolean USE_JMX=bool("useJmx",false); - - public static final OInt QTP_MAXTHREADS=integer("qtpMaxThreadsCount",-1); - public static final OInt JETTY_ACCEPTORS=integer("jettyAcceptorsCount",-1); - public static final OInt JETTY_SELECTORS=integer("jettySelectorsCount",0); - - public static final OString MIME_TYPES=string("mimeTypes"); - public static final OInt MAX_PARAM_COUNT=integer("maxParamCount",-1); - public static final OBoolean USAGE=bool("usage",false); - public static final OInt SESSION_TIMEOUT=integer("sessionTimeout",-1); - public static final OInt SESSION_EVICTION=integer("sessionEviction",1800); - public static final OInt REQUEST_HEADER_SIZE=integer("requestHeaderSize",8192); // default for jetty 9 - public static final OInt RESPONSE_HEADER_SIZE=integer("responseHeaderSize",8192); // default for jetty 9 - public static final OInt REQUEST_FORM_CONTENT_SIZE=integer("requestFormContentSize",-1); // no limit (compat with old winstone) - public static final OBoolean HELP=bool("help",false); - - public static final OClass REALM_CLASS_NAME=clazz("realmClassName", ArgumentsRealm.class); - - public static final OString ARGUMENTS_REALM_PASSWORD=string("argumentsRealm.passwd."); - public static final OString ARGUMENTS_REALM_ROLES=string("argumentsRealm.roles."); - public static final OFile FILEREALM_CONFIGFILE=file("fileRealm.configFile"); - - public static final OClass ACCESS_LOGGER_CLASSNAME=clazz("accessLoggerClassName",null); - public static final OString SIMPLE_ACCESS_LOGGER_FORMAT=string("simpleAccessLogger.format","combined"); - public static final OString SIMPLE_ACCESS_LOGGER_FILE=string("simpleAccessLogger.file","logs/###host###/###webapp###_access.log"); - + private static final OInt _KEEP_ALIVE_TIMEOUT = integer("KeepAliveTimeout", 30000); + + public static final OInt HTTP_PORT = integer("http" + _PORT, 8080); + public static final OString HTTP_LISTEN_ADDRESS = string("http" + _LISTEN_ADDRESS); + public static final OString HTTP_UNIX_DOMAIN_PATH = string("http" + _UNIX_DOMAIN_PATH); + public static final OInt HTTP_KEEP_ALIVE_TIMEOUT = + integer("http" + _KEEP_ALIVE_TIMEOUT, _KEEP_ALIVE_TIMEOUT.defaultValue); + + public static final OInt HTTPS_PORT = integer("https" + _PORT, -1); + public static final OString HTTPS_LISTEN_ADDRESS = string("https" + _LISTEN_ADDRESS); + public static final OInt HTTPS_KEEP_ALIVE_TIMEOUT = + integer("https" + _KEEP_ALIVE_TIMEOUT, _KEEP_ALIVE_TIMEOUT.defaultValue); + public static final OFile HTTPS_KEY_STORE = file("httpsKeyStore"); + public static final OString HTTPS_KEY_STORE_PASSWORD = string("httpsKeyStorePassword"); + public static final OString HTTPS_PRIVATE_KEY_PASSWORD = string("httpsPrivateKeyPassword"); + public static final OString HTTPS_KEY_MANAGER_TYPE = string("httpsKeyManagerType", "SunX509"); + public static final OString HTTPS_VERIFY_CLIENT = string("httpsVerifyClient", "false"); + public static final OString HTTPS_CERTIFICATE_ALIAS = string("httpsCertificateAlias"); + public static final OString HTTPS_EXCLUDE_PROTOCOLS = string("excludeProtocols", "SSL, SSLv2, SSLv2Hello, SSLv3"); + public static final OString HTTPS_EXCLUDE_CIPHER_SUITES = string("excludeCipherSuites"); + public static final OBoolean HTTPS_REDIRECT_HTTP = bool("httpsRedirectHttp", false); + public static final OBoolean HTTPS_SNI_HOST_CHECK = bool("httpsSniHostCheck", false); + public static final OBoolean HTTPS_SNI_REQUIRED = bool("httpsSniRequired", false); + + public static final OString HTTP2_LISTEN_ADDRESS = string("http2" + _LISTEN_ADDRESS); + public static final OInt HTTP2_PORT = integer("http2" + _PORT, -1); + + public static final OInt CONTROL_PORT = integer("controlPort", -1); + + public static final OBoolean USE_JMX = bool("useJmx", false); + + public static final OInt QTP_MAXTHREADS = integer("qtpMaxThreadsCount", -1); + public static final OInt JETTY_ACCEPTORS = integer("jettyAcceptorsCount", -1); + public static final OInt JETTY_SELECTORS = integer("jettySelectorsCount", 0); + + public static final OString MIME_TYPES = string("mimeTypes"); + public static final OInt MAX_PARAM_COUNT = integer("maxParamCount", -1); + public static final OBoolean USAGE = bool("usage", false); + public static final OInt SESSION_TIMEOUT = integer("sessionTimeout", -1); + public static final OInt SESSION_EVICTION = integer("sessionEviction", 1800); + public static final OInt REQUEST_HEADER_SIZE = integer("requestHeaderSize", 8192); // default for jetty 9 + public static final OInt RESPONSE_HEADER_SIZE = integer("responseHeaderSize", 8192); // default for jetty 9 + public static final OInt REQUEST_FORM_CONTENT_SIZE = + integer("requestFormContentSize", -1); // no limit (compat with old winstone) + public static final OBoolean HELP = bool("help", false); + + public static final OClass REALM_CLASS_NAME = clazz("realmClassName", ArgumentsRealm.class); + + public static final OString ARGUMENTS_REALM_PASSWORD = string("argumentsRealm.passwd."); + public static final OString ARGUMENTS_REALM_ROLES = string("argumentsRealm.roles."); + public static final OFile FILEREALM_CONFIGFILE = file("fileRealm.configFile"); + + public static final OClass ACCESS_LOGGER_CLASSNAME = clazz("accessLoggerClassName", null); + public static final OString SIMPLE_ACCESS_LOGGER_FORMAT = string("simpleAccessLogger.format", "combined"); + public static final OString SIMPLE_ACCESS_LOGGER_FILE = + string("simpleAccessLogger.file", "logs/###host###/###webapp###_access.log"); /** * Option name without the "--" prefix. @@ -117,7 +119,7 @@ public static List> all(Class clazz) { * Expected type. */ public final Class type; - + public final T defaultValue; public Option(String name, Class type, T defaultValue) { @@ -125,7 +127,7 @@ public Option(String name, Class type, T defaultValue) { this.type = type; this.defaultValue = defaultValue; } - + public void remove(Map args) { args.remove(name); } @@ -133,7 +135,7 @@ public void remove(Map args) { public void put(Map args, String value) { args.put(name, value); } - + public boolean isIn(Map args) { return args.containsKey(name); } @@ -151,15 +153,15 @@ public String toString() { } public static OString string(String name) { - return new OString(name,null); + return new OString(name, null); } - + public static OString string(String name, String defaultValue) { - return new OString(name,defaultValue); + return new OString(name, defaultValue); } - + public static OBoolean bool(String name, boolean defaultValue) { - return new OBoolean(name,defaultValue); + return new OBoolean(name, defaultValue); } public static OFile file(String name) { @@ -167,31 +169,31 @@ public static OFile file(String name) { } public static OClass clazz(String name, Class defaultValue) { - return new OClass(name,defaultValue); + return new OClass(name, defaultValue); } public static OInt integer(String name) { - return new OInt(name,-1); + return new OInt(name, -1); } - - public static OInt integer(String name,int defaultValue) { - return new OInt(name,defaultValue); + + public static OInt integer(String name, int defaultValue) { + return new OInt(name, defaultValue); } public static class OBoolean extends Option { public OBoolean(String name, boolean defaultValue) { super(name, Boolean.class, defaultValue); } - + public boolean get(Map args) { - return get(args,defaultValue); + return get(args, defaultValue); } public boolean get(Map args, boolean defaultValue) { return booleanArg(args, name, defaultValue); } } - + public static class OInt extends Option { public OInt(String name, int defaultValue) { super(name, Integer.class, defaultValue); @@ -215,7 +217,7 @@ public ODebugInt(String name, int defaultValue) { @Override public int get(Map args) { switch (super.get(args)) { - // before switching to java.util.Logging, winstone used a (1:9) range for log levels + // before switching to java.util.Logging, winstone used a (1:9) range for log levels case 1: return Level.OFF.intValue(); case 2: @@ -243,76 +245,76 @@ public static class OString extends Option { public OString(String name, String defaultValue) { super(name, String.class, defaultValue); } - + public String get(Map args) { - return get(args,defaultValue); + return get(args, defaultValue); } public char[] getCharArray(Map args) { String v = get(args); - return v!=null ? v.toCharArray() : null; + return v != null ? v.toCharArray() : null; } public String get(Map args, String defaultValue) { String v = args.get(name); - return v!=null ? v : defaultValue; + return v != null ? v : defaultValue; } } public static class OFile extends Option { public OFile(String name) { - super(name, File.class,null); + super(name, File.class, null); } @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "false positive, args come from command line") public File get(Map args, File defaultValue) { String v = args.get(name); - return v!=null ? new File(v) : defaultValue; + return v != null ? new File(v) : defaultValue; } public File get(Map args) { - return get(args,null); + return get(args, null); } } - + public static class OClass extends Option { - public OClass(String name,Class defaultValue) { + public OClass(String name, Class defaultValue) { super(name, Class.class, defaultValue); } - public Class get(Map args, Class expectedType) throws ClassNotFoundException { - return get(args,expectedType,getClass().getClassLoader()); + public Class get(Map args, Class expectedType) + throws ClassNotFoundException { + return get(args, expectedType, getClass().getClassLoader()); } - - public Class get(Map args, Class expectedType, ClassLoader cl) throws ClassNotFoundException { + + public Class get(Map args, Class expectedType, ClassLoader cl) + throws ClassNotFoundException { String v = args.get(name); - if (v==null) return defaultValue; - - v=v.trim(); - if (v.length()==0) return defaultValue; + if (v == null) return defaultValue; + + v = v.trim(); + if (v.length() == 0) return defaultValue; Class c = Class.forName(v, true, cl); if (!expectedType.isAssignableFrom(c)) - throw new ClassNotFoundException("Expected a subype of "+expectedType+" but got "+c+" instead"); + throw new ClassNotFoundException("Expected a subype of " + expectedType + " but got " + c + " instead"); return c.asSubclass(expectedType); } } - + // static { -// String[] protocols = {"http","https"}; -// for (int i=0; i args, String name, boolean defaultTrue) { String value = args.get(name); - if (defaultTrue) - return (value == null) || (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); - else - return (value != null) && (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); + if (defaultTrue) return (value == null) || (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); + else return (value != null) && (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); } public static String stringArg(Map args, String name, String defaultValue) { @@ -322,5 +324,4 @@ public static String stringArg(Map args, String name, String def public static int intArg(Map args, String name, int defaultValue) { return Integer.parseInt(stringArg(args, name, "" + defaultValue)); } - } diff --git a/src/main/java/winstone/realm/ArgumentsRealm.java b/src/main/java/winstone/realm/ArgumentsRealm.java index e13f2599..c5edca0a 100644 --- a/src/main/java/winstone/realm/ArgumentsRealm.java +++ b/src/main/java/winstone/realm/ArgumentsRealm.java @@ -6,31 +6,31 @@ */ package winstone.realm; -import org.eclipse.jetty.security.HashLoginService; -import org.eclipse.jetty.security.UserStore; -import org.eclipse.jetty.util.security.Credential; -import winstone.Logger; -import winstone.WinstoneResourceBundle; -import winstone.cmdline.Option; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.logging.Level; +import org.eclipse.jetty.security.HashLoginService; +import org.eclipse.jetty.security.UserStore; +import org.eclipse.jetty.util.security.Credential; +import winstone.Logger; +import winstone.WinstoneResourceBundle; +import winstone.cmdline.Option; /** * Base class for authentication realms. Subclasses provide the source of * authentication roles, usernames, passwords, etc, and when asked for * validation respond with a role if valid, or null otherwise. - * + * * @author mailto: Rick Knowles * @author Kohsuke Kawaguchi * @version $Id: ArgumentsRealm.java,v 1.4 2007/06/01 15:55:41 rickknowles Exp $ */ public class ArgumentsRealm extends HashLoginService { - private static final WinstoneResourceBundle REALM_RESOURCES = new WinstoneResourceBundle("winstone.realm.LocalStrings"); + private static final WinstoneResourceBundle REALM_RESOURCES = + new WinstoneResourceBundle("winstone.realm.LocalStrings"); /** * Constructor - this sets up an authentication realm, using the arguments @@ -38,8 +38,8 @@ public class ArgumentsRealm extends HashLoginService { */ public ArgumentsRealm(Map args) { UserStore userStore = new UserStore(); - setUserStore( userStore ); - int count=0; + setUserStore(userStore); + int count = 0; for (Map.Entry entry : args.entrySet()) { String key = entry.getKey(); if (key.startsWith(Option.ARGUMENTS_REALM_PASSWORD.name)) { @@ -65,7 +65,6 @@ public ArgumentsRealm(Map args) { } } - Logger.log(Level.FINER, REALM_RESOURCES, "ArgumentsRealm.Initialised", - "" + count); + Logger.log(Level.FINER, REALM_RESOURCES, "ArgumentsRealm.Initialised", "" + count); } } diff --git a/src/main/java/winstone/realm/FileRealm.java b/src/main/java/winstone/realm/FileRealm.java index c98d8b1a..b3eee4eb 100644 --- a/src/main/java/winstone/realm/FileRealm.java +++ b/src/main/java/winstone/realm/FileRealm.java @@ -6,19 +6,6 @@ */ package winstone.realm; -import org.eclipse.jetty.security.HashLoginService; -import org.eclipse.jetty.security.UserStore; -import org.eclipse.jetty.util.security.Credential; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import winstone.Logger; -import winstone.WinstoneException; -import winstone.WinstoneResourceBundle; -import winstone.cmdline.Option; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; @@ -28,13 +15,26 @@ import java.util.Map; import java.util.StringTokenizer; import java.util.logging.Level; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import org.eclipse.jetty.security.HashLoginService; +import org.eclipse.jetty.security.UserStore; +import org.eclipse.jetty.util.security.Credential; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import winstone.Logger; +import winstone.WinstoneException; +import winstone.WinstoneResourceBundle; +import winstone.cmdline.Option; /** * @author rickk * @version $Id: FileRealm.java,v 1.4 2006/08/30 04:07:52 rickknowles Exp $ */ public class FileRealm extends HashLoginService { - private static final WinstoneResourceBundle REALM_RESOURCES = new WinstoneResourceBundle("winstone.realm.LocalStrings"); + private static final WinstoneResourceBundle REALM_RESOURCES = + new WinstoneResourceBundle("winstone.realm.LocalStrings"); static final String DEFAULT_FILE_NAME = "users.xml"; static final String ELEM_USER = "user"; @@ -48,15 +48,14 @@ public class FileRealm extends HashLoginService { */ public FileRealm(Map args) { UserStore userStore = new UserStore(); - setUserStore( userStore ); + setUserStore(userStore); // Get the filename and parse the xml doc File realmFile = Option.FILEREALM_CONFIGFILE.get(args); - if (realmFile==null) realmFile = new File(DEFAULT_FILE_NAME); + if (realmFile == null) realmFile = new File(DEFAULT_FILE_NAME); if (!realmFile.exists()) - throw new WinstoneException(REALM_RESOURCES.getString( - "FileRealm.FileNotFound", realmFile.getPath())); - try (InputStream inFile = new FileInputStream(realmFile)){ - int count=0; + throw new WinstoneException(REALM_RESOURCES.getString("FileRealm.FileNotFound", realmFile.getPath())); + try (InputStream inFile = new FileInputStream(realmFile)) { + int count = 0; Document doc = this.parseStreamToXML(inFile); Node rootElm = doc.getDocumentElement(); for (int n = 0; n < rootElm.getChildNodes().getLength(); n++) { @@ -70,18 +69,13 @@ public FileRealm(Map args) { // Loop through for attributes for (int j = 0; j < child.getAttributes().getLength(); j++) { Node thisAtt = child.getAttributes().item(j); - if (thisAtt.getNodeName().equals(ATT_USERNAME)) - userName = thisAtt.getNodeValue(); - else if (thisAtt.getNodeName().equals(ATT_PASSWORD)) - password = thisAtt.getNodeValue(); - else if (thisAtt.getNodeName().equals(ATT_ROLELIST)) - roleList = thisAtt.getNodeValue(); + if (thisAtt.getNodeName().equals(ATT_USERNAME)) userName = thisAtt.getNodeValue(); + else if (thisAtt.getNodeName().equals(ATT_PASSWORD)) password = thisAtt.getNodeValue(); + else if (thisAtt.getNodeName().equals(ATT_ROLELIST)) roleList = thisAtt.getNodeValue(); } - if ((userName == null) || (password == null) - || (roleList == null)) - Logger.log(Level.FINEST, REALM_RESOURCES, - "FileRealm.SkippingUser", userName); + if ((userName == null) || (password == null) || (roleList == null)) + Logger.log(Level.FINEST, REALM_RESOURCES, "FileRealm.SkippingUser", userName); else { // Parse the role list into an array and sort it StringTokenizer st = new StringTokenizer(roleList, ","); @@ -97,11 +91,9 @@ else if (thisAtt.getNodeName().equals(ATT_ROLELIST)) } } } - Logger.log(Level.FINER, REALM_RESOURCES, "FileRealm.Initialised", - "" + count); + Logger.log(Level.FINER, REALM_RESOURCES, "FileRealm.Initialised", "" + count); } catch (java.io.IOException err) { - throw new WinstoneException(REALM_RESOURCES - .getString("FileRealm.ErrorLoading"), err); + throw new WinstoneException(REALM_RESOURCES.getString("FileRealm.ErrorLoading"), err); } } @@ -125,8 +117,7 @@ private Document parseStreamToXML(InputStream in) { DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(in); } catch (Throwable errParser) { - throw new WinstoneException(REALM_RESOURCES - .getString("FileRealm.XMLParseError"), errParser); + throw new WinstoneException(REALM_RESOURCES.getString("FileRealm.XMLParseError"), errParser); } } } diff --git a/src/main/java/winstone/tools/WinstoneControl.java b/src/main/java/winstone/tools/WinstoneControl.java index 15ed910a..b1c1e43b 100644 --- a/src/main/java/winstone/tools/WinstoneControl.java +++ b/src/main/java/winstone/tools/WinstoneControl.java @@ -6,6 +6,11 @@ */ package winstone.tools; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.util.Map; +import java.util.logging.Level; import winstone.Launcher; import winstone.Logger; import winstone.WinstoneResourceBundle; @@ -15,12 +20,6 @@ import winstone.cmdline.Option.OInt; import winstone.cmdline.Option.OString; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.net.Socket; -import java.util.Map; -import java.util.logging.Level; - /** * Included so that we can control winstone from the command line a little more * easily. @@ -29,17 +28,17 @@ * @version $Id: WinstoneControl.java,v 1.6 2006/03/13 15:37:29 rickknowles Exp $ */ public class WinstoneControl { - private final static WinstoneResourceBundle TOOLS_RESOURCES = new WinstoneResourceBundle("winstone.tools.LocalStrings"); + private static final WinstoneResourceBundle TOOLS_RESOURCES = + new WinstoneResourceBundle("winstone.tools.LocalStrings"); - final static String OPERATION_SHUTDOWN = "shutdown"; - final static String OPERATION_RELOAD = "reload:"; + static final String OPERATION_SHUTDOWN = "shutdown"; + static final String OPERATION_RELOAD = "reload:"; static int TIMEOUT = 10000; - public final static OInt CONTROL_PORT = Option.integer("controlPort"); - public final static OInt PORT = Option.integer("port"); - public final static OInt DEBUG = new ODebugInt("debug", 5); - public final static OString HOST = Option.string("host", "localhost"); - + public static final OInt CONTROL_PORT = Option.integer("controlPort"); + public static final OInt PORT = Option.integer("port"); + public static final OInt DEBUG = new ODebugInt("debug", 5); + public static final OString HOST = Option.string("host", "localhost"); /** * Parses command line parameters, and calls the appropriate method for @@ -48,7 +47,7 @@ public class WinstoneControl { public static void main(String[] argv) throws Exception { // Load args from the config file - Map options = new CmdLineParser(Option.all(WinstoneControl.class)).parse(argv,"operation"); + Map options = new CmdLineParser(Option.all(WinstoneControl.class)).parse(argv, "operation"); String operation = options.get("operation"); if (operation.equals("")) { @@ -61,15 +60,15 @@ public static void main(String[] argv) throws Exception { String host = HOST.get(options); int port = PORT.get(options, CONTROL_PORT.get(options)); - Logger.log(Level.INFO, TOOLS_RESOURCES, "WinstoneControl.UsingHostPort",host, port); + Logger.log(Level.INFO, TOOLS_RESOURCES, "WinstoneControl.UsingHostPort", host, port); // Check for shutdown if (operation.equalsIgnoreCase(OPERATION_SHUTDOWN)) { Socket socket = new Socket(host, port); socket.setSoTimeout(TIMEOUT); - try(OutputStream out = socket.getOutputStream()){ - out.write( Launcher.SHUTDOWN_TYPE ); - Logger.log(Level.INFO, TOOLS_RESOURCES, "WinstoneControl.ShutdownOK", host, port ); + try (OutputStream out = socket.getOutputStream()) { + out.write(Launcher.SHUTDOWN_TYPE); + Logger.log(Level.INFO, TOOLS_RESOURCES, "WinstoneControl.ShutdownOK", host, port); } } @@ -78,15 +77,14 @@ else if (operation.toLowerCase().startsWith(OPERATION_RELOAD.toLowerCase())) { String webappName = operation.substring(OPERATION_RELOAD.length()); Socket socket = new Socket(host, port); socket.setSoTimeout(TIMEOUT); - try(OutputStream out = socket.getOutputStream(); // - ObjectOutputStream objOut = new ObjectOutputStream( out )) { - out.write( Launcher.RELOAD_TYPE ); - objOut.writeUTF( host ); - objOut.writeUTF( webappName ); + try (OutputStream out = socket.getOutputStream(); // + ObjectOutputStream objOut = new ObjectOutputStream(out)) { + out.write(Launcher.RELOAD_TYPE); + objOut.writeUTF(host); + objOut.writeUTF(webappName); } - Logger.log(Level.INFO, TOOLS_RESOURCES, "WinstoneControl.ReloadOK",host, port); - } - else { + Logger.log(Level.INFO, TOOLS_RESOURCES, "WinstoneControl.ReloadOK", host, port); + } else { printUsage(); } } diff --git a/src/main/java/winstone/tools/WinstoneControlOption.java b/src/main/java/winstone/tools/WinstoneControlOption.java index 0241b68b..d1e5b9bb 100644 --- a/src/main/java/winstone/tools/WinstoneControlOption.java +++ b/src/main/java/winstone/tools/WinstoneControlOption.java @@ -3,5 +3,4 @@ /** * @author Kohsuke Kawaguchi */ -public class WinstoneControlOption { -} +public class WinstoneControlOption {} diff --git a/src/test/java/winstone/AbstractWinstoneTest.java b/src/test/java/winstone/AbstractWinstoneTest.java index 6b7f3afb..6747aa63 100644 --- a/src/test/java/winstone/AbstractWinstoneTest.java +++ b/src/test/java/winstone/AbstractWinstoneTest.java @@ -6,7 +6,6 @@ import java.net.ConnectException; import java.net.Socket; import java.nio.file.Path; - import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.dynamic.HttpClientTransportDynamic; @@ -14,7 +13,6 @@ import org.eclipse.jetty.io.ClientConnector; import org.junit.After; - /** * @author Kohsuke Kawaguchi */ @@ -23,26 +21,22 @@ public class AbstractWinstoneTest { @After public void tearDown() { - if (winstone!=null) - winstone.shutdown(); + if (winstone != null) winstone.shutdown(); } - public String makeRequest(String url) - throws Exception { + public String makeRequest(String url) throws Exception { return makeRequest(null, url); } - public String makeRequest(String path, String url) - throws Exception { + public String makeRequest(String path, String url) throws Exception { HttpClient httpClient; - if (path != null) { + if (path != null) { Path unixDomainPath = Path.of(path); ClientConnector clientConnector = ClientConnector.forUnixDomain(unixDomainPath); httpClient = new HttpClient(new HttpClientTransportDynamic(clientConnector)); - } - else { + } else { httpClient = new HttpClient(); } httpClient.start(); diff --git a/src/test/java/winstone/FormSubmissionTest.java b/src/test/java/winstone/FormSubmissionTest.java index 37dda2e1..531c2fee 100644 --- a/src/test/java/winstone/FormSubmissionTest.java +++ b/src/test/java/winstone/FormSubmissionTest.java @@ -9,7 +9,6 @@ import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; - import org.eclipse.jetty.server.ServerConnector; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -19,7 +18,7 @@ public class FormSubmissionTest extends AbstractWinstoneTest { @Issue("JENKINS-60409") @Test public void largeForm() throws Exception { - Map args = new HashMap<>(); + Map args = new HashMap<>(); args.put("warfile", "target/test-classes/test.war"); args.put("prefix", "/"); args.put("httpPort", "0"); @@ -28,7 +27,7 @@ public void largeForm() throws Exception { args.put("requestFormContentSize", "999"); */ winstone = new Launcher(args); - int port = ((ServerConnector)winstone.server.getConnectors()[0]).getLocalPort(); + int port = ((ServerConnector) winstone.server.getConnectors()[0]).getLocalPort(); for (int size = 1; size <= 9_999_999; size *= 3) { System.out.println("trying size " + size); HttpRequest request = HttpRequest.newBuilder(new URI("http://127.0.0.2:" + port + "/AcceptFormServlet")) @@ -37,8 +36,10 @@ public void largeForm() throws Exception { HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(HttpURLConnection.HTTP_OK, response.statusCode()); - assertEquals("correct response at size " + size, "received " + (size + "x=".length()) + " bytes", response.body()); + assertEquals( + "correct response at size " + size, + "received " + (size + "x=".length()) + " bytes", + response.body()); } } - } diff --git a/src/test/java/winstone/Http2ConnectorFactoryTest.java b/src/test/java/winstone/Http2ConnectorFactoryTest.java index 82224ab4..e1f2e6fa 100644 --- a/src/test/java/winstone/Http2ConnectorFactoryTest.java +++ b/src/test/java/winstone/Http2ConnectorFactoryTest.java @@ -5,10 +5,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import org.eclipse.jetty.server.LowResourceMonitor; -import org.eclipse.jetty.server.ServerConnector; -import org.junit.Test; - import java.net.HttpURLConnection; import java.net.URI; import java.net.http.HttpClient; @@ -16,14 +12,15 @@ import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; - import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; +import org.eclipse.jetty.server.LowResourceMonitor; +import org.eclipse.jetty.server.ServerConnector; +import org.junit.Test; public class Http2ConnectorFactoryTest extends AbstractWinstoneTest { - private static final String DISABLE_HOSTNAME_VERIFICATION = - "jdk.internal.httpclient.disableHostnameVerification"; + private static final String DISABLE_HOSTNAME_VERIFICATION = "jdk.internal.httpclient.disableHostnameVerification"; private String request(X509TrustManager tm, int port) throws Exception { String disableHostnameVerification = System.getProperty(DISABLE_HOSTNAME_VERIFICATION); @@ -36,8 +33,7 @@ private String request(X509TrustManager tm, int port) throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new X509TrustManager[] {tm}, null); HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build(); - HttpResponse response = - client.send(request, HttpResponse.BodyHandlers.ofString()); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(HttpURLConnection.HTTP_OK, response.statusCode()); return response.body(); } finally { diff --git a/src/test/java/winstone/HttpConnectorFactoryTest.java b/src/test/java/winstone/HttpConnectorFactoryTest.java index 7253dcb7..c76a636b 100644 --- a/src/test/java/winstone/HttpConnectorFactoryTest.java +++ b/src/test/java/winstone/HttpConnectorFactoryTest.java @@ -1,5 +1,12 @@ package winstone; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static winstone.Launcher.WINSTONE_PORT_FILE_NAME_PROPERTY; + import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -18,13 +25,6 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static winstone.Launcher.WINSTONE_PORT_FILE_NAME_PROPERTY; - /** * @author Kohsuke Kawaguchi */ @@ -35,15 +35,14 @@ public class HttpConnectorFactoryTest extends AbstractWinstoneTest { @Test public void testListenUnixDomainPath() throws Exception { - Map args = new HashMap<>(); + Map args = new HashMap<>(); args.put("warfile", "target/test-classes/test.war"); args.put("prefix", "/"); args.put("httpUnixDomainPath", "target/jetty.socket"); - + try { winstone = new Launcher(args); - } - catch (IOException ioe) { + } catch (IOException ioe) { if (ioe.getCause() instanceof UnsupportedOperationException) { /* skip JDKs less than 16 */ return; @@ -51,7 +50,9 @@ public void testListenUnixDomainPath() throws Exception { throw ioe; } - String path = ((UnixDomainServerConnector)winstone.server.getConnectors()[0]).getUnixDomainPath().toString(); + String path = ((UnixDomainServerConnector) winstone.server.getConnectors()[0]) + .getUnixDomainPath() + .toString(); assertEquals( "This servlet has been accessed via GET 1001 times\r\n", @@ -65,15 +66,15 @@ public void testListenUnixDomainPath() throws Exception { @Test public void testListenAddress() throws Exception { - Map args = new HashMap<>(); + Map args = new HashMap<>(); args.put("warfile", "target/test-classes/test.war"); args.put("prefix", "/"); args.put("httpPort", "0"); // see README development section for getting this to work on macOS args.put("httpListenAddress", "127.0.0.2"); winstone = new Launcher(args); - int port = ((ServerConnector)winstone.server.getConnectors()[0]).getLocalPort(); - assertConnectionRefused("127.0.0.1",port); + int port = ((ServerConnector) winstone.server.getConnectors()[0]).getLocalPort(); + assertConnectionRefused("127.0.0.1", port); assertEquals( "This servlet has been accessed via GET 1001 times\r\n", diff --git a/src/test/java/winstone/HttpsConnectorFactoryTest.java b/src/test/java/winstone/HttpsConnectorFactoryTest.java index 81de0dda..38b972d3 100644 --- a/src/test/java/winstone/HttpsConnectorFactoryTest.java +++ b/src/test/java/winstone/HttpsConnectorFactoryTest.java @@ -5,13 +5,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import org.eclipse.jetty.server.HttpConnectionFactory; -import org.eclipse.jetty.server.LowResourceMonitor; -import org.eclipse.jetty.server.ServerConnector; -import org.junit.Test; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.X509TrustManager; import java.net.HttpURLConnection; import java.net.URI; import java.net.http.HttpClient; @@ -22,7 +15,12 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; - +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; +import org.eclipse.jetty.server.HttpConnectionFactory; +import org.eclipse.jetty.server.LowResourceMonitor; +import org.eclipse.jetty.server.ServerConnector; +import org.junit.Test; import org.jvnet.hudson.test.Issue; /** @@ -30,20 +28,19 @@ */ public class HttpsConnectorFactoryTest extends AbstractWinstoneTest { - private static final String DISABLE_HOSTNAME_VERIFICATION = - "jdk.internal.httpclient.disableHostnameVerification"; + private static final String DISABLE_HOSTNAME_VERIFICATION = "jdk.internal.httpclient.disableHostnameVerification"; private String request(X509TrustManager tm, int port) throws Exception { String disableHostnameVerification = System.getProperty(DISABLE_HOSTNAME_VERIFICATION); try { System.setProperty(DISABLE_HOSTNAME_VERIFICATION, Boolean.TRUE.toString()); - HttpRequest request = - HttpRequest.newBuilder(new URI("https://localhost:" + port + "/CountRequestsServlet")).GET().build(); + HttpRequest request = HttpRequest.newBuilder(new URI("https://localhost:" + port + "/CountRequestsServlet")) + .GET() + .build(); SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new X509TrustManager[] {tm}, null); HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build(); - HttpResponse response = - client.send(request, HttpResponse.BodyHandlers.ofString()); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(HttpURLConnection.HTTP_OK, response.statusCode()); return response.body(); } finally { @@ -54,11 +51,11 @@ private String request(X509TrustManager tm, int port) throws Exception { } } } - + @Issue("JENKINS-60857") @Test public void wildcard() throws Exception { - Map args = new HashMap<>(); + Map args = new HashMap<>(); args.put("warfile", "target/test-classes/test.war"); args.put("prefix", "/"); args.put("httpPort", "-1"); @@ -67,12 +64,12 @@ public void wildcard() throws Exception { args.put("httpsKeyStore", "src/ssl/wildcard.jks"); args.put("httpsKeyStorePassword", "changeit"); winstone = new Launcher(args); - int port = (( ServerConnector)winstone.server.getConnectors()[0]).getLocalPort(); + int port = ((ServerConnector) winstone.server.getConnectors()[0]).getLocalPort(); assertConnectionRefused("127.0.0.2", port); assertEquals( "This servlet has been accessed via GET 1001 times\r\n", request(new TrustEveryoneManager(), port)); - LowResourceMonitor lowResourceMonitor = winstone.server.getBean( LowResourceMonitor.class); + LowResourceMonitor lowResourceMonitor = winstone.server.getBean(LowResourceMonitor.class); assertNotNull(lowResourceMonitor); assertFalse(lowResourceMonitor.isLowOnResources()); assertTrue(lowResourceMonitor.isAcceptingInLowResources()); @@ -80,7 +77,7 @@ public void wildcard() throws Exception { @Test public void httpRedirect() throws Exception { - Map args = new HashMap<>(); + Map args = new HashMap<>(); args.put("warfile", "target/test-classes/test.war"); args.put("prefix", "/"); args.put("httpPort", "0"); @@ -89,19 +86,24 @@ public void httpRedirect() throws Exception { args.put("httpsKeyStorePassword", "changeit"); args.put("httpsRedirectHttp", "true"); winstone = new Launcher(args); - List serverConnectors = - Arrays.stream( winstone.server.getConnectors() ) - .map(connector -> (ServerConnector)connector ).collect(Collectors.toList()); + List serverConnectors = Arrays.stream(winstone.server.getConnectors()) + .map(connector -> (ServerConnector) connector) + .collect(Collectors.toList()); int httpsPort = serverConnectors.stream() - .filter(serverConnector -> serverConnector.getDefaultProtocol().startsWith("SSL")) - .findFirst().get().getLocalPort(); + .filter(serverConnector -> serverConnector.getDefaultProtocol().startsWith("SSL")) + .findFirst() + .get() + .getLocalPort(); ServerConnector scNonSsl = serverConnectors.stream() .filter(serverConnector -> !serverConnector.getDefaultProtocol().startsWith("SSL")) - .findFirst().get(); + .findFirst() + .get(); int httpPort = scNonSsl.getLocalPort(); - scNonSsl.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration().setSecurePort(httpsPort); + scNonSsl.getConnectionFactory(HttpConnectionFactory.class) + .getHttpConfiguration() + .setSecurePort(httpsPort); assertEquals( "This servlet has been accessed via GET 1001 times\r\n", @@ -114,10 +116,10 @@ public void httpRedirect() throws Exception { } private String requestRedirect(X509TrustManager tm, int httpPort, int httpsPort) throws Exception { - HttpRequest request = - HttpRequest.newBuilder(new URI("http://localhost:" + httpPort + "/CountRequestsServlet")).GET().build(); - HttpResponse response = - HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:" + httpPort + "/CountRequestsServlet")) + .GET() + .build(); + HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, response.statusCode()); assertTrue(response.body().isEmpty()); String newUrl = response.headers().firstValue("Location").orElse(null); @@ -142,5 +144,4 @@ private String requestRedirect(X509TrustManager tm, int httpPort, int httpsPort) } } } - } diff --git a/src/test/java/winstone/LauncherTest.java b/src/test/java/winstone/LauncherTest.java index 9e3d6d5f..e36504c7 100644 --- a/src/test/java/winstone/LauncherTest.java +++ b/src/test/java/winstone/LauncherTest.java @@ -4,9 +4,6 @@ import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertEquals; -import org.eclipse.jetty.server.ServerConnector; -import org.junit.Test; - import java.net.HttpURLConnection; import java.net.URI; import java.net.http.HttpClient; @@ -18,6 +15,8 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Filter; import java.util.logging.LogRecord; +import org.eclipse.jetty.server.ServerConnector; +import org.junit.Test; /** * @author Kohsuke Kawaguchi @@ -25,17 +24,17 @@ public class LauncherTest extends AbstractWinstoneTest { @Test public void mimeType() throws Exception { - Map args = new HashMap<>(); + Map args = new HashMap<>(); args.put("warfile", "target/test-classes/test.war"); args.put("prefix", "/"); args.put("httpPort", "0"); args.put("mimeTypes", "xxx=text/xxx"); winstone = new Launcher(args); - int port = ((ServerConnector)winstone.server.getConnectors()[0]).getLocalPort(); - HttpRequest request = - HttpRequest.newBuilder(new URI("http://127.0.0.2:" + port + "/test.xxx")).GET().build(); - HttpResponse response = - HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + int port = ((ServerConnector) winstone.server.getConnectors()[0]).getLocalPort(); + HttpRequest request = HttpRequest.newBuilder(new URI("http://127.0.0.2:" + port + "/test.xxx")) + .GET() + .build(); + HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(HttpURLConnection.HTTP_OK, response.statusCode()); assertEquals("text/xxx", response.headers().firstValue("Content-Type").get()); assertEquals("Hello", response.body()); @@ -60,7 +59,8 @@ public void extraLibFolderDeprecation() throws Exception { makeRequest("http://127.0.0.2:" + port + "/CountRequestsServlet")); assertThat( filter.messages, - hasItem("You are using an extra library folder, support for which will end on or after January 1, 2023.")); + hasItem( + "You are using an extra library folder, support for which will end on or after January 1, 2023.")); } finally { logger.setFilter(orig); } diff --git a/src/test/java/winstone/TrustEveryoneManager.java b/src/test/java/winstone/TrustEveryoneManager.java index af2e8ed8..0f2b6675 100644 --- a/src/test/java/winstone/TrustEveryoneManager.java +++ b/src/test/java/winstone/TrustEveryoneManager.java @@ -1,26 +1,23 @@ package winstone; -import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; +import javax.net.ssl.X509TrustManager; /** * @author Kohsuke Kawaguchi */ public class TrustEveryoneManager implements X509TrustManager { - public TrustEveryoneManager() throws Exception { - } + public TrustEveryoneManager() throws Exception {} @Override - public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { - } + public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {} @Override - public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { - } + public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } -} \ No newline at end of file +} diff --git a/src/test/java/winstone/TrustManagerImpl.java b/src/test/java/winstone/TrustManagerImpl.java index d9f9f7a8..501eba83 100644 --- a/src/test/java/winstone/TrustManagerImpl.java +++ b/src/test/java/winstone/TrustManagerImpl.java @@ -1,10 +1,10 @@ package winstone; -import javax.net.ssl.X509TrustManager; import java.io.FileInputStream; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import javax.net.ssl.X509TrustManager; /** * {@link X509TrustManager} that only recognizes our self-signed certificate. @@ -27,9 +27,9 @@ public void checkClientTrusted(X509Certificate[] xcs, String string) throws Cert @Override public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { for (X509Certificate x509Certificate : xcs) { - System.out.println("certificate: " + x509Certificate.getIssuerX500Principal().getName()); - if (cert.getSubjectX500Principal().equals(x509Certificate.getIssuerX500Principal())) - return; + System.out.println( + "certificate: " + x509Certificate.getIssuerX500Principal().getName()); + if (cert.getSubjectX500Principal().equals(x509Certificate.getIssuerX500Principal())) return; } throw new CertificateException("Untrusted certificate?"); @@ -37,6 +37,6 @@ public void checkServerTrusted(X509Certificate[] xcs, String string) throws Cert @Override public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[]{cert}; + return new X509Certificate[] {cert}; } -} \ No newline at end of file +} diff --git a/src/test/java/winstone/accesslog/SimpleAccessLoggerTest.java b/src/test/java/winstone/accesslog/SimpleAccessLoggerTest.java index 5ad3f0da..4e97431b 100644 --- a/src/test/java/winstone/accesslog/SimpleAccessLoggerTest.java +++ b/src/test/java/winstone/accesslog/SimpleAccessLoggerTest.java @@ -2,17 +2,16 @@ import static org.junit.Assert.assertEquals; -import org.eclipse.jetty.server.ServerConnector; -import org.junit.Test; -import winstone.AbstractWinstoneTest; -import winstone.Launcher; - import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; +import org.eclipse.jetty.server.ServerConnector; +import org.junit.Test; +import winstone.AbstractWinstoneTest; +import winstone.Launcher; /** * @author Kohsuke Kawaguchi @@ -27,15 +26,15 @@ public void testSimpleConnection() throws Exception { Files.deleteIfExists(logFile); // Initialise container - Map args = new HashMap<>(); + Map args = new HashMap<>(); args.put("warfile", "target/test-classes/test.war"); args.put("prefix", "/examples"); args.put("httpPort", "0"); - args.put("accessLoggerClassName",SimpleAccessLogger.class.getName()); - args.put("simpleAccessLogger.file",logFile.toAbsolutePath().toString()); - args.put("simpleAccessLogger.format","###ip### - ###user### ###uriLine### ###status###"); + args.put("accessLoggerClassName", SimpleAccessLogger.class.getName()); + args.put("simpleAccessLogger.file", logFile.toAbsolutePath().toString()); + args.put("simpleAccessLogger.format", "###ip### - ###user### ###uriLine### ###status###"); winstone = new Launcher(args); - int port = ((ServerConnector)winstone.server.getConnectors()[0]).getLocalPort(); + int port = ((ServerConnector) winstone.server.getConnectors()[0]).getLocalPort(); // make a request assertEquals( "This servlet has been accessed via GET 1001 times\r\n", @@ -44,13 +43,11 @@ public void testSimpleConnection() throws Exception { // check the log file // check the log file every 100ms for 5s String text = ""; - for(int i=0; i < 50; ++i) { + for (int i = 0; i < 50; ++i) { Thread.sleep(100); text = Files.readString(logFile, StandardCharsets.UTF_8); - if (!"".equals(text)) - break; + if (!"".equals(text)) break; } - assertEquals(String.format("127.0.0.1 - - GET /examples/CountRequestsServlet HTTP/1.1 200%n"),text); + assertEquals(String.format("127.0.0.1 - - GET /examples/CountRequestsServlet HTTP/1.1 200%n"), text); } - } diff --git a/src/test/java/winstone/realm/ArgumentsRealmTest.java b/src/test/java/winstone/realm/ArgumentsRealmTest.java index 4b0ebf71..f3c6485c 100644 --- a/src/test/java/winstone/realm/ArgumentsRealmTest.java +++ b/src/test/java/winstone/realm/ArgumentsRealmTest.java @@ -3,11 +3,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -import org.eclipse.jetty.server.ServerConnector; -import org.junit.Test; -import winstone.AbstractWinstoneTest; -import winstone.Launcher; - import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; @@ -17,6 +12,10 @@ import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; +import org.eclipse.jetty.server.ServerConnector; +import org.junit.Test; +import winstone.AbstractWinstoneTest; +import winstone.Launcher; /** * @author Kohsuke Kawaguchi @@ -24,27 +23,29 @@ public class ArgumentsRealmTest extends AbstractWinstoneTest { @Test public void realm() throws Exception { - Map args = new HashMap<>(); + Map args = new HashMap<>(); args.put("warfile", "target/test-classes/test.war"); args.put("prefix", "/"); args.put("httpPort", "0"); - args.put("argumentsRealm.passwd.joe","eoj"); - args.put("argumentsRealm.roles.joe","loginUser"); + args.put("argumentsRealm.passwd.joe", "eoj"); + args.put("argumentsRealm.roles.joe", "loginUser"); winstone = new Launcher(args); - int port = ((ServerConnector)winstone.server.getConnectors()[0]).getLocalPort(); - HttpRequest request = - HttpRequest.newBuilder(new URI("http://localhost:" + port + "/secure/secret.txt")).GET().build(); - HttpResponse response = - HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + int port = ((ServerConnector) winstone.server.getConnectors()[0]).getLocalPort(); + HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:" + port + "/secure/secret.txt")) + .GET() + .build(); + HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, response.statusCode()); assertNotEquals("diamond", response.body()); - HttpClient client = HttpClient.newBuilder().authenticator(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication("joe", "eoj".toCharArray()); - } - }).build(); + HttpClient client = HttpClient.newBuilder() + .authenticator(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication("joe", "eoj".toCharArray()); + } + }) + .build(); response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(HttpURLConnection.HTTP_OK, response.statusCode()); assertEquals("diamond", response.body()); diff --git a/src/test/java/winstone/testApplication/filters/TimingFilter.java b/src/test/java/winstone/testApplication/filters/TimingFilter.java index 038469ca..a22a4d2a 100644 --- a/src/test/java/winstone/testApplication/filters/TimingFilter.java +++ b/src/test/java/winstone/testApplication/filters/TimingFilter.java @@ -8,7 +8,6 @@ import java.io.IOException; import java.util.Enumeration; - import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -30,10 +29,8 @@ public class TimingFilter implements Filter { @Override public void init(FilterConfig config) { - String dumpRequestParams = config - .getInitParameter("dumpRequestParameters"); - this.dumpRequestParams = ((dumpRequestParams != null) && dumpRequestParams - .equalsIgnoreCase("true")); + String dumpRequestParams = config.getInitParameter("dumpRequestParameters"); + this.dumpRequestParams = ((dumpRequestParams != null) && dumpRequestParams.equalsIgnoreCase("true")); this.context = config.getServletContext(); } @@ -47,19 +44,16 @@ public void destroy() { * the request parameters to the servlet context log */ @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { if (this.dumpRequestParams) - for (Enumeration paramNames = request.getParameterNames(); paramNames - .hasMoreElements();) { + for (Enumeration paramNames = request.getParameterNames(); paramNames.hasMoreElements(); ) { String name = paramNames.nextElement(); - this.context.log("Request parameter: " + name + "=" - + request.getParameter(name)); + this.context.log("Request parameter: " + name + "=" + request.getParameter(name)); } long startTime = System.currentTimeMillis(); chain.doFilter(request, response); - this.context.log("Filter chain executed in " - + (System.currentTimeMillis() - startTime) + "ms"); + this.context.log("Filter chain executed in " + (System.currentTimeMillis() - startTime) + "ms"); } } diff --git a/src/test/java/winstone/testApplication/filters/WriteAfterServletFilter.java b/src/test/java/winstone/testApplication/filters/WriteAfterServletFilter.java index 3f162123..61decab9 100644 --- a/src/test/java/winstone/testApplication/filters/WriteAfterServletFilter.java +++ b/src/test/java/winstone/testApplication/filters/WriteAfterServletFilter.java @@ -1,7 +1,6 @@ package winstone.testApplication.filters; import java.io.IOException; - import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -19,11 +18,10 @@ public void init(FilterConfig filterConfig) {} public void destroy() {} @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { chain.doFilter(request, response); ServletOutputStream os = response.getOutputStream(); os.print("Hello"); } - } diff --git a/src/test/java/winstone/testApplication/listeners/SessionListener.java b/src/test/java/winstone/testApplication/listeners/SessionListener.java index 1b811d2b..ad6cbe2b 100644 --- a/src/test/java/winstone/testApplication/listeners/SessionListener.java +++ b/src/test/java/winstone/testApplication/listeners/SessionListener.java @@ -14,57 +14,64 @@ /** * Logs messages when any session event is received - * + * * @author Rick Knowles * @version $Id: SessionListener.java,v 1.2 2006/02/28 07:32:46 rickknowles Exp $ */ -public class SessionListener implements HttpSessionListener, - HttpSessionAttributeListener, HttpSessionActivationListener { +public class SessionListener + implements HttpSessionListener, HttpSessionAttributeListener, HttpSessionActivationListener { @Override public void sessionCreated(HttpSessionEvent se) { - se.getSession().getServletContext().log( - "Session Created - id=" + se.getSession().getId()); + se.getSession() + .getServletContext() + .log("Session Created - id=" + se.getSession().getId()); } @Override public void sessionDestroyed(HttpSessionEvent se) { - se.getSession().getServletContext().log( - "Session Destroyed - id=" + se.getSession().getId()); + se.getSession() + .getServletContext() + .log("Session Destroyed - id=" + se.getSession().getId()); } @Override public void attributeAdded(HttpSessionBindingEvent se) { - se.getSession().getServletContext().log( - "Session Attribute added (session id=" + se.getSession() + .getServletContext() + .log("Session Attribute added (session id=" + se.getSession().getId() + ") " + se.getName() + "=" + se.getValue()); } @Override public void attributeRemoved(HttpSessionBindingEvent se) { - se.getSession().getServletContext().log( - "Session Attribute removed (session id=" + se.getSession() + .getServletContext() + .log("Session Attribute removed (session id=" + se.getSession().getId() + ") " + se.getName() + "=" + se.getValue()); } @Override public void attributeReplaced(HttpSessionBindingEvent se) { - se.getSession().getServletContext().log( - "Session Attribute replaced (session id=" + se.getSession() + .getServletContext() + .log("Session Attribute replaced (session id=" + se.getSession().getId() + ") " + se.getName() + "=" + se.getValue()); } @Override public void sessionDidActivate(HttpSessionEvent se) { - se.getSession().getServletContext().log( - "Session activated - id=" + se.getSession().getId()); + se.getSession() + .getServletContext() + .log("Session activated - id=" + se.getSession().getId()); } @Override public void sessionWillPassivate(HttpSessionEvent se) { - se.getSession().getServletContext().log( - "Session passivating - id=" + se.getSession().getId()); + se.getSession() + .getServletContext() + .log("Session passivating - id=" + se.getSession().getId()); } } diff --git a/src/test/java/winstone/testApplication/servlets/AcceptFormServlet.java b/src/test/java/winstone/testApplication/servlets/AcceptFormServlet.java index 9eba0484..32ee7bbb 100644 --- a/src/test/java/winstone/testApplication/servlets/AcceptFormServlet.java +++ b/src/test/java/winstone/testApplication/servlets/AcceptFormServlet.java @@ -22,5 +22,4 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws S pw.print("received " + req.getContentLength() + " bytes"); } } - } diff --git a/src/test/java/winstone/testApplication/servlets/CountRequestsServlet.java b/src/test/java/winstone/testApplication/servlets/CountRequestsServlet.java index beb362d7..59e99d76 100644 --- a/src/test/java/winstone/testApplication/servlets/CountRequestsServlet.java +++ b/src/test/java/winstone/testApplication/servlets/CountRequestsServlet.java @@ -7,7 +7,6 @@ package winstone.testApplication.servlets; import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; @@ -17,7 +16,7 @@ /** * Simple test servlet that counts the number of times it has been requested, * and returns that number in the response. - * + * * @author Rick Knowles * @version $Id: CountRequestsServlet.java,v 1.3 2006/02/28 07:32:49 rickknowles Exp $ */ @@ -34,12 +33,11 @@ public void init() { * Get implementation - increments and shows the access count */ @Override - protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { numberOfGets++; ServletOutputStream out = response.getOutputStream(); - out.println("This servlet has been accessed via GET " - + numberOfGets + " times"); + out.println("This servlet has been accessed via GET " + numberOfGets + " times"); out.flush(); } } diff --git a/src/test/java/winstone/testApplication/servlets/UnavailableServlet.java b/src/test/java/winstone/testApplication/servlets/UnavailableServlet.java index 4653d4f5..84f989cf 100644 --- a/src/test/java/winstone/testApplication/servlets/UnavailableServlet.java +++ b/src/test/java/winstone/testApplication/servlets/UnavailableServlet.java @@ -8,7 +8,6 @@ import java.io.IOException; import java.io.Writer; - import javax.servlet.ServletException; import javax.servlet.UnavailableException; import javax.servlet.http.HttpServlet; @@ -17,7 +16,7 @@ /** * Used to test the unavailable exception processing - * + * * @author Rick Knowles * @version $Id: UnavailableServlet.java,v 1.2 2006/02/28 07:32:49 rickknowles Exp $ */ @@ -28,21 +27,16 @@ public class UnavailableServlet extends HttpServlet { public void init() throws ServletException { String errorTime = getServletConfig().getInitParameter("errorTime"); this.errorAtInit = ((errorTime == null) || errorTime.equals("init")); - if (this.errorAtInit) - throw new UnavailableException( - "Error thrown deliberately during init"); + if (this.errorAtInit) throw new UnavailableException("Error thrown deliberately during init"); } @Override - protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - if (!this.errorAtInit) - throw new UnavailableException( - "Error thrown deliberately during get"); + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + if (!this.errorAtInit) throw new UnavailableException("Error thrown deliberately during get"); try (Writer out = response.getWriter()) { out.write("This should not be shown, because we've thrown unavailable exceptions"); } } - } diff --git a/src/test/java/winstone/testCase/HttpConnectorTest.java b/src/test/java/winstone/testCase/HttpConnectorTest.java index 847f22d5..549eaacc 100644 --- a/src/test/java/winstone/testCase/HttpConnectorTest.java +++ b/src/test/java/winstone/testCase/HttpConnectorTest.java @@ -18,11 +18,9 @@ import java.util.HashMap; import java.util.Map; import java.util.logging.Level; - import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; - import winstone.Launcher; import winstone.Logger; @@ -48,10 +46,9 @@ public HttpConnectorTest(String name) { /** * Test the simple case of connecting, retrieving and disconnecting */ - public void testSimpleConnection() - throws URISyntaxException, IOException, InterruptedException { + public void testSimpleConnection() throws URISyntaxException, IOException, InterruptedException { // Initialise container - Map args = new HashMap<>(); + Map args = new HashMap<>(); args.put("webroot", "target/testwebapp"); args.put("prefix", "/examples"); args.put("httpPort", "10003"); @@ -62,14 +59,13 @@ public void testSimpleConnection() Launcher winstone = new Launcher(args); // Check for a simple connection - HttpRequest request = - HttpRequest.newBuilder(new URI("http://localhost:10003/examples/CountRequestsServlet")).GET().build(); - HttpResponse response = - HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:10003/examples/CountRequestsServlet")) + .GET() + .build(); + HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(HttpURLConnection.HTTP_OK, response.statusCode()); assertEquals( - "This servlet has been accessed via GET 1001 times\r\n", - response.body()); + "This servlet has been accessed via GET 1001 times\r\n", response.body()); winstone.shutdown(); Thread.sleep(500); } @@ -77,10 +73,9 @@ public void testSimpleConnection() /** * Test the keep alive case */ - public void testWriteAfterServlet() - throws URISyntaxException, IOException, InterruptedException { + public void testWriteAfterServlet() throws URISyntaxException, IOException, InterruptedException { // Initialise container - Map args = new HashMap<>(); + Map args = new HashMap<>(); args.put("webroot", "target/testwebapp"); args.put("prefix", "/examples"); args.put("httpPort", "10005"); @@ -91,10 +86,10 @@ public void testWriteAfterServlet() Launcher winstone = new Launcher(args); // Check for a simple connection - HttpRequest request = - HttpRequest.newBuilder(new URI("http://localhost:10005/examples/TestWriteAfterServlet")).GET().build(); - HttpResponse response = - HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:10005/examples/TestWriteAfterServlet")) + .GET() + .build(); + HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(HttpURLConnection.HTTP_OK, response.statusCode()); assertEquals( "This servlet has been accessed via GET 1001 times\r\nHello", diff --git a/src/test/java/winstone/testCase/WinstoneResourceBundleTest.java b/src/test/java/winstone/testCase/WinstoneResourceBundleTest.java index d3e88d48..cc12d255 100644 --- a/src/test/java/winstone/testCase/WinstoneResourceBundleTest.java +++ b/src/test/java/winstone/testCase/WinstoneResourceBundleTest.java @@ -11,40 +11,47 @@ /** * Simple tests for the string replacer - * + * * @author Rick Knowles * @version $Id: WinstoneResourceBundleTest.java,v 1.1 2006/11/09 05:39:43 rickknowles Exp $ */ public class WinstoneResourceBundleTest extends TestCase { public void testGlobalReplace() { - assertEquals("One token", "Foo = bar squared", WinstoneResourceBundle.globalReplace( - "Foo = [#0] squared", "[#0]", "bar")); - assertEquals("Repeated token", "Foo = bar bar squared", WinstoneResourceBundle.globalReplace( - "Foo = [#0] [#0] squared", "[#0]", "bar")); - assertEquals("Two tokens", "Foo = blah bar squared", WinstoneResourceBundle.globalReplace( - "Foo = [#1] [#0] squared", new String[][] {{"[#0]", "bar"}, {"[#1]", "blah"}})); + assertEquals( + "One token", + "Foo = bar squared", + WinstoneResourceBundle.globalReplace("Foo = [#0] squared", "[#0]", "bar")); + assertEquals( + "Repeated token", + "Foo = bar bar squared", + WinstoneResourceBundle.globalReplace("Foo = [#0] [#0] squared", "[#0]", "bar")); + assertEquals( + "Two tokens", + "Foo = blah bar squared", + WinstoneResourceBundle.globalReplace( + "Foo = [#1] [#0] squared", new String[][] {{"[#0]", "bar"}, {"[#1]", "blah"}})); } -// public static void testSpeed() throws Exception { -// String tokens[][] = new String[20][2]; -// for (int n = 0; n < tokens.length; n++) { -// tokens[n] = new String[] {"[#" + n + "]", "token" + n}; -// } -// Random rnd = new Random(); -// String inputs[] = new String[5000]; -// for (int n = 0; n < inputs.length; n++) { -// inputs[n] = ""; -// for (int k = 0; k < tokens.length; k++) { -// inputs[n] += "[#" + (rnd.nextInt() % tokens.length) + "] abc"; -// } -// } -// -// long startTime = System.currentTimeMillis(); -// for (int n = 0; n < inputs.length; n++) { -// WinstoneResourceBundle.globalReplace(inputs[n], tokens); -// } -// System.out.println("Replaced " + tokens.length + " tokens in " + inputs.length + " strings in " + -// (System.currentTimeMillis() - startTime) + "ms"); -// } + // public static void testSpeed() throws Exception { + // String tokens[][] = new String[20][2]; + // for (int n = 0; n < tokens.length; n++) { + // tokens[n] = new String[] {"[#" + n + "]", "token" + n}; + // } + // Random rnd = new Random(); + // String inputs[] = new String[5000]; + // for (int n = 0; n < inputs.length; n++) { + // inputs[n] = ""; + // for (int k = 0; k < tokens.length; k++) { + // inputs[n] += "[#" + (rnd.nextInt() % tokens.length) + "] abc"; + // } + // } + // + // long startTime = System.currentTimeMillis(); + // for (int n = 0; n < inputs.length; n++) { + // WinstoneResourceBundle.globalReplace(inputs[n], tokens); + // } + // System.out.println("Replaced " + tokens.length + " tokens in " + inputs.length + " strings in " + + // (System.currentTimeMillis() - startTime) + "ms"); + // } } diff --git a/src/test/java/winstone/testCase/load/LoadTest.java b/src/test/java/winstone/testCase/load/LoadTest.java index b99d406a..fd87472b 100644 --- a/src/test/java/winstone/testCase/load/LoadTest.java +++ b/src/test/java/winstone/testCase/load/LoadTest.java @@ -12,12 +12,10 @@ import java.util.List; import java.util.Map; import java.util.logging.Level; - import org.junit.Ignore; import org.junit.Test; import winstone.Logger; import winstone.WinstoneResourceBundle; - import winstone.cmdline.Option; /** @@ -45,9 +43,15 @@ public class LoadTest { private static String LOCAL_RESOURCE_FILE = "winstone.testCase.load.LocalStrings"; - public LoadTest(WinstoneResourceBundle resources, String url, - boolean useKeepAlives, int startThreads, int endThreads, - int stepSize, long stepPeriod, long gracePeriod) { + public LoadTest( + WinstoneResourceBundle resources, + String url, + boolean useKeepAlives, + int startThreads, + int endThreads, + int stepSize, + long stepPeriod, + long gracePeriod) { this.resources = resources; this.url = url; this.useKeepAlives = useKeepAlives; @@ -57,8 +61,16 @@ public LoadTest(WinstoneResourceBundle resources, String url, this.stepPeriod = stepPeriod; this.gracePeriod = gracePeriod; - Logger.log(Level.INFO, resources, "LoadTest.Config", this.url, this.useKeepAlives + "", this.startThreads + "", - this.endThreads + "", this.stepSize + "", this.stepPeriod + "", + Logger.log( + Level.INFO, + resources, + "LoadTest.Config", + this.url, + this.useKeepAlives + "", + this.startThreads + "", + this.endThreads + "", + this.stepSize + "", + this.stepPeriod + "", this.gracePeriod + ""); } @@ -68,15 +80,13 @@ public void test() throws InterruptedException { // Loop through in steps for (int n = this.startThreads; n <= this.endThreads; n += this.stepSize) { - if (this.useKeepAlives) - client = HttpClient.newHttpClient(); + if (this.useKeepAlives) client = HttpClient.newHttpClient(); // Spawn the threads int noOfSeconds = (int) this.stepPeriod / 1000; List threads = new ArrayList<>(); for (int m = 0; m < n; m++) - threads.add(new LoadTestThread(this.url, this, this.resources, - client, noOfSeconds - 1)); + threads.add(new LoadTestThread(this.url, this, this.resources, client, noOfSeconds - 1)); // Sleep for step period Thread.sleep(this.stepPeriod + gracePeriod); @@ -85,8 +95,12 @@ public void test() throws InterruptedException { Long averageSuccessTime = this.successCount == 0 ? null : this.successTimeTotal / this.successCount; // Write out results - Logger.log(Level.INFO, resources, "LoadTest.LineResult", - n + "", this.successCount + "", + Logger.log( + Level.INFO, + resources, + "LoadTest.LineResult", + n + "", + this.successCount + "", ((noOfSeconds * n) - this.successCount) + "", averageSuccessTime + ""); @@ -95,7 +109,6 @@ public void test() throws InterruptedException { this.successTimeTotal = 0; this.successCount = 0; - } } @@ -108,19 +121,16 @@ public void incSuccessCount() { } public static void main(String[] args) throws Exception { - WinstoneResourceBundle resources = new WinstoneResourceBundle( - LOCAL_RESOURCE_FILE); + WinstoneResourceBundle resources = new WinstoneResourceBundle(LOCAL_RESOURCE_FILE); // Loop for args - Map options = new HashMap<>(); + Map options = new HashMap<>(); // String operation = ""; for (String option : args) { if (option.startsWith("--")) { int equalPos = option.indexOf('='); - String paramName = option.substring(2, equalPos == -1 ? option - .length() : equalPos); - String paramValue = (equalPos == -1 ? "true" : option - .substring(equalPos + 1)); + String paramName = option.substring(2, equalPos == -1 ? option.length() : equalPos); + String paramValue = (equalPos == -1 ? "true" : option.substring(equalPos + 1)); options.put(paramName, paramValue); } } @@ -139,10 +149,15 @@ public static void main(String[] args) throws Exception { String stepPeriod = Option.stringArg(options, "stepPeriod", "5000"); String gracePeriod = Option.stringArg(options, "gracePeriod", "5000"); - LoadTest lt = new LoadTest(resources, url, keepAlive, Integer - .parseInt(startThreads), Integer.parseInt(endThreads), Integer - .parseInt(stepSize), Integer.parseInt(stepPeriod), Integer - .parseInt(gracePeriod)); + LoadTest lt = new LoadTest( + resources, + url, + keepAlive, + Integer.parseInt(startThreads), + Integer.parseInt(endThreads), + Integer.parseInt(stepSize), + Integer.parseInt(stepPeriod), + Integer.parseInt(gracePeriod)); lt.test(); } @@ -153,5 +168,4 @@ public static void main(String[] args) throws Exception { private static void printUsage(WinstoneResourceBundle resources) { System.out.println(resources.getString("LoadTest.Usage")); } - } diff --git a/src/test/java/winstone/testCase/load/LoadTestThread.java b/src/test/java/winstone/testCase/load/LoadTestThread.java index 1a3b83b2..139230d8 100644 --- a/src/test/java/winstone/testCase/load/LoadTestThread.java +++ b/src/test/java/winstone/testCase/load/LoadTestThread.java @@ -13,13 +13,12 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.logging.Level; - import winstone.Logger; import winstone.WinstoneResourceBundle; /** * A single worked thread in the load testing program - * + * * @author Rick Knowles * @version $Id: LoadTestThread.java,v 1.2 2006/02/28 07:32:49 rickknowles Exp $ */ @@ -33,9 +32,8 @@ public class LoadTestThread implements Runnable { private boolean interrupted; private LoadTestThread next; - public LoadTestThread(String url, LoadTest loadTest, - WinstoneResourceBundle resources, HttpClient client, - int delayedThreads) { + public LoadTestThread( + String url, LoadTest loadTest, WinstoneResourceBundle resources, HttpClient client, int delayedThreads) { this.resources = resources; this.url = url; this.loadTest = loadTest; @@ -47,9 +45,7 @@ public LoadTestThread(String url, LoadTest loadTest, this.thread.start(); // Launch the next second's getter - if (delayedThreads > 0) - this.next = new LoadTestThread(url, loadTest, resources, client, - delayedThreads - 1); + if (delayedThreads > 0) this.next = new LoadTestThread(url, loadTest, resources, client, delayedThreads - 1); } @Override @@ -68,12 +64,11 @@ public void run() { } // Access the URL - HttpRequest request = HttpRequest.newBuilder(new URI(this.url)).GET().build(); - HttpResponse response = - this.client.send(request, HttpResponse.BodyHandlers.ofString()); + HttpRequest request = + HttpRequest.newBuilder(new URI(this.url)).GET().build(); + HttpResponse response = this.client.send(request, HttpResponse.BodyHandlers.ofString()); int responseCode = response.statusCode(); - if (responseCode >= 400) - throw new IOException("Failed with status " + responseCode); + if (responseCode >= 400) throw new IOException("Failed with status " + responseCode); if (this.interrupted) { return; } @@ -87,7 +82,6 @@ public void run() { public void destroy() { this.interrupted = true; this.thread.interrupt(); - if (this.next != null) - this.next.destroy(); + if (this.next != null) this.next.destroy(); } }