Java Code Examples for io.undertow.servlet.api.DeploymentInfo#addInitParameter()

The following examples show how to use io.undertow.servlet.api.DeploymentInfo#addInitParameter() . 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: WebServer.java    From metamodel-membrane with Apache License 2.0 5 votes vote down vote up
public static void startServer(int port, boolean enableCors) throws Exception {
    final DeploymentInfo deployment = Servlets.deployment().setClassLoader(WebServer.class.getClassLoader());
    deployment.setContextPath("");
    deployment.setDeploymentName("membrane");
    deployment.addInitParameter("contextConfigLocation", "classpath:context/application-context.xml");
    deployment.setResourceManager(new FileResourceManager(new File("."), 0));
    deployment.addListener(Servlets.listener(ContextLoaderListener.class));
    deployment.addListener(Servlets.listener(RequestContextListener.class));
    deployment.addServlet(Servlets.servlet("dispatcher", DispatcherServlet.class).addMapping("/*")
            .addInitParam("contextConfigLocation", "classpath:context/dispatcher-servlet.xml"));
    deployment.addFilter(Servlets.filter(CharacterEncodingFilter.class).addInitParam("forceEncoding", "true")
            .addInitParam("encoding", "UTF-8"));

    final DeploymentManager manager = Servlets.defaultContainer().addDeployment(deployment);
    manager.deploy();

    final HttpHandler handler;
    if (enableCors) {
        CorsHandlers corsHandlers = new CorsHandlers();
        handler = corsHandlers.allowOrigin(manager.start());
    } else {
        handler = manager.start();
    }

    final Undertow server = Undertow.builder().addHttpListener(port, "0.0.0.0").setHandler(handler).build();
    server.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // graceful shutdown of everything
            server.stop();
            try {
                manager.stop();
            } catch (ServletException e) {
            }
            manager.undeploy();
        }
    });
}
 
Example 2
Source File: KeycloakOnUndertow.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private DeploymentInfo createAuthServerDeploymentInfo() {
    ResteasyDeployment deployment = new ResteasyDeployment();
    deployment.setApplicationClass(KeycloakApplication.class.getName());

    // RESTEASY-2034
    deployment.setProperty(ResteasyContextParameters.RESTEASY_DISABLE_HTML_SANITIZER, true);

    DeploymentInfo di = undertow.undertowDeployment(deployment);
    di.setClassLoader(getClass().getClassLoader());
    di.setContextPath("/auth");
    di.setDeploymentName("Keycloak");
    if (configuration.getKeycloakConfigPropertyOverridesMap() != null) {
        try {
            di.addInitParameter(JsonConfigProviderFactory.SERVER_CONTEXT_CONFIG_PROPERTY_OVERRIDES,
              JsonSerialization.writeValueAsString(configuration.getKeycloakConfigPropertyOverridesMap()));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    di.setDefaultServletConfig(new DefaultServletConfig(true));
    di.addWelcomePage("theme/keycloak/welcome/resources/index.html");

    FilterInfo filter = Servlets.filter("SessionFilter", TestKeycloakSessionServletFilter.class);
    di.addFilter(filter);
    di.addFilterUrlMapping("SessionFilter", "/*", DispatcherType.REQUEST);
    filter.setAsyncSupported(true);

    return di;
}
 
Example 3
Source File: KeycloakBaseSpringBootConfiguration.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void customize(DeploymentInfo deploymentInfo) {

            io.undertow.servlet.api.LoginConfig loginConfig = new io.undertow.servlet.api.LoginConfig(keycloakProperties.getRealm());
            loginConfig.addFirstAuthMethod("KEYCLOAK");

            deploymentInfo.setLoginConfig(loginConfig);

            deploymentInfo.addInitParameter("keycloak.config.resolver", KeycloakSpringBootConfigResolverWrapper.class.getName());
            
            
            /* Support for '*' as all roles allowed
             * We clear out the role in the SecurityConstraints
             * and set the EmptyRoleSemantic to Authenticate
             * But we will set EmptyRoleSemantic to DENY (default)
             * if roles are non existing or left empty
             */
            Iterator<io.undertow.servlet.api.SecurityConstraint> it = this.getSecurityConstraints().iterator();
            while (it.hasNext()) {
            	io.undertow.servlet.api.SecurityConstraint securityConstraint = it.next();
            	Set<String> rolesAllowed = securityConstraint.getRolesAllowed();
            	
            	if (rolesAllowed.contains("*") || rolesAllowed.contains("**") ) {
            		io.undertow.servlet.api.SecurityConstraint allRolesAllowed = new io.undertow.servlet.api.SecurityConstraint();
            		allRolesAllowed.setEmptyRoleSemantic(EmptyRoleSemantic.AUTHENTICATE);
            		allRolesAllowed.setTransportGuaranteeType(securityConstraint.getTransportGuaranteeType());
            		for (WebResourceCollection wr : securityConstraint.getWebResourceCollections()) {
            			allRolesAllowed.addWebResourceCollection(wr);
            		}
            		deploymentInfo.addSecurityConstraint(allRolesAllowed);
            	} else // left empty will fall back on default EmptyRoleSemantic.DENY
            		deploymentInfo.addSecurityConstraint(securityConstraint);
            	
            }
            deploymentInfo.addServletExtension(new KeycloakServletExtension());
        }
 
Example 4
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;
}