Search in sources :

Example 31 with Wrapper

use of org.apache.catalina.Wrapper in project tomcat by apache.

the class ContextConfig method configureContext.

private void configureContext(WebXml webxml) {
    // As far as possible, process in alphabetical order so it is easy to
    // check everything is present
    // Some validation depends on correct public ID
    context.setPublicId(webxml.getPublicId());
    // Everything else in order
    context.setEffectiveMajorVersion(webxml.getMajorVersion());
    context.setEffectiveMinorVersion(webxml.getMinorVersion());
    for (Entry<String, String> entry : webxml.getContextParams().entrySet()) {
        context.addParameter(entry.getKey(), entry.getValue());
    }
    context.setDenyUncoveredHttpMethods(webxml.getDenyUncoveredHttpMethods());
    context.setDisplayName(webxml.getDisplayName());
    context.setDistributable(webxml.isDistributable());
    for (ContextLocalEjb ejbLocalRef : webxml.getEjbLocalRefs().values()) {
        context.getNamingResources().addLocalEjb(ejbLocalRef);
    }
    for (ContextEjb ejbRef : webxml.getEjbRefs().values()) {
        context.getNamingResources().addEjb(ejbRef);
    }
    for (ContextEnvironment environment : webxml.getEnvEntries().values()) {
        context.getNamingResources().addEnvironment(environment);
    }
    for (ErrorPage errorPage : webxml.getErrorPages().values()) {
        context.addErrorPage(errorPage);
    }
    for (FilterDef filter : webxml.getFilters().values()) {
        if (filter.getAsyncSupported() == null) {
            filter.setAsyncSupported("false");
        }
        context.addFilterDef(filter);
    }
    for (FilterMap filterMap : webxml.getFilterMappings()) {
        context.addFilterMap(filterMap);
    }
    context.setJspConfigDescriptor(webxml.getJspConfigDescriptor());
    for (String listener : webxml.getListeners()) {
        context.addApplicationListener(listener);
    }
    for (Entry<String, String> entry : webxml.getLocaleEncodingMappings().entrySet()) {
        context.addLocaleEncodingMappingParameter(entry.getKey(), entry.getValue());
    }
    // Prevents IAE
    if (webxml.getLoginConfig() != null) {
        context.setLoginConfig(webxml.getLoginConfig());
    }
    for (MessageDestinationRef mdr : webxml.getMessageDestinationRefs().values()) {
        context.getNamingResources().addMessageDestinationRef(mdr);
    }
    // messageDestinations were ignored in Tomcat 6, so ignore here
    context.setIgnoreAnnotations(webxml.isMetadataComplete());
    for (Entry<String, String> entry : webxml.getMimeMappings().entrySet()) {
        context.addMimeMapping(entry.getKey(), entry.getValue());
    }
    context.setRequestCharacterEncoding(webxml.getRequestEncoding());
    // Name is just used for ordering
    for (ContextResourceEnvRef resource : webxml.getResourceEnvRefs().values()) {
        context.getNamingResources().addResourceEnvRef(resource);
    }
    for (ContextResource resource : webxml.getResourceRefs().values()) {
        context.getNamingResources().addResource(resource);
    }
    context.setResponseCharacterEncoding(webxml.getResponseEncoding());
    boolean allAuthenticatedUsersIsAppRole = webxml.getSecurityRoles().contains(SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS);
    for (SecurityConstraint constraint : webxml.getSecurityConstraints()) {
        if (allAuthenticatedUsersIsAppRole) {
            constraint.treatAllAuthenticatedUsersAsApplicationRole();
        }
        context.addConstraint(constraint);
    }
    for (String role : webxml.getSecurityRoles()) {
        context.addSecurityRole(role);
    }
    for (ContextService service : webxml.getServiceRefs().values()) {
        context.getNamingResources().addService(service);
    }
    for (ServletDef servlet : webxml.getServlets().values()) {
        Wrapper wrapper = context.createWrapper();
        if (servlet.getLoadOnStartup() != null) {
            wrapper.setLoadOnStartup(servlet.getLoadOnStartup().intValue());
        }
        if (servlet.getEnabled() != null) {
            wrapper.setEnabled(servlet.getEnabled().booleanValue());
        }
        wrapper.setName(servlet.getServletName());
        Map<String, String> params = servlet.getParameterMap();
        for (Entry<String, String> entry : params.entrySet()) {
            wrapper.addInitParameter(entry.getKey(), entry.getValue());
        }
        wrapper.setRunAs(servlet.getRunAs());
        Set<SecurityRoleRef> roleRefs = servlet.getSecurityRoleRefs();
        for (SecurityRoleRef roleRef : roleRefs) {
            wrapper.addSecurityReference(roleRef.getName(), roleRef.getLink());
        }
        wrapper.setServletClass(servlet.getServletClass());
        MultipartDef multipartdef = servlet.getMultipartDef();
        if (multipartdef != null) {
            if (multipartdef.getMaxFileSize() != null && multipartdef.getMaxRequestSize() != null && multipartdef.getFileSizeThreshold() != null) {
                wrapper.setMultipartConfigElement(new MultipartConfigElement(multipartdef.getLocation(), Long.parseLong(multipartdef.getMaxFileSize()), Long.parseLong(multipartdef.getMaxRequestSize()), Integer.parseInt(multipartdef.getFileSizeThreshold())));
            } else {
                wrapper.setMultipartConfigElement(new MultipartConfigElement(multipartdef.getLocation()));
            }
        }
        if (servlet.getAsyncSupported() != null) {
            wrapper.setAsyncSupported(servlet.getAsyncSupported().booleanValue());
        }
        wrapper.setOverridable(servlet.isOverridable());
        context.addChild(wrapper);
    }
    for (Entry<String, String> entry : webxml.getServletMappings().entrySet()) {
        context.addServletMappingDecoded(entry.getKey(), entry.getValue());
    }
    SessionConfig sessionConfig = webxml.getSessionConfig();
    if (sessionConfig != null) {
        if (sessionConfig.getSessionTimeout() != null) {
            context.setSessionTimeout(sessionConfig.getSessionTimeout().intValue());
        }
        SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig();
        scc.setName(sessionConfig.getCookieName());
        scc.setDomain(sessionConfig.getCookieDomain());
        scc.setPath(sessionConfig.getCookiePath());
        scc.setComment(sessionConfig.getCookieComment());
        if (sessionConfig.getCookieHttpOnly() != null) {
            scc.setHttpOnly(sessionConfig.getCookieHttpOnly().booleanValue());
        }
        if (sessionConfig.getCookieSecure() != null) {
            scc.setSecure(sessionConfig.getCookieSecure().booleanValue());
        }
        if (sessionConfig.getCookieMaxAge() != null) {
            scc.setMaxAge(sessionConfig.getCookieMaxAge().intValue());
        }
        if (sessionConfig.getSessionTrackingModes().size() > 0) {
            context.getServletContext().setSessionTrackingModes(sessionConfig.getSessionTrackingModes());
        }
    }
    for (String welcomeFile : webxml.getWelcomeFiles()) {
        /*
             * The following will result in a welcome file of "" so don't add
             * that to the context
             * <welcome-file-list>
             *   <welcome-file/>
             * </welcome-file-list>
             */
        if (welcomeFile != null && welcomeFile.length() > 0) {
            context.addWelcomeFile(welcomeFile);
        }
    }
    // Do this last as it depends on servlets
    for (JspPropertyGroup jspPropertyGroup : webxml.getJspPropertyGroups()) {
        String jspServletName = context.findServletMapping("*.jsp");
        if (jspServletName == null) {
            jspServletName = "jsp";
        }
        if (context.findChild(jspServletName) != null) {
            for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
                context.addServletMappingDecoded(urlPattern, jspServletName, true);
            }
        } else {
            if (log.isDebugEnabled()) {
                for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
                    log.debug("Skipping " + urlPattern + " , no servlet " + jspServletName);
                }
            }
        }
    }
    for (Entry<String, String> entry : webxml.getPostConstructMethods().entrySet()) {
        context.addPostConstructMethod(entry.getKey(), entry.getValue());
    }
    for (Entry<String, String> entry : webxml.getPreDestroyMethods().entrySet()) {
        context.addPreDestroyMethod(entry.getKey(), entry.getValue());
    }
}
Also used : ContextEnvironment(org.apache.tomcat.util.descriptor.web.ContextEnvironment) Wrapper(org.apache.catalina.Wrapper) ContextService(org.apache.tomcat.util.descriptor.web.ContextService) ErrorPage(org.apache.tomcat.util.descriptor.web.ErrorPage) FilterDef(org.apache.tomcat.util.descriptor.web.FilterDef) ServletDef(org.apache.tomcat.util.descriptor.web.ServletDef) SessionConfig(org.apache.tomcat.util.descriptor.web.SessionConfig) SecurityRoleRef(org.apache.tomcat.util.descriptor.web.SecurityRoleRef) ContextEjb(org.apache.tomcat.util.descriptor.web.ContextEjb) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource) JspPropertyGroup(org.apache.tomcat.util.descriptor.web.JspPropertyGroup) MessageDestinationRef(org.apache.tomcat.util.descriptor.web.MessageDestinationRef) MultipartConfigElement(javax.servlet.MultipartConfigElement) ContextLocalEjb(org.apache.tomcat.util.descriptor.web.ContextLocalEjb) MultipartDef(org.apache.tomcat.util.descriptor.web.MultipartDef) SessionCookieConfig(javax.servlet.SessionCookieConfig) ContextResourceEnvRef(org.apache.tomcat.util.descriptor.web.ContextResourceEnvRef)

Example 32 with Wrapper

use of org.apache.catalina.Wrapper in project tomcat by apache.

the class ContextConfig method convertJsps.

private void convertJsps(WebXml webXml) {
    Map<String, String> jspInitParams;
    ServletDef jspServlet = webXml.getServlets().get("jsp");
    if (jspServlet == null) {
        jspInitParams = new HashMap<>();
        Wrapper w = (Wrapper) context.findChild("jsp");
        if (w != null) {
            String[] params = w.findInitParameters();
            for (String param : params) {
                jspInitParams.put(param, w.findInitParameter(param));
            }
        }
    } else {
        jspInitParams = jspServlet.getParameterMap();
    }
    for (ServletDef servletDef : webXml.getServlets().values()) {
        if (servletDef.getJspFile() != null) {
            convertJsp(servletDef, jspInitParams);
        }
    }
}
Also used : Wrapper(org.apache.catalina.Wrapper) ServletDef(org.apache.tomcat.util.descriptor.web.ServletDef)

Example 33 with Wrapper

use of org.apache.catalina.Wrapper in project tomcat by apache.

the class TestStandardWrapper method doTest.

private void doTest(String servletClassName, boolean usePost, boolean useRole, boolean expect200, boolean denyUncovered) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.setDenyUncoveredHttpMethods(denyUncovered);
    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servletClassName);
    wrapper.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/", "servlet");
    if (useRole) {
        TesterMapRealm realm = new TesterMapRealm();
        realm.addUser("testUser", "testPwd");
        realm.addUserRole("testUser", "testRole");
        ctx.setRealm(realm);
        ctx.setLoginConfig(new LoginConfig("BASIC", null, null, null));
        ctx.getPipeline().addValve(new BasicAuthenticator());
    }
    tomcat.start();
    ByteChunk bc = new ByteChunk();
    Map<String, List<String>> reqHeaders = null;
    if (useRole) {
        reqHeaders = new HashMap<>();
        List<String> authHeaders = new ArrayList<>();
        // testUser, testPwd
        authHeaders.add("Basic dGVzdFVzZXI6dGVzdFB3ZA==");
        reqHeaders.put("Authorization", authHeaders);
    }
    int rc;
    if (usePost) {
        rc = postUrl(null, "http://localhost:" + getPort() + "/", bc, reqHeaders, null);
    } else {
        rc = getUrl("http://localhost:" + getPort() + "/", bc, reqHeaders, null);
    }
    if (expect200) {
        assertEquals("OK", bc.toString());
        assertEquals(200, rc);
    } else {
        assertTrue(bc.getLength() > 0);
        assertEquals(403, rc);
    }
}
Also used : Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) Wrapper(org.apache.catalina.Wrapper) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) ArrayList(java.util.ArrayList) HttpConstraint(javax.servlet.annotation.HttpConstraint) HttpMethodConstraint(javax.servlet.annotation.HttpMethodConstraint) TesterMapRealm(org.apache.catalina.startup.TesterMapRealm) BasicAuthenticator(org.apache.catalina.authenticator.BasicAuthenticator) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) ArrayList(java.util.ArrayList) List(java.util.List)

Example 34 with Wrapper

use of org.apache.catalina.Wrapper in project tomcat by apache.

the class TestDefaultServlet method testCustomCompressedFile.

/*
     * Verify serving of custom compressed resources from context root.
     */
@Test
public void testCustomCompressedFile() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp");
    long brSize = new File(appDir, "index.html.br").length();
    long gzSize = new File(appDir, "index.html.gz").length();
    // app dir is relative to server home
    Context ctxt = tomcat.addContext("", appDir.getAbsolutePath());
    Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default", DefaultServlet.class.getName());
    defaultServlet.addInitParameter("precompressed", "gzip=.gz,custom=.br");
    ctxt.addServletMappingDecoded("/", "default");
    ctxt.addMimeMapping("html", "text/html");
    tomcat.start();
    TestCompressedClient client = new TestCompressedClient(getPort());
    client.reset();
    client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: br, gzip ; q = 0.5 , custom" + CRLF + CRLF });
    client.connect();
    client.processRequest();
    assertTrue(client.isResponse200());
    List<String> responseHeaders = client.getResponseHeaders();
    assertTrue(responseHeaders.contains("Content-Encoding: custom"));
    assertTrue(responseHeaders.contains("Content-Length: " + brSize));
    assertTrue(responseHeaders.contains("Vary: accept-encoding"));
    client.reset();
    client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: br;q=1,gzip,custom" + CRLF + CRLF });
    client.connect();
    client.processRequest();
    assertTrue(client.isResponse200());
    responseHeaders = client.getResponseHeaders();
    assertTrue(responseHeaders.contains("Content-Encoding: gzip"));
    assertTrue(responseHeaders.contains("Content-Length: " + gzSize));
    assertTrue(responseHeaders.contains("Vary: accept-encoding"));
}
Also used : Context(org.apache.catalina.Context) Wrapper(org.apache.catalina.Wrapper) Tomcat(org.apache.catalina.startup.Tomcat) File(java.io.File) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 35 with Wrapper

use of org.apache.catalina.Wrapper in project tomcat by apache.

the class TestDefaultServlet method testIdentityAndStarAcceptEncodings.

/*
     * Verify that "*" and "identity" values are handled correctly in accept-encoding header.
     */
@Test
public void testIdentityAndStarAcceptEncodings() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp");
    long brSize = new File(appDir, "index.html.br").length();
    long indexSize = new File(appDir, "index.html").length();
    // app dir is relative to server home
    Context ctxt = tomcat.addContext("", appDir.getAbsolutePath());
    Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default", DefaultServlet.class.getName());
    defaultServlet.addInitParameter("precompressed", "br=.br,gzip=.gz");
    ctxt.addServletMappingDecoded("/", "default");
    ctxt.addMimeMapping("html", "text/html");
    tomcat.start();
    TestCompressedClient client = new TestCompressedClient(getPort());
    client.reset();
    client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: gzip;q=0.9,*" + CRLF + CRLF });
    client.connect();
    client.processRequest();
    assertTrue(client.isResponse200());
    List<String> responseHeaders = client.getResponseHeaders();
    assertTrue(responseHeaders.contains("Content-Encoding: br"));
    assertTrue(responseHeaders.contains("Content-Length: " + brSize));
    assertTrue(responseHeaders.contains("Vary: accept-encoding"));
    client.reset();
    client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: gzip;q=0.9,br;q=0,identity," + CRLF + CRLF });
    client.connect();
    client.processRequest();
    assertTrue(client.isResponse200());
    responseHeaders = client.getResponseHeaders();
    assertFalse(responseHeaders.contains("Content-Encoding"));
    assertTrue(responseHeaders.contains("Content-Length: " + indexSize));
    assertTrue(responseHeaders.contains("Vary: accept-encoding"));
}
Also used : Context(org.apache.catalina.Context) Wrapper(org.apache.catalina.Wrapper) Tomcat(org.apache.catalina.startup.Tomcat) File(java.io.File) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Aggregations

Wrapper (org.apache.catalina.Wrapper)109 Context (org.apache.catalina.Context)57 Tomcat (org.apache.catalina.startup.Tomcat)48 AsyncContext (javax.servlet.AsyncContext)33 Test (org.junit.Test)31 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)28 ServletRequestWrapper (javax.servlet.ServletRequestWrapper)24 ServletResponseWrapper (javax.servlet.ServletResponseWrapper)24 TesterContext (org.apache.tomcat.unittest.TesterContext)24 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)22 IOException (java.io.IOException)18 StandardWrapper (org.apache.catalina.core.StandardWrapper)16 TesterAccessLogValve (org.apache.catalina.valves.TesterAccessLogValve)14 File (java.io.File)13 Container (org.apache.catalina.Container)13 ServletException (javax.servlet.ServletException)9 HashMap (java.util.HashMap)7 StandardContext (org.apache.catalina.core.StandardContext)7 Servlet (javax.servlet.Servlet)6 ArrayList (java.util.ArrayList)5