Merge remote-tracking branch 'origin/jetty-9.4.x' into jetty-10.0.x

This commit is contained in:
gregw 2020-07-20 12:01:53 +02:00
commit 965e73e9e9
15 changed files with 490 additions and 139 deletions

View File

@ -22,9 +22,11 @@ import java.net.URI;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Random; import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@ -46,18 +48,33 @@ import org.eclipse.jetty.util.TypeUtil;
*/ */
public class DigestAuthentication extends AbstractAuthentication public class DigestAuthentication extends AbstractAuthentication
{ {
private final Random random;
private final String user; private final String user;
private final String password; private final String password;
/** /** Construct a DigestAuthentication with a {@link SecureRandom} nonce.
* @param uri the URI to match for the authentication * @param uri the URI to match for the authentication
* @param realm the realm to match for the authentication * @param realm the realm to match for the authentication
* @param user the user that wants to authenticate * @param user the user that wants to authenticate
* @param password the password of the user * @param password the password of the user
*/ */
public DigestAuthentication(URI uri, String realm, String user, String password) public DigestAuthentication(URI uri, String realm, String user, String password)
{
this(uri, realm, user, password, new SecureRandom());
}
/**
* @param uri the URI to match for the authentication
* @param realm the realm to match for the authentication
* @param user the user that wants to authenticate
* @param password the password of the user
* @param random the Random generator to use for nonces.
*/
public DigestAuthentication(URI uri, String realm, String user, String password, Random random)
{ {
super(uri, realm); super(uri, realm);
Objects.requireNonNull(random);
this.random = random;
this.user = user; this.user = user;
this.password = password; this.password = password;
} }
@ -216,7 +233,6 @@ public class DigestAuthentication extends AbstractAuthentication
private String newClientNonce() private String newClientNonce()
{ {
Random random = new Random();
byte[] bytes = new byte[8]; byte[] bytes = new byte[8];
random.nextBytes(bytes); random.nextBytes(bytes);
return toHexString(bytes); return toHexString(bytes);

View File

@ -27,7 +27,6 @@ import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.jetty.client.AsyncContentProvider; import org.eclipse.jetty.client.AsyncContentProvider;
@ -102,15 +101,10 @@ public class MultiPartContentProvider extends AbstractTypedContentProvider imple
private static String makeBoundary() private static String makeBoundary()
{ {
Random random = new Random();
StringBuilder builder = new StringBuilder("JettyHttpClientBoundary"); StringBuilder builder = new StringBuilder("JettyHttpClientBoundary");
int length = builder.length(); builder.append(Long.toString(System.identityHashCode(builder), 36));
while (builder.length() < length + 16) builder.append(Long.toString(System.identityHashCode(Thread.currentThread()), 36));
{ builder.append(Long.toString(System.nanoTime(), 36));
long rnd = random.nextLong();
builder.append(Long.toString(rnd < 0 ? -rnd : rnd, 36));
}
builder.setLength(length + 16);
return builder.toString(); return builder.toString();
} }

View File

@ -129,9 +129,11 @@ public class OSGiWebappClassLoader extends WebAppClassLoader implements BundleRe
public Enumeration<URL> getResources(String name) throws IOException public Enumeration<URL> getResources(String name) throws IOException
{ {
Enumeration<URL> osgiUrls = _osgiBundleClassLoader.getResources(name); Enumeration<URL> osgiUrls = _osgiBundleClassLoader.getResources(name);
if (osgiUrls != null && osgiUrls.hasMoreElements())
return osgiUrls;
Enumeration<URL> urls = super.getResources(name); Enumeration<URL> urls = super.getResources(name);
List<URL> resources = toList(osgiUrls, urls); return urls;
return Collections.enumeration(resources);
} }
@Override @Override

View File

@ -24,6 +24,7 @@
<module>jetty-osgi-boot-warurl</module> <module>jetty-osgi-boot-warurl</module>
<module>jetty-osgi-httpservice</module> <module>jetty-osgi-httpservice</module>
<module>test-jetty-osgi-webapp</module> <module>test-jetty-osgi-webapp</module>
<module>test-jetty-osgi-webapp-resources</module>
<module>test-jetty-osgi-context</module> <module>test-jetty-osgi-context</module>
<module>test-jetty-osgi-fragment</module> <module>test-jetty-osgi-fragment</module>
<module>test-jetty-osgi-server</module> <module>test-jetty-osgi-server</module>

View File

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty.osgi</groupId>
<artifactId>jetty-osgi-project</artifactId>
<version>9.4.31-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>test-jetty-osgi-webapp-resources</artifactId>
<name>OSGi Test :: Webapp With Resources</name>
<url>http://www.eclipse.org/jetty</url>
<packaging>war</packaging>
<properties>
<bundle-symbolic-name>${project.groupId}.webapp.resources</bundle-symbolic-name>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/classes</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<supportedProjectTypes>
<supportedProjectType>war</supportedProjectType>
</supportedProjectTypes>
<instructions>
<Export-Package>!com.acme*</Export-Package>
<Web-ContextPath>/</Web-ContextPath>
</instructions>
</configuration>
</plugin>
<!-- also make this webapp an osgi bundle -->
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<!-- must deploy: required for jetty-distribution -->
<skip>false</skip>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,67 @@
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package com.acme;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Dump Servlet Request.
*/
@SuppressWarnings("serial")
public class HelloWorld extends HttpServlet
{
@Override
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
out.println("<html>");
out.println("<h1>Hello World</h1>");
Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources("fake.properties");
while (resources.hasMoreElements())
out.println(resources.nextElement().toString());
out.println("</html>");
out.flush();
}
}

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
metadata-complete="false"
version="3.1">
<display-name>WebApp With Resources</display-name>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>com.acme.HelloWorld</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
</web-app>

View File

@ -393,6 +393,13 @@
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.jetty.osgi</groupId>
<artifactId>test-jetty-osgi-webapp-resources</artifactId>
<version>${project.version}</version>
<type>war</type>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.eclipse.jetty.osgi</groupId> <groupId>org.eclipse.jetty.osgi</groupId>
<artifactId>test-jetty-osgi-fragment</artifactId> <artifactId>test-jetty-osgi-fragment</artifactId>
@ -550,6 +557,23 @@
</plugins> </plugins>
</pluginManagement> </pluginManagement>
<plugins> <plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>process-test-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
</execution>
</executions>
<configuration>
<includeArtifactIds>test-jetty-osgi-webapp-resources</includeArtifactIds>
<outputDirectory>target</outputDirectory>
<stripVersion>true</stripVersion>
</configuration>
</plugin>
<plugin> <plugin>
<groupId>org.apache.servicemix.tooling</groupId> <groupId>org.apache.servicemix.tooling</groupId>
<artifactId>depends-maven-plugin</artifactId> <artifactId>depends-maven-plugin</artifactId>

View File

@ -0,0 +1,43 @@
<?xml version="1.0"?><!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">
<!-- ============================================================= --><!-- Configure the Jetty Server instance with an ID "Server" --><!-- by adding an HTTP connector. --><!-- This configuration must be used in conjunction with jetty.xml --><!-- ============================================================= -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<!-- =========================================================== -->
<!-- Add an HTTP Connector. -->
<!-- Configure an o.e.j.server.ServerConnector with a single -->
<!-- HttpConnectionFactory instance using the common httpConfig -->
<!-- instance defined in jetty.xml -->
<!-- -->
<!-- Consult the javadoc of o.e.j.server.ServerConnector and -->
<!-- o.e.j.server.HttpConnectionFactory for all configuration -->
<!-- that may be set here. -->
<!-- =========================================================== -->
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="factories">
<Array type="org.eclipse.jetty.server.ConnectionFactory">
<Item>
<New class="org.eclipse.jetty.server.HttpConnectionFactory">
<Arg name="config"><Ref refid="httpConfig" /></Arg>
</New>
</Item>
</Array>
</Arg>
<Call name="addLifeCycleListener">
<Arg>
<New class="org.eclipse.jetty.osgi.boot.utils.ServerConnectorListener">
<Set name="sysPropertyName">boot.resources.port</Set>
</New>
</Arg>
</Call>
<Set name="host"><Property name="jetty.http.host" /></Set>
<Set name="port"><Property name="jetty.http.port" default="80" /></Set>
<Set name="idleTimeout"><Property name="jetty.http.idleTimeout" default="30000"/></Set>
</New>
</Arg>
</Call>
</Configure>

View File

@ -0,0 +1,143 @@
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.osgi.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import javax.inject.Inject;
import aQute.bnd.osgi.Constants;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.tinybundles.core.TinyBundle;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
/**
* TestJettyOSGiClasspathResources
*
*/
@RunWith(PaxExam.class)
public class TestJettyOSGiClasspathResources
{
private static final String LOG_LEVEL = "WARN";
@Inject
BundleContext bundleContext = null;
@Configuration
public static Option[] configure()
{
ArrayList<Option> options = new ArrayList<>();
options.add(CoreOptions.junitBundles());
options.addAll(TestOSGiUtil.configureJettyHomeAndPort(false, "jetty-http-boot-with-resources.xml"));
options.add(CoreOptions.bootDelegationPackages("org.xml.sax", "org.xml.*", "org.w3c.*", "javax.xml.*", "javax.activation.*"));
options.add(CoreOptions.systemPackages("com.sun.org.apache.xalan.internal.res", "com.sun.org.apache.xml.internal.utils",
"com.sun.org.apache.xml.internal.utils", "com.sun.org.apache.xpath.internal",
"com.sun.org.apache.xpath.internal.jaxp", "com.sun.org.apache.xpath.internal.objects"));
options.addAll(TestOSGiUtil.coreJettyDependencies());
options.add(mavenBundle().groupId("biz.aQute.bnd").artifactId("bndlib").versionAsInProject().start());
options.add(mavenBundle().groupId("org.ops4j.pax.tinybundles").artifactId("tinybundles").version("2.1.1").start());
options.add(mavenBundle().groupId("org.eclipse.jetty.osgi").artifactId("test-jetty-osgi-webapp-resources").type("war").versionAsInProject());
options.add(systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value(LOG_LEVEL));
options.add(systemProperty("org.eclipse.jetty.LEVEL").value(LOG_LEVEL));
options.add(CoreOptions.cleanCaches(true));
return options.toArray(new Option[options.size()]);
}
@Test
public void testWebInfResourceNotOnBundleClasspath() throws Exception
{
//Test the test-jetty-osgi-webapp-resource bundle with a
//Bundle-Classpath that does NOT include WEB-INF/classes
HttpClient client = new HttpClient();
try
{
client.start();
String port = System.getProperty("boot.resources.port");
assertNotNull(port);
ContentResponse response = client.GET("http://127.0.0.1:" + port + "/hello/a");
assertEquals(HttpStatus.OK_200, response.getStatus());
String content = response.getContentAsString();
//check that fake.properties is only listed once from the classpath
assertEquals(content.indexOf("fake.properties"), content.lastIndexOf("fake.properties"));
}
finally
{
client.stop();
}
}
@Test
public void testWebInfResourceOnBundleClasspath() throws Exception
{
Bundle webappBundle = TestOSGiUtil.getBundle(bundleContext, "org.eclipse.jetty.osgi.webapp.resources");
//Make a new bundle based on the test-jetty-osgi-webapp-resources war bundle, but
//change the Bundle-Classpath so that WEB-INF/classes IS on the bundle classpath
File warFile = new File("target/test-jetty-osgi-webapp-resources.war");
TinyBundle tiny = TinyBundles.bundle();
tiny.read(new FileInputStream(warFile));
tiny.set(Constants.BUNDLE_CLASSPATH, "., WEB-INF/classes/");
tiny.set(Constants.BUNDLE_SYMBOLICNAME, "org.eclipse.jetty.osgi.webapp.resources.alt");
InputStream is = tiny.build(TinyBundles.withBnd());
bundleContext.installBundle("dummyAltLocation", is);
webappBundle.stop();
Bundle bundle = TestOSGiUtil.getBundle(bundleContext, "org.eclipse.jetty.osgi.webapp.resources.alt");
bundle.start();
HttpClient client = new HttpClient();
try
{
client.start();
String port = System.getProperty("boot.resources.port");
assertNotNull(port);
ContentResponse response = client.GET("http://127.0.0.1:" + port + "/hello/a");
String content = response.getContentAsString();
assertEquals(HttpStatus.OK_200, response.getStatus());
//check that fake.properties is only listed once from the classpath
assertEquals(content.indexOf("fake.properties"), content.lastIndexOf("fake.properties"));
}
finally
{
client.stop();
}
}
}

View File

@ -18,7 +18,6 @@
package org.eclipse.jetty.plus.webapp; package org.eclipse.jetty.plus.webapp;
import java.util.Random;
import javax.naming.Context; import javax.naming.Context;
import javax.naming.InitialContext; import javax.naming.InitialContext;
import javax.naming.NameNotFoundException; import javax.naming.NameNotFoundException;
@ -110,8 +109,7 @@ public class PlusConfiguration extends AbstractConfiguration
Thread.currentThread().setContextClassLoader(wac.getClassLoader()); Thread.currentThread().setContextClassLoader(wac.getClassLoader());
try try
{ {
Random random = new Random(); _key = (int)(this.hashCode() ^ System.nanoTime());
_key = random.nextInt();
Context context = new InitialContext(); Context context = new InitialContext();
Context compCtx = (Context)context.lookup("java:comp"); Context compCtx = (Context)context.lookup("java:comp");
compCtx.addToEnvironment(NamingContext.LOCK_PROPERTY, _key); compCtx.addToEnvironment(NamingContext.LOCK_PROPERTY, _key);

View File

@ -33,7 +33,7 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* FilterHolderTest * FilterHolderTest
@ -67,13 +67,13 @@ public class FilterHolderTest
Filter filter = new Filter() Filter filter = new Filter()
{ {
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException public void init(FilterConfig filterConfig)
{ {
counter.incrementAndGet(); counter.incrementAndGet();
} }
@Override @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
{ {
} }
@ -89,14 +89,9 @@ public class FilterHolderTest
fh.setName("xx"); fh.setName("xx");
fh.setFilter(filter); fh.setFilter(filter);
try (StacklessLogging stackless = new StacklessLogging(FilterHolder.class)) try (StacklessLogging ignored = new StacklessLogging(FilterHolder.class))
{ {
fh.initialize(); assertThrows(IllegalStateException.class, fh::initialize);
fail("Not started");
}
catch (Exception e)
{
//expected
} }
fh.start(); fh.start();

View File

@ -91,6 +91,7 @@ import org.slf4j.LoggerFactory;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@ -111,7 +112,7 @@ public class ServletContextHandlerTest
private static int __initIndex = 0; private static int __initIndex = 0;
private static int __destroyIndex = 0; private static int __destroyIndex = 0;
public class StopTestFilter implements Filter public static class StopTestFilter implements Filter
{ {
int _initIndex; int _initIndex;
int _destroyIndex; int _destroyIndex;
@ -135,7 +136,7 @@ public class ServletContextHandlerTest
} }
} }
public class StopTestServlet extends GenericServlet public static class StopTestServlet extends GenericServlet
{ {
int _initIndex; int _initIndex;
int _destroyIndex; int _destroyIndex;
@ -160,7 +161,7 @@ public class ServletContextHandlerTest
} }
} }
public class StopTestListener implements ServletContextListener public static class StopTestListener implements ServletContextListener
{ {
int _initIndex; int _initIndex;
int _destroyIndex; int _destroyIndex;
@ -195,7 +196,7 @@ public class ServletContextHandlerTest
} }
@Override @Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException public void onStartup(Set<Class<?>> c, ServletContext ctx)
{ {
//add a programmatic listener //add a programmatic listener
if (ctx.getAttribute("MySCI.startup") != null) if (ctx.getAttribute("MySCI.startup") != null)
@ -251,7 +252,7 @@ public class ServletContextHandlerTest
public static class MySCIStarter extends AbstractLifeCycle implements ServletContextHandler.ServletContainerInitializerCaller public static class MySCIStarter extends AbstractLifeCycle implements ServletContextHandler.ServletContainerInitializerCaller
{ {
ServletContainerInitializer _sci = null; ServletContainerInitializer _sci;
ContextHandler.Context _ctx; ContextHandler.Context _ctx;
MySCIStarter(ContextHandler.Context ctx, ServletContainerInitializer sci) MySCIStarter(ContextHandler.Context ctx, ServletContainerInitializer sci)
@ -593,7 +594,7 @@ public class ServletContextHandlerTest
} }
} }
public class InitialListener implements ServletContextListener public static class InitialListener implements ServletContextListener
{ {
@Override @Override
public void contextInitialized(ServletContextEvent sce) public void contextInitialized(ServletContextEvent sce)
@ -623,18 +624,18 @@ public class ServletContextHandlerTest
{ {
fail(e); fail(e);
} }
// And also test you can't add a ServletContextListener from a ServletContextListener // And also test you can't add a ServletContextListener from a ServletContextListener
try try
{ {
MyContextListener contextListener = sce.getServletContext().createListener(MyContextListener.class); MyContextListener contextListener = sce.getServletContext().createListener(MyContextListener.class);
sce.getServletContext().addListener(contextListener); assertThrows(IllegalArgumentException.class, () -> sce.getServletContext().addListener(contextListener), "Adding SCI from an SCI!");
fail("Adding SCL from an SCL!");
} }
catch (IllegalArgumentException e) catch (IllegalArgumentException e)
{ {
//expected //expected
} }
catch (Exception x) catch (ServletException x)
{ {
fail(x); fail(x);
} }
@ -750,7 +751,7 @@ public class ServletContextHandlerTest
} }
@Test @Test
public void testAddSessionListener() throws Exception public void testAddSessionListener()
{ {
ContextHandlerCollection contexts = new ContextHandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection();
_server.setHandler(contexts); _server.setHandler(contexts);
@ -831,7 +832,7 @@ public class ServletContextHandlerTest
ListenerHolder initialListener = new ListenerHolder(); ListenerHolder initialListener = new ListenerHolder();
initialListener.setListener(new InitialListener()); initialListener.setListener(new InitialListener());
root.getServletHandler().addListener(initialListener); root.getServletHandler().addListener(initialListener);
ServletHolder holder0 = root.addServlet(TestServlet.class, "/test"); root.addServlet(TestServlet.class, "/test");
_server.start(); _server.start();
ListenerHolder[] listenerHolders = root.getServletHandler().getListeners(); ListenerHolder[] listenerHolders = root.getServletHandler().getListeners();
@ -879,7 +880,7 @@ public class ServletContextHandlerTest
StringBuffer request = new StringBuffer(); StringBuffer request = new StringBuffer();
request.append("GET /test?session=replace HTTP/1.0\n"); request.append("GET /test?session=replace HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("Cookie: " + sessionid + "\n"); request.append("Cookie: ").append(sessionid).append("\n");
request.append("\n"); request.append("\n");
response = _connector.getResponse(request.toString()); response = _connector.getResponse(request.toString());
assertThat(response, Matchers.containsString("200 OK")); assertThat(response, Matchers.containsString("200 OK"));
@ -890,7 +891,7 @@ public class ServletContextHandlerTest
request = new StringBuffer(); request = new StringBuffer();
request.append("GET /test?session=remove HTTP/1.0\n"); request.append("GET /test?session=remove HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("Cookie: " + sessionid + "\n"); request.append("Cookie: ").append(sessionid).append("\n");
request.append("\n"); request.append("\n");
response = _connector.getResponse(request.toString()); response = _connector.getResponse(request.toString());
assertThat(response, Matchers.containsString("200 OK")); assertThat(response, Matchers.containsString("200 OK"));
@ -903,7 +904,7 @@ public class ServletContextHandlerTest
request = new StringBuffer(); request = new StringBuffer();
request.append("GET /test?session=change HTTP/1.0\n"); request.append("GET /test?session=change HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("Cookie: " + sessionid + "\n"); request.append("Cookie: ").append(sessionid).append("\n");
request.append("\n"); request.append("\n");
response = _connector.getResponse(request.toString()); response = _connector.getResponse(request.toString());
assertThat(response, Matchers.containsString("200 OK")); assertThat(response, Matchers.containsString("200 OK"));
@ -914,7 +915,7 @@ public class ServletContextHandlerTest
request = new StringBuffer(); request = new StringBuffer();
request.append("GET /test?session=delete HTTP/1.0\n"); request.append("GET /test?session=delete HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("Cookie: " + sessionid + "\n"); request.append("Cookie: ").append(sessionid).append("\n");
request.append("\n"); request.append("\n");
response = _connector.getResponse(request.toString()); response = _connector.getResponse(request.toString());
assertThat(response, Matchers.containsString("200 OK")); assertThat(response, Matchers.containsString("200 OK"));
@ -994,12 +995,12 @@ public class ServletContextHandlerTest
} }
@Test @Test
public void testAddServletFromServlet() throws Exception public void testAddServletFromServlet()
{ {
//A servlet cannot be added by another servlet //A servlet cannot be added by another servlet
Logger logger = LoggerFactory.getLogger(ContextHandler.class.getName() + "ROOT"); Logger logger = LoggerFactory.getLogger(ContextHandler.class.getName() + "ROOT");
try (StacklessLogging stackless = new StacklessLogging(logger)) try (StacklessLogging ignored = new StacklessLogging(logger))
{ {
ServletContextHandler context = new ServletContextHandler(); ServletContextHandler context = new ServletContextHandler();
context.setLogger(logger); context.setLogger(logger);
@ -1008,17 +1009,8 @@ public class ServletContextHandlerTest
holder.setInitOrder(0); holder.setInitOrder(0);
context.setContextPath("/"); context.setContextPath("/");
_server.setHandler(context); _server.setHandler(context);
_server.start(); ServletException se = assertThrows(ServletException.class, _server::start);
fail("Servlet can only be added from SCI or SCL"); assertThat("Servlet can only be added from SCI or SCL", se.getCause(), instanceOf(IllegalStateException.class));
}
catch (Exception e)
{
if (e instanceof ServletException)
{
assertTrue(e.getCause() instanceof IllegalStateException);
}
else
fail(e);
} }
} }
@ -1093,12 +1085,12 @@ public class ServletContextHandlerTest
} }
@Test @Test
public void testAddFilterFromServlet() throws Exception public void testAddFilterFromServlet()
{ {
//A filter cannot be added from a servlet //A filter cannot be added from a servlet
Logger logger = LoggerFactory.getLogger(ContextHandler.class.getName() + "ROOT"); Logger logger = LoggerFactory.getLogger(ContextHandler.class.getName() + "ROOT");
try (StacklessLogging stackless = new StacklessLogging(logger)) try (StacklessLogging ignored = new StacklessLogging(logger))
{ {
ServletContextHandler context = new ServletContextHandler(); ServletContextHandler context = new ServletContextHandler();
context.setLogger(logger); context.setLogger(logger);
@ -1107,34 +1099,25 @@ public class ServletContextHandlerTest
holder.setInitOrder(0); holder.setInitOrder(0);
context.setContextPath("/"); context.setContextPath("/");
_server.setHandler(context); _server.setHandler(context);
_server.start(); ServletException se = assertThrows(ServletException.class, _server::start);
fail("Filter can only be added from SCI or SCL"); assertThat("Filter can only be added from SCI or SCL", se.getCause(), instanceOf(IllegalStateException.class));
}
catch (Exception e)
{
if (e instanceof ServletException)
{
assertTrue(e.getCause() instanceof IllegalStateException);
}
else
fail(e);
} }
} }
@Test @Test
public void testAddServletByClassFromFilter() throws Exception public void testAddServletByClassFromFilter()
{ {
//A servlet cannot be added from a Filter //A servlet cannot be added from a Filter
Logger logger = LoggerFactory.getLogger(ContextHandler.class.getName() + "ROOT"); Logger logger = LoggerFactory.getLogger(ContextHandler.class.getName() + "ROOT");
try (StacklessLogging stackless = new StacklessLogging(logger)) try (StacklessLogging ignored = new StacklessLogging(logger))
{ {
ServletContextHandler context = new ServletContextHandler(); ServletContextHandler context = new ServletContextHandler();
context.setLogger(logger); context.setLogger(logger);
FilterHolder holder = new FilterHolder(new Filter() FilterHolder holder = new FilterHolder(new Filter()
{ {
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException public void init(FilterConfig filterConfig)
{ {
ServletRegistration rego = filterConfig.getServletContext().addServlet("hello", HelloServlet.class); ServletRegistration rego = filterConfig.getServletContext().addServlet("hello", HelloServlet.class);
rego.addMapping("/hello/*"); rego.addMapping("/hello/*");
@ -1142,7 +1125,6 @@ public class ServletContextHandlerTest
@Override @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{ {
} }
@ -1155,37 +1137,24 @@ public class ServletContextHandlerTest
context.getServletHandler().setStartWithUnavailable(false); context.getServletHandler().setStartWithUnavailable(false);
context.setContextPath("/"); context.setContextPath("/");
_server.setHandler(context); _server.setHandler(context);
_server.start(); assertThrows(IllegalStateException.class, _server::start, "Servlet can only be added from SCI or SCL");
fail("Servlet can only be added from SCI or SCL");
}
catch (Exception e)
{
if (!(e instanceof IllegalStateException))
{
if (e instanceof ServletException)
{
assertTrue(e.getCause() instanceof IllegalStateException);
}
else
fail(e);
}
} }
} }
@Test @Test
public void testAddServletByInstanceFromFilter() throws Exception public void testAddServletByInstanceFromFilter()
{ {
//A servlet cannot be added from a Filter //A servlet cannot be added from a Filter
Logger logger = LoggerFactory.getLogger(ContextHandler.class.getName() + "ROOT"); Logger logger = LoggerFactory.getLogger(ContextHandler.class.getName() + "ROOT");
try (StacklessLogging stackless = new StacklessLogging(logger)) try (StacklessLogging ignored = new StacklessLogging(logger))
{ {
ServletContextHandler context = new ServletContextHandler(); ServletContextHandler context = new ServletContextHandler();
context.setLogger(logger); context.setLogger(logger);
FilterHolder holder = new FilterHolder(new Filter() FilterHolder holder = new FilterHolder(new Filter()
{ {
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException public void init(FilterConfig filterConfig)
{ {
ServletRegistration rego = filterConfig.getServletContext().addServlet("hello", new HelloServlet()); ServletRegistration rego = filterConfig.getServletContext().addServlet("hello", new HelloServlet());
rego.addMapping("/hello/*"); rego.addMapping("/hello/*");
@ -1193,7 +1162,6 @@ public class ServletContextHandlerTest
@Override @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{ {
} }
@ -1206,37 +1174,24 @@ public class ServletContextHandlerTest
context.getServletHandler().setStartWithUnavailable(false); context.getServletHandler().setStartWithUnavailable(false);
context.setContextPath("/"); context.setContextPath("/");
_server.setHandler(context); _server.setHandler(context);
_server.start(); assertThrows(IllegalStateException.class, _server::start, "Servlet can only be added from SCI or SCL");
fail("Servlet can only be added from SCI or SCL");
}
catch (Exception e)
{
if (!(e instanceof IllegalStateException))
{
if (e instanceof ServletException)
{
assertTrue(e.getCause() instanceof IllegalStateException);
}
else
fail(e);
}
} }
} }
@Test @Test
public void testAddServletByClassNameFromFilter() throws Exception public void testAddServletByClassNameFromFilter()
{ {
//A servlet cannot be added from a Filter //A servlet cannot be added from a Filter
Logger logger = LoggerFactory.getLogger(ContextHandler.class.getName() + "ROOT"); Logger logger = LoggerFactory.getLogger(ContextHandler.class.getName() + "ROOT");
try (StacklessLogging stackless = new StacklessLogging(logger)) try (StacklessLogging ignored = new StacklessLogging(logger))
{ {
ServletContextHandler context = new ServletContextHandler(); ServletContextHandler context = new ServletContextHandler();
context.setLogger(logger); context.setLogger(logger);
FilterHolder holder = new FilterHolder(new Filter() FilterHolder holder = new FilterHolder(new Filter()
{ {
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException public void init(FilterConfig filterConfig)
{ {
ServletRegistration rego = filterConfig.getServletContext().addServlet("hello", HelloServlet.class.getName()); ServletRegistration rego = filterConfig.getServletContext().addServlet("hello", HelloServlet.class.getName());
rego.addMapping("/hello/*"); rego.addMapping("/hello/*");
@ -1244,7 +1199,6 @@ public class ServletContextHandlerTest
@Override @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{ {
} }
@ -1257,20 +1211,7 @@ public class ServletContextHandlerTest
context.getServletHandler().setStartWithUnavailable(false); context.getServletHandler().setStartWithUnavailable(false);
context.setContextPath("/"); context.setContextPath("/");
_server.setHandler(context); _server.setHandler(context);
_server.start(); assertThrows(IllegalStateException.class, _server::start, "Servlet can only be added from SCI or SCL");
fail("Servlet can only be added from SCI or SCL");
}
catch (Exception e)
{
if (!(e instanceof IllegalStateException))
{
if (e instanceof ServletException)
{
assertTrue(e.getCause() instanceof IllegalStateException);
}
else
fail(e);
}
} }
} }
@ -1299,7 +1240,7 @@ public class ServletContextHandlerTest
_server.setHandler(context); _server.setHandler(context);
_server.start(); _server.start();
StringBuffer request = new StringBuffer(); StringBuilder request = new StringBuilder();
request.append("GET /hello HTTP/1.0\n"); request.append("GET /hello HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("\n"); request.append("\n");
@ -1319,7 +1260,7 @@ public class ServletContextHandlerTest
class ServletAddingSCI implements ServletContainerInitializer class ServletAddingSCI implements ServletContainerInitializer
{ {
@Override @Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException public void onStartup(Set<Class<?>> c, ServletContext ctx)
{ {
ServletRegistration rego = ctx.addServlet("hello", HelloServlet.class); ServletRegistration rego = ctx.addServlet("hello", HelloServlet.class);
rego.addMapping("/hello/*"); rego.addMapping("/hello/*");
@ -1329,7 +1270,7 @@ public class ServletContextHandlerTest
root.addBean(new MySCIStarter(root.getServletContext(), new ServletAddingSCI()), true); root.addBean(new MySCIStarter(root.getServletContext(), new ServletAddingSCI()), true);
_server.start(); _server.start();
StringBuffer request = new StringBuffer(); StringBuilder request = new StringBuilder();
request.append("GET /hello HTTP/1.0\n"); request.append("GET /hello HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("\n"); request.append("\n");
@ -1491,7 +1432,7 @@ public class ServletContextHandlerTest
_server.setHandler(context); _server.setHandler(context);
_server.start(); _server.start();
StringBuffer request = new StringBuffer(); StringBuilder request = new StringBuilder();
request.append("GET /test HTTP/1.0\n"); request.append("GET /test HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("\n"); request.append("\n");
@ -1511,7 +1452,7 @@ public class ServletContextHandlerTest
_server.setHandler(context); _server.setHandler(context);
_server.start(); _server.start();
StringBuffer request = new StringBuffer(); StringBuilder request = new StringBuilder();
request.append("GET /test HTTP/1.0\n"); request.append("GET /test HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("\n"); request.append("\n");
@ -1537,7 +1478,7 @@ public class ServletContextHandlerTest
_server.setHandler(context); _server.setHandler(context);
_server.start(); _server.start();
StringBuffer request = new StringBuffer(); StringBuilder request = new StringBuilder();
request.append("GET /test HTTP/1.0\n"); request.append("GET /test HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("\n"); request.append("\n");
@ -1564,7 +1505,7 @@ public class ServletContextHandlerTest
_server.setHandler(context); _server.setHandler(context);
_server.start(); _server.start();
StringBuffer request = new StringBuffer(); StringBuilder request = new StringBuilder();
request.append("GET /test HTTP/1.0\n"); request.append("GET /test HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("\n"); request.append("\n");
@ -1590,7 +1531,7 @@ public class ServletContextHandlerTest
_server.setHandler(context); _server.setHandler(context);
_server.start(); _server.start();
StringBuffer request = new StringBuffer(); StringBuilder request = new StringBuilder();
request.append("GET /test HTTP/1.0\n"); request.append("GET /test HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("\n"); request.append("\n");
@ -1613,7 +1554,7 @@ public class ServletContextHandlerTest
_server.setHandler(context); _server.setHandler(context);
_server.start(); _server.start();
StringBuffer request = new StringBuffer(); StringBuilder request = new StringBuilder();
request.append("GET /test HTTP/1.0\n"); request.append("GET /test HTTP/1.0\n");
request.append("Host: localhost\n"); request.append("Host: localhost\n");
request.append("\n"); request.append("\n");
@ -1657,7 +1598,7 @@ public class ServletContextHandlerTest
} }
@Test @Test
public void testSetSecurityHandler() throws Exception public void testSetSecurityHandler()
{ {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY);
assertNotNull(context.getSessionHandler()); assertNotNull(context.getSessionHandler());
@ -1683,7 +1624,7 @@ public class ServletContextHandlerTest
@Override @Override
protected boolean checkUserDataPermissions(String pathInContext, Request request, Response response, protected boolean checkUserDataPermissions(String pathInContext, Request request, Response response,
RoleInfo constraintInfo) throws IOException RoleInfo constraintInfo)
{ {
return false; return false;
} }
@ -1697,7 +1638,6 @@ public class ServletContextHandlerTest
@Override @Override
protected boolean checkWebResourcePermissions(String pathInContext, Request request, Response response, protected boolean checkWebResourcePermissions(String pathInContext, Request request, Response response,
Object constraintInfo, UserIdentity userIdentity) Object constraintInfo, UserIdentity userIdentity)
throws IOException
{ {
return false; return false;
} }
@ -1803,7 +1743,7 @@ public class ServletContextHandlerTest
list.addHandler(new AbstractHandler() list.addHandler(new AbstractHandler()
{ {
@Override @Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{ {
response.sendError(404, "Fell Through"); response.sendError(404, "Fell Through");
} }
@ -1896,6 +1836,7 @@ public class ServletContextHandlerTest
} }
} }
@SuppressWarnings("deprecation")
public static class DecoratedObjectFactoryServlet extends HttpServlet public static class DecoratedObjectFactoryServlet extends HttpServlet
{ {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -2014,7 +1955,7 @@ public class ServletContextHandlerTest
} }
else if ("change".equalsIgnoreCase(action)) else if ("change".equalsIgnoreCase(action))
{ {
HttpSession session = req.getSession(true); req.getSession(true);
req.changeSessionId(); req.changeSessionId();
} }
else if ("replace".equalsIgnoreCase(action)) else if ("replace".equalsIgnoreCase(action))

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.websocket.core.internal;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Objects; import java.util.Objects;
import java.util.Random; import java.util.Random;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
@ -83,6 +84,29 @@ public class WebSocketConnection extends AbstractConnection implements Connectio
Scheduler scheduler, Scheduler scheduler,
ByteBufferPool bufferPool, ByteBufferPool bufferPool,
WebSocketCoreSession coreSession) WebSocketCoreSession coreSession)
{
this(endp, executor, scheduler, bufferPool, coreSession, null);
}
/**
* Create a WSConnection.
* <p>
* It is assumed that the WebSocket Upgrade Handshake has already
* completed successfully before creating this connection.
* </p>
* @param endp The endpoint ever which Websockot is sent/received
* @param executor A thread executor to use for WS callbacks.
* @param scheduler A scheduler to use for timeouts
* @param bufferPool A pool of buffers to use.
* @param coreSession The WC core session to which frames are delivered.
* @param randomMask A Random used to mask frames. If null then SecureRandom will be created if needed.
*/
public WebSocketConnection(EndPoint endp,
Executor executor,
Scheduler scheduler,
ByteBufferPool bufferPool,
WebSocketCoreSession coreSession,
Random randomMask)
{ {
super(endp, executor); super(endp, executor);
@ -92,15 +116,15 @@ public class WebSocketConnection extends AbstractConnection implements Connectio
Objects.requireNonNull(bufferPool, "ByteBufferPool"); Objects.requireNonNull(bufferPool, "ByteBufferPool");
this.bufferPool = bufferPool; this.bufferPool = bufferPool;
this.coreSession = coreSession; this.coreSession = coreSession;
this.generator = new Generator(); this.generator = new Generator();
this.parser = new Parser(bufferPool, coreSession); this.parser = new Parser(bufferPool, coreSession);
this.flusher = new Flusher(scheduler, coreSession.getOutputBufferSize(), generator, endp); this.flusher = new Flusher(scheduler, coreSession.getOutputBufferSize(), generator, endp);
this.setInputBufferSize(coreSession.getInputBufferSize()); this.setInputBufferSize(coreSession.getInputBufferSize());
this.random = this.coreSession.getBehavior() == Behavior.CLIENT ? new Random(endp.hashCode()) : null; if (this.coreSession.getBehavior() == Behavior.CLIENT && randomMask == null)
randomMask = new SecureRandom();
this.random = randomMask;
} }
@Override @Override