Search in sources :

Example 56 with HttpHandler

use of io.undertow.server.HttpHandler in project openremote by openremote.

the class AbstractHttpServerProtocol method undeploy.

protected void undeploy(AssetAttribute protocolConfiguration) {
    Pair<DeploymentInfo, HttpHandler> deploymentInfoHttpHandlerPair = deployments.get(protocolConfiguration.getReferenceOrThrow());
    if (deploymentInfoHttpHandlerPair == null) {
        LOG.info("Deployment doesn't exist for protocol configuration: " + protocolConfiguration);
        return;
    }
    DeploymentInfo deploymentInfo = deploymentInfoHttpHandlerPair.key;
    try {
        LOG.info("Un-registering HTTP Server Protocol request handler '" + this.getClass().getSimpleName() + "' for request path: " + deploymentInfo.getContextPath());
        webService.getRequestPathHandler().removePrefixPath(deploymentInfo.getContextPath());
        DeploymentManager manager = Servlets.defaultContainer().getDeployment(deploymentInfo.getDeploymentName());
        manager.stop();
        manager.undeploy();
        Servlets.defaultContainer().removeDeployment(deploymentInfo);
        deployments.remove(protocolConfiguration.getReferenceOrThrow());
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "An exception occurred whilst un-deploying protocolConfiguration: " + protocolConfiguration.getReferenceOrThrow(), ex);
        throw new RuntimeException(ex);
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) DeploymentManager(io.undertow.servlet.api.DeploymentManager) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) ServletException(javax.servlet.ServletException)

Example 57 with HttpHandler

use of io.undertow.server.HttpHandler in project openremote by openremote.

the class WebService method build.

protected Undertow.Builder build(Container container, Undertow.Builder builder) {
    LOG.info("Building web routing with custom routes: " + getPrefixRoutes().keySet());
    IdentityService identityService = container.hasService(IdentityService.class) ? container.getService(IdentityService.class) : null;
    ResteasyDeployment resteasyDeployment = createResteasyDeployment(container);
    HttpHandler apiHandler = createApiHandler(identityService, resteasyDeployment);
    HttpHandler jsApiHandler = createJsApiHandler(identityService, resteasyDeployment);
    requestPathHandler = new PathHandler(apiHandler);
    HttpHandler handler = exchange -> {
        String requestPath = exchange.getRequestPath();
        LOG.fine("Handling request: " + exchange.getRequestMethod() + " " + exchange.getRequestPath());
        // Other services can register routes here with a prefix patch match
        boolean handled = false;
        for (Map.Entry<String, HttpHandler> entry : getPrefixRoutes().entrySet()) {
            if (requestPath.startsWith(entry.getKey())) {
                LOG.fine("Handling with '" + entry.getValue().getClass().getName() + "' path prefix: " + entry.getKey());
                entry.getValue().handleRequest(exchange);
                handled = true;
                break;
            }
        }
        if (handled)
            return;
        // Redirect / to default realm
        if (requestPath.equals("/")) {
            LOG.fine("Handling root request, redirecting client to default realm: " + requestPath);
            new RedirectHandler(fromUri(exchange.getRequestURL()).replacePath(getDefaultRealm()).build().toString()).handleRequest(exchange);
            return;
        }
        // Serve JavaScript API with path /jsapi/*
        if (jsApiHandler != null && requestPath.startsWith(JSAPI_PATH)) {
            LOG.fine("Serving JS API call: " + requestPath);
            jsApiHandler.handleRequest(exchange);
            return;
        }
        // Serve /<realm>/index.html
        Matcher realmRootMatcher = PATTERN_REALM_ROOT.matcher(requestPath);
        if (getRealmIndexHandler() != null && realmRootMatcher.matches()) {
            LOG.fine("Serving index document of realm: " + requestPath);
            exchange.setRelativePath("/index.html");
            getRealmIndexHandler().handleRequest(exchange);
            return;
        }
        Matcher realmSubMatcher = PATTERN_REALM_SUB.matcher(requestPath);
        if (!realmSubMatcher.matches()) {
            exchange.setStatusCode(NOT_FOUND.getStatusCode());
            throw new WebApplicationException(NOT_FOUND);
        }
        // Extract realm from path and push it into REQUEST_HEADER_REALM header
        String realm = realmSubMatcher.group(1);
        // Move the realm from path segment to header
        exchange.getRequestHeaders().put(HttpString.tryFromString(REQUEST_HEADER_REALM), realm);
        // Rewrite path, remove realm segment
        URI url = fromUri(exchange.getRequestURL()).replacePath(realmSubMatcher.group(2)).build();
        exchange.setRequestURI(url.toString(), true);
        exchange.setRequestPath(url.getPath());
        exchange.setRelativePath(url.getPath());
        // Look for registered path handlers and fallback to API handler
        LOG.fine("Serving HTTP call: " + url.getPath());
        requestPathHandler.handleRequest(exchange);
    };
    handler = new WebServiceExceptions.RootUndertowExceptionHandler(devMode, handler);
    if (getBoolean(container.getConfig(), WEBSERVER_DUMP_REQUESTS, WEBSERVER_DUMP_REQUESTS_DEFAULT)) {
        handler = new RequestDumpingHandler(handler);
    }
    builder.setHandler(handler);
    return builder;
}
Also used : java.util(java.util) UriBuilder.fromUri(javax.ws.rs.core.UriBuilder.fromUri) JSAPIServlet(org.openremote.container.web.jsapi.JSAPIServlet) ServletInfo(io.undertow.servlet.api.ServletInfo) Undertow(io.undertow.Undertow) HttpString(io.undertow.util.HttpString) RedirectHandler(io.undertow.server.handlers.RedirectHandler) Servlets(io.undertow.servlet.Servlets) Container(org.openremote.container.Container) PathHandler(io.undertow.server.handlers.PathHandler) Matcher(java.util.regex.Matcher) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) ContainerService(org.openremote.container.ContainerService) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) RequestDumpingHandler(io.undertow.server.handlers.RequestDumpingHandler) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) ModelValueMessageBodyConverter(org.openremote.container.json.ModelValueMessageBodyConverter) Logger(java.util.logging.Logger) DeploymentManager(io.undertow.servlet.api.DeploymentManager) Inet4Address(java.net.Inet4Address) HttpServlet30Dispatcher(org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher) CORSFilter(org.openremote.container.security.CORSFilter) HttpHandler(io.undertow.server.HttpHandler) Options(org.xnio.Options) IdentityService(org.openremote.container.security.IdentityService) MapAccess(org.openremote.container.util.MapAccess) ResteasyContextParameters(org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters) JacksonConfig(org.openremote.container.json.JacksonConfig) WebApplicationException(javax.ws.rs.WebApplicationException) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) Pattern(java.util.regex.Pattern) HttpHandler(io.undertow.server.HttpHandler) WebApplicationException(javax.ws.rs.WebApplicationException) Matcher(java.util.regex.Matcher) RedirectHandler(io.undertow.server.handlers.RedirectHandler) PathHandler(io.undertow.server.handlers.PathHandler) HttpString(io.undertow.util.HttpString) URI(java.net.URI) IdentityService(org.openremote.container.security.IdentityService) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) RequestDumpingHandler(io.undertow.server.handlers.RequestDumpingHandler)

Example 58 with HttpHandler

use of io.undertow.server.HttpHandler in project openremote by openremote.

the class DefaultWebsocketComponent method deploy.

@Override
protected void deploy() throws Exception {
    WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
    getConsumers().entrySet().forEach(consumerEntry -> {
        String endpointPath = MessageBrokerSetupService.WEBSOCKET_PATH + "/" + consumerEntry.getKey();
        LOG.info("Deploying websocket endpoint: " + endpointPath);
        webSocketDeploymentInfo.addEndpoint(ServerEndpointConfig.Builder.create(WebsocketAdapter.class, endpointPath).configurator(new DefaultContainerConfigurator() {

            @SuppressWarnings("unchecked")
            @Override
            public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
                return (T) new WebsocketAdapter(consumerEntry.getValue());
            }

            @SuppressWarnings("unchecked")
            @Override
            public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
                Principal principal = request.getUserPrincipal();
                if (principal == null) {
                    throw new WebApplicationException("Request is not authenticated, can't access user principal", FORBIDDEN);
                }
                AuthContext authContext;
                if (principal instanceof KeycloakPrincipal) {
                    KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) principal;
                    authContext = new AccessTokenAuthContext(keycloakPrincipal.getKeycloakSecurityContext().getRealm(), keycloakPrincipal.getKeycloakSecurityContext().getToken());
                } else if (principal instanceof BasicAuthContext) {
                    authContext = (BasicAuthContext) principal;
                } else {
                    throw new WebApplicationException("Unsupported user principal type: " + principal, INTERNAL_SERVER_ERROR);
                }
                config.getUserProperties().put(WebsocketConstants.HANDSHAKE_AUTH, authContext);
                super.modifyHandshake(config, request, response);
            }
        }).build());
    });
    // We use the I/O thread to handle received websocket frames, as we expect to quickly hand them over to
    // an internal asynchronous message queue for processing, so we don't need a separate worker thread
    // pool for websocket frame processing
    webSocketDeploymentInfo.setDispatchToWorkerThread(false);
    // Make the shit Undertow/Websocket JSR client bootstrap happy - this is the pool that would be used
    // when Undertow acts as a WebSocket client, which we don't do... and I'm not even sure it can do that...
    webSocketDeploymentInfo.setWorker(Xnio.getInstance().createWorker(OptionMap.builder().set(Options.WORKER_TASK_MAX_THREADS, 1).set(Options.WORKER_NAME, "WebsocketInternalClient").set(Options.THREAD_DAEMON, true).getMap()));
    boolean directBuffers = Boolean.getBoolean("io.undertow.websockets.direct-buffers");
    webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(directBuffers, 1024, 100, 12));
    deploymentInfo = new DeploymentInfo().setDeploymentName("WebSocket Deployment").setContextPath(MessageBrokerSetupService.WEBSOCKET_PATH).addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo).setClassLoader(WebsocketComponent.class.getClassLoader());
    WebResourceCollection resourceCollection = new WebResourceCollection();
    resourceCollection.addUrlPattern("/*");
    // Require authentication, but authorize specific roles later in Camel
    SecurityConstraint constraint = new SecurityConstraint();
    constraint.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.AUTHENTICATE);
    constraint.addWebResourceCollection(resourceCollection);
    deploymentInfo.addSecurityConstraints(constraint);
    HttpHandler handler = webService.addServletDeployment(identityService, deploymentInfo, true);
    webService.getPrefixRoutes().put(MessageBrokerSetupService.WEBSOCKET_PATH, handler);
}
Also used : HttpHandler(io.undertow.server.HttpHandler) WebApplicationException(javax.ws.rs.WebApplicationException) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) BasicAuthContext(org.openremote.container.security.basic.BasicAuthContext) AccessTokenAuthContext(org.openremote.container.security.keycloak.AccessTokenAuthContext) AuthContext(org.openremote.container.security.AuthContext) BasicAuthContext(org.openremote.container.security.basic.BasicAuthContext) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) HandshakeResponse(javax.websocket.HandshakeResponse) WebsocketAdapter(org.openremote.container.web.socket.WebsocketAdapter) AccessTokenAuthContext(org.openremote.container.security.keycloak.AccessTokenAuthContext) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) DefaultContainerConfigurator(io.undertow.websockets.jsr.DefaultContainerConfigurator) KeycloakPrincipal(org.keycloak.KeycloakPrincipal) Principal(java.security.Principal) HandshakeRequest(javax.websocket.server.HandshakeRequest) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 59 with HttpHandler

use of io.undertow.server.HttpHandler in project camel by apache.

the class CamelRootHandler method remove.

public synchronized void remove(String path, String[] methods, boolean prefixMatch) {
    String basePath = getBasePath(path);
    HttpHandler basePathHandler = pathHandler.getHandler(basePath);
    if (basePathHandler == null) {
        return;
    }
    if (path.contains("{")) {
        // Removing a handler for the template path
        String relativePath = path.substring(basePath.length());
        CamelPathTemplateHandler templateHandler = (CamelPathTemplateHandler) basePathHandler;
        CamelMethodHandler targetHandler = templateHandler.get(relativePath);
        if (methods != null && methods.length != 0) {
            targetHandler.remove(methods);
        } else {
            targetHandler.removeDefault();
        }
        if (targetHandler.isEmpty()) {
            templateHandler.remove(relativePath);
            if (templateHandler.isEmpty()) {
                pathHandler.removePrefixPath(basePath);
            }
        }
    } else {
        // Removing a handler for the static path
        if (basePathHandler instanceof CamelPathTemplateHandler) {
            String relativePath = path.substring(basePath.length());
            CamelPathTemplateHandler templateHandler = (CamelPathTemplateHandler) basePathHandler;
            CamelMethodHandler targetHandler = templateHandler.getDefault();
            if (methods != null && methods.length != 0) {
                targetHandler.remove(methods);
            } else {
                targetHandler.removeDefault();
            }
            if (targetHandler.isEmpty()) {
                templateHandler.remove(relativePath);
                if (templateHandler.isEmpty()) {
                    pathHandler.removePrefixPath(basePath);
                }
            }
        } else {
            CamelMethodHandler targetHandler = (CamelMethodHandler) basePathHandler;
            if (methods != null && methods.length != 0) {
                targetHandler.remove(methods);
            } else {
                targetHandler.removeDefault();
            }
            if (targetHandler.isEmpty()) {
                if (prefixMatch) {
                    pathHandler.removePrefixPath(basePath);
                } else {
                    pathHandler.removeExactPath(basePath);
                }
            }
        }
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler)

Example 60 with HttpHandler

use of io.undertow.server.HttpHandler in project undertow by undertow-io.

the class ServerSentEventSCI method onStartup.

@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
    if (c == null || c.isEmpty()) {
        return;
    }
    try {
        final Map<String, ServerSentEventConnectionCallback> callbacks = new HashMap<>();
        ServletContextImpl servletContext = (ServletContextImpl) ctx;
        final List<InstanceHandle<?>> handles = new ArrayList<>();
        for (Class<?> clazz : c) {
            final ServerSentEvent annotation = clazz.getAnnotation(ServerSentEvent.class);
            if (annotation == null) {
                continue;
            }
            String path = annotation.value();
            final InstanceHandle<?> instance = servletContext.getDeployment().getDeploymentInfo().getClassIntrospecter().createInstanceFactory(clazz).createInstance();
            handles.add(instance);
            callbacks.put(path, (ServerSentEventConnectionCallback) instance.getInstance());
        }
        if (callbacks.isEmpty()) {
            return;
        }
        servletContext.getDeployment().getDeploymentInfo().addInnerHandlerChainWrapper(new HandlerWrapper() {

            @Override
            public HttpHandler wrap(HttpHandler handler) {
                PathTemplateHandler pathTemplateHandler = new PathTemplateHandler(handler, false);
                for (Map.Entry<String, ServerSentEventConnectionCallback> e : callbacks.entrySet()) {
                    pathTemplateHandler.add(e.getKey(), new ServerSentEventHandler(e.getValue()));
                }
                return pathTemplateHandler;
            }
        });
        servletContext.addListener(new ServletContextListener() {

            @Override
            public void contextInitialized(ServletContextEvent sce) {
            }

            @Override
            public void contextDestroyed(ServletContextEvent sce) {
                for (InstanceHandle<?> h : handles) {
                    h.release();
                }
            }
        });
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) HashMap(java.util.HashMap) ServletContextListener(javax.servlet.ServletContextListener) ServerSentEventConnectionCallback(io.undertow.server.handlers.sse.ServerSentEventConnectionCallback) PathTemplateHandler(io.undertow.server.handlers.PathTemplateHandler) ServletContextImpl(io.undertow.servlet.spec.ServletContextImpl) ArrayList(java.util.ArrayList) ServerSentEventHandler(io.undertow.server.handlers.sse.ServerSentEventHandler) HandlerWrapper(io.undertow.server.HandlerWrapper) ServletException(javax.servlet.ServletException) ServletException(javax.servlet.ServletException) InstanceHandle(io.undertow.servlet.api.InstanceHandle) ServletContextEvent(javax.servlet.ServletContextEvent)

Aggregations

HttpHandler (io.undertow.server.HttpHandler)126 HttpServerExchange (io.undertow.server.HttpServerExchange)72 IOException (java.io.IOException)54 BeforeClass (org.junit.BeforeClass)35 Test (org.junit.Test)25 TestHttpClient (io.undertow.testutils.TestHttpClient)20 HttpResponse (org.apache.http.HttpResponse)20 HttpGet (org.apache.http.client.methods.HttpGet)19 PathHandler (io.undertow.server.handlers.PathHandler)17 HttpString (io.undertow.util.HttpString)15 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)13 Undertow (io.undertow.Undertow)12 ArrayList (java.util.ArrayList)11 HandlerWrapper (io.undertow.server.HandlerWrapper)9 InMemorySessionManager (io.undertow.server.session.InMemorySessionManager)9 SessionAttachmentHandler (io.undertow.server.session.SessionAttachmentHandler)9 Header (org.apache.http.Header)9 SessionCookieConfig (io.undertow.server.session.SessionCookieConfig)8 AuthenticationMechanism (io.undertow.security.api.AuthenticationMechanism)7 AuthenticationCallHandler (io.undertow.security.handlers.AuthenticationCallHandler)7