Search in sources :

Example 26 with Container

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

the class StandardContext method stopInternal.

/**
     * Stop this component and implement the requirements
     * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
@Override
protected synchronized void stopInternal() throws LifecycleException {
    // Send j2ee.state.stopping notification
    if (this.getObjectName() != null) {
        Notification notification = new Notification("j2ee.state.stopping", this.getObjectName(), sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }
    setState(LifecycleState.STOPPING);
    // Binding thread
    ClassLoader oldCCL = bindThread();
    try {
        // Stop our child containers, if any
        final Container[] children = findChildren();
        // Stop ContainerBackgroundProcessor thread
        threadStop();
        for (int i = 0; i < children.length; i++) {
            children[i].stop();
        }
        // Stop our filters
        filterStop();
        Manager manager = getManager();
        if (manager instanceof Lifecycle && ((Lifecycle) manager).getState().isAvailable()) {
            ((Lifecycle) manager).stop();
        }
        // Stop our application listeners
        listenerStop();
        // Finalize our character set mapper
        setCharsetMapper(null);
        // Normal container shutdown processing
        if (log.isDebugEnabled())
            log.debug("Processing standard container shutdown");
        // after the application has finished with the resource
        if (namingResources != null) {
            namingResources.stop();
        }
        fireLifecycleEvent(Lifecycle.CONFIGURE_STOP_EVENT, null);
        // Stop the Valves in our pipeline (including the basic), if any
        if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) {
            ((Lifecycle) pipeline).stop();
        }
        // Clear all application-originated servlet context attributes
        if (context != null)
            context.clearAttributes();
        Realm realm = getRealmInternal();
        if (realm instanceof Lifecycle) {
            ((Lifecycle) realm).stop();
        }
        Loader loader = getLoader();
        if (loader instanceof Lifecycle) {
            ClassLoader classLoader = loader.getClassLoader();
            ((Lifecycle) loader).stop();
            if (classLoader != null) {
                InstanceManagerBindings.unbind(classLoader);
            }
        }
        // Stop resources
        resourcesStop();
    } finally {
        // Unbinding thread
        unbindThread(oldCCL);
    }
    // Send j2ee.state.stopped notification
    if (this.getObjectName() != null) {
        Notification notification = new Notification("j2ee.state.stopped", this.getObjectName(), sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }
    // Reset application context
    context = null;
    // This object will no longer be visible or used.
    try {
        resetContext();
    } catch (Exception ex) {
        log.error("Error resetting context " + this + " " + ex, ex);
    }
    //reset the instance manager
    setInstanceManager(null);
    if (log.isDebugEnabled())
        log.debug("Stopping complete");
}
Also used : Container(org.apache.catalina.Container) Lifecycle(org.apache.catalina.Lifecycle) WebappLoader(org.apache.catalina.loader.WebappLoader) Loader(org.apache.catalina.Loader) Manager(org.apache.catalina.Manager) InstanceManager(org.apache.tomcat.InstanceManager) StandardManager(org.apache.catalina.session.StandardManager) Realm(org.apache.catalina.Realm) Notification(javax.management.Notification) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) LifecycleException(org.apache.catalina.LifecycleException) ListenerNotFoundException(javax.management.ListenerNotFoundException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) MalformedURLException(java.net.MalformedURLException)

Example 27 with Container

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

the class ApplicationContext method getContext.

@Override
public ServletContext getContext(String uri) {
    // Validate the format of the specified argument
    if (uri == null || !uri.startsWith("/")) {
        return null;
    }
    Context child = null;
    try {
        // Look for an exact match
        Container host = context.getParent();
        child = (Context) host.findChild(uri);
        // Non-running contexts should be ignored.
        if (child != null && !child.getState().isAvailable()) {
            child = null;
        }
        // Remove any version information and use the mapper
        if (child == null) {
            int i = uri.indexOf("##");
            if (i > -1) {
                uri = uri.substring(0, i);
            }
            // Note: This could be more efficient with a dedicated Mapper
            //       method but such an implementation would require some
            //       refactoring of the Mapper to avoid copy/paste of
            //       existing code.
            MessageBytes hostMB = MessageBytes.newInstance();
            hostMB.setString(host.getName());
            MessageBytes pathMB = MessageBytes.newInstance();
            pathMB.setString(uri);
            MappingData mappingData = new MappingData();
            ((Engine) host.getParent()).getService().getMapper().map(hostMB, pathMB, null, mappingData);
            child = mappingData.context;
        }
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        return null;
    }
    if (child == null) {
        return null;
    }
    if (context.getCrossContext()) {
        // If crossContext is enabled, can always return the context
        return child.getServletContext();
    } else if (child == context) {
        // Can still return the current context
        return context.getServletContext();
    } else {
        // Nothing to return
        return null;
    }
}
Also used : Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) Container(org.apache.catalina.Container) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) MappingData(org.apache.catalina.mapper.MappingData) Engine(org.apache.catalina.Engine)

Example 28 with Container

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

the class StandardContext method resetContext.

private void resetContext() throws Exception {
    // again for this object
    for (Container child : findChildren()) {
        removeChild(child);
    }
    startupTime = 0;
    startTime = 0;
    tldScanTime = 0;
    // Bugzilla 32867
    distributable = false;
    applicationListeners = new String[0];
    applicationEventListenersList.clear();
    applicationLifecycleListenersObjects = new Object[0];
    jspConfigDescriptor = null;
    initializers.clear();
    createdServlets.clear();
    postConstructMethods.clear();
    preDestroyMethods.clear();
    if (log.isDebugEnabled())
        log.debug("resetContext " + getObjectName());
}
Also used : Container(org.apache.catalina.Container)

Example 29 with Container

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

the class StandardContext method startInternal.

/**
     * Start this component and implement the requirements
     * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
@Override
protected synchronized void startInternal() throws LifecycleException {
    if (log.isDebugEnabled())
        log.debug("Starting " + getBaseName());
    // Send j2ee.state.starting notification
    if (this.getObjectName() != null) {
        Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }
    setConfigured(false);
    boolean ok = true;
    // ensure the NamingResources follows the correct lifecycle
    if (namingResources != null) {
        namingResources.start();
    }
    // Add missing components as necessary
    if (getResources() == null) {
        // (1) Required by Loader
        if (log.isDebugEnabled())
            log.debug("Configuring default Resources");
        try {
            setResources(new StandardRoot(this));
        } catch (IllegalArgumentException e) {
            log.error(sm.getString("standardContext.resourcesInit"), e);
            ok = false;
        }
    }
    if (ok) {
        resourcesStart();
    }
    if (getLoader() == null) {
        WebappLoader webappLoader = new WebappLoader(getParentClassLoader());
        webappLoader.setDelegate(getDelegate());
        setLoader(webappLoader);
    }
    // An explicit cookie processor hasn't been specified; use the default
    if (cookieProcessor == null) {
        cookieProcessor = new Rfc6265CookieProcessor();
    }
    // Initialize character set mapper
    getCharsetMapper();
    // Post work directory
    postWorkDirectory();
    // Validate required extensions
    boolean dependencyCheck = true;
    try {
        dependencyCheck = ExtensionValidator.validateApplication(getResources(), this);
    } catch (IOException ioe) {
        log.error(sm.getString("standardContext.extensionValidationError"), ioe);
        dependencyCheck = false;
    }
    if (!dependencyCheck) {
        // do not make application available if dependency check fails
        ok = false;
    }
    // Reading the "catalina.useNaming" environment variable
    String useNamingProperty = System.getProperty("catalina.useNaming");
    if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) {
        useNaming = false;
    }
    if (ok && isUseNaming()) {
        if (getNamingContextListener() == null) {
            NamingContextListener ncl = new NamingContextListener();
            ncl.setName(getNamingContextName());
            ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite());
            addLifecycleListener(ncl);
            setNamingContextListener(ncl);
        }
    }
    // Standard container startup
    if (log.isDebugEnabled())
        log.debug("Processing standard container startup");
    // Binding thread
    ClassLoader oldCCL = bindThread();
    try {
        if (ok) {
            // Start our subordinate components, if any
            Loader loader = getLoader();
            if (loader instanceof Lifecycle) {
                ((Lifecycle) loader).start();
            }
            // since the loader just started, the webapp classloader is now
            // created.
            setClassLoaderProperty("clearReferencesRmiTargets", getClearReferencesRmiTargets());
            setClassLoaderProperty("clearReferencesStopThreads", getClearReferencesStopThreads());
            setClassLoaderProperty("clearReferencesStopTimerThreads", getClearReferencesStopTimerThreads());
            setClassLoaderProperty("clearReferencesHttpClientKeepAliveThread", getClearReferencesHttpClientKeepAliveThread());
            // By calling unbindThread and bindThread in a row, we setup the
            // current Thread CCL to be the webapp classloader
            unbindThread(oldCCL);
            oldCCL = bindThread();
            // Initialize logger again. Other components might have used it
            // too early, so it should be reset.
            logger = null;
            getLogger();
            Realm realm = getRealmInternal();
            if (null != realm) {
                if (realm instanceof Lifecycle) {
                    ((Lifecycle) realm).start();
                }
                // Place the CredentialHandler into the ServletContext so
                // applications can have access to it. Wrap it in a "safe"
                // handler so application's can't modify it.
                CredentialHandler safeHandler = new CredentialHandler() {

                    @Override
                    public boolean matches(String inputCredentials, String storedCredentials) {
                        return getRealmInternal().getCredentialHandler().matches(inputCredentials, storedCredentials);
                    }

                    @Override
                    public String mutate(String inputCredentials) {
                        return getRealmInternal().getCredentialHandler().mutate(inputCredentials);
                    }
                };
                context.setAttribute(Globals.CREDENTIAL_HANDLER, safeHandler);
            }
            // Notify our interested LifecycleListeners
            fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null);
            // Start our child containers, if not already started
            for (Container child : findChildren()) {
                if (!child.getState().isAvailable()) {
                    child.start();
                }
            }
            // if any
            if (pipeline instanceof Lifecycle) {
                ((Lifecycle) pipeline).start();
            }
            // Acquire clustered manager
            Manager contextManager = null;
            Manager manager = getManager();
            if (manager == null) {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("standardContext.cluster.noManager", Boolean.valueOf((getCluster() != null)), Boolean.valueOf(distributable)));
                }
                if ((getCluster() != null) && distributable) {
                    try {
                        contextManager = getCluster().createManager(getName());
                    } catch (Exception ex) {
                        log.error("standardContext.clusterFail", ex);
                        ok = false;
                    }
                } else {
                    contextManager = new StandardManager();
                }
            }
            // Configure default manager if none was specified
            if (contextManager != null) {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("standardContext.manager", contextManager.getClass().getName()));
                }
                setManager(contextManager);
            }
            if (manager != null && (getCluster() != null) && distributable) {
                //let the cluster know that there is a context that is distributable
                //and that it has its own manager
                getCluster().registerManager(manager);
            }
        }
        if (!getConfigured()) {
            log.error(sm.getString("standardContext.configurationFail"));
            ok = false;
        }
        // We put the resources into the servlet context
        if (ok)
            getServletContext().setAttribute(Globals.RESOURCES_ATTR, getResources());
        if (ok) {
            if (getInstanceManager() == null) {
                javax.naming.Context context = null;
                if (isUseNaming() && getNamingContextListener() != null) {
                    context = getNamingContextListener().getEnvContext();
                }
                Map<String, Map<String, String>> injectionMap = buildInjectionMap(getIgnoreAnnotations() ? new NamingResourcesImpl() : getNamingResources());
                setInstanceManager(new DefaultInstanceManager(context, injectionMap, this, this.getClass().getClassLoader()));
            }
            getServletContext().setAttribute(InstanceManager.class.getName(), getInstanceManager());
            InstanceManagerBindings.bind(getLoader().getClassLoader(), getInstanceManager());
        }
        // Create context attributes that will be required
        if (ok) {
            getServletContext().setAttribute(JarScanner.class.getName(), getJarScanner());
        }
        // Set up the context init params
        mergeParameters();
        // Call ServletContainerInitializers
        for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializers.entrySet()) {
            try {
                entry.getKey().onStartup(entry.getValue(), getServletContext());
            } catch (ServletException e) {
                log.error(sm.getString("standardContext.sciFail"), e);
                ok = false;
                break;
            }
        }
        // Configure and call application event listeners
        if (ok) {
            if (!listenerStart()) {
                log.error(sm.getString("standardContext.listenerFail"));
                ok = false;
            }
        }
        // change constraints
        if (ok) {
            checkConstraintsForUncoveredMethods(findConstraints());
        }
        try {
            // Start manager
            Manager manager = getManager();
            if (manager instanceof Lifecycle) {
                ((Lifecycle) manager).start();
            }
        } catch (Exception e) {
            log.error(sm.getString("standardContext.managerFail"), e);
            ok = false;
        }
        // Configure and call application filters
        if (ok) {
            if (!filterStart()) {
                log.error(sm.getString("standardContext.filterFail"));
                ok = false;
            }
        }
        // Load and initialize all "load on startup" servlets
        if (ok) {
            if (!loadOnStartup(findChildren())) {
                log.error(sm.getString("standardContext.servletFail"));
                ok = false;
            }
        }
        // Start ContainerBackgroundProcessor thread
        super.threadStart();
    } finally {
        // Unbinding thread
        unbindThread(oldCCL);
    }
    // Set available status depending upon startup success
    if (ok) {
        if (log.isDebugEnabled())
            log.debug("Starting completed");
    } else {
        log.error(sm.getString("standardContext.startFailed", getName()));
    }
    startTime = System.currentTimeMillis();
    // Send j2ee.state.running notification
    if (ok && (this.getObjectName() != null)) {
        Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }
    // The WebResources implementation caches references to JAR files. On
    // some platforms these references may lock the JAR files. Since web
    // application start is likely to have read from lots of JARs, trigger
    // a clean-up now.
    getResources().gc();
    // Reinitializing if something went wrong
    if (!ok) {
        setState(LifecycleState.FAILED);
    } else {
        setState(LifecycleState.STARTING);
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) CredentialHandler(org.apache.catalina.CredentialHandler) InstanceManager(org.apache.tomcat.InstanceManager) StandardRoot(org.apache.catalina.webresources.StandardRoot) WebappLoader(org.apache.catalina.loader.WebappLoader) Loader(org.apache.catalina.Loader) Manager(org.apache.catalina.Manager) InstanceManager(org.apache.tomcat.InstanceManager) StandardManager(org.apache.catalina.session.StandardManager) StandardJarScanner(org.apache.tomcat.util.scan.StandardJarScanner) JarScanner(org.apache.tomcat.JarScanner) Notification(javax.management.Notification) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) ServletException(javax.servlet.ServletException) Container(org.apache.catalina.Container) Rfc6265CookieProcessor(org.apache.tomcat.util.http.Rfc6265CookieProcessor) Realm(org.apache.catalina.Realm) Lifecycle(org.apache.catalina.Lifecycle) StandardManager(org.apache.catalina.session.StandardManager) IOException(java.io.IOException) LifecycleException(org.apache.catalina.LifecycleException) ListenerNotFoundException(javax.management.ListenerNotFoundException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) MalformedURLException(java.net.MalformedURLException) NamingResourcesImpl(org.apache.catalina.deploy.NamingResourcesImpl) WebappLoader(org.apache.catalina.loader.WebappLoader) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 30 with Container

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

the class Request method doGetSession.

// ------------------------------------------------------ Protected Methods
protected Session doGetSession(boolean create) {
    // There cannot be a session if no context has been assigned yet
    Context context = getContext();
    if (context == null) {
        return (null);
    }
    // Return the current session if it exists and is valid
    if ((session != null) && !session.isValid()) {
        session = null;
    }
    if (session != null) {
        return (session);
    }
    // Return the requested session if it exists and is valid
    Manager manager = context.getManager();
    if (manager == null) {
        // Sessions are not supported
        return (null);
    }
    if (requestedSessionId != null) {
        try {
            session = manager.findSession(requestedSessionId);
        } catch (IOException e) {
            session = null;
        }
        if ((session != null) && !session.isValid()) {
            session = null;
        }
        if (session != null) {
            session.access();
            return (session);
        }
    }
    // Create a new session if requested and the response is not committed
    if (!create) {
        return (null);
    }
    if (response != null && context.getServletContext().getEffectiveSessionTrackingModes().contains(SessionTrackingMode.COOKIE) && response.getResponse().isCommitted()) {
        throw new IllegalStateException(sm.getString("coyoteRequest.sessionCreateCommitted"));
    }
    // Re-use session IDs provided by the client in very limited
    // circumstances.
    String sessionId = getRequestedSessionId();
    if (requestedSessionSSL) {
    // If the session ID has been obtained from the SSL handshake then
    // use it.
    } else if (("/".equals(context.getSessionCookiePath()) && isRequestedSessionIdFromCookie())) {
        /* This is the common(ish) use case: using the same session ID with
             * multiple web applications on the same host. Typically this is
             * used by Portlet implementations. It only works if sessions are
             * tracked via cookies. The cookie must have a path of "/" else it
             * won't be provided for requests to all web applications.
             *
             * Any session ID provided by the client should be for a session
             * that already exists somewhere on the host. Check if the context
             * is configured for this to be confirmed.
             */
        if (context.getValidateClientProvidedNewSessionId()) {
            boolean found = false;
            for (Container container : getHost().findChildren()) {
                Manager m = ((Context) container).getManager();
                if (m != null) {
                    try {
                        if (m.findSession(sessionId) != null) {
                            found = true;
                            break;
                        }
                    } catch (IOException e) {
                    // Ignore. Problems with this manager will be
                    // handled elsewhere.
                    }
                }
            }
            if (!found) {
                sessionId = null;
            }
        }
    } else {
        sessionId = null;
    }
    session = manager.createSession(sessionId);
    // Creating a new session cookie based on that session
    if (session != null && context.getServletContext().getEffectiveSessionTrackingModes().contains(SessionTrackingMode.COOKIE)) {
        Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie(context, session.getIdInternal(), isSecure());
        response.addSessionCookieInternal(cookie);
    }
    if (session == null) {
        return null;
    }
    session.access();
    return session;
}
Also used : ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) ServerCookie(org.apache.tomcat.util.http.ServerCookie) Cookie(javax.servlet.http.Cookie) Container(org.apache.catalina.Container) IOException(java.io.IOException) StringManager(org.apache.tomcat.util.res.StringManager) Manager(org.apache.catalina.Manager) InstanceManager(org.apache.tomcat.InstanceManager)

Aggregations

Container (org.apache.catalina.Container)125 Context (org.apache.catalina.Context)26 Host (org.apache.catalina.Host)20 Engine (org.apache.catalina.Engine)18 IOException (java.io.IOException)17 StandardContext (org.apache.catalina.core.StandardContext)17 ObjectName (javax.management.ObjectName)15 StandardHost (org.apache.catalina.core.StandardHost)13 Wrapper (org.apache.catalina.Wrapper)11 ArrayList (java.util.ArrayList)10 Valve (org.apache.catalina.Valve)10 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)10 Realm (org.apache.catalina.Realm)9 File (java.io.File)8 LifecycleException (org.apache.catalina.LifecycleException)8 StandardWrapper (org.apache.catalina.core.StandardWrapper)8 ServletContext (javax.servlet.ServletContext)7 ServletException (javax.servlet.ServletException)7 Lifecycle (org.apache.catalina.Lifecycle)7 Service (org.apache.catalina.Service)7