Skip to content

Commit

Permalink
Merge pull request #5054 from eclipse/jetty-10.0.x-5043-AnonymousWebS…
Browse files Browse the repository at this point in the history
…ocketListener

Issue #5043 - allow anonymous WebSocketListener / Endpoint classes to be used
  • Loading branch information
joakime authored Jul 22, 2020
2 parents b5eff0e + 0a30525 commit 25a2326
Show file tree
Hide file tree
Showing 8 changed files with 122 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
package org.eclipse.jetty.websocket.javax.client.internal;

import javax.websocket.ClientEndpoint;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;

import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketContainer;
Expand Down Expand Up @@ -49,7 +48,7 @@ public EndpointConfig newDefaultEndpointConfig(Class<?> endpointClass)
public JavaxWebSocketFrameHandlerMetadata getMetadata(Class<?> endpointClass, EndpointConfig endpointConfig)
{
if (javax.websocket.Endpoint.class.isAssignableFrom(endpointClass))
return createEndpointMetadata((Class<? extends Endpoint>)endpointClass, endpointConfig);
return createEndpointMetadata(endpointConfig);

if (endpointClass.getAnnotation(ClientEndpoint.class) == null)
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,20 +250,20 @@ private MethodHandle toMethodHandle(MethodHandles.Lookup lookup, Method method)
}
}

protected JavaxWebSocketFrameHandlerMetadata createEndpointMetadata(Class<? extends Endpoint> endpointClass, EndpointConfig endpointConfig)
protected JavaxWebSocketFrameHandlerMetadata createEndpointMetadata(EndpointConfig endpointConfig)
{
JavaxWebSocketFrameHandlerMetadata metadata = new JavaxWebSocketFrameHandlerMetadata(endpointConfig);
MethodHandles.Lookup lookup = getApplicationMethodHandleLookup(endpointClass);
MethodHandles.Lookup lookup = getServerMethodHandleLookup();

Method openMethod = ReflectUtils.findMethod(endpointClass, "onOpen", Session.class, EndpointConfig.class);
Method openMethod = ReflectUtils.findMethod(Endpoint.class, "onOpen", Session.class, EndpointConfig.class);
MethodHandle open = toMethodHandle(lookup, openMethod);
metadata.setOpenHandler(open, openMethod);

Method closeMethod = ReflectUtils.findMethod(endpointClass, "onClose", Session.class, CloseReason.class);
Method closeMethod = ReflectUtils.findMethod(Endpoint.class, "onClose", Session.class, CloseReason.class);
MethodHandle close = toMethodHandle(lookup, closeMethod);
metadata.setCloseHandler(close, closeMethod);

Method errorMethod = ReflectUtils.findMethod(endpointClass, "onError", Session.class, Throwable.class);
Method errorMethod = ReflectUtils.findMethod(Endpoint.class, "onError", Session.class, Throwable.class);
MethodHandle error = toMethodHandle(lookup, errorMethod);
metadata.setErrorHandler(error, errorMethod);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

import javax.websocket.ClientEndpoint;
import javax.websocket.ClientEndpointConfig;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;

import org.eclipse.jetty.websocket.util.InvokerUtils;
Expand All @@ -43,7 +42,7 @@ public JavaxWebSocketFrameHandlerMetadata getMetadata(Class<?> endpointClass, En
{
if (javax.websocket.Endpoint.class.isAssignableFrom(endpointClass))
{
return createEndpointMetadata((Class<? extends Endpoint>)endpointClass, endpointConfig);
return createEndpointMetadata(endpointConfig);
}

if (endpointClass.getAnnotation(ClientEndpoint.class) == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

package org.eclipse.jetty.websocket.javax.server.internal;

import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.server.ServerEndpoint;

Expand All @@ -42,7 +41,7 @@ public JavaxWebSocketServerFrameHandlerFactory(JavaxWebSocketContainer container
public JavaxWebSocketFrameHandlerMetadata getMetadata(Class<?> endpointClass, EndpointConfig endpointConfig)
{
if (javax.websocket.Endpoint.class.isAssignableFrom(endpointClass))
return createEndpointMetadata((Class<? extends Endpoint>)endpointClass, endpointConfig);
return createEndpointMetadata(endpointConfig);

ServerEndpoint anno = endpointClass.getAnnotation(ServerEndpoint.class);
if (anno == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@

public class JavaxOnCloseTest
{
private static BlockingArrayQueue<OnCloseEndpoint> serverEndpoints = new BlockingArrayQueue<>();
private static final BlockingArrayQueue<OnCloseEndpoint> serverEndpoints = new BlockingArrayQueue<>();

private Server server;
private ServerConnector connector;
private JavaxWebSocketClientContainer client = new JavaxWebSocketClientContainer();
private final JavaxWebSocketClientContainer client = new JavaxWebSocketClientContainer();

@ServerEndpoint("/")
public static class OnCloseEndpoint extends EventSocket
Expand Down Expand Up @@ -84,7 +84,7 @@ public void onClose(CloseReason reason)
@ClientEndpoint
public static class BlockingClientEndpoint extends EventSocket
{
private CountDownLatch blockInClose = new CountDownLatch(1);
private final CountDownLatch blockInClose = new CountDownLatch(1);

public void unBlockClose()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,18 @@

package org.eclipse.jetty.websocket.javax.tests.client;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession;
import org.eclipse.jetty.websocket.javax.tests.LocalServer;
import org.eclipse.jetty.websocket.javax.tests.WSEndpointTracker;
Expand All @@ -35,6 +40,7 @@

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class EndpointEchoTest
{
Expand Down Expand Up @@ -105,4 +111,45 @@ public void testEchoClassRef() throws Exception
session.close();
endpoint.awaitCloseEvent("Client");
}

@Test
public void testEchoAnonymousInstance() throws Exception
{
CountDownLatch openLatch = new CountDownLatch(1);
CountDownLatch closeLatch = new CountDownLatch(1);
BlockingQueue<String> textMessages = new BlockingArrayQueue<>();
Endpoint clientEndpoint = new Endpoint()
{
@Override
public void onOpen(Session session, EndpointConfig config)
{
// Cannot replace this with a lambda or it breaks ReflectUtils.findGenericClassFor().
session.addMessageHandler(new MessageHandler.Whole<String>()
{
@Override
public void onMessage(String message)
{
textMessages.add(message);
}
});
openLatch.countDown();
}

@Override
public void onClose(Session session, CloseReason closeReason)
{
closeLatch.countDown();
}
};

WebSocketContainer container = ContainerProvider.getWebSocketContainer();
Session session = container.connectToServer(clientEndpoint, null, server.getWsUri().resolve("/echo/text"));
assertTrue(openLatch.await(5, TimeUnit.SECONDS));
session.getBasicRemote().sendText("Echo");

String resp = textMessages.poll(1, TimeUnit.SECONDS);
assertThat("Response echo", resp, is("Echo"));
session.close();
assertTrue(closeLatch.await(5, TimeUnit.SECONDS));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -195,60 +195,63 @@ private MethodHandle toMethodHandle(MethodHandles.Lookup lookup, Method method)
private JettyWebSocketFrameHandlerMetadata createListenerMetadata(Class<?> endpointClass)
{
JettyWebSocketFrameHandlerMetadata metadata = new JettyWebSocketFrameHandlerMetadata();
MethodHandles.Lookup lookup = JettyWebSocketFrameHandlerFactory.getApplicationMethodHandleLookup(endpointClass);
MethodHandles.Lookup lookup = JettyWebSocketFrameHandlerFactory.getServerMethodHandleLookup();

Method openMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketConnect", Session.class);
if (!WebSocketConnectionListener.class.isAssignableFrom(endpointClass))
throw new IllegalArgumentException("Class " + endpointClass + " does not implement " + WebSocketConnectionListener.class);

Method openMethod = ReflectUtils.findMethod(WebSocketConnectionListener.class, "onWebSocketConnect", Session.class);
MethodHandle open = toMethodHandle(lookup, openMethod);
metadata.setOpenHandler(open, openMethod);

Method closeMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketClose", int.class, String.class);
Method closeMethod = ReflectUtils.findMethod(WebSocketConnectionListener.class, "onWebSocketClose", int.class, String.class);
MethodHandle close = toMethodHandle(lookup, closeMethod);
metadata.setCloseHandler(close, closeMethod);

Method errorMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketError", Throwable.class);
Method errorMethod = ReflectUtils.findMethod(WebSocketConnectionListener.class, "onWebSocketError", Throwable.class);
MethodHandle error = toMethodHandle(lookup, errorMethod);
metadata.setErrorHandler(error, errorMethod);

// Simple Data Listener
if (WebSocketListener.class.isAssignableFrom(endpointClass))
{
Method textMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketText", String.class);
Method textMethod = ReflectUtils.findMethod(WebSocketListener.class, "onWebSocketText", String.class);
MethodHandle text = toMethodHandle(lookup, textMethod);
metadata.setTextHandler(StringMessageSink.class, text, textMethod);

Method binaryMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketBinary", byte[].class, int.class, int.class);
Method binaryMethod = ReflectUtils.findMethod(WebSocketListener.class, "onWebSocketBinary", byte[].class, int.class, int.class);
MethodHandle binary = toMethodHandle(lookup, binaryMethod);
metadata.setBinaryHandle(ByteArrayMessageSink.class, binary, binaryMethod);
}

// Ping/Pong Listener
if (WebSocketPingPongListener.class.isAssignableFrom(endpointClass))
{
Method pongMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketPong", ByteBuffer.class);
Method pongMethod = ReflectUtils.findMethod(WebSocketPingPongListener.class, "onWebSocketPong", ByteBuffer.class);
MethodHandle pong = toMethodHandle(lookup, pongMethod);
metadata.setPongHandle(pong, pongMethod);

Method pingMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketPing", ByteBuffer.class);
Method pingMethod = ReflectUtils.findMethod(WebSocketPingPongListener.class, "onWebSocketPing", ByteBuffer.class);
MethodHandle ping = toMethodHandle(lookup, pingMethod);
metadata.setPingHandle(ping, pingMethod);
}

// Partial Data / Message Listener
if (WebSocketPartialListener.class.isAssignableFrom(endpointClass))
{
Method textMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketPartialText", String.class, boolean.class);
Method textMethod = ReflectUtils.findMethod(WebSocketPartialListener.class, "onWebSocketPartialText", String.class, boolean.class);
MethodHandle text = toMethodHandle(lookup, textMethod);
metadata.setTextHandler(PartialStringMessageSink.class, text, textMethod);

Method binaryMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketPartialBinary", ByteBuffer.class, boolean.class);
Method binaryMethod = ReflectUtils.findMethod(WebSocketPartialListener.class, "onWebSocketPartialBinary", ByteBuffer.class, boolean.class);
MethodHandle binary = toMethodHandle(lookup, binaryMethod);
metadata.setBinaryHandle(PartialByteBufferMessageSink.class, binary, binaryMethod);
}

// Frame Listener
if (WebSocketFrameListener.class.isAssignableFrom(endpointClass))
{
Method frameMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketFrame", Frame.class);
Method frameMethod = ReflectUtils.findMethod(WebSocketFrameListener.class, "onWebSocketFrame", Frame.class);
MethodHandle frame = toMethodHandle(lookup, frameMethod);
metadata.setFrameHandler(frame, frameMethod);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,27 @@
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.websocket.tests.EchoSocket;
import org.eclipse.jetty.websocket.tests.EventSocket;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
Expand All @@ -60,6 +67,8 @@ public void before() throws Exception
contextHandler.setContextPath("/");
JettyWebSocketServletContainerInitializer.configure(contextHandler, (context, container) ->
{
container.addMapping("/echo", (req, res) -> new EchoSocket());

for (Class<?> c : getClassListFromArguments(TextListeners.getTextListeners()))
{
container.addMapping("/text/" + c.getSimpleName(), (req, res) -> construct(c));
Expand Down Expand Up @@ -125,6 +134,47 @@ public void testBinaryListeners(Class<?> clazz) throws Exception
assertThat(clientEndpoint.closeReason, is("standard close"));
}

@Test
public void testAnonymousListener() throws Exception
{
CountDownLatch openLatch = new CountDownLatch(1);
CountDownLatch closeLatch = new CountDownLatch(1);
BlockingQueue<String> textMessages = new BlockingArrayQueue<>();
WebSocketListener clientEndpoint = new WebSocketListener()
{
@Override
public void onWebSocketConnect(Session session)
{
openLatch.countDown();
}

@Override
public void onWebSocketText(String message)
{
textMessages.add(message);
}

@Override
public void onWebSocketClose(int statusCode, String reason)
{
closeLatch.countDown();
}
};

Session session = client.connect(clientEndpoint, serverUri.resolve("/echo")).get(5, TimeUnit.SECONDS);
assertTrue(openLatch.await(5, TimeUnit.SECONDS));

// Send and receive echo on client.
String payload = "hello world";
session.getRemote().sendString(payload);
String echoMessage = textMessages.poll(5, TimeUnit.SECONDS);
assertThat(echoMessage, is(payload));

// Close normally.
session.close(StatusCode.NORMAL, "standard close");
assertTrue(closeLatch.await(5, TimeUnit.SECONDS));
}

private List<Class<?>> getClassListFromArguments(Stream<Arguments> stream)
{
return stream.map(arguments -> (Class<?>)arguments.get()[0]).collect(Collectors.toList());
Expand Down

0 comments on commit 25a2326

Please sign in to comment.