Search in sources :

Example 11 with DeploymentException

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

the class WsWebSocketContainer method createSSLEngine.

@SuppressWarnings("removal")
private SSLEngine createSSLEngine(ClientEndpointConfig clientEndpointConfig, String host, int port) throws DeploymentException {
    Map<String, Object> userProperties = clientEndpointConfig.getUserProperties();
    try {
        // See if a custom SSLContext has been provided
        SSLContext sslContext = clientEndpointConfig.getSSLContext();
        // specific method
        if (sslContext == null) {
            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)) {
                    KeyStoreUtil.load(ks, 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(host, port);
        String sslProtocolsValue = (String) userProperties.get(Constants.SSL_PROTOCOLS_PROPERTY);
        if (sslProtocolsValue != null) {
            engine.setEnabledProtocols(sslProtocolsValue.split(","));
        }
        engine.setUseClientMode(true);
        // Enable host verification
        // Start with current settings (returns a copy)
        SSLParameters sslParams = engine.getSSLParameters();
        // Use HTTPS since WebSocket starts over HTTP(S)
        sslParams.setEndpointIdentificationAlgorithm("HTTPS");
        // Write the parameters back
        engine.setSSLParameters(sslParams);
        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) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) EOFException(java.io.EOFException) SSLException(javax.net.ssl.SSLException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) DeploymentException(jakarta.websocket.DeploymentException) SSLParameters(javax.net.ssl.SSLParameters) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) DeploymentException(jakarta.websocket.DeploymentException) File(java.io.File)

Example 12 with DeploymentException

use of jakarta.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 "jakarta.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) || Modifier.isInterface(modifiers) || !isExported(clazz)) {
                // package - 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.getConstructor().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 (ReflectiveOperationException 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, true);
        }
    } catch (DeploymentException e) {
        throw new ServletException(e);
    }
}
Also used : ServerEndpointConfig(jakarta.websocket.server.ServerEndpointConfig) ServerApplicationConfig(jakarta.websocket.server.ServerApplicationConfig) Endpoint(jakarta.websocket.Endpoint) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) ServletException(jakarta.servlet.ServletException) Endpoint(jakarta.websocket.Endpoint) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) DeploymentException(jakarta.websocket.DeploymentException) HashSet(java.util.HashSet)

Example 13 with DeploymentException

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

the class WsRemoteEndpointImplBase method setEncoders.

protected void setEncoders(EndpointConfig endpointConfig) throws DeploymentException {
    encoderEntries.clear();
    for (Class<? extends Encoder> encoderClazz : endpointConfig.getEncoders()) {
        Encoder instance;
        InstanceManager instanceManager = wsSession.getInstanceManager();
        try {
            if (instanceManager == null) {
                instance = encoderClazz.getConstructor().newInstance();
            } else {
                instance = (Encoder) instanceManager.newInstance(encoderClazz);
            }
            instance.init(endpointConfig);
        } catch (ReflectiveOperationException | NamingException e) {
            throw new DeploymentException(sm.getString("wsRemoteEndpoint.invalidEncoder", encoderClazz.getName()), e);
        }
        EncoderEntry entry = new EncoderEntry(Util.getEncoderType(encoderClazz), instance);
        encoderEntries.add(entry);
    }
}
Also used : Utf8Encoder(org.apache.tomcat.util.buf.Utf8Encoder) Encoder(jakarta.websocket.Encoder) CharsetEncoder(java.nio.charset.CharsetEncoder) InstanceManager(org.apache.tomcat.InstanceManager) NamingException(javax.naming.NamingException) DeploymentException(jakarta.websocket.DeploymentException)

Example 14 with DeploymentException

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

the class WsHttpUpgradeHandler method init.

@Override
public void init(WebConnection connection) {
    this.connection = connection;
    if (serverEndpointConfig == null) {
        throw new IllegalStateException(sm.getString("wsHttpUpgradeHandler.noPreInit"));
    }
    String httpSessionId = null;
    Object session = handshakeRequest.getHttpSession();
    if (session != null) {
        httpSessionId = ((HttpSession) session).getId();
    }
    // Need to call onOpen using the web application's class loader
    // Create the frame using the application's class loader so it can pick
    // up application specific config from the ServerContainerImpl
    Thread t = Thread.currentThread();
    ClassLoader cl = t.getContextClassLoader();
    t.setContextClassLoader(applicationClassLoader);
    try {
        wsRemoteEndpointServer = new WsRemoteEndpointImplServer(socketWrapper, upgradeInfo, webSocketContainer);
        wsSession = new WsSession(wsRemoteEndpointServer, webSocketContainer, handshakeRequest.getRequestURI(), handshakeRequest.getParameterMap(), handshakeRequest.getQueryString(), handshakeRequest.getUserPrincipal(), httpSessionId, negotiatedExtensions, subProtocol, pathParameters, secure, serverEndpointConfig);
        ep = wsSession.getLocal();
        wsFrame = new WsFrameServer(socketWrapper, upgradeInfo, wsSession, transformation, applicationClassLoader);
        // WsFrame adds the necessary final transformations. Copy the
        // completed transformation chain to the remote end point.
        wsRemoteEndpointServer.setTransformation(wsFrame.getTransformation());
        ep.onOpen(wsSession, serverEndpointConfig);
        webSocketContainer.registerSession(serverEndpointConfig.getPath(), wsSession);
    } catch (DeploymentException e) {
        throw new IllegalArgumentException(e);
    } finally {
        t.setContextClassLoader(cl);
    }
}
Also used : DeploymentException(jakarta.websocket.DeploymentException) WsSession(org.apache.tomcat.websocket.WsSession)

Example 15 with DeploymentException

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

the class WsServerContainer method addEndpoint.

void addEndpoint(Class<?> pojo, boolean fromAnnotatedPojo) throws DeploymentException {
    if (deploymentFailed) {
        throw new DeploymentException(sm.getString("serverContainer.failedDeployment", servletContext.getContextPath(), servletContext.getVirtualServerName()));
    }
    ServerEndpointConfig sec;
    try {
        ServerEndpoint annotation = pojo.getAnnotation(ServerEndpoint.class);
        if (annotation == null) {
            throw new DeploymentException(sm.getString("serverContainer.missingAnnotation", pojo.getName()));
        }
        String path = annotation.value();
        // Validate encoders
        validateEncoders(annotation.encoders(), getInstanceManager(Thread.currentThread().getContextClassLoader()));
        // ServerEndpointConfig
        Class<? extends Configurator> configuratorClazz = annotation.configurator();
        Configurator configurator = null;
        if (!configuratorClazz.equals(Configurator.class)) {
            try {
                configurator = annotation.configurator().getConstructor().newInstance();
            } catch (ReflectiveOperationException e) {
                throw new DeploymentException(sm.getString("serverContainer.configuratorFail", annotation.configurator().getName(), pojo.getClass().getName()), e);
            }
        }
        sec = ServerEndpointConfig.Builder.create(pojo, path).decoders(Arrays.asList(annotation.decoders())).encoders(Arrays.asList(annotation.encoders())).subprotocols(Arrays.asList(annotation.subprotocols())).configurator(configurator).build();
    } catch (DeploymentException de) {
        failDeployment();
        throw de;
    }
    addEndpoint(sec, fromAnnotatedPojo);
}
Also used : ServerEndpointConfig(jakarta.websocket.server.ServerEndpointConfig) Configurator(jakarta.websocket.server.ServerEndpointConfig.Configurator) DeploymentException(jakarta.websocket.DeploymentException) ServerEndpoint(jakarta.websocket.server.ServerEndpoint)

Aggregations

DeploymentException (jakarta.websocket.DeploymentException)17 ServerEndpointConfig (jakarta.websocket.server.ServerEndpointConfig)4 ServletException (jakarta.servlet.ServletException)3 ServerContainer (jakarta.websocket.server.ServerContainer)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 NamingException (javax.naming.NamingException)3 ClientEndpoint (jakarta.websocket.ClientEndpoint)2 Encoder (jakarta.websocket.Encoder)2 Endpoint (jakarta.websocket.Endpoint)2 Extension (jakarta.websocket.Extension)2 ServerEndpoint (jakarta.websocket.server.ServerEndpoint)2 EOFException (java.io.EOFException)2 URISyntaxException (java.net.URISyntaxException)2 List (java.util.List)2 ExecutionException (java.util.concurrent.ExecutionException)2 TimeoutException (java.util.concurrent.TimeoutException)2 SSLEngine (javax.net.ssl.SSLEngine)2 SSLException (javax.net.ssl.SSLException)2 PojoMethodMapping (org.apache.tomcat.websocket.pojo.PojoMethodMapping)2