Search in sources :

Example 16 with DeploymentException

use of javax.websocket.DeploymentException in project AngularBeans by bessemHmidi.

the class AngularBeansServletContextListener method initJSR356.

public void initJSR356() throws ServletException {
    sockJsServer = new SockJsServer();
    sockJsServer.init();
    if (sockJsServer.options.websocket) {
        // Make sure we listen on all possible mappings of the servlet
        // for (String mapping :
        // getServletContext().getServletRegistration(context.getServletName()).getMappings())
        // {
        final String commonPrefix = extractPrefixFromMapping("/rt-service/*");
        //
        String websocketPath = commonPrefix + "/{server}/{session}/websocket";
        ServerEndpointConfig sockJsConfig = ServerEndpointConfig.Builder.create(SockJsEndpoint.class, websocketPath).configurator(configuratorFor(commonPrefix, false)).build();
        // rt-service/websocket
        String rawWebsocketPath = commonPrefix + "/websocket";
        ServerEndpointConfig rawWsConfig = ServerEndpointConfig.Builder.create(RawWebsocketEndpoint.class, rawWebsocketPath).configurator(configuratorFor(commonPrefix, true)).build();
        ServerContainer serverContainer = (ServerContainer) context.getAttribute("javax.websocket.server.ServerContainer");
        try {
            serverContainer.addEndpoint(sockJsConfig);
            serverContainer.addEndpoint(rawWsConfig);
            Logger.getLogger(this.getClass().getSimpleName()).info("deployement of programmatic Web socket EndPoint :" + rawWebsocketPath);
        } catch (DeploymentException ex) {
            throw new ServletException("Error deploying websocket endpoint:", ex);
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) DeploymentException(javax.websocket.DeploymentException) SockJsServer(org.projectodd.sockjs.SockJsServer) ServerContainer(javax.websocket.server.ServerContainer)

Example 17 with DeploymentException

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

the class WsWebSocketContainer method connectToServer.

// socketChannel is closed
@SuppressWarnings("resource")
@Override
public Session connectToServer(Endpoint endpoint, ClientEndpointConfig clientEndpointConfiguration, URI path) throws DeploymentException {
    boolean secure = false;
    ByteBuffer proxyConnect = null;
    URI proxyPath;
    // Validate scheme (and build proxyPath)
    String scheme = path.getScheme();
    if ("ws".equalsIgnoreCase(scheme)) {
        proxyPath = URI.create("http" + path.toString().substring(2));
    } else if ("wss".equalsIgnoreCase(scheme)) {
        proxyPath = URI.create("https" + path.toString().substring(3));
        secure = true;
    } else {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.pathWrongScheme", scheme));
    }
    // Validate host
    String host = path.getHost();
    if (host == null) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.pathNoHost"));
    }
    int port = path.getPort();
    SocketAddress sa = null;
    // Check to see if a proxy is configured. Javadoc indicates return value
    // will never be null
    List<Proxy> proxies = ProxySelector.getDefault().select(proxyPath);
    Proxy selectedProxy = null;
    for (Proxy proxy : proxies) {
        if (proxy.type().equals(Proxy.Type.HTTP)) {
            sa = proxy.address();
            if (sa instanceof InetSocketAddress) {
                InetSocketAddress inet = (InetSocketAddress) sa;
                if (inet.isUnresolved()) {
                    sa = new InetSocketAddress(inet.getHostName(), inet.getPort());
                }
            }
            selectedProxy = proxy;
            break;
        }
    }
    // scheme
    if (port == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else {
            // Must be wss due to scheme validation above
            port = 443;
        }
    }
    // If sa is null, no proxy is configured so need to create sa
    if (sa == null) {
        sa = new InetSocketAddress(host, port);
    } else {
        proxyConnect = createProxyRequest(host, port);
    }
    // Create the initial HTTP request to open the WebSocket connection
    Map<String, List<String>> reqHeaders = createRequestHeaders(host, port, clientEndpointConfiguration.getPreferredSubprotocols(), clientEndpointConfiguration.getExtensions());
    clientEndpointConfiguration.getConfigurator().beforeRequest(reqHeaders);
    if (Constants.DEFAULT_ORIGIN_HEADER_VALUE != null && !reqHeaders.containsKey(Constants.ORIGIN_HEADER_NAME)) {
        List<String> originValues = new ArrayList<>(1);
        originValues.add(Constants.DEFAULT_ORIGIN_HEADER_VALUE);
        reqHeaders.put(Constants.ORIGIN_HEADER_NAME, originValues);
    }
    ByteBuffer request = createRequest(path, reqHeaders);
    AsynchronousSocketChannel socketChannel;
    try {
        socketChannel = AsynchronousSocketChannel.open(getAsynchronousChannelGroup());
    } catch (IOException ioe) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.asynchronousSocketChannelFail"), ioe);
    }
    // Get the connection timeout
    long timeout = Constants.IO_TIMEOUT_MS_DEFAULT;
    String timeoutValue = (String) clientEndpointConfiguration.getUserProperties().get(Constants.IO_TIMEOUT_MS_PROPERTY);
    if (timeoutValue != null) {
        timeout = Long.valueOf(timeoutValue).intValue();
    }
    // Set-up
    // Same size as the WsFrame input buffer
    ByteBuffer response = ByteBuffer.allocate(maxBinaryMessageBufferSize);
    String subProtocol;
    boolean success = false;
    List<Extension> extensionsAgreed = new ArrayList<>();
    Transformation transformation = null;
    // Open the connection
    Future<Void> fConnect = socketChannel.connect(sa);
    AsyncChannelWrapper channel = null;
    if (proxyConnect != null) {
        try {
            fConnect.get(timeout, TimeUnit.MILLISECONDS);
            // Proxy CONNECT is clear text
            channel = new AsyncChannelWrapperNonSecure(socketChannel);
            writeRequest(channel, proxyConnect, timeout);
            HttpResponse httpResponse = processResponse(response, channel, timeout);
            if (httpResponse.getStatus() != 200) {
                throw new DeploymentException(sm.getString("wsWebSocketContainer.proxyConnectFail", selectedProxy, Integer.toString(httpResponse.getStatus())));
            }
        } catch (TimeoutException | InterruptedException | ExecutionException | EOFException e) {
            if (channel != null) {
                channel.close();
            }
            throw new DeploymentException(sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
        }
    }
    if (secure) {
        // Regardless of whether a non-secure wrapper was created for a
        // proxy CONNECT, need to use TLS from this point on so wrap the
        // original AsynchronousSocketChannel
        SSLEngine sslEngine = createSSLEngine(clientEndpointConfiguration.getUserProperties());
        channel = new AsyncChannelWrapperSecure(socketChannel, sslEngine);
    } else if (channel == null) {
        // Only need to wrap as this point if it wasn't wrapped to process a
        // proxy CONNECT
        channel = new AsyncChannelWrapperNonSecure(socketChannel);
    }
    try {
        fConnect.get(timeout, TimeUnit.MILLISECONDS);
        Future<Void> fHandshake = channel.handshake();
        fHandshake.get(timeout, TimeUnit.MILLISECONDS);
        writeRequest(channel, request, timeout);
        HttpResponse httpResponse = processResponse(response, channel, timeout);
        // TODO: Handle redirects
        if (httpResponse.status != 101) {
            throw new DeploymentException(sm.getString("wsWebSocketContainer.invalidStatus", Integer.toString(httpResponse.status)));
        }
        HandshakeResponse handshakeResponse = httpResponse.getHandshakeResponse();
        clientEndpointConfiguration.getConfigurator().afterResponse(handshakeResponse);
        // Sub-protocol
        List<String> protocolHeaders = handshakeResponse.getHeaders().get(Constants.WS_PROTOCOL_HEADER_NAME);
        if (protocolHeaders == null || protocolHeaders.size() == 0) {
            subProtocol = null;
        } else if (protocolHeaders.size() == 1) {
            subProtocol = protocolHeaders.get(0);
        } else {
            throw new DeploymentException(sm.getString("wsWebSocketContainer.invalidSubProtocol"));
        }
        // Extensions
        // Should normally only be one header but handle the case of
        // multiple headers
        List<String> extHeaders = handshakeResponse.getHeaders().get(Constants.WS_EXTENSIONS_HEADER_NAME);
        if (extHeaders != null) {
            for (String extHeader : extHeaders) {
                Util.parseExtensionHeader(extensionsAgreed, extHeader);
            }
        }
        // Build the transformations
        TransformationFactory factory = TransformationFactory.getInstance();
        for (Extension extension : extensionsAgreed) {
            List<List<Extension.Parameter>> wrapper = new ArrayList<>(1);
            wrapper.add(extension.getParameters());
            Transformation t = factory.create(extension.getName(), wrapper, false);
            if (t == null) {
                throw new DeploymentException(sm.getString("wsWebSocketContainer.invalidExtensionParameters"));
            }
            if (transformation == null) {
                transformation = t;
            } else {
                transformation.setNext(t);
            }
        }
        success = true;
    } catch (ExecutionException | InterruptedException | SSLException | EOFException | TimeoutException e) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
    } finally {
        if (!success) {
            channel.close();
        }
    }
    // Switch to WebSocket
    WsRemoteEndpointImplClient wsRemoteEndpointClient = new WsRemoteEndpointImplClient(channel);
    WsSession wsSession = new WsSession(endpoint, wsRemoteEndpointClient, this, null, null, null, null, null, extensionsAgreed, subProtocol, Collections.<String, String>emptyMap(), secure, clientEndpointConfiguration);
    WsFrameClient wsFrameClient = new WsFrameClient(response, channel, wsSession, transformation);
    // WsFrame adds the necessary final transformations. Copy the
    // completed transformation chain to the remote end point.
    wsRemoteEndpointClient.setTransformation(wsFrameClient.getTransformation());
    endpoint.onOpen(wsSession, clientEndpointConfiguration);
    registerSession(endpoint, wsSession);
    /* It is possible that the server sent one or more messages as soon as
         * the WebSocket connection was established. Depending on the exact
         * timing of when those messages were sent they could be sat in the
         * input buffer waiting to be read and will not trigger a "data
         * available to read" event. Therefore, it is necessary to process the
         * input buffer here. Note that this happens on the current thread which
         * means that this thread will be used for any onMessage notifications.
         * This is a special case. Subsequent "data available to read" events
         * will be handled by threads from the AsyncChannelGroup's executor.
         */
    wsFrameClient.startInputProcessing();
    return wsSession;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SSLEngine(javax.net.ssl.SSLEngine) ArrayList(java.util.ArrayList) URI(java.net.URI) SSLException(javax.net.ssl.SSLException) HandshakeResponse(javax.websocket.HandshakeResponse) Proxy(java.net.Proxy) EOFException(java.io.EOFException) List(java.util.List) ArrayList(java.util.ArrayList) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Endpoint(javax.websocket.Endpoint) ClientEndpoint(javax.websocket.ClientEndpoint) Extension(javax.websocket.Extension) AsynchronousSocketChannel(java.nio.channels.AsynchronousSocketChannel) DeploymentException(javax.websocket.DeploymentException)

Example 18 with DeploymentException

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

the class WsWebSocketContainer method createSSLEngine.

private SSLEngine createSSLEngine(Map<String, Object> userProperties) throws DeploymentException {
    try {
        // See if a custom SSLContext has been provided
        SSLContext sslContext = (SSLContext) userProperties.get(Constants.SSL_CONTEXT_PROPERTY);
        if (sslContext == null) {
            // Create the SSL Context
            sslContext = SSLContext.getInstance("TLS");
            // Trust store
            String sslTrustStoreValue = (String) userProperties.get(Constants.SSL_TRUSTSTORE_PROPERTY);
            if (sslTrustStoreValue != null) {
                String sslTrustStorePwdValue = (String) userProperties.get(Constants.SSL_TRUSTSTORE_PWD_PROPERTY);
                if (sslTrustStorePwdValue == null) {
                    sslTrustStorePwdValue = Constants.SSL_TRUSTSTORE_PWD_DEFAULT;
                }
                File keyStoreFile = new File(sslTrustStoreValue);
                KeyStore ks = KeyStore.getInstance("JKS");
                try (InputStream is = new FileInputStream(keyStoreFile)) {
                    ks.load(is, sslTrustStorePwdValue.toCharArray());
                }
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(ks);
                sslContext.init(null, tmf.getTrustManagers(), null);
            } else {
                sslContext.init(null, null, null);
            }
        }
        SSLEngine engine = sslContext.createSSLEngine();
        String sslProtocolsValue = (String) userProperties.get(Constants.SSL_PROTOCOLS_PROPERTY);
        if (sslProtocolsValue != null) {
            engine.setEnabledProtocols(sslProtocolsValue.split(","));
        }
        engine.setUseClientMode(true);
        return engine;
    } catch (Exception e) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.sslEngineFail"), e);
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SSLEngine(javax.net.ssl.SSLEngine) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) DeploymentException(javax.websocket.DeploymentException) SSLContext(javax.net.ssl.SSLContext) File(java.io.File) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) TimeoutException(java.util.concurrent.TimeoutException) EOFException(java.io.EOFException) SSLException(javax.net.ssl.SSLException) DeploymentException(javax.websocket.DeploymentException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 19 with DeploymentException

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

the class WsWebSocketContainer method connectToServer.

@Override
public Session connectToServer(Object pojo, URI path) throws DeploymentException {
    ClientEndpoint annotation = pojo.getClass().getAnnotation(ClientEndpoint.class);
    if (annotation == null) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.missingAnnotation", pojo.getClass().getName()));
    }
    Endpoint ep = new PojoEndpointClient(pojo, Arrays.asList(annotation.decoders()));
    Class<? extends ClientEndpointConfig.Configurator> configuratorClazz = annotation.configurator();
    ClientEndpointConfig.Configurator configurator = null;
    if (!ClientEndpointConfig.Configurator.class.equals(configuratorClazz)) {
        try {
            configurator = configuratorClazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new DeploymentException(sm.getString("wsWebSocketContainer.defaultConfiguratorFail"), e);
        }
    }
    ClientEndpointConfig.Builder builder = ClientEndpointConfig.Builder.create();
    // Avoid NPE when using RI API JAR - see BZ 56343
    if (configurator != null) {
        builder.configurator(configurator);
    }
    ClientEndpointConfig config = builder.decoders(Arrays.asList(annotation.decoders())).encoders(Arrays.asList(annotation.encoders())).preferredSubprotocols(Arrays.asList(annotation.subprotocols())).build();
    return connectToServer(ep, config, path);
}
Also used : Endpoint(javax.websocket.Endpoint) ClientEndpoint(javax.websocket.ClientEndpoint) PojoEndpointClient(org.apache.tomcat.websocket.pojo.PojoEndpointClient) DeploymentException(javax.websocket.DeploymentException) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) ClientEndpoint(javax.websocket.ClientEndpoint)

Example 20 with DeploymentException

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

the class WsSci method onStartup.

@Override
public void onStartup(Set<Class<?>> clazzes, ServletContext ctx) throws ServletException {
    WsServerContainer sc = init(ctx, true);
    if (clazzes == null || clazzes.size() == 0) {
        return;
    }
    // Group the discovered classes by type
    Set<ServerApplicationConfig> serverApplicationConfigs = new HashSet<>();
    Set<Class<? extends Endpoint>> scannedEndpointClazzes = new HashSet<>();
    Set<Class<?>> scannedPojoEndpoints = new HashSet<>();
    try {
        // wsPackage is "javax.websocket."
        String wsPackage = ContainerProvider.class.getName();
        wsPackage = wsPackage.substring(0, wsPackage.lastIndexOf('.') + 1);
        for (Class<?> clazz : clazzes) {
            int modifiers = clazz.getModifiers();
            if (!Modifier.isPublic(modifiers) || Modifier.isAbstract(modifiers)) {
                // Non-public or abstract - skip it.
                continue;
            }
            // Protect against scanning the WebSocket API JARs
            if (clazz.getName().startsWith(wsPackage)) {
                continue;
            }
            if (ServerApplicationConfig.class.isAssignableFrom(clazz)) {
                serverApplicationConfigs.add((ServerApplicationConfig) clazz.newInstance());
            }
            if (Endpoint.class.isAssignableFrom(clazz)) {
                @SuppressWarnings("unchecked") Class<? extends Endpoint> endpoint = (Class<? extends Endpoint>) clazz;
                scannedEndpointClazzes.add(endpoint);
            }
            if (clazz.isAnnotationPresent(ServerEndpoint.class)) {
                scannedPojoEndpoints.add(clazz);
            }
        }
    } catch (InstantiationException | IllegalAccessException e) {
        throw new ServletException(e);
    }
    // Filter the results
    Set<ServerEndpointConfig> filteredEndpointConfigs = new HashSet<>();
    Set<Class<?>> filteredPojoEndpoints = new HashSet<>();
    if (serverApplicationConfigs.isEmpty()) {
        filteredPojoEndpoints.addAll(scannedPojoEndpoints);
    } else {
        for (ServerApplicationConfig config : serverApplicationConfigs) {
            Set<ServerEndpointConfig> configFilteredEndpoints = config.getEndpointConfigs(scannedEndpointClazzes);
            if (configFilteredEndpoints != null) {
                filteredEndpointConfigs.addAll(configFilteredEndpoints);
            }
            Set<Class<?>> configFilteredPojos = config.getAnnotatedEndpointClasses(scannedPojoEndpoints);
            if (configFilteredPojos != null) {
                filteredPojoEndpoints.addAll(configFilteredPojos);
            }
        }
    }
    try {
        // Deploy endpoints
        for (ServerEndpointConfig config : filteredEndpointConfigs) {
            sc.addEndpoint(config);
        }
        // Deploy POJOs
        for (Class<?> clazz : filteredPojoEndpoints) {
            sc.addEndpoint(clazz);
        }
    } catch (DeploymentException e) {
        throw new ServletException(e);
    }
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ServerApplicationConfig(javax.websocket.server.ServerApplicationConfig) ServerEndpoint(javax.websocket.server.ServerEndpoint) Endpoint(javax.websocket.Endpoint) ServletException(javax.servlet.ServletException) ServerEndpoint(javax.websocket.server.ServerEndpoint) Endpoint(javax.websocket.Endpoint) DeploymentException(javax.websocket.DeploymentException) HashSet(java.util.HashSet)

Aggregations

DeploymentException (javax.websocket.DeploymentException)36 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)16 ServerContainer (javax.websocket.server.ServerContainer)11 ServletException (javax.servlet.ServletException)7 WebSocketContainer (javax.websocket.WebSocketContainer)7 IOException (java.io.IOException)6 PrintWriter (java.io.PrintWriter)6 ArrayList (java.util.ArrayList)6 Endpoint (javax.websocket.Endpoint)5 ServerEndpoint (javax.websocket.server.ServerEndpoint)5 ExecutionException (java.util.concurrent.ExecutionException)3 ClientEndpoint (javax.websocket.ClientEndpoint)3 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)3 Extension (javax.websocket.Extension)3 WebSocketExtension (io.undertow.websockets.WebSocketExtension)2 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)2 EOFException (java.io.EOFException)2 InetSocketAddress (java.net.InetSocketAddress)2 ClosedChannelException (java.nio.channels.ClosedChannelException)2 HashMap (java.util.HashMap)2