Merge pull request #4420 from eclipse/jetty-10.0.x-4407-JavaxAnnotatedConfigDefault

- tests for annotations as default ServerEndpointConfig
- merge annotated ServerEndpointConfig with provided config
- clean up usage of ClientEndpointConfig and testing
- ServerFHF now extends ClientFHF

Signed-off-by: Lachlan Roberts <lachlan@webtide.com>
This commit is contained in:
Lachlan 2019-12-17 13:07:38 +11:00 committed by GitHub
commit 5e558a566d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 114 additions and 161 deletions

View File

@ -67,7 +67,7 @@ public class WebSocketJsrServerTest
TrackingClientEndpoint clientEndpoint = new TrackingClientEndpoint();
Session session = javaxWebSocketClient.connectToServer(clientEndpoint, wsUri);
Session session = javaxWebSocketClient.connectToServer(clientEndpoint, null, wsUri);
session.getBasicRemote().sendText("Hello World");
String response = clientEndpoint.messages.poll(2, SECONDS);

View File

@ -41,7 +41,6 @@ import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.websocket.core.WebSocketComponents;
import org.eclipse.jetty.websocket.core.client.WebSocketCoreClient;
import org.eclipse.jetty.websocket.javax.common.ConfiguredEndpoint;
import org.eclipse.jetty.websocket.javax.common.InvalidWebSocketException;
import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketContainer;
import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketExtensionConfig;
import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketFrameHandler;
@ -200,30 +199,33 @@ public class JavaxWebSocketClientContainer extends JavaxWebSocketContainer imple
}
@Override
public Session connectToServer(final Class<? extends Endpoint> endpointClass, final ClientEndpointConfig config, URI path) throws IOException
public Session connectToServer(final Class<? extends Endpoint> endpointClass, final ClientEndpointConfig providedConfig, URI path) throws DeploymentException, IOException
{
ConfiguredEndpoint instance = newConfiguredEndpoint(endpointClass, config);
return connect(instance, path);
return connectToServer(newEndpoint(endpointClass), providedConfig, path);
}
@Override
public Session connectToServer(final Class<?> annotatedEndpointClass, final URI path) throws IOException
public Session connectToServer(final Class<?> annotatedEndpointClass, final URI path) throws DeploymentException, IOException
{
ConfiguredEndpoint instance = newConfiguredEndpoint(annotatedEndpointClass, new BasicClientEndpointConfig());
return connect(instance, path);
return connectToServer(newEndpoint(annotatedEndpointClass), path);
}
@Override
public Session connectToServer(final Endpoint endpoint, final ClientEndpointConfig config, final URI path) throws DeploymentException, IOException
public Session connectToServer(final Endpoint endpoint, final ClientEndpointConfig providedConfig, final URI path) throws DeploymentException, IOException
{
ConfiguredEndpoint instance = newConfiguredEndpoint(endpoint, config);
ClientEndpointConfig config = providedConfig;
if (config == null)
config = new BasicClientEndpointConfig();
ConfiguredEndpoint instance = new ConfiguredEndpoint(endpoint, config);
return connect(instance, path);
}
@Override
public Session connectToServer(Object endpoint, URI path) throws DeploymentException, IOException
{
ConfiguredEndpoint instance = newConfiguredEndpoint(endpoint, new BasicClientEndpointConfig());
ClientEndpointConfig config = getAnnotatedConfig(endpoint);
ConfiguredEndpoint instance = new ConfiguredEndpoint(endpoint, config);
return connect(instance, path);
}
@ -239,34 +241,24 @@ public class JavaxWebSocketClientContainer extends JavaxWebSocketContainer imple
return getHttpClient().getExecutor();
}
private ConfiguredEndpoint newConfiguredEndpoint(Class<?> endpointClass, EndpointConfig config)
private <T> T newEndpoint(Class<T> endpointClass) throws DeploymentException
{
try
{
return newConfiguredEndpoint(endpointClass.getConstructor().newInstance(), config);
return endpointClass.getConstructor().newInstance();
}
catch (Throwable e)
{
throw new InvalidWebSocketException("Unable to instantiate websocket: " + endpointClass.getName());
throw new DeploymentException("Unable to instantiate websocket: " + endpointClass.getName());
}
}
private ConfiguredEndpoint newConfiguredEndpoint(Object endpoint, EndpointConfig providedConfig) throws DeploymentException
{
EndpointConfig config = readAnnotatedConfig(endpoint, providedConfig != null
? providedConfig : new BasicClientEndpointConfig());
return new ConfiguredEndpoint(endpoint, config);
}
protected EndpointConfig readAnnotatedConfig(Object endpoint, EndpointConfig config) throws DeploymentException
private ClientEndpointConfig getAnnotatedConfig(Object endpoint) throws DeploymentException
{
ClientEndpoint anno = endpoint.getClass().getAnnotation(ClientEndpoint.class);
if (anno != null)
{
// Overwrite Config from Annotation
// TODO: should we merge with provided config?
return new AnnotatedClientEndpointConfig(anno);
}
return config;
if (anno == null)
throw new DeploymentException("Could not get ClientEndpoint annotation for " + endpoint.getClass().getName());
return new AnnotatedClientEndpointConfig(anno);
}
}

View File

@ -29,6 +29,11 @@ import org.eclipse.jetty.websocket.javax.common.util.InvokerUtils;
public class JavaxWebSocketClientFrameHandlerFactory extends JavaxWebSocketFrameHandlerFactory
{
public JavaxWebSocketClientFrameHandlerFactory(JavaxWebSocketContainer container, InvokerUtils.ParamIdentifier paramIdentifier)
{
super(container, paramIdentifier);
}
public JavaxWebSocketClientFrameHandlerFactory(JavaxWebSocketContainer container)
{
super(container, InvokerUtils.PARAM_IDENTITY);

View File

@ -24,7 +24,6 @@ import java.util.concurrent.Executor;
import java.util.function.Function;
import javax.servlet.ServletContext;
import javax.websocket.DeploymentException;
import javax.websocket.EndpointConfig;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
@ -160,18 +159,6 @@ public class JavaxWebSocketServerContainer extends JavaxWebSocketClientContainer
return frameHandlerFactory;
}
protected EndpointConfig readAnnotatedConfig(Object endpoint, EndpointConfig config) throws DeploymentException
{
ServerEndpoint anno = endpoint.getClass().getAnnotation(ServerEndpoint.class);
if (anno != null)
{
// Overwrite with Config from Annotation.
return new AnnotatedServerEndpointConfig(this, endpoint.getClass(), anno, config);
}
return config;
}
@Override
public void addEndpoint(Class<?> endpointClass) throws DeploymentException
{
if (endpointClass == null)
@ -185,10 +172,7 @@ public class JavaxWebSocketServerContainer extends JavaxWebSocketClientContainer
{
ServerEndpoint anno = endpointClass.getAnnotation(ServerEndpoint.class);
if (anno == null)
{
throw new DeploymentException(String.format("Class must be @%s annotated: %s",
ServerEndpoint.class.getName(), endpointClass.getName()));
}
throw new DeploymentException(String.format("Class must be @%s annotated: %s", ServerEndpoint.class.getName(), endpointClass.getName()));
ServerEndpointConfig config = new AnnotatedServerEndpointConfig(this, endpointClass, anno);
addEndpointMapping(config);
@ -207,36 +191,36 @@ public class JavaxWebSocketServerContainer extends JavaxWebSocketClientContainer
}
@Override
public void addEndpoint(ServerEndpointConfig config) throws DeploymentException
public void addEndpoint(ServerEndpointConfig providedConfig) throws DeploymentException
{
if (config == null)
{
if (providedConfig == null)
throw new DeploymentException("ServerEndpointConfig is null");
}
if (isStarted() || isStarting())
{
if (LOG.isDebugEnabled())
{
LOG.debug("addEndpoint({}) path={} endpoint={}", config, config.getPath(), config.getEndpointClass());
}
Class<?> endpointClass = providedConfig.getEndpointClass();
try
{
// If we have annotations merge the annotated ServerEndpointConfig with the provided one.
ServerEndpoint anno = endpointClass.getAnnotation(ServerEndpoint.class);
ServerEndpointConfig config = (anno == null) ? providedConfig
: new AnnotatedServerEndpointConfig(this, endpointClass, anno, providedConfig);
if (LOG.isDebugEnabled())
LOG.debug("addEndpoint({}) path={} endpoint={}", config, config.getPath(), endpointClass);
addEndpointMapping(config);
}
catch (WebSocketException e)
{
throw new DeploymentException("Unable to deploy: " + config.getEndpointClass().getName(), e);
throw new DeploymentException("Unable to deploy: " + endpointClass.getName(), e);
}
}
else
{
if (deferredEndpointConfigs == null)
{
deferredEndpointConfigs = new ArrayList<>();
}
deferredEndpointConfigs.add(config);
deferredEndpointConfigs.add(providedConfig);
}
}

View File

@ -24,14 +24,14 @@ import javax.websocket.server.ServerEndpoint;
import org.eclipse.jetty.http.pathmap.UriTemplatePathSpec;
import org.eclipse.jetty.websocket.core.FrameHandler;
import org.eclipse.jetty.websocket.javax.client.JavaxWebSocketClientFrameHandlerFactory;
import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketContainer;
import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketFrameHandlerFactory;
import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketFrameHandlerMetadata;
import org.eclipse.jetty.websocket.servlet.FrameHandlerFactory;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
public class JavaxWebSocketServerFrameHandlerFactory extends JavaxWebSocketFrameHandlerFactory implements FrameHandlerFactory
public class JavaxWebSocketServerFrameHandlerFactory extends JavaxWebSocketClientFrameHandlerFactory implements FrameHandlerFactory
{
public JavaxWebSocketServerFrameHandlerFactory(JavaxWebSocketContainer container)
{
@ -53,10 +53,9 @@ public class JavaxWebSocketServerFrameHandlerFactory extends JavaxWebSocketFrame
}
ServerEndpoint anno = endpointClass.getAnnotation(ServerEndpoint.class);
if (anno == null)
{
return null;
return super.createMetadata(endpointClass, endpointConfig);
}
UriTemplatePathSpec templatePathSpec = new UriTemplatePathSpec(anno.value());

View File

@ -18,15 +18,13 @@
package org.eclipse.jetty.websocket.javax.tests.client;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.websocket.ClientEndpoint;
import javax.websocket.ClientEndpointConfig;
import javax.websocket.ContainerProvider;
import javax.websocket.Decoder;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import javax.websocket.HandshakeResponse;
import javax.websocket.OnMessage;
@ -41,14 +39,13 @@ import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class AnnotatedEndpointConfigTest
public class AnnotatedClientEndpointTest
{
@ClientEndpoint(
subprotocols = {"chat", "echo-whole"},
@ -92,9 +89,7 @@ public class AnnotatedEndpointConfigTest
}
private static CoreServer server;
private static ClientEndpointConfig ceconfig;
private static EndpointConfig config;
private static Session session;
private static ClientEndpointConfig config;
private static AnnotatedEndpointClient clientEndpoint;
@BeforeAll
@ -106,36 +101,33 @@ public class AnnotatedEndpointConfigTest
// Start Server
server.start();
// Connect client
// Create Client
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
server.addBean(container); // allow to shutdown with server
// Connect to Server
clientEndpoint = new AnnotatedEndpointClient();
session = container.connectToServer(clientEndpoint, server.getWsUri());
assertThat("Session", session, notNullValue());
config = clientEndpoint.config;
assertThat("EndpointConfig", config, notNullValue());
assertThat("EndpointConfig", config, instanceOf(ClientEndpointConfig.class));
ceconfig = (ClientEndpointConfig)config;
assertThat("EndpointConfig", ceconfig, notNullValue());
assertNotNull(container.connectToServer(clientEndpoint, server.getWsUri()));
assertNotNull(clientEndpoint.config);
assertThat(clientEndpoint.config, instanceOf(ClientEndpointConfig.class));
config = (ClientEndpointConfig)clientEndpoint.config;
}
@AfterAll
public static void stopEnv()
{
// Disconnect client
// Close Session
try
{
session.close();
if (clientEndpoint.session != null)
clientEndpoint.session.close();
}
catch (Exception e)
catch (IOException e)
{
e.printStackTrace(System.err);
e.printStackTrace();
}
// Stop server
// Stop Server
try
{
server.stop();
@ -149,69 +141,39 @@ public class AnnotatedEndpointConfigTest
@Test
public void testTextMax() throws Exception
{
assertThat("Client Text Max",
clientEndpoint.session.getMaxTextMessageBufferSize(),
is(111222));
assertThat(clientEndpoint.session.getMaxTextMessageBufferSize(), is(111222));
}
@Test
public void testBinaryMax() throws Exception
{
assertThat("Client Binary Max",
clientEndpoint.session.getMaxBinaryMessageBufferSize(),
is(333444));
assertThat(clientEndpoint.session.getMaxBinaryMessageBufferSize(), is(333444));
}
@Test
public void testSubProtocols() throws Exception
{
List<String> subprotocols = ceconfig.getPreferredSubprotocols();
assertThat("Client Preferred SubProtocols", subprotocols, contains("chat", "echo-whole"));
String subprotocols = String.join(", ", config.getPreferredSubprotocols());
assertThat(subprotocols, is("chat, echo-whole"));
}
@Test
public void testDecoders() throws Exception
{
List<Class<? extends Decoder>> decoders = config.getDecoders();
assertThat("Decoders", decoders, notNullValue());
Class<?> expectedClass = DateDecoder.class;
boolean hasExpectedDecoder = false;
for (Class<? extends Decoder> decoder : decoders)
{
if (expectedClass.isAssignableFrom(decoder))
{
hasExpectedDecoder = true;
}
}
assertTrue(hasExpectedDecoder, "Client Decoders has " + expectedClass.getName());
String decoders = config.getDecoders().stream().map(Class::getName).collect(joining(", "));
assertThat(decoders, is(DateDecoder.class.getName()));
}
@Test
public void testEncoders() throws Exception
{
List<Class<? extends Encoder>> encoders = config.getEncoders();
assertThat("AvailableEncoders", encoders, notNullValue());
Class<?> expectedClass = TimeEncoder.class;
boolean hasExpectedEncoder = false;
for (Class<? extends Encoder> encoder : encoders)
{
if (expectedClass.isAssignableFrom(encoder))
{
hasExpectedEncoder = true;
}
}
assertTrue(hasExpectedEncoder, "Client AvailableEncoders has " + expectedClass.getName());
String encoders = config.getEncoders().stream().map(Class::getName).collect(joining(", "));
assertThat(encoders, is(TimeEncoder.class.getName()));
}
@Test
public void testConfigurator() throws Exception
{
ClientEndpointConfig ceconfig = (ClientEndpointConfig)config;
assertThat("Client Configurator", ceconfig.getConfigurator(), instanceOf(AnnotatedEndpointConfigurator.class));
assertThat(config.getConfigurator(), instanceOf(AnnotatedEndpointConfigurator.class));
}
}

View File

@ -77,7 +77,7 @@ public class EndpointEchoTest
ClientEndpoint clientEndpoint = new ClientEndpoint();
assertThat(clientEndpoint, Matchers.instanceOf(javax.websocket.Endpoint.class));
// Issue connect using instance of class that extends Endpoint
Session session = container.connectToServer(clientEndpoint, server.getWsUri().resolve("/echo/text"));
Session session = container.connectToServer(clientEndpoint, null, server.getWsUri().resolve("/echo/text"));
session.getBasicRemote().sendText("Echo");
String resp = clientEndpoint.messageQueue.poll(1, TimeUnit.SECONDS);
@ -91,7 +91,7 @@ public class EndpointEchoTest
{
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
// Issue connect using class reference (class extends Endpoint)
Session session = container.connectToServer(ClientEndpoint.class, server.getWsUri().resolve("/echo/text"));
Session session = container.connectToServer(ClientEndpoint.class, null, server.getWsUri().resolve("/echo/text"));
session.getBasicRemote().sendText("Echo");
JavaxWebSocketSession jsrSession = (JavaxWebSocketSession)session;

View File

@ -82,7 +82,7 @@ public class WriteTimeoutTest
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
ClientEndpoint clientEndpoint = new ClientEndpoint();
assertThat(clientEndpoint, Matchers.instanceOf(javax.websocket.Endpoint.class));
Session session = container.connectToServer(clientEndpoint, server.getWsUri().resolve("/logSocket"));
Session session = container.connectToServer(clientEndpoint, null, server.getWsUri().resolve("/logSocket"));
session.getAsyncRemote().setSendTimeout(5);

View File

@ -60,7 +60,7 @@ public class MisbehavingClassTest
try (StacklessLogging ignored = new StacklessLogging(WebSocketCoreSession.class))
{
// expecting RuntimeException during onOpen
container.connectToServer(socket, server.getWsUri());
container.connectToServer(socket, null, server.getWsUri());
assertThat("Close should have occurred", socket.closeLatch.await(1, TimeUnit.SECONDS), is(true));
Throwable cause = socket.errors.pop();
assertThat("Error", cause, instanceOf(RuntimeException.class));

View File

@ -18,54 +18,49 @@
package org.eclipse.jetty.websocket.javax.tests.server;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.websocket.server.ServerEndpointConfig;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.websocket.core.CloseStatus;
import org.eclipse.jetty.websocket.core.Frame;
import org.eclipse.jetty.websocket.core.OpCode;
import org.eclipse.jetty.websocket.javax.tests.Fuzzer;
import org.eclipse.jetty.websocket.javax.tests.WSServer;
import org.eclipse.jetty.websocket.javax.tests.LocalServer;
import org.eclipse.jetty.websocket.javax.tests.coders.DateDecoder;
import org.eclipse.jetty.websocket.javax.tests.coders.TimeEncoder;
import org.eclipse.jetty.websocket.javax.tests.server.configs.EchoSocketConfigurator;
import org.eclipse.jetty.websocket.javax.tests.server.sockets.ConfiguredEchoSocket;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Example of an annotated echo server discovered via annotation scanning.
*/
public class AnnotatedServerEndpointTest
{
private static WSServer server;
private LocalServer server;
private String path = "/echo";
private String subprotocol = "echo";
@BeforeAll
public static void startServer() throws Exception
@BeforeEach
public void startServer() throws Exception
{
Path testdir = MavenTestingUtils.getTargetTestingPath(AnnotatedServerEndpointTest.class.getName());
server = new WSServer(testdir, "app");
server.createWebInf();
server.copyEndpoint(ConfiguredEchoSocket.class);
server.copyClass(EchoSocketConfigurator.class);
server.copyClass(DateDecoder.class);
server.copyClass(TimeEncoder.class);
server = new LocalServer();
server.start();
server.getServerContainer().addEndpoint(ConfiguredEchoSocket.class);
WebAppContext webapp = server.createWebAppContext();
server.deployWebapp(webapp);
ServerEndpointConfig endpointConfig = ServerEndpointConfig.Builder
.create(ConfiguredEchoSocket.class, "/override")
.subprotocols(Collections.singletonList("override"))
.build();
server.getServerContainer().addEndpoint(endpointConfig);
}
@AfterAll
public static void stopServer() throws Exception
@AfterEach
public void stopServer() throws Exception
{
server.stop();
}
@ -73,7 +68,7 @@ public class AnnotatedServerEndpointTest
private void assertResponse(String message, String expectedText) throws Exception
{
Map<String, String> headers = new HashMap<>();
headers.put(HttpHeader.SEC_WEBSOCKET_SUBPROTOCOL.asString(), "echo");
headers.put(HttpHeader.SEC_WEBSOCKET_SUBPROTOCOL.asString(), subprotocol);
List<Frame> send = new ArrayList<>();
send.add(new Frame(OpCode.TEXT).setPayload(message));
@ -83,7 +78,7 @@ public class AnnotatedServerEndpointTest
expect.add(new Frame(OpCode.TEXT).setPayload(expectedText));
expect.add(CloseStatus.toFrame(CloseStatus.NORMAL));
try (Fuzzer session = server.newNetworkFuzzer("/app/echo", headers))
try (Fuzzer session = server.newNetworkFuzzer(path, headers))
{
session.sendFrames(send);
session.expect(expect);
@ -125,4 +120,18 @@ public class AnnotatedServerEndpointTest
{
assertResponse("subprotocols", "chat, echo, test");
}
@Test
public void testOverrideEndpointConfig() throws Exception
{
this.path = "/override";
this.subprotocol = "override";
assertResponse("configurator", EchoSocketConfigurator.class.getName());
assertResponse("text-max", "111,222");
assertResponse("binary-max", "333,444");
assertResponse("decoders", DateDecoder.class.getName());
assertResponse("encoders", TimeEncoder.class.getName());
assertResponse("subprotocols", "override");
}
}

View File

@ -30,11 +30,12 @@ import javax.servlet.ServletException;
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.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import javax.websocket.server.ServerEndpoint;
@ -73,9 +74,10 @@ public class WebSocketServerContainerExecutorTest
}
}
public static class EndpointAdapter extends Endpoint
@ClientEndpoint
public static class EndpointAdapter
{
@Override
@OnOpen
public void onOpen(Session session, EndpointConfig config)
{
/* do nothing */