Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2012 Red Hat, Inc., and individual contributors
   * as indicated by the @author tags.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.apache.catalina.startup;
 
 
 import java.io.File;
 import java.util.Map;
 import java.util.Set;
 
 
Startup event listener for a Context that configures the properties of that Context, and the associated defined servlets.

Author(s):
Craig R. McClanahan
Jean-Francois Arcand
Version:
$Revision: 1500 $ $Date: 2010-07-02 11:46:55 +0200 (Fri, 02 Jul 2010) $
 
 
 public class ContextConfig
     implements LifecycleListener {
 
     // ----------------------------------------------------- Instance Variables
 

    
Custom mappings of login methods to authenticators
 
     protected Map customAuthenticators;


    
The set of Authenticators that we know how to configure. The key is the name of the implemented authentication method, and the value is the fully qualified Java class name of the corresponding Valve.
 
     protected static Properties authenticators = null;
 
     static {
         // Load our mapping properties
          = new Properties();
         InputStream is = null;
         try {
             is = ContextConfig.class.getClassLoader().getResourceAsStream("org/apache/catalina/startup/Authenticators.properties");
             if (is != null) {
                 .load(is);
             } else {
             }
         } catch (IOException e) {
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
        }
    }

    
The Context we are associated with.
    protected Context context = null;


    
Track any fatal errors during startup configuration processing.
    protected boolean ok = false;


    
Deployment count.
    protected static long deploymentCount = 0L;
    
    
    protected static final LoginConfig DUMMY_LOGIN_CONFIG =
                                new LoginConfig("NONE"nullnullnull);
    // ------------------------------------------------------------- Properties


    
Sets custom mappings of login methods to authenticators.

Parameters:
customAuthenticators Custom mappings of login methods to authenticators
    public void setCustomAuthenticators(Map customAuthenticators) {
        this. = customAuthenticators;
    }
    // --------------------------------------------------------- Public Methods


    
Process events for an associated Context.

Parameters:
event The lifecycle event that has occurred
    public void lifecycleEvent(LifecycleEvent event) {
        // Identify the context we are associated with
         = (Contextevent.getLifecycle();
        // Process the event that has occurred
        if (event.getType().equals(.)) {
            start();
        } else if (event.getType().equals(.)) {
            beforeStart();
        } else if (event.getType().equals(.)) {
            
        } else if (event.getType().equals(.)) {
            completeConfig();
        } else if (event.getType().equals(.)) {
            stop();
        } else if (event.getType().equals(.)) {
            init();
        } else if (event.getType().equals(.)) {
            destroy();
        } else if (event.getType().equals(.)) {
            loadOnStartup();
        } else if (event.getType().equals(.)) {
            beforeLoadOnStartup(event.getData());
        } else if (event.getType().equals(.)) {
            afterLoadOnStartup(event.getData());
        }
    }
    // -------------------------------------------------------- Protected Methods


    
Process the application configuration file, if it exists.
    protected void applicationWebConfig() {
    }
    
    
Parse TLDs. This is separate, and is not subject to the order defined. Also, all TLDs from all JARs are parsed.
    protected void applicationTldConfig() {
        
    }
    

    
Set up an Authenticator automatically if required, and one has not already been configured.
    protected void authenticatorConfig() {
        // Does this Context require an Authenticator?
        SecurityConstraint constraints[] = .findConstraints();
        if ((constraints == null) || (constraints.length == 0))
            return;
        LoginConfig loginConfig = .getLoginConfig();
        if (loginConfig == null) {
            loginConfig = ;
            .setLoginConfig(loginConfig);
        }
        // Has an authenticator been configured already?
        if ( instanceof Authenticator)
            return;
        if ( instanceof ContainerBase) {
            Pipeline pipeline = ((ContainerBase).getPipeline();
            if (pipeline != null) {
                Valve basic = pipeline.getBasic();
                if ((basic != null) && (basic instanceof Authenticator)) {
                    if (.getAuthenticator() == null) {
                        .setAuthenticator((Authenticatorbasic);
                    }
                    return;
                }
                Valve valves[] = pipeline.getValves();
                for (int i = 0; i < valves.lengthi++) {
                    if (valves[iinstanceof Authenticator) {
                        if (.getAuthenticator() == null) {
                            .setAuthenticator((Authenticatorvalves[i]);
                        }
                        return;
                    }
                }
            }
        } else {
            return;     // Cannot install a Valve even if it would be needed
        }
        // Has a Realm been configured for us to authenticate against?
        if (.getRealm() == null) {
            ..noRealmFound();
             = false;
            return;
        }
        /*
         * First check to see if there is a custom mapping for the login
         * method. If so, use it. Otherwise, check if there is a mapping in
         * org/apache/catalina/startup/Authenticators.properties.
         */
        Valve authenticator = null;
        if ( != null) {
            authenticator = (Valve)
                .get(loginConfig.getAuthMethod());
        }
        if (authenticator == null) {
            // Identify the class name of the Valve we should configure
            String authenticatorName = null;
            authenticatorName =
                    .getProperty(loginConfig.getAuthMethod());
            if (authenticatorName == null) {
                ..noAuthenticatorForAuthMethod(loginConfig.getAuthMethod());
                 = false;
                return;
            }
            // Instantiate and install an Authenticator of the requested class
            try {
                Class authenticatorClass = Class.forName(authenticatorName);
                authenticator = (ValveauthenticatorClass.newInstance();
            } catch (Throwable t) {
                ..failedLoadingAuthenticator(authenticatorNamet);
                 = false;
            }
        }
        if (authenticator instanceof Authenticator) {
            .setAuthenticator((Authenticatorauthenticator);
        }
        if (authenticator != null &&  instanceof ContainerBase) {
            Pipeline pipeline = ((ContainerBase).getPipeline();
            if (pipeline != null) {
                ((ContainerBase).addValve(authenticator);
                ..authenticatorConfigured(loginConfig.getAuthMethod());
            }
        }
    }
    protected String getBaseDir() {
        Container engineC=.getParent().getParent();
        ifengineC instanceof StandardEngine ) {
            return ((StandardEngine)engineC).getBaseDir();
        }
        return System.getProperty("catalina.base");
    }

    
Process the default configuration file, if it exists. The default config must be read with the container loader - so container servlets can be loaded
    protected void defaultWebConfig() {
        
    }


    
Parse fragments order.
    protected void createFragmentsOrder() {
        
    }
    
    
    
Process additional descriptors: TLDs, web fragments, and map overlays.
    protected void applicationExtraDescriptorsConfig() {
        
    }
    
    
    
Find and parse ServletContainerInitializer service in specified JAR.
        
    }
    
    
    
Process a "init" event for this Context.
    protected void init() {
        .setConfigured(false);
         = true;
    }
    
    
    
Process a "before start" event for this Context.
    protected void beforeStart() {
    }
    
    
    
Process a "start" event for this Context.
    protected void start() {
        // Called from StandardContext.start()
        // Process the default and application web.xml files
        if () {
            defaultWebConfig();
        }
        // Scan the main descriptors
        if () {
            applicationWebConfig();
        }
        // Parse any Servlet context initializer defined in a Jar
        if () {
        }
        // Parse fragment order
        if () {
            createFragmentsOrder();
        }
        // Scan fragments, TLDs and annotations
        if () {
            applicationExtraDescriptorsConfig();
        }
        // Parse any TLDs found for listeners
        if () {
            applicationTldConfig();
        }
        // Dump the contents of this pipeline if requested
        if ((..isDebugEnabled()) && ( instanceof ContainerBase)) {
            ..debug("Pipeline Configuration:");
            Pipeline pipeline = ((ContainerBase).getPipeline();
            Valve valves[] = null;
            if (pipeline != null)
                valves = pipeline.getValves();
            if (valves != null) {
                for (int i = 0; i < valves.lengthi++) {
                    ..debug("  " + valves[i].getInfo());
                }
            }
            ..debug("======================");
        }
        // Make our application available if no problems were encountered
        if () {
            .setConfigured(true);
        } else {
            .setConfigured(false);
        }
    }

    
Process a "start" event for this Context.
    protected void completeConfig() {
        
    }
    protected void loadOnStartup() {
    }
    protected void beforeLoadOnStartup(Object data) {
    }
    protected void afterLoadOnStartup(Object data) {
    }

    
Process a "stop" event for this Context.
    protected void stop() {
        int i;
        // Removing children
        Container[] children = .findChildren();
        for (i = 0; i < children.lengthi++) {
            .removeChild(children[i]);
        }
        // Removing application parameters
        /*
        ApplicationParameter[] applicationParameters =
            context.findApplicationParameters();
        for (i = 0; i < applicationParameters.length; i++) {
            context.removeApplicationParameter
                (applicationParameters[i].getName());
        }
        */
        // Removing security constraints
        SecurityConstraint[] securityConstraints = .findConstraints();
        for (i = 0; i < securityConstraints.lengthi++) {
            .removeConstraint(securityConstraints[i]);
        }
        // Removing errors pages
        ErrorPage[] errorPages = .findErrorPages();
        for (i = 0; i < errorPages.lengthi++) {
            .removeErrorPage(errorPages[i]);
        }
        // Removing filter defs
        FilterDef[] filterDefs = .findFilterDefs();
        for (i = 0; i < filterDefs.lengthi++) {
            .removeFilterDef(filterDefs[i]);
        }
        // Removing filter maps
        FilterMap[] filterMaps = .findFilterMaps();
        for (i = 0; i < filterMaps.lengthi++) {
            .removeFilterMap(filterMaps[i]);
        }
        // Removing Mime mappings
        String[] mimeMappings = .findMimeMappings();
        for (i = 0; i < mimeMappings.lengthi++) {
            .removeMimeMapping(mimeMappings[i]);
        }
        // Removing parameters
        String[] parameters = .findParameters();
        for (i = 0; i < parameters.lengthi++) {
            .removeParameter(parameters[i]);
        }
        // Removing sercurity role
        String[] securityRoles = .findSecurityRoles();
        for (i = 0; i < securityRoles.lengthi++) {
            .removeSecurityRole(securityRoles[i]);
        }
        // Removing servlet mappings
        String[] servletMappings = .findServletMappings();
        for (i = 0; i < servletMappings.lengthi++) {
            .removeServletMapping(servletMappings[i]);
        }
        // FIXME : Removing status pages
        // Removing taglibs
        String[] taglibs = .findTaglibs();
        for (i = 0; i < taglibs.lengthi++) {
            .removeTaglib(taglibs[i]);
        }
        // FIXME: remove JSP property groups
        
        // FIXME: remove JSP tag libraries
        
        // Removing welcome files
        String[] welcomeFiles = .findWelcomeFiles();
        for (i = 0; i < welcomeFiles.lengthi++) {
            .removeWelcomeFile(welcomeFiles[i]);
        }
        // Removing wrapper lifecycles
        String[] wrapperLifecycles = .findWrapperLifecycles();
        for (i = 0; i < wrapperLifecycles.lengthi++) {
            .removeWrapperLifecycle(wrapperLifecycles[i]);
        }
        // Removing wrapper listeners
        String[] wrapperListeners = .findWrapperListeners();
        for (i = 0; i < wrapperListeners.lengthi++) {
            .removeWrapperListener(wrapperListeners[i]);
        }
         = true;
    }
    
    
    
Process a "destroy" event for this Context.
    protected void destroy() {
        // Called from StandardContext.destroy()
        // Changed to getWorkPath per Bugzilla 35819.
        String workDir = ((StandardContext).getWorkPath();
        if (workDir != null)
            ExpandWar.delete(new File(workDir));
    }
    
    
    
Translate servlet security associated with Servlets to security constraints.
    protected void resolveServletSecurity() {
        // Skip all patterns for which a static security constraint has been defined
        HashSet<StringexcludedPatterns = new HashSet<String>();
        SecurityConstraint[] staticConstraints = .findConstraints();
        for (SecurityConstraint staticConstraint : staticConstraints) {
            for (SecurityCollection collection : staticConstraint.findCollections()) {
                for (String urlPattern : collection.findPatterns()) {
                    excludedPatterns.add(urlPattern);
                }
            }
        }
        // Iterate over servlet security objects
        Container wrappers[] = .findChildren();
        for (int i = 0; i < wrappers.lengthi++) {
            Wrapper wrapper = (Wrapperwrappers[i];
            ServletSecurityElement servletSecurity = wrapper.getServletSecurity();
            if (servletSecurity != null) {
                
                ArrayList<StringmethodOmissions = new ArrayList<String>();
                boolean classPA = servletSecurity.getEmptyRoleSemantic().equals(.);
                boolean classDA = servletSecurity.getEmptyRoleSemantic().equals(.);
                boolean classTP = servletSecurity.getTransportGuarantee().equals(.);
                String[] classRA = servletSecurity.getRolesAllowed();
                Collection<HttpMethodConstraintElementhttpMethodConstraints = 
                    servletSecurity.getHttpMethodConstraints();
                // Process method constraints
                if (httpMethodConstraints != null && httpMethodConstraints.size() > 0)
                {
                   for (HttpMethodConstraintElement httpMethodConstraint : httpMethodConstraints)
                   {
                       String method = toHttpMethod(httpMethodConstraint.getMethodName());
                      methodOmissions.add(method);
                      boolean methodPA = httpMethodConstraint.getEmptyRoleSemantic().equals(.);
                      boolean methodDA = httpMethodConstraint.getEmptyRoleSemantic().equals(.);
                      boolean methodTP = httpMethodConstraint.getTransportGuarantee().equals(.);
                      String[] methodRA = httpMethodConstraint.getRolesAllowed();
                      if (methodDA || methodTP || (methodRA != null && methodRA.length > 0))
                      {
                         // Define a constraint specific for the method
                         SecurityConstraint constraint = new SecurityConstraint();
                         if (methodDA) {
                             constraint.setAuthConstraint(true);
                         }
                         if (methodPA && (methodRA == null || methodRA.length == 0)) {
                             constraint.addAuthRole("*");
                         }
                         if (methodRA != null) {
                             for (String role : methodRA) {
                                 constraint.addAuthRole(role);
                             }
                         }
                         if (methodTP) {
                             constraint.setUserConstraint(.....);
                         }
                         SecurityCollection collection = new SecurityCollection();
                         collection.addMethod(method);
                         // Determine pattern set
                         String[] urlPatterns = wrapper.findMappings();
                         Set<StringservletSecurityPatterns = new HashSet<String>();
                         for (String urlPattern : urlPatterns) {
                             if (!excludedPatterns.contains(urlPattern)) {
                                 servletSecurityPatterns.add(urlPattern);
                             }
                         }
                         for (String urlPattern : servletSecurityPatterns) {
                             collection.addPattern(urlPattern);
                         }
                         constraint.addCollection(collection);
                         .addConstraint(constraint);
                      }
                   }
                }
                if (classDA || classTP || (classRA != null && classRA.length > 0))
                {
                    // Define a constraint for the class
                    SecurityConstraint constraint = new SecurityConstraint();
                    if (classPA && (classRA == null || classRA.length == 0)) {
                        constraint.addAuthRole("*");
                    }
                    if (classDA) {
                        constraint.setAuthConstraint(true);
                    }
                    if (classRA != null) {
                        for (String role : classRA) {
                            constraint.addAuthRole(role);
                        }
                    }
                    if (classTP) {
                        constraint.setUserConstraint(.....);
                    }
                    SecurityCollection collection = new SecurityCollection();
                    // Determine pattern set
                    String[] urlPatterns = wrapper.findMappings();
                    Set<StringservletSecurityPatterns = new HashSet<String>();
                    for (String urlPattern : urlPatterns) {
                        if (!excludedPatterns.contains(urlPattern)) {
                            servletSecurityPatterns.add(urlPattern);
                        }
                    }
                    for (String urlPattern : servletSecurityPatterns) {
                        collection.addPattern(urlPattern);
                    }
                    for (String methodOmission : methodOmissions) {
                        collection.addMethodOmission(methodOmission);
                    }
                    constraint.addCollection(collection);
                    .addConstraint(constraint);
                }
                
            }
        }
    }
    
    
    
Although this does not comply with the spec, it is likely Java method names will be used in the annotations. Since it is not possible to validate, this would be an error that is invisible for the user.

Parameters:
method
Returns:
    protected String toHttpMethod(String method) {
        if (method == null || method.length() < 3 || (!method.startsWith("do")))
            return method;
        return method.substring(2).toUpperCase();
    }
    
    
    
Validate the usage of security role names in the web application deployment descriptor. If any problems are found, issue warning messages (for backwards compatibility) and add the missing roles. (To make these problems fatal instead, simply set the ok instance variable to false as well).
    protected void validateSecurityRoles() {
        // Check role names used in <security-constraint> elements
        SecurityConstraint constraints[] = .findConstraints();
        for (int i = 0; i < constraints.lengthi++) {
            String roles[] = constraints[i].findAuthRoles();
            for (int j = 0; j < roles.lengthj++) {
                if (!"*".equals(roles[j]) &&
                    !.findSecurityRole(roles[j])) {
                    ..roleValidationAuth(roles[j]);
                    .addSecurityRole(roles[j]);
                }
            }
        }
        // Check role names used in <servlet> elements
        Container wrappers[] = .findChildren();
        for (int i = 0; i < wrappers.lengthi++) {
            Wrapper wrapper = (Wrapperwrappers[i];
            String runAs = wrapper.getRunAs();
            if ((runAs != null) && !.findSecurityRole(runAs)) {
                ..roleValidationRunAs(runAs);
                .addSecurityRole(runAs);
            }
            String names[] = wrapper.findSecurityReferences();
            for (int j = 0; j < names.lengthj++) {
                String link = wrapper.findSecurityReference(names[j]);
                if ((link != null) && !.findSecurityRole(link)) {
                    ..roleValidationLink(link);
                    .addSecurityRole(link);
                }
            }
        }
    }
    protected String getHostConfigPath(String resourceName) {
        StringBuilder result = new StringBuilder();
        Container container = ;
        Container host = null;
        Container engine = null;
        while (container != null) {
            if (container instanceof Host)
                host = container;
            if (container instanceof Engine)
                engine = container;
            container = container.getParent();
        }
        if (engine != null) {
            result.append(engine.getName()).append('/');
        }
        if (host != null) {
            result.append(host.getName()).append('/');
        }
        result.append(resourceName);
        return result.toString();
    }
New to GrepCode? Check out our FAQ X