Merge pull request #6325 from eclipse/jetty-9.4.x-6287-WebSocketClientClassLoading

Issue #6287 - fix classloading for WebSocketClient in webapp
This commit is contained in:
Lachlan 2021-06-03 15:22:05 +10:00 committed by GitHub
commit 121d8c27ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 511 additions and 4 deletions

View File

@ -325,6 +325,12 @@ public class ClientContainer extends ContainerLifeCycle implements WebSocketCont
return client;
}
@Override
public ClassLoader getClassLoader()
{
return client.getClassLoader();
}
public EndpointMetadata getClientEndpointMetadata(Class<?> endpoint, EndpointConfig config)
{
synchronized (endpointClientMetadataCache)

View File

@ -0,0 +1,217 @@
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.websocket.jsr356.server;
import java.net.URI;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import javax.websocket.server.ServerEndpoint;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.http.BadMessageException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.eclipse.jetty.websocket.common.WebSocketSession;
import org.eclipse.jetty.websocket.jsr356.ClientContainer;
import org.eclipse.jetty.xml.XmlConfiguration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class JavaxClientClassLoaderTest
{
private final WebAppTester server = new WebAppTester();
private HttpClient httpClient;
@FunctionalInterface
interface ThrowingRunnable
{
void run() throws Exception;
}
public void start(ThrowingRunnable configuration) throws Exception
{
configuration.run();
server.start();
httpClient = new HttpClient();
httpClient.start();
}
@AfterEach
public void after() throws Exception
{
httpClient.stop();
server.stop();
}
@ClientEndpoint()
public static class ClientSocket
{
LinkedBlockingQueue<String> textMessages = new LinkedBlockingQueue<>();
@OnOpen
public void onOpen(Session session)
{
session.getAsyncRemote().sendText("ContextClassLoader: " + Thread.currentThread().getContextClassLoader());
}
@OnMessage
public void onMessage(String message)
{
textMessages.add(message);
}
}
@WebServlet("/servlet")
public static class WebSocketClientServlet extends HttpServlet
{
private final WebSocketContainer clientContainer = ContainerProvider.getWebSocketContainer();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
{
URI wsEchoUri = URI.create("ws://localhost:" + req.getServerPort() + "/echo/");
ClientSocket clientSocket = new ClientSocket();
try (Session ignored = clientContainer.connectToServer(clientSocket, wsEchoUri))
{
String recv = clientSocket.textMessages.poll(5, TimeUnit.SECONDS);
assertNotNull(recv);
resp.setStatus(HttpStatus.OK_200);
resp.getWriter().println(recv);
resp.getWriter().println("ClientClassLoader: " + clientContainer.getClass().getClassLoader());
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
@ServerEndpoint("/")
public static class EchoSocket
{
@OnMessage
public void onMessage(Session session, String message) throws Exception
{
session.getBasicRemote().sendText(message);
}
}
public WebAppTester.WebApp createWebSocketWebapp(String contextName) throws Exception
{
WebAppTester.WebApp app = this.server.createWebApp(contextName);
// We must hide the websocket classes from the webapp if we are to include websocket client jars in WEB-INF/lib.
WebAppContext context = app.getWebAppContext();
context.getServerClasspathPattern().include("org.eclipse.jetty.websocket.");
context.getSystemClasspathPattern().exclude("org.eclipse.jetty.websocket.");
// Copy over the individual jars required for Javax WebSocket.
app.createWebInf();
app.copyLib(WebSocketContainer.class, "websocket-javax-api.jar");
app.copyLib(ClientContainer.class, "websocket-javax-client.jar");
app.copyLib(WebSocketClient.class, "websocket-jetty-client.jar");
app.copyLib(WebSocketSession.class, "websocket-common.jar");
app.copyLib(ContainerLifeCycle.class, "jetty-util.jar");
app.copyLib(Response.class, "jetty-client.jar");
app.copyLib(ByteBufferPool.class, "jetty-io.jar");
app.copyLib(BadMessageException.class, "jetty-http.jar");
app.copyLib(XmlConfiguration.class, "jetty-xml.jar");
return app;
}
@Test
public void websocketProvidedByServer() throws Exception
{
start(() ->
{
WebAppTester.WebApp app1 = server.createWebApp("/app");
app1.createWebInf();
app1.copyClass(WebSocketClientServlet.class);
app1.copyClass(ClientSocket.class);
app1.deploy();
WebAppTester.WebApp app2 = server.createWebApp("/echo");
app2.createWebInf();
app2.copyClass(EchoSocket.class);
app2.deploy();
});
// After hitting each WebApp we will get 200 response if test succeeds.
ContentResponse response = httpClient.GET(server.getServerUri().resolve("/app/servlet"));
assertThat(response.getStatus(), is(HttpStatus.OK_200));
// The ContextClassLoader in the WebSocketClients onOpen was the WebAppClassloader.
assertThat(response.getContentAsString(), containsString("ContextClassLoader: WebAppClassLoader"));
// Verify that we used Servers version of WebSocketClient.
ClassLoader serverClassLoader = server.getServer().getClass().getClassLoader();
assertThat(response.getContentAsString(), containsString("ClientClassLoader: " + serverClassLoader)); }
@Test
public void websocketProvidedByWebApp() throws Exception
{
start(() ->
{
WebAppTester.WebApp app1 = createWebSocketWebapp("/app");
app1.createWebInf();
app1.copyClass(WebSocketClientServlet.class);
app1.copyClass(ClientSocket.class);
app1.copyClass(EchoSocket.class);
app1.deploy();
// Do not exclude JavaxWebSocketConfiguration for this webapp (we need the websocket server classes).
WebAppTester.WebApp app2 = server.createWebApp("/echo");
app2.createWebInf();
app2.copyClass(EchoSocket.class);
app2.deploy();
});
// After hitting each WebApp we will get 200 response if test succeeds.
ContentResponse response = httpClient.GET(server.getServerUri().resolve("/app/servlet"));
assertThat(response.getStatus(), is(HttpStatus.OK_200));
// The ContextClassLoader in the WebSocketClients onOpen was the WebAppClassloader.
assertThat(response.getContentAsString(), containsString("ContextClassLoader: WebAppClassLoader"));
// Verify that we used WebApps version of WebSocketClient.
assertThat(response.getContentAsString(), containsString("ClientClassLoader: WebAppClassLoader"));
}
}

View File

@ -0,0 +1,261 @@
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.websocket.jsr356.server;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.plus.webapp.EnvConfiguration;
import org.eclipse.jetty.plus.webapp.PlusConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.JAR;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.ArrayUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.PathResource;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.FragmentConfiguration;
import org.eclipse.jetty.webapp.JettyWebXmlConfiguration;
import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.webapp.WebXmlConfiguration;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* Utility to build out exploded directory WebApps.
*/
public class WebAppTester extends ContainerLifeCycle
{
private static final Logger LOG = Log.getLogger(Server.class);
private final Path _testDir;
private final Server _server;
private final ServerConnector _serverConnector;
private final ContextHandlerCollection _contexts;
public WebAppTester()
{
this(null);
}
public WebAppTester(Path testDir)
{
if (testDir == null)
{
try
{
Path targetTestingPath = MavenTestingUtils.getTargetTestingPath();
FS.ensureDirExists(targetTestingPath);
_testDir = Files.createTempDirectory(targetTestingPath, "contexts");
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
else
{
_testDir = testDir;
FS.ensureDirExists(_testDir);
}
_server = new Server();
_serverConnector = new ServerConnector(_server);
_server.addConnector(_serverConnector);
_contexts = new ContextHandlerCollection();
_server.setHandler(_contexts);
addBean(_server);
}
@Override
protected void doStop() throws Exception
{
// Recursively delete testDir when stopping.
org.eclipse.jetty.util.IO.delete(_testDir.toFile());
}
public Server getServer()
{
return _server;
}
public URI getServerUri()
{
if (!isStarted())
throw new IllegalStateException("Not Started");
return URI.create("http://localhost:" + getPort());
}
public int getPort()
{
return _serverConnector.getLocalPort();
}
public WebApp createWebApp(String contextPath)
{
return new WebApp(contextPath);
}
public class WebApp
{
private final WebAppContext _context;
private final Path _contextDir;
private final Path _webInf;
private final Path _classesDir;
private final Path _libDir;
private WebApp(String contextPath)
{
// Ensure context directory.
String contextDirName = contextPath.replace("/", "");
if (contextDirName.length() == 0)
contextDirName = "ROOT";
_contextDir = _testDir.resolve(contextDirName);
FS.ensureEmpty(_contextDir);
// Ensure WEB-INF directories.
_webInf = _contextDir.resolve("WEB-INF");
FS.ensureDirExists(_webInf);
_classesDir = _webInf.resolve("classes");
FS.ensureDirExists(_classesDir);
_libDir = _webInf.resolve("lib");
FS.ensureDirExists(_libDir);
// Configure the WebAppContext.
_context = new WebAppContext();
_context.setContextPath(contextPath);
_context.setBaseResource(new PathResource(_contextDir));
_context.setConfigurations(new Configuration[]
{
new WebInfConfiguration(),
new WebXmlConfiguration(),
new MetaInfConfiguration(),
new FragmentConfiguration(),
new EnvConfiguration(),
new PlusConfiguration(),
new AnnotationConfiguration(),
new JettyWebXmlConfiguration()
});
}
public WebAppContext getWebAppContext()
{
return _context;
}
public String getContextPath()
{
return _context.getContextPath();
}
public Path getContextDir()
{
return _contextDir;
}
public void addConfiguration(Configuration... configurations)
{
_context.setConfigurations(ArrayUtil.add(_context.getConfigurations(), configurations));
}
public void createWebInf() throws IOException
{
String emptyWebXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<web-app\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xmlns=\"http://java.sun.com/xml/ns/javaee\"\n" +
" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n" +
" metadata-complete=\"false\"\n" +
" version=\"3.0\">\n" +
"</web-app>";
File webXml = _webInf.resolve("web.xml").toFile();
try (FileWriter out = new FileWriter(webXml))
{
out.write(emptyWebXml);
}
}
public void copyWebInf(String testResourceName) throws IOException
{
File testWebXml = MavenTestingUtils.getTestResourceFile(testResourceName);
Path webXml = _webInf.resolve("web.xml");
IO.copy(testWebXml, webXml.toFile());
}
public void copyClass(Class<?> clazz) throws Exception
{
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String endpointPath = TypeUtil.toClassReference(clazz);
URL classUrl = cl.getResource(endpointPath);
assertThat("Class URL for: " + clazz, classUrl, notNullValue());
Path destFile = _classesDir.resolve(endpointPath);
FS.ensureDirExists(destFile.getParent());
File srcFile = new File(classUrl.toURI());
IO.copy(srcFile, destFile.toFile());
}
public void copyLib(Class<?> clazz, String jarFileName) throws URISyntaxException, IOException
{
Path jarFile = _libDir.resolve(jarFileName);
URL codeSourceURL = clazz.getProtectionDomain().getCodeSource().getLocation();
assertThat("Class CodeSource URL is file scheme", codeSourceURL.getProtocol(), is("file"));
File sourceCodeSourceFile = new File(codeSourceURL.toURI());
if (sourceCodeSourceFile.isDirectory())
{
LOG.info("Creating " + jarFile + " from " + sourceCodeSourceFile);
JAR.create(sourceCodeSourceFile, jarFile.toFile());
}
else
{
LOG.info("Copying " + sourceCodeSourceFile + " to " + jarFile);
IO.copy(sourceCodeSourceFile, jarFile.toFile());
}
}
public void deploy()
{
_contexts.addHandler(_context);
_contexts.manage(_context);
_context.setThrowUnavailableOnStartupException(true);
if (LOG.isDebugEnabled())
LOG.debug("{}", _context.dump());
}
}
}

View File

@ -76,6 +76,7 @@ public class WebSocketClient extends ContainerLifeCycle implements WebSocketCont
private final Supplier<DecoratedObjectFactory> objectFactorySupplier;
// WebSocket Specifics
private final ClassLoader classloader;
private final WebSocketPolicy policy;
private final WebSocketExtensionFactory extensionRegistry;
private final SessionTracker sessionTracker = new SessionTracker();
@ -112,6 +113,7 @@ public class WebSocketClient extends ContainerLifeCycle implements WebSocketCont
*/
public WebSocketClient(HttpClient httpClient, DecoratedObjectFactory decoratedObjectFactory)
{
this.classloader = Thread.currentThread().getContextClassLoader();
this.httpClient = Objects.requireNonNull(httpClient, "HttpClient");
addBean(httpClient);
@ -262,6 +264,7 @@ public class WebSocketClient extends ContainerLifeCycle implements WebSocketCont
*/
public WebSocketClient(final WebSocketContainerScope scope, EventDriverFactory eventDriverFactory, SessionFactory sessionFactory, HttpClient httpClient)
{
this.classloader = Thread.currentThread().getContextClassLoader();
this.httpClient = httpClient == null ? HttpClientProvider.get(scope) : httpClient;
addBean(this.httpClient);
@ -386,6 +389,12 @@ public class WebSocketClient extends ContainerLifeCycle implements WebSocketCont
return wsReq.sendAsync();
}
@Override
public ClassLoader getClassLoader()
{
return classloader;
}
public void setEventDriverFactory(EventDriverFactory eventDriverFactory)
{
this.eventDriverFactory = eventDriverFactory;

View File

@ -73,12 +73,12 @@ public class WebSocketSession extends ContainerLifeCycle implements Session, Rem
private final WebSocketPolicy policy;
private final AtomicBoolean onCloseCalled = new AtomicBoolean(false);
private final RemoteEndpointFactory remoteEndpointFactory;
private ClassLoader classLoader;
private final ClassLoader classLoader;
private ExtensionFactory extensionFactory;
private String protocolVersion;
private Map<String, String[]> parameterMap = new HashMap<>();
private final Map<String, String[]> parameterMap = new HashMap<>();
private RemoteEndpoint remote;
private IncomingFrames incomingHandler;
private final IncomingFrames incomingHandler;
private OutgoingFrames outgoingHandler;
private UpgradeRequest upgradeRequest;
private UpgradeResponse upgradeResponse;
@ -98,7 +98,7 @@ public class WebSocketSession extends ContainerLifeCycle implements Session, Rem
Objects.requireNonNull(containerScope, "Container Scope cannot be null");
Objects.requireNonNull(requestURI, "Request URI cannot be null");
this.classLoader = Thread.currentThread().getContextClassLoader();
this.classLoader = containerScope.getClassLoader();
this.containerScope = containerScope;
this.requestURI = requestURI;
this.websocket = websocket;

View File

@ -67,6 +67,20 @@ public interface WebSocketContainerScope
*/
SslContextFactory getSslContextFactory();
/**
* <p>The ClassLoader used to load classes for the WebSocketSession.</p>
* <p>By default this will be the ContextClassLoader at the time this method is called. However this will be overridden
* by the WebSocketClient to use the ContextClassLoader at the time it was created, this is because the
* client uses its own {@link org.eclipse.jetty.util.thread.ThreadPool} so the WebSocketSessions may be created when
* the ContextClassLoader is not set.</p>
*
* @return the classloader.
*/
default ClassLoader getClassLoader()
{
return Thread.currentThread().getContextClassLoader();
}
/**
* Test for if the container has been started.
*