Search in sources :

Example 16 with Extension

use of javax.websocket.Extension in project jetty.project by eclipse.

the class ClientContainer method connect.

private Session connect(EndpointInstance instance, URI path) throws IOException {
    Objects.requireNonNull(instance, "EndpointInstance cannot be null");
    Objects.requireNonNull(path, "Path cannot be null");
    ClientEndpointConfig config = (ClientEndpointConfig) instance.getConfig();
    ClientUpgradeRequest req = new ClientUpgradeRequest();
    UpgradeListener upgradeListener = null;
    for (Extension ext : config.getExtensions()) {
        req.addExtensions(new JsrExtensionConfig(ext));
    }
    if (config.getPreferredSubprotocols().size() > 0) {
        req.setSubProtocols(config.getPreferredSubprotocols());
    }
    if (config.getConfigurator() != null) {
        upgradeListener = new JsrUpgradeListener(config.getConfigurator());
    }
    Future<org.eclipse.jetty.websocket.api.Session> futSess = client.connect(instance, path, req, upgradeListener);
    try {
        return (JsrSession) futSess.get();
    } catch (InterruptedException e) {
        throw new IOException("Connect failure", e);
    } catch (ExecutionException e) {
        // Unwrap Actual Cause
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            // Just rethrow
            throw (IOException) cause;
        } else {
            throw new IOException("Connect failure", cause);
        }
    }
}
Also used : IOException(java.io.IOException) Extension(javax.websocket.Extension) UpgradeListener(org.eclipse.jetty.websocket.client.io.UpgradeListener) EmptyClientEndpointConfig(org.eclipse.jetty.websocket.jsr356.client.EmptyClientEndpointConfig) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) ClientUpgradeRequest(org.eclipse.jetty.websocket.client.ClientUpgradeRequest) ExecutionException(java.util.concurrent.ExecutionException) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Session(javax.websocket.Session)

Example 17 with Extension

use of javax.websocket.Extension in project jetty.project by eclipse.

the class JsrCreator method createWebSocket.

@Override
public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
    JsrHandshakeRequest jsrHandshakeRequest = new JsrHandshakeRequest(req);
    JsrHandshakeResponse jsrHandshakeResponse = new JsrHandshakeResponse(resp);
    // Get raw config, as defined when the endpoint was added to the container
    ServerEndpointConfig config = metadata.getConfig();
    // Establish a copy of the config, so that the UserProperties are unique
    // per upgrade request.
    config = new BasicServerEndpointConfig(containerScope, config);
    // Bug 444617 - Expose localAddress and remoteAddress for jsr modify handshake to use
    // This is being implemented as an optional set of userProperties so that
    // it is not JSR api breaking.  A few users on #jetty and a few from cometd
    // have asked for access to this information.
    Map<String, Object> userProperties = config.getUserProperties();
    userProperties.put(PROP_LOCAL_ADDRESS, req.getLocalSocketAddress());
    userProperties.put(PROP_REMOTE_ADDRESS, req.getRemoteSocketAddress());
    userProperties.put(PROP_LOCALES, Collections.list(req.getLocales()));
    // Get Configurator from config object (not guaranteed to be unique per endpoint upgrade)
    ServerEndpointConfig.Configurator configurator = config.getConfigurator();
    // [JSR] Step 1: check origin
    if (!configurator.checkOrigin(req.getOrigin())) {
        try {
            resp.sendForbidden("Origin mismatch");
        } catch (IOException e) {
            if (LOG.isDebugEnabled())
                LOG.debug("Unable to send error response", e);
        }
        return null;
    }
    // [JSR] Step 2: deal with sub protocols
    List<String> supported = config.getSubprotocols();
    List<String> requested = req.getSubProtocols();
    String subprotocol = configurator.getNegotiatedSubprotocol(supported, requested);
    if (StringUtil.isNotBlank(subprotocol)) {
        resp.setAcceptedSubProtocol(subprotocol);
    }
    // [JSR] Step 3: deal with extensions
    List<Extension> installedExtensions = new ArrayList<>();
    for (String extName : extensionFactory.getAvailableExtensions().keySet()) {
        installedExtensions.add(new JsrExtension(extName));
    }
    List<Extension> requestedExts = new ArrayList<>();
    for (ExtensionConfig reqCfg : req.getExtensions()) {
        requestedExts.add(new JsrExtension(reqCfg));
    }
    List<Extension> usedExtensions = configurator.getNegotiatedExtensions(installedExtensions, requestedExts);
    List<ExtensionConfig> configs = new ArrayList<>();
    if (usedExtensions != null) {
        for (Extension used : usedExtensions) {
            ExtensionConfig ecfg = new ExtensionConfig(used.getName());
            for (Parameter param : used.getParameters()) {
                ecfg.setParameter(param.getName(), param.getValue());
            }
            configs.add(ecfg);
        }
    }
    resp.setExtensions(configs);
    // [JSR] Step 4: build out new ServerEndpointConfig
    PathSpec pathSpec = jsrHandshakeRequest.getRequestPathSpec();
    if (pathSpec instanceof UriTemplatePathSpec) {
        // We have a PathParam path spec
        UriTemplatePathSpec wspathSpec = (UriTemplatePathSpec) pathSpec;
        String requestPath = req.getRequestPath();
        // Wrap the config with the path spec information
        config = new PathParamServerEndpointConfig(containerScope, config, wspathSpec, requestPath);
    }
    // [JSR] Step 5: Call modifyHandshake
    configurator.modifyHandshake(config, jsrHandshakeRequest, jsrHandshakeResponse);
    try {
        // [JSR] Step 6: create endpoint class
        Class<?> endpointClass = config.getEndpointClass();
        Object endpoint = config.getConfigurator().getEndpointInstance(endpointClass);
        // This will allow CDI to see Session for injection into Endpoint classes.
        return new EndpointInstance(endpoint, config, metadata);
    } catch (InstantiationException e) {
        if (LOG.isDebugEnabled())
            LOG.debug("Unable to create websocket: " + config.getEndpointClass().getName(), e);
        return null;
    }
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ArrayList(java.util.ArrayList) EndpointInstance(org.eclipse.jetty.websocket.jsr356.endpoints.EndpointInstance) IOException(java.io.IOException) UriTemplatePathSpec(org.eclipse.jetty.http.pathmap.UriTemplatePathSpec) PathSpec(org.eclipse.jetty.http.pathmap.PathSpec) JsrExtension(org.eclipse.jetty.websocket.jsr356.JsrExtension) Extension(javax.websocket.Extension) JsrExtension(org.eclipse.jetty.websocket.jsr356.JsrExtension) UriTemplatePathSpec(org.eclipse.jetty.http.pathmap.UriTemplatePathSpec) ExtensionConfig(org.eclipse.jetty.websocket.api.extensions.ExtensionConfig) Parameter(javax.websocket.Extension.Parameter)

Example 18 with Extension

use of javax.websocket.Extension in project jetty.project by eclipse.

the class ExtensionStackProcessingTest method testDeflateFrameExtension.

@Test
public void testDeflateFrameExtension() throws Exception {
    assumeDeflateFrameAvailable();
    ClientEndpointConfig config = ClientEndpointConfig.Builder.create().extensions(Arrays.<Extension>asList(new JsrExtension("deflate-frame"))).build();
    final String content = "deflate_me";
    final CountDownLatch messageLatch = new CountDownLatch(1);
    URI uri = URI.create("ws://localhost:" + connector.getLocalPort());
    Session session = client.connectToServer(new EndpointAdapter() {

        @Override
        public void onMessage(String message) {
            Assert.assertEquals(content, message);
            messageLatch.countDown();
        }
    }, config, uri);
    // Make sure everything is wired properly.
    OutgoingFrames firstOut = ((JsrSession) session).getOutgoingHandler();
    Assert.assertTrue(firstOut instanceof ExtensionStack);
    ExtensionStack extensionStack = (ExtensionStack) firstOut;
    Assert.assertTrue(extensionStack.isRunning());
    OutgoingFrames secondOut = extensionStack.getNextOutgoing();
    Assert.assertTrue(secondOut instanceof DeflateFrameExtension);
    DeflateFrameExtension deflateExtension = (DeflateFrameExtension) secondOut;
    Assert.assertTrue(deflateExtension.isRunning());
    OutgoingFrames thirdOut = deflateExtension.getNextOutgoing();
    Assert.assertTrue(thirdOut instanceof WebSocketClientConnection);
    final CountDownLatch latch = new CountDownLatch(1);
    session.getAsyncRemote().sendText(content, new SendHandler() {

        @Override
        public void onResult(SendResult result) {
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(messageLatch.await(5, TimeUnit.SECONDS));
}
Also used : SendHandler(javax.websocket.SendHandler) WebSocketClientConnection(org.eclipse.jetty.websocket.client.io.WebSocketClientConnection) JsrSession(org.eclipse.jetty.websocket.jsr356.JsrSession) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ExtensionStack(org.eclipse.jetty.websocket.common.extensions.ExtensionStack) JsrExtension(org.eclipse.jetty.websocket.jsr356.JsrExtension) Extension(javax.websocket.Extension) DeflateFrameExtension(org.eclipse.jetty.websocket.common.extensions.compress.DeflateFrameExtension) JsrExtension(org.eclipse.jetty.websocket.jsr356.JsrExtension) SendResult(javax.websocket.SendResult) OutgoingFrames(org.eclipse.jetty.websocket.api.extensions.OutgoingFrames) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) DeflateFrameExtension(org.eclipse.jetty.websocket.common.extensions.compress.DeflateFrameExtension) Session(javax.websocket.Session) JsrSession(org.eclipse.jetty.websocket.jsr356.JsrSession) Test(org.junit.Test)

Example 19 with Extension

use of javax.websocket.Extension in project jetty.project by eclipse.

the class ExtensionStackProcessingTest method testPerMessageDeflateExtension.

@Test
public void testPerMessageDeflateExtension() throws Exception {
    assumeDeflateFrameAvailable();
    ClientEndpointConfig config = ClientEndpointConfig.Builder.create().extensions(Arrays.<Extension>asList(new JsrExtension("permessage-deflate"))).build();
    final String content = "deflate_me";
    final CountDownLatch messageLatch = new CountDownLatch(1);
    URI uri = URI.create("ws://localhost:" + connector.getLocalPort());
    Session session = client.connectToServer(new EndpointAdapter() {

        @Override
        public void onMessage(String message) {
            Assert.assertEquals(content, message);
            messageLatch.countDown();
        }
    }, config, uri);
    final CountDownLatch latch = new CountDownLatch(1);
    session.getAsyncRemote().sendText(content, new SendHandler() {

        @Override
        public void onResult(SendResult result) {
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(messageLatch.await(5, TimeUnit.SECONDS));
}
Also used : Extension(javax.websocket.Extension) DeflateFrameExtension(org.eclipse.jetty.websocket.common.extensions.compress.DeflateFrameExtension) JsrExtension(org.eclipse.jetty.websocket.jsr356.JsrExtension) SendHandler(javax.websocket.SendHandler) SendResult(javax.websocket.SendResult) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) JsrExtension(org.eclipse.jetty.websocket.jsr356.JsrExtension) Session(javax.websocket.Session) JsrSession(org.eclipse.jetty.websocket.jsr356.JsrSession) Test(org.junit.Test)

Example 20 with Extension

use of javax.websocket.Extension in project spring-framework by spring-projects.

the class AbstractStandardUpgradeStrategy method upgrade.

@Override
public void upgrade(ServerHttpRequest request, ServerHttpResponse response, String selectedProtocol, List<WebSocketExtension> selectedExtensions, Principal user, WebSocketHandler wsHandler, Map<String, Object> attrs) throws HandshakeFailureException {
    HttpHeaders headers = request.getHeaders();
    InetSocketAddress localAddr = null;
    try {
        localAddr = request.getLocalAddress();
    } catch (Exception ex) {
    // Ignore
    }
    InetSocketAddress remoteAddr = null;
    try {
        remoteAddr = request.getRemoteAddress();
    } catch (Exception ex) {
    // Ignore
    }
    StandardWebSocketSession session = new StandardWebSocketSession(headers, attrs, localAddr, remoteAddr, user);
    StandardWebSocketHandlerAdapter endpoint = new StandardWebSocketHandlerAdapter(wsHandler, session);
    List<Extension> extensions = new ArrayList<>();
    for (WebSocketExtension extension : selectedExtensions) {
        extensions.add(new WebSocketToStandardExtensionAdapter(extension));
    }
    upgradeInternal(request, response, selectedProtocol, extensions, endpoint);
}
Also used : Extension(javax.websocket.Extension) WebSocketExtension(org.springframework.web.socket.WebSocketExtension) HttpHeaders(org.springframework.http.HttpHeaders) WebSocketExtension(org.springframework.web.socket.WebSocketExtension) StandardWebSocketHandlerAdapter(org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter) StandardWebSocketSession(org.springframework.web.socket.adapter.standard.StandardWebSocketSession) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) HandshakeFailureException(org.springframework.web.socket.server.HandshakeFailureException) WebSocketToStandardExtensionAdapter(org.springframework.web.socket.adapter.standard.WebSocketToStandardExtensionAdapter)

Aggregations

Extension (javax.websocket.Extension)22 ArrayList (java.util.ArrayList)16 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)6 URI (java.net.URI)5 WebSocketExtension (io.undertow.websockets.WebSocketExtension)4 DeploymentException (javax.websocket.DeploymentException)4 Endpoint (javax.websocket.Endpoint)4 Parameter (javax.websocket.Extension.Parameter)4 Session (javax.websocket.Session)4 IOException (java.io.IOException)3 InetSocketAddress (java.net.InetSocketAddress)3 HashMap (java.util.HashMap)3 List (java.util.List)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)3 JsrExtension (org.eclipse.jetty.websocket.jsr356.JsrExtension)3 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)2 ExtensionHandshake (io.undertow.websockets.extensions.ExtensionHandshake)2 HashSet (java.util.HashSet)2 ExecutionException (java.util.concurrent.ExecutionException)2