Search in sources :

Example 16 with ClientEndpointConfig

use of javax.websocket.ClientEndpointConfig in project tomcat by apache.

the class TesterWsClientAutobahn method executeTestCase.

private static void executeTestCase(WebSocketContainer wsc, int testCase) throws Exception {
    URI uri = new URI("ws://" + HOST + ":" + PORT + "/runCase?case=" + testCase + "&agent=" + USER_AGENT);
    TestCaseClient testCaseClient = new TestCaseClient();
    Extension permessageDeflate = new WsExtension("permessage-deflate");
    // Advertise support for client_max_window_bits
    // Client only supports some values so there will be some failures here
    // Note Autobahn returns a 400 response if you provide a value for
    // client_max_window_bits
    permessageDeflate.getParameters().add(new WsExtensionParameter("client_max_window_bits", null));
    List<Extension> extensions = new ArrayList<>(1);
    extensions.add(permessageDeflate);
    Endpoint ep = new PojoEndpointClient(testCaseClient, null);
    ClientEndpointConfig.Builder builder = ClientEndpointConfig.Builder.create();
    ClientEndpointConfig config = builder.extensions(extensions).build();
    wsc.connectToServer(ep, config, uri);
    testCaseClient.waitForClose();
}
Also used : Extension(javax.websocket.Extension) Endpoint(javax.websocket.Endpoint) ClientEndpoint(javax.websocket.ClientEndpoint) PojoEndpointClient(org.apache.tomcat.websocket.pojo.PojoEndpointClient) ArrayList(java.util.ArrayList) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) URI(java.net.URI)

Example 17 with ClientEndpointConfig

use of javax.websocket.ClientEndpointConfig in project tomcat by apache.

the class TestWsWebSocketContainer method doTestPerMessageDeflateClient.

private void doTestPerMessageDeflateClient(String msg, int count) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");
    tomcat.start();
    Extension perMessageDeflate = new WsExtension(PerMessageDeflate.NAME);
    List<Extension> extensions = new ArrayList<>(1);
    extensions.add(perMessageDeflate);
    ClientEndpointConfig clientConfig = ClientEndpointConfig.Builder.create().extensions(extensions).build();
    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    Session wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class, clientConfig, new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(count);
    BasicText handler = new BasicText(latch, msg);
    wsSession.addMessageHandler(handler);
    for (int i = 0; i < count; i++) {
        wsSession.getBasicRemote().sendText(msg);
    }
    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    ((WsWebSocketContainer) wsContainer).destroy();
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) WebSocketContainer(javax.websocket.WebSocketContainer) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) Endpoint(javax.websocket.Endpoint) ServerEndpoint(javax.websocket.server.ServerEndpoint) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) Extension(javax.websocket.Extension) BasicText(org.apache.tomcat.websocket.TesterMessageCountClient.BasicText) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) Session(javax.websocket.Session)

Example 18 with ClientEndpointConfig

use of javax.websocket.ClientEndpointConfig in project undertow by undertow-io.

the class ServerWebSocketContainer method connectToServer.

public Session connectToServer(final Endpoint endpointInstance, final ClientEndpointConfig config, WebSocketClient.ConnectionBuilder connectionBuilder) throws DeploymentException, IOException {
    if (closed) {
        throw new ClosedChannelException();
    }
    ClientEndpointConfig cec = config != null ? config : ClientEndpointConfig.Builder.create().build();
    WebSocketClientNegotiation clientNegotiation = connectionBuilder.getClientNegotiation();
    IoFuture<WebSocketChannel> session = connectionBuilder.connect();
    Number timeout = (Number) cec.getUserProperties().get(TIMEOUT);
    if (session.await(timeout == null ? DEFAULT_WEB_SOCKET_TIMEOUT_SECONDS : timeout.intValue(), TimeUnit.SECONDS) == IoFuture.Status.WAITING) {
        //add a notifier to close the channel if the connection actually completes
        session.cancel();
        session.addNotifier(new IoFuture.HandlingNotifier<WebSocketChannel, Object>() {

            @Override
            public void handleDone(WebSocketChannel data, Object attachment) {
                IoUtils.safeClose(data);
            }
        }, null);
        throw JsrWebSocketMessages.MESSAGES.connectionTimedOut();
    }
    WebSocketChannel channel;
    try {
        channel = session.get();
    } catch (UpgradeFailedException e) {
        throw new DeploymentException(e.getMessage(), e);
    }
    EndpointSessionHandler sessionHandler = new EndpointSessionHandler(this);
    final List<Extension> extensions = new ArrayList<>();
    final Map<String, Extension> extMap = new HashMap<>();
    for (Extension ext : cec.getExtensions()) {
        extMap.put(ext.getName(), ext);
    }
    for (WebSocketExtension e : clientNegotiation.getSelectedExtensions()) {
        Extension ext = extMap.get(e.getName());
        if (ext == null) {
            throw JsrWebSocketMessages.MESSAGES.extensionWasNotPresentInClientHandshake(e.getName(), clientNegotiation.getSupportedExtensions());
        }
        extensions.add(ExtensionImpl.create(e));
    }
    ConfiguredClientEndpoint configured = clientEndpoints.get(endpointInstance.getClass());
    if (configured == null) {
        synchronized (clientEndpoints) {
            configured = clientEndpoints.get(endpointInstance.getClass());
            if (configured == null) {
                clientEndpoints.put(endpointInstance.getClass(), configured = new ConfiguredClientEndpoint());
            }
        }
    }
    EncodingFactory encodingFactory = EncodingFactory.createFactory(classIntrospecter, cec.getDecoders(), cec.getEncoders());
    UndertowSession undertowSession = new UndertowSession(channel, connectionBuilder.getUri(), Collections.<String, String>emptyMap(), Collections.<String, List<String>>emptyMap(), sessionHandler, null, new ImmediateInstanceHandle<>(endpointInstance), cec, connectionBuilder.getUri().getQuery(), encodingFactory.createEncoding(cec), configured, clientNegotiation.getSelectedSubProtocol(), extensions, connectionBuilder);
    endpointInstance.onOpen(undertowSession, cec);
    channel.resumeReceives();
    return undertowSession;
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) WebSocketExtension(io.undertow.websockets.WebSocketExtension) HashMap(java.util.HashMap) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) ArrayList(java.util.ArrayList) IoFuture(org.xnio.IoFuture) WebSocketExtension(io.undertow.websockets.WebSocketExtension) Extension(javax.websocket.Extension) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation) UpgradeFailedException(org.xnio.http.UpgradeFailedException) DeploymentException(javax.websocket.DeploymentException) ClientEndpointConfig(javax.websocket.ClientEndpointConfig)

Example 19 with ClientEndpointConfig

use of javax.websocket.ClientEndpointConfig in project undertow by undertow-io.

the class ServerWebSocketContainer method connectToServer.

@Override
public Session connectToServer(final Endpoint endpointInstance, final ClientEndpointConfig config, final URI path) throws DeploymentException, IOException {
    if (closed) {
        throw new ClosedChannelException();
    }
    ClientEndpointConfig cec = config != null ? config : ClientEndpointConfig.Builder.create().build();
    XnioSsl ssl = null;
    for (WebsocketClientSslProvider provider : clientSslProviders) {
        ssl = provider.getSsl(xnioWorker, endpointInstance, cec, path);
        if (ssl != null) {
            break;
        }
    }
    //in theory we should not be able to connect until the deployment is complete, but the definition of when a deployment is complete is a bit nebulous.
    WebSocketClientNegotiation clientNegotiation = new ClientNegotiation(cec.getPreferredSubprotocols(), toExtensionList(cec.getExtensions()), cec);
    WebSocketClient.ConnectionBuilder connectionBuilder = WebSocketClient.connectionBuilder(xnioWorker, bufferPool, path).setSsl(ssl).setBindAddress(clientBindAddress).setClientNegotiation(clientNegotiation);
    return connectToServer(endpointInstance, config, connectionBuilder);
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) XnioSsl(org.xnio.ssl.XnioSsl) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) WebSocketClient(io.undertow.websockets.client.WebSocketClient) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation)

Example 20 with ClientEndpointConfig

use of javax.websocket.ClientEndpointConfig in project undertow by undertow-io.

the class WebsocketBasicAuthTestCase method testAuthenticatedWebsocket.

@Test
public void testAuthenticatedWebsocket() throws Exception {
    ProgramaticClientEndpoint endpoint = new ProgramaticClientEndpoint();
    ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().configurator(new ClientConfigurator() {

        @Override
        public void beforeRequest(Map<String, List<String>> headers) {
            headers.put(AUTHORIZATION.toString(), Collections.singletonList(BASIC + " " + FlexBase64.encodeString("user1:password1".getBytes(), false)));
        }
    }).build();
    ContainerProvider.getWebSocketContainer().connectToServer(endpoint, clientEndpointConfig, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/servletContext/secured"));
    Assert.assertEquals("user1", endpoint.getResponses().poll(15, TimeUnit.SECONDS));
    endpoint.session.close();
    endpoint.closeLatch.await(10, TimeUnit.SECONDS);
}
Also used : ClientEndpointConfig(javax.websocket.ClientEndpointConfig) ClientConfigurator(io.undertow.websockets.jsr.test.annotated.ClientConfigurator) Map(java.util.Map) HashMap(java.util.HashMap) URI(java.net.URI) Test(org.junit.Test)

Aggregations

ClientEndpointConfig (javax.websocket.ClientEndpointConfig)44 Test (org.junit.Test)26 URI (java.net.URI)25 Session (javax.websocket.Session)19 Endpoint (javax.websocket.Endpoint)13 CountDownLatch (java.util.concurrent.CountDownLatch)12 WebSocketContainer (javax.websocket.WebSocketContainer)12 ClientEndpoint (javax.websocket.ClientEndpoint)8 Context (org.apache.catalina.Context)7 DefaultServlet (org.apache.catalina.servlets.DefaultServlet)7 Tomcat (org.apache.catalina.startup.Tomcat)7 ArrayList (java.util.ArrayList)6 EndpointConfig (javax.websocket.EndpointConfig)6 Extension (javax.websocket.Extension)6 BasicText (org.apache.tomcat.websocket.TesterMessageCountClient.BasicText)6 AnnotatedClientEndpointMetadata (org.eclipse.jetty.websocket.jsr356.client.AnnotatedClientEndpointMetadata)5 List (java.util.List)4 ServerEndpoint (javax.websocket.server.ServerEndpoint)4 AnnotatedEndpointScanner (org.eclipse.jetty.websocket.jsr356.annotations.AnnotatedEndpointScanner)4 EmptyClientEndpointConfig (org.eclipse.jetty.websocket.jsr356.client.EmptyClientEndpointConfig)4