Search in sources :

Example 21 with Endpoint

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());
    }
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) Endpoint(javax.websocket.Endpoint) RemoteEndpoint(javax.websocket.RemoteEndpoint) ServerEndpoint(javax.websocket.server.ServerEndpoint) Random(java.util.Random) ArrayList(java.util.ArrayList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) Test(org.junit.Test)

Example 22 with Endpoint

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);
    }
}
Also used : WarMetaData(org.jboss.as.web.common.WarMetaData) CompositeIndex(org.jboss.as.server.deployment.annotation.CompositeIndex) ServerApplicationConfig(javax.websocket.server.ServerApplicationConfig) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) Endpoint(javax.websocket.Endpoint) ServerEndpoint(javax.websocket.server.ServerEndpoint) ClientEndpoint(javax.websocket.ClientEndpoint) Module(org.jboss.modules.Module) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) AnnotationInstance(org.jboss.jandex.AnnotationInstance) HashSet(java.util.HashSet) ClassInfo(org.jboss.jandex.ClassInfo)

Example 23 with Endpoint

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;
    }
}
Also used : SimpleEndpointMetadata(org.eclipse.jetty.websocket.jsr356.client.SimpleEndpointMetadata) InvalidWebSocketException(org.eclipse.jetty.websocket.api.InvalidWebSocketException) Endpoint(javax.websocket.Endpoint) ClientEndpoint(javax.websocket.ClientEndpoint) AnnotatedEndpointScanner(org.eclipse.jetty.websocket.jsr356.annotations.AnnotatedEndpointScanner) EmptyClientEndpointConfig(org.eclipse.jetty.websocket.jsr356.client.EmptyClientEndpointConfig) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) ClientEndpoint(javax.websocket.ClientEndpoint) AnnotatedClientEndpointMetadata(org.eclipse.jetty.websocket.jsr356.client.AnnotatedClientEndpointMetadata) SimpleEndpointMetadata(org.eclipse.jetty.websocket.jsr356.client.SimpleEndpointMetadata) AnnotatedClientEndpointMetadata(org.eclipse.jetty.websocket.jsr356.client.AnnotatedClientEndpointMetadata) EndpointMetadata(org.eclipse.jetty.websocket.jsr356.metadata.EndpointMetadata)

Example 24 with Endpoint

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;
}
Also used : ServerEndpoint(javax.websocket.server.ServerEndpoint) Endpoint(javax.websocket.Endpoint) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) AnnotatedEndpointScanner(org.eclipse.jetty.websocket.jsr356.annotations.AnnotatedEndpointScanner) DeploymentException(javax.websocket.DeploymentException) ServerEndpoint(javax.websocket.server.ServerEndpoint)

Example 25 with Endpoint

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);
    }
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ServerApplicationConfig(javax.websocket.server.ServerApplicationConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ServletException(javax.servlet.ServletException) ServerEndpoint(javax.websocket.server.ServerEndpoint) Endpoint(javax.websocket.Endpoint) DeploymentException(javax.websocket.DeploymentException) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ServerContainer(org.eclipse.jetty.websocket.jsr356.server.ServerContainer) HashSet(java.util.HashSet)

Aggregations

Endpoint (javax.websocket.Endpoint)46 Session (javax.websocket.Session)29 URI (java.net.URI)24 EndpointConfig (javax.websocket.EndpointConfig)24 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)20 AtomicReference (java.util.concurrent.atomic.AtomicReference)18 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)14 UndertowSession (io.undertow.websockets.jsr.UndertowSession)14 AnnotatedClientEndpoint (io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint)14 FrameChecker (io.undertow.websockets.utils.FrameChecker)14 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)14 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)14 FutureResult (org.xnio.FutureResult)14 IOException (java.io.IOException)13 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)12 MessageHandler (javax.websocket.MessageHandler)12 ByteBuffer (java.nio.ByteBuffer)11 ServerEndpoint (javax.websocket.server.ServerEndpoint)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 ClientEndpoint (javax.websocket.ClientEndpoint)10