use of javax.websocket.Endpoint in project undertow by undertow-io.
the class TestMessagesReceivedInOrder method testMessagesReceivedInOrder.
@Test
public void testMessagesReceivedInOrder() throws Exception {
stacks.clear();
EchoSocket.receivedEchos = new FutureResult<>();
final ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
final CountDownLatch done = new CountDownLatch(1);
final AtomicReference<String> error = new AtomicReference<>();
ContainerProvider.getWebSocketContainer().connectToServer(new Endpoint() {
@Override
public void onOpen(final Session session, EndpointConfig endpointConfig) {
try {
RemoteEndpoint.Basic rem = session.getBasicRemote();
List<String> messages = new ArrayList<>();
for (int i = 0; i < MESSAGES; i++) {
byte[] data = new byte[2048];
(new Random()).nextBytes(data);
String crc = md5(data);
rem.sendBinary(ByteBuffer.wrap(data));
messages.add(crc);
}
List<String> received = EchoSocket.receivedEchos.getIoFuture().get();
StringBuilder sb = new StringBuilder();
boolean fail = false;
for (int i = 0; i < messages.size(); i++) {
if (received.size() <= i) {
fail = true;
sb.append(i + ": should be " + messages.get(i) + " but is empty.");
} else {
if (!messages.get(i).equals(received.get(i))) {
fail = true;
sb.append(i + ": should be " + messages.get(i) + " but is " + received.get(i) + " (but found at " + received.indexOf(messages.get(i)) + ").");
}
}
}
if (fail) {
error.set(sb.toString());
}
done.countDown();
} catch (Throwable t) {
t.printStackTrace();
}
}
}, clientEndpointConfig, new URI(DefaultServer.getDefaultServerURL() + "/webSocket"));
assertTrue(done.await(30, TimeUnit.SECONDS));
if (error.get() != null) {
Assert.fail(error.get());
}
}
use of javax.websocket.Endpoint in project wildfly by wildfly.
the class UndertowJSRWebSocketDeploymentProcessor method deploy.
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
if (module == null) {
return;
}
ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(module.getClassLoader());
WarMetaData metaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
if (metaData == null || metaData.getMergedJBossWebMetaData() == null) {
return;
}
if (!metaData.getMergedJBossWebMetaData().isEnableWebSockets()) {
return;
}
final Set<Class<?>> annotatedEndpoints = new HashSet<>();
final Set<Class<? extends Endpoint>> endpoints = new HashSet<>();
final Set<Class<? extends ServerApplicationConfig>> config = new HashSet<>();
final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
final List<AnnotationInstance> serverEndpoints = index.getAnnotations(SERVER_ENDPOINT);
if (serverEndpoints != null) {
for (AnnotationInstance endpoint : serverEndpoints) {
if (endpoint.target() instanceof ClassInfo) {
ClassInfo clazz = (ClassInfo) endpoint.target();
try {
Class<?> moduleClass = ClassLoadingUtils.loadClass(clazz.name().toString(), module);
if (!Modifier.isAbstract(moduleClass.getModifiers())) {
annotatedEndpoints.add(moduleClass);
}
} catch (ClassNotFoundException e) {
UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketEndpoint(clazz.name().toString(), e);
}
}
}
}
final List<AnnotationInstance> clientEndpoints = index.getAnnotations(CLIENT_ENDPOINT);
if (clientEndpoints != null) {
for (AnnotationInstance endpoint : clientEndpoints) {
if (endpoint.target() instanceof ClassInfo) {
ClassInfo clazz = (ClassInfo) endpoint.target();
try {
Class<?> moduleClass = ClassLoadingUtils.loadClass(clazz.name().toString(), module);
if (!Modifier.isAbstract(moduleClass.getModifiers())) {
annotatedEndpoints.add(moduleClass);
}
} catch (ClassNotFoundException e) {
UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketEndpoint(clazz.name().toString(), e);
}
}
}
}
final Set<ClassInfo> subclasses = index.getAllKnownImplementors(SERVER_APPLICATION_CONFIG);
if (subclasses != null) {
for (final ClassInfo clazz : subclasses) {
try {
Class<?> moduleClass = ClassLoadingUtils.loadClass(clazz.name().toString(), module);
if (!Modifier.isAbstract(moduleClass.getModifiers())) {
config.add((Class) moduleClass);
}
} catch (ClassNotFoundException e) {
UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketConfig(clazz.name().toString(), e);
}
}
}
final Set<ClassInfo> epClasses = index.getAllKnownSubclasses(ENDPOINT);
if (epClasses != null) {
for (final ClassInfo clazz : epClasses) {
try {
Class<?> moduleClass = ClassLoadingUtils.loadClass(clazz.name().toString(), module);
if (!Modifier.isAbstract(moduleClass.getModifiers())) {
endpoints.add((Class) moduleClass);
}
} catch (ClassNotFoundException e) {
UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketConfig(clazz.name().toString(), e);
}
}
}
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
doDeployment(deploymentUnit, webSocketDeploymentInfo, annotatedEndpoints, config, endpoints);
installWebsockets(phaseContext, webSocketDeploymentInfo);
} finally {
Thread.currentThread().setContextClassLoader(oldCl);
}
}
use of javax.websocket.Endpoint in project jetty.project by eclipse.
the class ClientContainer method getClientEndpointMetadata.
public EndpointMetadata getClientEndpointMetadata(Class<?> endpoint, EndpointConfig config) {
synchronized (endpointClientMetadataCache) {
EndpointMetadata metadata = endpointClientMetadataCache.get(endpoint);
if (metadata != null) {
return metadata;
}
ClientEndpoint anno = endpoint.getAnnotation(ClientEndpoint.class);
if (anno != null) {
// Annotated takes precedence here
AnnotatedClientEndpointMetadata annoMetadata = new AnnotatedClientEndpointMetadata(this, endpoint);
AnnotatedEndpointScanner<ClientEndpoint, ClientEndpointConfig> scanner = new AnnotatedEndpointScanner<>(annoMetadata);
scanner.scan();
metadata = annoMetadata;
} else if (Endpoint.class.isAssignableFrom(endpoint)) {
// extends Endpoint
@SuppressWarnings("unchecked") Class<? extends Endpoint> eendpoint = (Class<? extends Endpoint>) endpoint;
metadata = new SimpleEndpointMetadata(eendpoint, config);
} else {
StringBuilder err = new StringBuilder();
err.append("Not a recognized websocket [");
err.append(endpoint.getName());
err.append("] does not extend @").append(ClientEndpoint.class.getName());
err.append(" or extend from ").append(Endpoint.class.getName());
throw new InvalidWebSocketException(err.toString());
}
endpointClientMetadataCache.put(endpoint, metadata);
return metadata;
}
}
use of javax.websocket.Endpoint in project jetty.project by eclipse.
the class ServerContainer method getServerEndpointMetadata.
public ServerEndpointMetadata getServerEndpointMetadata(final Class<?> endpoint, final ServerEndpointConfig config) throws DeploymentException {
ServerEndpointMetadata metadata = null;
ServerEndpoint anno = endpoint.getAnnotation(ServerEndpoint.class);
if (anno != null) {
// Annotated takes precedence here
AnnotatedServerEndpointMetadata ametadata = new AnnotatedServerEndpointMetadata(this, endpoint, config);
AnnotatedEndpointScanner<ServerEndpoint, ServerEndpointConfig> scanner = new AnnotatedEndpointScanner<>(ametadata);
metadata = ametadata;
scanner.scan();
} else if (Endpoint.class.isAssignableFrom(endpoint)) {
// extends Endpoint
@SuppressWarnings("unchecked") Class<? extends Endpoint> eendpoint = (Class<? extends Endpoint>) endpoint;
metadata = new SimpleServerEndpointMetadata(eendpoint, config);
} else {
StringBuilder err = new StringBuilder();
err.append("Not a recognized websocket [");
err.append(endpoint.getName());
err.append("] does not extend @").append(ServerEndpoint.class.getName());
err.append(" or extend from ").append(Endpoint.class.getName());
throw new DeploymentException("Unable to identify as valid Endpoint: " + endpoint);
}
return metadata;
}
use of javax.websocket.Endpoint in project jetty.project by eclipse.
the class WebSocketServerContainerInitializer method onStartup.
@Override
public void onStartup(Set<Class<?>> c, ServletContext context) throws ServletException {
if (!isEnabledViaContext(context, ENABLE_KEY, true)) {
LOG.info("JSR-356 is disabled by configuration");
return;
}
ContextHandler handler = ContextHandler.getContextHandler(context);
if (handler == null) {
throw new ServletException("Not running on Jetty, JSR-356 support unavailable");
}
if (!(handler instanceof ServletContextHandler)) {
throw new ServletException("Not running in Jetty ServletContextHandler, JSR-356 support unavailable");
}
ServletContextHandler jettyContext = (ServletContextHandler) handler;
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(context.getClassLoader());
// Create the Jetty ServerContainer implementation
ServerContainer jettyContainer = configureContext(jettyContext);
// make sure context is cleaned up when the context stops
context.addListener(new ContextDestroyListener());
if (c.isEmpty()) {
if (LOG.isDebugEnabled()) {
LOG.debug("No JSR-356 annotations or interfaces discovered");
}
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Found {} classes", c.size());
}
// Now process the incoming classes
Set<Class<? extends Endpoint>> discoveredExtendedEndpoints = new HashSet<>();
Set<Class<?>> discoveredAnnotatedEndpoints = new HashSet<>();
Set<Class<? extends ServerApplicationConfig>> serverAppConfigs = new HashSet<>();
filterClasses(c, discoveredExtendedEndpoints, discoveredAnnotatedEndpoints, serverAppConfigs);
if (LOG.isDebugEnabled()) {
LOG.debug("Discovered {} extends Endpoint classes", discoveredExtendedEndpoints.size());
LOG.debug("Discovered {} @ServerEndpoint classes", discoveredAnnotatedEndpoints.size());
LOG.debug("Discovered {} ServerApplicationConfig classes", serverAppConfigs.size());
}
// Process the server app configs to determine endpoint filtering
boolean wasFiltered = false;
Set<ServerEndpointConfig> deployableExtendedEndpointConfigs = new HashSet<>();
Set<Class<?>> deployableAnnotatedEndpoints = new HashSet<>();
for (Class<? extends ServerApplicationConfig> clazz : serverAppConfigs) {
if (LOG.isDebugEnabled()) {
LOG.debug("Found ServerApplicationConfig: {}", clazz);
}
try {
ServerApplicationConfig config = clazz.newInstance();
Set<ServerEndpointConfig> seconfigs = config.getEndpointConfigs(discoveredExtendedEndpoints);
if (seconfigs != null) {
wasFiltered = true;
deployableExtendedEndpointConfigs.addAll(seconfigs);
}
Set<Class<?>> annotatedClasses = config.getAnnotatedEndpointClasses(discoveredAnnotatedEndpoints);
if (annotatedClasses != null) {
wasFiltered = true;
deployableAnnotatedEndpoints.addAll(annotatedClasses);
}
} catch (InstantiationException | IllegalAccessException e) {
throw new ServletException("Unable to instantiate: " + clazz.getName(), e);
}
}
// Default behavior if nothing filtered
if (!wasFiltered) {
deployableAnnotatedEndpoints.addAll(discoveredAnnotatedEndpoints);
// Note: it is impossible to determine path of "extends Endpoint" discovered classes
deployableExtendedEndpointConfigs = new HashSet<>();
}
if (LOG.isDebugEnabled()) {
LOG.debug("Deploying {} ServerEndpointConfig(s)", deployableExtendedEndpointConfigs.size());
}
// Deploy what should be deployed.
for (ServerEndpointConfig config : deployableExtendedEndpointConfigs) {
try {
jettyContainer.addEndpoint(config);
} catch (DeploymentException e) {
throw new ServletException(e);
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Deploying {} @ServerEndpoint(s)", deployableAnnotatedEndpoints.size());
}
for (Class<?> annotatedClass : deployableAnnotatedEndpoints) {
try {
jettyContainer.addEndpoint(annotatedClass);
} catch (DeploymentException e) {
throw new ServletException(e);
}
}
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
Aggregations