io.undertow.websockets.jsr.WebSocketDeploymentInfo Java Examples

The following examples show how to use io.undertow.websockets.jsr.WebSocketDeploymentInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestMessagesReceivedInOrder.java    From quarkus-http with Apache License 2.0 9 votes vote down vote up
@BeforeClass
public static void setup() throws ServletException {

    final ServletContainer container = ServletContainer.Factory.newInstance();

    DeploymentInfo builder = new DeploymentInfo()
            .setClassLoader(TestMessagesReceivedInOrder.class.getClassLoader())
            .setContextPath("/")
            .setResourceManager(new TestResourceLoader(TestMessagesReceivedInOrder.class))
            .setClassIntrospecter(TestClassIntrospector.INSTANCE)
            .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                    new WebSocketDeploymentInfo()
                            .setDispatchToWorkerThread(true)
                            .addEndpoint(EchoSocket.class)
            )
            .setDeploymentName("servletContext.war");


    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();


    DefaultServer.setRootHandler(Handlers.path().addPrefixPath("/", manager.start()));
}
 
Example #2
Source File: ProgrammaticWebSocketServer.java    From wildfly-samples with MIT License 9 votes vote down vote up
public ProgrammaticWebSocketServer() throws IOException {
    final Xnio xnio = Xnio.getInstance("nio", Undertow.class.getClassLoader());
    final XnioWorker xnioWorker = xnio.createWorker(OptionMap.builder().getMap());

    WebSocketDeploymentInfo websocket = new WebSocketDeploymentInfo()
            .addEndpoint(MyAnnotatedEndpoint.class)
            .setWorker(xnioWorker);

    DeploymentInfo deploymentInfo = deployment()
            .setClassLoader(MyAnnotatedEndpoint.class.getClassLoader())
            .setContextPath("/myapp")
            .setDeploymentName("websockets")
            .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, websocket);

    manager = defaultContainer().addDeployment(deploymentInfo);
    manager.deploy();
}
 
Example #3
Source File: AnnotatedWebSocketServer.java    From wildfly-samples with MIT License 7 votes vote down vote up
public AnnotatedWebSocketServer() throws IOException {
    final Xnio xnio = Xnio.getInstance("nio", Undertow.class.getClassLoader());
    final XnioWorker xnioWorker = xnio.createWorker(OptionMap.builder().getMap());

    WebSocketDeploymentInfo websocket = new WebSocketDeploymentInfo()
            .addEndpoint(MyAnnotatedEndpoint.class)
            .setWorker(xnioWorker);

    DeploymentInfo deploymentInfo = deployment()
            .setClassLoader(MyAnnotatedEndpoint.class.getClassLoader())
            .setContextPath("/myapp")
            .setDeploymentName("websockets")
            .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, websocket);

    manager = defaultContainer().addDeployment(deploymentInfo);
    manager.deploy();
}
 
Example #4
Source File: CamelWebSocketJSR356Recorder.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
public void registerServerContainer(DeploymentManager deploymentManager) {
    ServletContextImpl servletContext = deploymentManager.getDeployment().getServletContext();
    ServerContainer container = (ServerContainer) servletContext.getAttribute(ServerContainer.class.getName());

    JSR356WebSocketComponent.registerServer(servletContext.getContextPath(), container);

    WebSocketDeploymentInfo deploymentInfo = (WebSocketDeploymentInfo) servletContext
            .getAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
    for (ServerEndpointConfig config : deploymentInfo.getProgramaticEndpoints()) {
        try {
            CamelServerEndpoint endpoint = config.getConfigurator().getEndpointInstance(CamelServerEndpoint.class);
            JSR356WebSocketComponent.ContextBag context = JSR356WebSocketComponent
                    .getContext(servletContext.getContextPath());
            context.getEndpoints().put(config.getPath(), endpoint);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #5
Source File: WebSocketJSR356Processor.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Record(ExecutionTime.STATIC_INIT)
@BuildStep
public void createWebsocketEndpoints(List<ServletContextAttributeBuildItem> servletContext,
        CamelWebSocketJSR356Recorder recorder, CamelWebSocketJSR356Config config) {
    ServletContextAttributeBuildItem wsDeploymentInfoAttribute = servletContext
            .stream()
            .filter(context -> context.getKey().equals(WebSocketDeploymentInfo.ATTRIBUTE_NAME))
            .findFirst()
            .orElseThrow(() -> new IllegalStateException(
                    "Servlet context attribute: " + WebSocketDeploymentInfo.ATTRIBUTE_NAME + " not found"));

    recorder.configureWebsocketEndpoints((WebSocketDeploymentInfo) wsDeploymentInfoAttribute.getValue(), config);
}
 
Example #6
Source File: CamelWebSocketJSR356Recorder.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public void configureWebsocketEndpoints(WebSocketDeploymentInfo deploymentInfo, CamelWebSocketJSR356Config config) {
    List<String> endpointPaths = config.serverEndpointPaths.orElseGet(Collections::emptyList);
    for (String path : endpointPaths) {
        CamelServerEndpoint endpoint = new CamelServerEndpoint();
        ServerEndpointConfig.Builder builder = ServerEndpointConfig.Builder.create(CamelServerEndpoint.class, path);
        builder.configurator(new CamelWebSocketJSR356EndpointConfigurator(endpoint));
        deploymentInfo.addEndpoint(builder.build());
    }
}
 
Example #7
Source File: ProgramaticAutobahnServer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public void run() {

        try {

            final ServletContainer container = ServletContainer.Factory.newInstance();
            DeploymentInfo builder = new DeploymentInfo()
                    .setClassLoader(ProgramaticAutobahnServer.class.getClassLoader())
                    .setContextPath("/")
                    .setClassIntrospecter(TestClassIntrospector.INSTANCE)
                    .setDeploymentName("servletContext.war")
                    .addFilter(new FilterInfo("filter", JsrWebSocketFilter.class))
                    .addFilterUrlMapping("filter", "/*", DispatcherType.REQUEST)

                    .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                            new WebSocketDeploymentInfo()
                                    .setDispatchToWorkerThread(true)
                                    .addEndpoint(new ServerEndpointConfigImpl(ProgramaticAutobahnEndpoint.class, "/"))
                    );

            DeploymentManager manager = container.addDeployment(builder);
            manager.deploy();


            Undertow.builder().addHttpListener(port, "localhost")
                    .setHandler(manager.start())
                    .build();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
Example #8
Source File: AnnotatedAutobahnServer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public void run() {


        try {
            final ServletContainer container = ServletContainer.Factory.newInstance();

            DeploymentInfo builder = new DeploymentInfo()
                    .setClassLoader(AnnotatedAutobahnServer.class.getClassLoader())
                    .setContextPath("/")
                    .setClassIntrospecter(TestClassIntrospector.INSTANCE)
                    .setDeploymentName("servletContext.war")
                    .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                            new WebSocketDeploymentInfo()
                                    .addEndpoint(AutobahnAnnotatedEndpoint.class)
                                    .setDispatchToWorkerThread(true)
                    )
                    .addFilter(new FilterInfo("filter", JsrWebSocketFilter.class))
                    .addFilterUrlMapping("filter", "/*", DispatcherType.REQUEST);

            DeploymentManager manager = container.addDeployment(builder);
            manager.deploy();

            Undertow.builder().addHttpListener(port, "localhost")
                    .setHandler(manager.start())
                    .build();

        } catch (Exception e) {
            log.error("failed to start server", e);
        }
    }
 
Example #9
Source File: SuspendResumeTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws ServletException {

    final ServletContainer container = ServletContainer.Factory.newInstance();

    DeploymentInfo builder = new DeploymentInfo()
            .setClassLoader(TestMessagesReceivedInOrder.class.getClassLoader())
            .setContextPath("/")
            .setResourceManager(new TestResourceLoader(TestMessagesReceivedInOrder.class))
            .setClassIntrospecter(TestClassIntrospector.INSTANCE)
            .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                    new WebSocketDeploymentInfo()
                            .addListener(new WebSocketDeploymentInfo.ContainerReadyListener() {
                                @Override
                                public void ready(ServerWebSocketContainer c) {
                                    serverContainer = c;
                                }
                            })
                            .addEndpoint(SuspendResumeEndpoint.class)
            )
            .setDeploymentName("servletContext.war");


    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();


    DefaultServer.setRootHandler(Handlers.path().addPrefixPath("/", manager.start()));
}
 
Example #10
Source File: CustomizationBean.java    From momo-cloud-permission with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(UndertowServletWebServerFactory factory) {
    factory.addDeploymentInfoCustomizers(deploymentInfo -> {
        WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
        webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(false, 1024));
        deploymentInfo.addServletContextAttribute("io.undertow.websockets.jsr.WebSocketDeploymentInfo", webSocketDeploymentInfo);
    });
}
 
Example #11
Source File: ClassProviderStarter.java    From websocket-classloader with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ServletException {
    final Xnio xnio = Xnio.getInstance("nio", Undertow.class.getClassLoader());
    final XnioWorker xnioWorker = xnio.createWorker(OptionMap.builder().getMap());
    final WebSocketDeploymentInfo webSockets = new WebSocketDeploymentInfo()
            .addEndpoint(ClassProvider.class)
            .setWorker(xnioWorker);
    final DeploymentManager deploymentManager = Servlets.defaultContainer()
            .addDeployment(Servlets.deployment()
                    .setClassLoader(ClassProviderStarter.class.getClassLoader())
                    .setContextPath("/")
                    .setDeploymentName("class-provider")
                    .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSockets));

    deploymentManager.deploy();
    //noinspection deprecation
    Undertow.builder()
            .addListener(5000, "localhost")
            .setHandler(deploymentManager.start())
            .build()
            .start();
}
 
Example #12
Source File: DeploymentManagerFactory.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
@SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE", justification = "False positive")
private DeploymentInfo configureDeploymentInfo() {
    // Basic deployment attributes
    DeploymentInfo deploymentInfo = Servlets.deployment()
            .setEagerFilterInit(true)
            .setClassLoader(mostCompleteClassLoader)
            .setDeploymentName(applicationConfig.getId())
            .setDisplayName(applicationConfig.getName())
            .setDefaultSessionTimeout(serverConfig.getDefaultSessionTimeout())
            .setResourceManager(new ClassPathResourceManager(mostCompleteClassLoader, META_INF_RESOURCES))
            .addWelcomePages(serverConfig.getWelcomeFiles())
            .addErrorPages(buildUndertowErrorPages(serverConfig.getErrorPages()))
            .setContextPath(serverConfig.getContextPath());

    // Configure WebSockets if enabled
    if (serverConfig.webSocket().isEnabled()) {
        LOGGER.info("WebSocket support is enabled");
        deploymentInfo.addServletContextAttribute(
                WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                new WebSocketDeploymentInfo()
                        .setBuffers(new DefaultByteBufferPool(
                                undertowConfig.isDirectBuffers(),
                                undertowConfig.getBufferSize()))
                        .setWorker(xnioWorker)
        );
    }

    // Redirect to HTTPS if configured
    if (serverConfig.isHttp() && serverConfig.isHttps() && serverConfig.isPreferHttps()) {
        LOGGER.info("Automatic redirection to HTTPS is enabled");
        deploymentInfo
                .addSecurityConstraint(new SecurityConstraint()
                        .addWebResourceCollection(new WebResourceCollection().addUrlPattern("/*"))
                        .setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL)
                        .setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT))
                .setConfidentialPortManager(ex -> serverConfig.getSecurePort());
    }

    // Add custom init parameters
    for (Map.Entry<String, String> initParameter : initParameters.entrySet()) {
        LOGGER.debug("Servlet init parameter {} = {}", initParameter.getKey(), initParameter.getValue());
        deploymentInfo.addInitParameter(initParameter.getKey(), initParameter.getValue());
    }

    // Register ServletContainerInitializers
    for (ServletContainerInitializer sci : loadServletContainerInitializers()) {
        LOGGER.debug("Registering ServletContainerInitializer {}", sci.getClass().getName());
        deploymentInfo.addServletContainerInitializer(createServletContainerInitializerInfo(sci));
    }

    return deploymentInfo;
}
 
Example #13
Source File: UndertowWebServer.java    From hammock with Apache License 2.0 4 votes vote down vote up
@Override
public void start() {
    DeploymentInfo di = new DeploymentInfo()
            .setContextPath("/")
            .setDeploymentName("Undertow")
            .setResourceManager(new ClassPathResourceManager(getClass().getClassLoader()))
            .setClassLoader(ClassLoader.getSystemClassLoader());

    super.getListeners().forEach(c ->di.addListener(listener(c)));

    Collection<Class<?>> endpoints = extension.getEndpointClasses();
    if(!endpoints.isEmpty()) {
        WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
        endpoints.forEach(webSocketDeploymentInfo::addEndpoint);
        di.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo);
    }

    getServletContextAttributes().forEach(di::addServletContextAttribute);
    servlets.forEach(di::addServlet);
    getFilterDescriptors().forEach(filterDescriptor -> {
        FilterInfo filterInfo = filter(filterDescriptor.displayName(), filterDescriptor.getClazz()).setAsyncSupported(filterDescriptor.asyncSupported());
        if(filterDescriptor.initParams() != null) {
            for (WebInitParam param : filterDescriptor.initParams()) {
                filterInfo.addInitParam(param.name(), param.value());
            }
        }
        di.addFilter(filterInfo);
        for(String url : filterDescriptor.urlPatterns()) {
            for(DispatcherType dispatcherType : filterDescriptor.dispatcherTypes()) {
                di.addFilterUrlMapping(filterDescriptor.displayName(), url, dispatcherType);
            }
        }
    });

    getInitParams().forEach(di::addInitParameter);

    DeploymentManager deploymentManager = Servlets.defaultContainer().addDeployment(di);
    deploymentManager.deploy();
    try {
        HttpHandler servletHandler = deploymentManager.start();
        PathHandler path = path(Handlers.redirect("/"))
                .addPrefixPath("/", servletHandler);
        Builder undertowBuilder = Undertow.builder()
                .addHttpListener(webServerConfiguration.getPort(), webServerConfiguration.getAddress())
                .setHandler(path);
        if (hammockRuntime.isSecuredConfigured()){
        	KeyManager[] keyManagers = loadKeyManager();
        	TrustManager[] trustManagers = loadTrustManager();
        	SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagers, trustManagers, null);
        	undertowBuilder = undertowBuilder.addHttpsListener(webServerConfiguration.getSecuredPort(), webServerConfiguration.getAddress(), sslContext);
        }
        this.undertow = undertowBuilder.build();
        this.undertow.start();
    } catch (ServletException | GeneralSecurityException | IOException e) {
        throw new RuntimeException("Unable to start server", e);
    }
}