Search in sources :

Example 51 with PathHandler

use of io.undertow.server.handlers.PathHandler 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 52 with PathHandler

use of io.undertow.server.handlers.PathHandler in project undertow by undertow-io.

the class DeploymentUtils method setupServlet.

/**
     * Sets up a simple servlet deployment with the provided servlets.
     *
     * This is just a convenience method for simple deployments
     *
     * @param servlets The servlets to add
     */
public static Deployment setupServlet(final ServletExtension servletExtension, final ServletInfo... servlets) {
    final PathHandler pathHandler = new PathHandler();
    final ServletContainer container = ServletContainer.Factory.newInstance();
    DeploymentInfo builder = new DeploymentInfo().setClassLoader(SimpleServletTestCase.class.getClassLoader()).setContextPath("/servletContext").setClassIntrospecter(TestClassIntrospector.INSTANCE).setDeploymentName("servletContext.war").addServlets(servlets);
    if (servletExtension != null) {
        builder.addServletExtension(servletExtension);
    }
    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();
    try {
        pathHandler.addPrefixPath(builder.getContextPath(), manager.start());
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
    DefaultServer.setRootHandler(pathHandler);
    return manager.getDeployment();
}
Also used : ServletException(javax.servlet.ServletException) DeploymentManager(io.undertow.servlet.api.DeploymentManager) ServletContainer(io.undertow.servlet.api.ServletContainer) PathHandler(io.undertow.server.handlers.PathHandler) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) SimpleServletTestCase(io.undertow.servlet.test.SimpleServletTestCase)

Example 53 with PathHandler

use of io.undertow.server.handlers.PathHandler in project undertow by undertow-io.

the class AbstractResponseWrapperTestCase method setup.

@Before
public void setup() throws ServletException {
    DeploymentInfo builder = new DeploymentInfo();
    builder.setExceptionHandler(LoggingExceptionHandler.builder().add(IllegalArgumentException.class, "io.undertow", Logger.Level.DEBUG).build());
    final PathHandler root = new PathHandler();
    final ServletContainer container = ServletContainer.Factory.newInstance();
    builder.addServlet(new ServletInfo("wrapperServlet", WrapperServlet.class).addMapping("/*"));
    builder.addFilter(new FilterInfo("standard", StandardRequestWrappingFilter.class));
    builder.addFilterUrlMapping("standard", "/standard", DispatcherType.REQUEST);
    builder.addFilter(new FilterInfo("nonstandard", NonStandardRequestWrappingFilter.class));
    builder.addFilterUrlMapping("nonstandard", "/nonstandard", DispatcherType.REQUEST);
    builder.setClassIntrospecter(TestClassIntrospector.INSTANCE).setClassLoader(AbstractResponseWrapperTestCase.class.getClassLoader()).setContextPath("/servletContext").setDeploymentName("servletContext.war").setAllowNonStandardWrappers(isNonStandardAllowed());
    final DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();
    root.addPrefixPath(builder.getContextPath(), manager.start());
    DefaultServer.setRootHandler(root);
}
Also used : ServletInfo(io.undertow.servlet.api.ServletInfo) DeploymentManager(io.undertow.servlet.api.DeploymentManager) ServletContainer(io.undertow.servlet.api.ServletContainer) PathHandler(io.undertow.server.handlers.PathHandler) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) FilterInfo(io.undertow.servlet.api.FilterInfo) Before(org.junit.Before)

Example 54 with PathHandler

use of io.undertow.server.handlers.PathHandler in project undertow by undertow-io.

the class CrossContextServletSessionTestCase method setup.

@BeforeClass
public static void setup() throws ServletException {
    final ServletContainer container = ServletContainer.Factory.newInstance();
    final PathHandler path = new PathHandler();
    DefaultServer.setRootHandler(path);
    createDeployment("1", container, path);
    createDeployment("2", container, path);
}
Also used : ServletContainer(io.undertow.servlet.api.ServletContainer) PathHandler(io.undertow.server.handlers.PathHandler) BeforeClass(org.junit.BeforeClass)

Example 55 with PathHandler

use of io.undertow.server.handlers.PathHandler in project undertow by undertow-io.

the class ServletSessionPersistenceTestCase method testSimpleSessionUsage.

@Test
public void testSimpleSessionUsage() throws IOException, ServletException {
    final PathHandler pathHandler = new PathHandler();
    final ServletContainer container = ServletContainer.Factory.newInstance();
    DeploymentInfo builder = new DeploymentInfo().setClassLoader(SimpleServletTestCase.class.getClassLoader()).setContextPath("/servletContext").setClassIntrospecter(TestClassIntrospector.INSTANCE).setDeploymentName("servletContext.war").setSessionPersistenceManager(new InMemorySessionPersistence()).setServletSessionConfig(new ServletSessionConfig().setPath("/servletContext/aa")).addServlets(new ServletInfo("servlet", SessionServlet.class).addMapping("/aa/b"));
    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();
    try {
        pathHandler.addPrefixPath(builder.getContextPath(), manager.start());
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
    DefaultServer.setRootHandler(pathHandler);
    TestHttpClient client = new TestHttpClient();
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/aa/b");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("1", response);
        String cookieValue = result.getHeaders("Set-Cookie")[0].getValue();
        Assert.assertTrue(cookieValue, cookieValue.contains("JSESSIONID"));
        Assert.assertTrue(cookieValue, cookieValue.contains("/servletContext/aa"));
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("2", response);
        manager.stop();
        manager.undeploy();
        manager.deploy();
        pathHandler.addPrefixPath(builder.getContextPath(), manager.start());
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("3", response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : DeploymentManager(io.undertow.servlet.api.DeploymentManager) HttpGet(org.apache.http.client.methods.HttpGet) PathHandler(io.undertow.server.handlers.PathHandler) HttpResponse(org.apache.http.HttpResponse) ServletSessionConfig(io.undertow.servlet.api.ServletSessionConfig) SimpleServletTestCase(io.undertow.servlet.test.SimpleServletTestCase) TestHttpClient(io.undertow.testutils.TestHttpClient) ServletInfo(io.undertow.servlet.api.ServletInfo) ServletException(javax.servlet.ServletException) ServletContainer(io.undertow.servlet.api.ServletContainer) InMemorySessionPersistence(io.undertow.servlet.util.InMemorySessionPersistence) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) Test(org.junit.Test)

Aggregations

PathHandler (io.undertow.server.handlers.PathHandler)94 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)60 DeploymentManager (io.undertow.servlet.api.DeploymentManager)59 ServletContainer (io.undertow.servlet.api.ServletContainer)58 ServletInfo (io.undertow.servlet.api.ServletInfo)50 BeforeClass (org.junit.BeforeClass)48 Test (org.junit.Test)30 TestHttpClient (io.undertow.testutils.TestHttpClient)28 HttpResponse (org.apache.http.HttpResponse)25 HttpGet (org.apache.http.client.methods.HttpGet)24 PathResourceManager (io.undertow.server.handlers.resource.PathResourceManager)22 CanonicalPathHandler (io.undertow.server.handlers.CanonicalPathHandler)21 ResourceHandler (io.undertow.server.handlers.resource.ResourceHandler)21 Path (java.nio.file.Path)21 SimpleServletTestCase (io.undertow.servlet.test.SimpleServletTestCase)17 HttpHandler (io.undertow.server.HttpHandler)16 FilterInfo (io.undertow.servlet.api.FilterInfo)14 LoginConfig (io.undertow.servlet.api.LoginConfig)12 Header (org.apache.http.Header)12 TestResourceLoader (io.undertow.servlet.test.util.TestResourceLoader)11