Search in sources :

Example 26 with Wrapper

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

the class ApplicationContext method addJspFile.

@Override
public Dynamic addJspFile(String jspName, String jspFile) {
    // jspName is validated in addServlet()
    if (jspFile == null || !jspFile.startsWith("/")) {
        throw new IllegalArgumentException(sm.getString("applicationContext.addJspFile.iae", jspFile));
    }
    String jspServletClassName = null;
    Map<String, String> jspFileInitParams = new HashMap<>();
    Wrapper jspServlet = (Wrapper) context.findChild("jsp");
    if (jspServlet == null) {
        // No JSP servlet currently defined.
        // Use default JSP Servlet class name
        jspServletClassName = Constants.JSP_SERVLET_CLASS;
    } else {
        // JSP Servlet defined.
        // Use same JSP Servlet class name
        jspServletClassName = jspServlet.getServletClass();
        // Use same init parameters
        String[] params = jspServlet.findInitParameters();
        for (String param : params) {
            jspFileInitParams.put(param, jspServlet.findInitParameter(param));
        }
    }
    // Add init parameter to specify JSP file
    jspFileInitParams.put("jspFile", jspFile);
    return addServlet(jspName, jspServletClassName, null, jspFileInitParams);
}
Also used : Wrapper(org.apache.catalina.Wrapper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 27 with Wrapper

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

the class ApplicationContext method getRequestDispatcher.

@Override
public RequestDispatcher getRequestDispatcher(String path) {
    // Validate the path argument
    if (path == null)
        return (null);
    if (!path.startsWith("/"))
        throw new IllegalArgumentException(sm.getString("applicationContext.requestDispatcher.iae", path));
    // Get query string
    String queryString = null;
    String normalizedPath = path;
    int pos = normalizedPath.indexOf('?');
    if (pos >= 0) {
        queryString = normalizedPath.substring(pos + 1);
        normalizedPath = normalizedPath.substring(0, pos);
    }
    normalizedPath = RequestUtil.normalize(normalizedPath);
    if (normalizedPath == null)
        return (null);
    if (getContext().getDispatchersUseEncodedPaths()) {
        // Decode
        String decodedPath;
        try {
            decodedPath = URLDecoder.decode(normalizedPath, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // Impossible
            return null;
        }
        // Security check to catch attempts to encode /../ sequences
        normalizedPath = RequestUtil.normalize(decodedPath);
        if (!decodedPath.equals(normalizedPath)) {
            getContext().getLogger().warn(sm.getString("applicationContext.illegalDispatchPath", path), new IllegalArgumentException());
            return null;
        }
    }
    pos = normalizedPath.length();
    // Use the thread local URI and mapping data
    DispatchData dd = dispatchData.get();
    if (dd == null) {
        dd = new DispatchData();
        dispatchData.set(dd);
    }
    MessageBytes uriMB = dd.uriMB;
    uriMB.recycle();
    // Use the thread local mapping data
    MappingData mappingData = dd.mappingData;
    // Map the URI
    CharChunk uriCC = uriMB.getCharChunk();
    try {
        uriCC.append(context.getPath(), 0, context.getPath().length());
        /*
             * Ignore any trailing path params (separated by ';') for mapping
             * purposes
             */
        int semicolon = normalizedPath.indexOf(';');
        if (pos >= 0 && semicolon > pos) {
            semicolon = -1;
        }
        uriCC.append(normalizedPath, 0, semicolon > 0 ? semicolon : pos);
        service.getMapper().map(context, uriMB, mappingData);
        if (mappingData.wrapper == null) {
            return (null);
        }
        /*
             * Append any trailing path params (separated by ';') that were
             * ignored for mapping purposes, so that they're reflected in the
             * RequestDispatcher's requestURI
             */
        if (semicolon > 0) {
            uriCC.append(normalizedPath, semicolon, pos - semicolon);
        }
    } catch (Exception e) {
        // Should never happen
        log(sm.getString("applicationContext.mapping.error"), e);
        return (null);
    }
    Wrapper wrapper = mappingData.wrapper;
    String wrapperPath = mappingData.wrapperPath.toString();
    String pathInfo = mappingData.pathInfo.toString();
    ServletMapping mapping = (new ApplicationMapping(mappingData)).getServletMapping();
    mappingData.recycle();
    String encodedUri = URLEncoder.DEFAULT.encode(uriCC.toString(), "UTF-8");
    // Construct a RequestDispatcher to process this request
    return new ApplicationDispatcher(wrapper, encodedUri, wrapperPath, pathInfo, queryString, mapping, null);
}
Also used : Wrapper(org.apache.catalina.Wrapper) ServletMapping(javax.servlet.http.ServletMapping) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) MappingData(org.apache.catalina.mapper.MappingData) CharChunk(org.apache.tomcat.util.buf.CharChunk)

Example 28 with Wrapper

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

the class MapperListener method containerEvent.

// --------------------------------------------- Container Listener methods
@Override
public void containerEvent(ContainerEvent event) {
    if (Container.ADD_CHILD_EVENT.equals(event.getType())) {
        Container child = (Container) event.getData();
        addListeners(child);
        // to register the child so register it here
        if (child.getState().isAvailable()) {
            if (child instanceof Host) {
                registerHost((Host) child);
            } else if (child instanceof Context) {
                registerContext((Context) child);
            } else if (child instanceof Wrapper) {
                // will have its own "after_start" life-cycle event later.
                if (child.getParent().getState().isAvailable()) {
                    registerWrapper((Wrapper) child);
                }
            }
        }
    } else if (Container.REMOVE_CHILD_EVENT.equals(event.getType())) {
        Container child = (Container) event.getData();
        removeListeners(child);
    // No need to unregister - life-cycle listener will handle this when
    // the child stops
    } else if (Host.ADD_ALIAS_EVENT.equals(event.getType())) {
        // Handle dynamically adding host aliases
        mapper.addHostAlias(((Host) event.getSource()).getName(), event.getData().toString());
    } else if (Host.REMOVE_ALIAS_EVENT.equals(event.getType())) {
        // Handle dynamically removing host aliases
        mapper.removeHostAlias(event.getData().toString());
    } else if (Wrapper.ADD_MAPPING_EVENT.equals(event.getType())) {
        // Handle dynamically adding wrappers
        Wrapper wrapper = (Wrapper) event.getSource();
        Context context = (Context) wrapper.getParent();
        String contextPath = context.getPath();
        if ("/".equals(contextPath)) {
            contextPath = "";
        }
        String version = context.getWebappVersion();
        String hostName = context.getParent().getName();
        String wrapperName = wrapper.getName();
        String mapping = (String) event.getData();
        boolean jspWildCard = ("jsp".equals(wrapperName) && mapping.endsWith("/*"));
        mapper.addWrapper(hostName, contextPath, version, mapping, wrapper, jspWildCard, context.isResourceOnlyServlet(wrapperName));
    } else if (Wrapper.REMOVE_MAPPING_EVENT.equals(event.getType())) {
        // Handle dynamically removing wrappers
        Wrapper wrapper = (Wrapper) event.getSource();
        Context context = (Context) wrapper.getParent();
        String contextPath = context.getPath();
        if ("/".equals(contextPath)) {
            contextPath = "";
        }
        String version = context.getWebappVersion();
        String hostName = context.getParent().getName();
        String mapping = (String) event.getData();
        mapper.removeWrapper(hostName, contextPath, version, mapping);
    } else if (Context.ADD_WELCOME_FILE_EVENT.equals(event.getType())) {
        // Handle dynamically adding welcome files
        Context context = (Context) event.getSource();
        String hostName = context.getParent().getName();
        String contextPath = context.getPath();
        if ("/".equals(contextPath)) {
            contextPath = "";
        }
        String welcomeFile = (String) event.getData();
        mapper.addWelcomeFile(hostName, contextPath, context.getWebappVersion(), welcomeFile);
    } else if (Context.REMOVE_WELCOME_FILE_EVENT.equals(event.getType())) {
        // Handle dynamically removing welcome files
        Context context = (Context) event.getSource();
        String hostName = context.getParent().getName();
        String contextPath = context.getPath();
        if ("/".equals(contextPath)) {
            contextPath = "";
        }
        String welcomeFile = (String) event.getData();
        mapper.removeWelcomeFile(hostName, contextPath, context.getWebappVersion(), welcomeFile);
    } else if (Context.CLEAR_WELCOME_FILES_EVENT.equals(event.getType())) {
        // Handle dynamically clearing welcome files
        Context context = (Context) event.getSource();
        String hostName = context.getParent().getName();
        String contextPath = context.getPath();
        if ("/".equals(contextPath)) {
            contextPath = "";
        }
        mapper.clearWelcomeFiles(hostName, contextPath, context.getWebappVersion());
    }
}
Also used : Context(org.apache.catalina.Context) Wrapper(org.apache.catalina.Wrapper) Container(org.apache.catalina.Container) Host(org.apache.catalina.Host)

Example 29 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 30 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)

Aggregations

Wrapper (org.apache.catalina.Wrapper)87 Context (org.apache.catalina.Context)53 Tomcat (org.apache.catalina.startup.Tomcat)46 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)14 TesterAccessLogValve (org.apache.catalina.valves.TesterAccessLogValve)14 File (java.io.File)11 Container (org.apache.catalina.Container)11 StandardWrapper (org.apache.catalina.core.StandardWrapper)10 StandardContext (org.apache.catalina.core.StandardContext)6 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)6 ServletException (javax.servlet.ServletException)5 ArrayList (java.util.ArrayList)4 ServletContext (javax.servlet.ServletContext)4