Search in sources :

Example 1 with StandardManager

use of org.apache.catalina.session.StandardManager 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 2 with StandardManager

use of org.apache.catalina.session.StandardManager in project spring-boot by spring-projects.

the class TomcatServletWebServerFactory method configurePersistSession.

private void configurePersistSession(Manager manager) {
    Assert.state(manager instanceof StandardManager, "Unable to persist HTTP session state using manager type " + manager.getClass().getName());
    File dir = getValidSessionStoreDir();
    File file = new File(dir, "SESSIONS.ser");
    ((StandardManager) manager).setPathname(file.getAbsolutePath());
}
Also used : StandardManager(org.apache.catalina.session.StandardManager) File(java.io.File)

Example 3 with StandardManager

use of org.apache.catalina.session.StandardManager in project tomee by apache.

the class TomcatWebAppBuilder method init.

/**
     * {@inheritDoc}
     */
@Override
public void init(final StandardContext standardContext) {
    if (isIgnored(standardContext)) {
        return;
    }
    // just adding a carriage return to get logs more readable
    logger.info("------------------------- " + Contexts.getHostname(standardContext).replace("_", hosts.getDefaultHost()) + " -> " + finalName(standardContext.getPath()));
    if (FORCE_RELOADABLE) {
        final ContextInfo ctxInfo = getContextInfo(standardContext);
        if (ctxInfo == null || (ctxInfo.appInfo != null && ctxInfo.appInfo.webAppAlone)) {
            // don't do it for ears
            standardContext.setReloadable(true);
        }
    }
    if (SKIP_TLD) {
        if (standardContext.getJarScanner() != null && standardContext.getJarScanner().getJarScanFilter() != null) {
            final JarScanFilter jarScanFilter = standardContext.getJarScanner().getJarScanFilter();
            if (StandardJarScanFilter.class.isInstance(jarScanFilter)) {
                StandardJarScanFilter.class.cast(jarScanFilter).setDefaultTldScan(false);
            }
        }
    }
    final String name = standardContext.getName();
    initJ2EEInfo(standardContext);
    File warFile = Contexts.warPath(standardContext);
    if (!warFile.exists()) {
        return;
    }
    if (!warFile.isDirectory()) {
        try {
            warFile = DeploymentLoader.unpack(warFile);
        } catch (final OpenEJBException e) {
            logger.error("can't unpack '" + warFile.getAbsolutePath() + "'");
        }
    }
    standardContext.setCrossContext(SystemInstance.get().getOptions().get(OPENEJB_CROSSCONTEXT_PROPERTY, false));
    standardContext.setNamingResources(new OpenEJBNamingResource(standardContext.getNamingResources()));
    String sessionManager = SystemInstance.get().getOptions().get(OPENEJB_SESSION_MANAGER_PROPERTY + "." + name, (String) null);
    if (sessionManager == null) {
        sessionManager = SystemInstance.get().getOptions().get(OPENEJB_SESSION_MANAGER_PROPERTY, (String) null);
    }
    if (sessionManager != null) {
        if (sessionManagerClass == null) {
            try {
                // the manager should be in standardclassloader
                sessionManagerClass = ParentClassLoaderFinder.Helper.get().loadClass(sessionManager);
            } catch (final ClassNotFoundException e) {
                logger.error("can't find '" + sessionManager + "', StandardManager will be used", e);
                sessionManagerClass = StandardManager.class;
            }
        }
        try {
            final Manager mgr = (Manager) sessionManagerClass.newInstance();
            standardContext.setManager(mgr);
        } catch (final Exception e) {
            logger.error("can't instantiate '" + sessionManager + "', StandardManager will be used", e);
        }
    }
    final LifecycleListener[] listeners = standardContext.findLifecycleListeners();
    for (final LifecycleListener l : listeners) {
        if (l instanceof ContextConfig) {
            standardContext.removeLifecycleListener(l);
        }
    }
    standardContext.addLifecycleListener(new OpenEJBContextConfig(new StandardContextInfo(standardContext)));
    // force manually the namingContextListener to merge jndi in an easier way
    final NamingContextListener ncl = new NamingContextListener();
    try {
        ncl.setName((String) getNamingContextName.invoke(standardContext));
    } catch (final Exception e) {
        ncl.setName(getId(standardContext));
    }
    ncl.setExceptionOnFailedWrite(standardContext.getJndiExceptionOnFailedWrite());
    standardContext.setNamingContextListener(ncl);
    standardContext.addLifecycleListener(ncl);
    standardContext.addLifecycleListener(new TomcatJavaJndiBinder());
    // listen some events
    standardContext.addContainerListener(new TomEEContainerListener());
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) StandardManager(org.apache.catalina.session.StandardManager) JarScanFilter(org.apache.tomcat.JarScanFilter) StandardJarScanFilter(org.apache.tomcat.util.scan.StandardJarScanFilter) OpenEJBContextConfig(org.apache.catalina.startup.OpenEJBContextConfig) LifecycleListener(org.apache.catalina.LifecycleListener) Manager(org.apache.catalina.Manager) InstanceManager(org.apache.tomcat.InstanceManager) StandardManager(org.apache.catalina.session.StandardManager) DeploymentExceptionManager(org.apache.openejb.assembler.classic.DeploymentExceptionManager) TransactionManager(javax.transaction.TransactionManager) StandardJarScanFilter(org.apache.tomcat.util.scan.StandardJarScanFilter) LifecycleException(org.apache.catalina.LifecycleException) NameNotFoundException(javax.naming.NameNotFoundException) IOException(java.io.IOException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) ContextConfig(org.apache.catalina.startup.ContextConfig) OpenEJBContextConfig(org.apache.catalina.startup.OpenEJBContextConfig) NamingContextListener(org.apache.catalina.core.NamingContextListener) File(java.io.File) JarFile(java.util.jar.JarFile)

Example 4 with StandardManager

use of org.apache.catalina.session.StandardManager in project tomcat by apache.

the class MBeanFactory method createStandardManager.

/**
     * Create a new StandardManager.
     *
     * @param parent MBean Name of the associated parent component
     * @return the object name of the created manager
     *
     * @exception Exception if an MBean cannot be created or registered
     */
public String createStandardManager(String parent) throws Exception {
    // Create a new StandardManager instance
    StandardManager manager = new StandardManager();
    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    Container container = getParentContainerFromParent(pname);
    if (container instanceof Context) {
        ((Context) container).setManager(manager);
    } else {
        throw new Exception(sm.getString("mBeanFactory.managerContext"));
    }
    ObjectName oname = manager.getObjectName();
    if (oname != null) {
        return (oname.toString());
    } else {
        return null;
    }
}
Also used : Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) Container(org.apache.catalina.Container) StandardManager(org.apache.catalina.session.StandardManager) ObjectName(javax.management.ObjectName)

Example 5 with StandardManager

use of org.apache.catalina.session.StandardManager in project spring-boot by spring-projects.

the class TomcatServletWebServerFactory method configureSession.

private void configureSession(Context context) {
    long sessionTimeout = getSessionTimeoutInMinutes();
    context.setSessionTimeout((int) sessionTimeout);
    if (isPersistSession()) {
        Manager manager = context.getManager();
        if (manager == null) {
            manager = new StandardManager();
            context.setManager(manager);
        }
        configurePersistSession(manager);
    } else {
        context.addLifecycleListener(new DisablePersistSessionListener());
    }
}
Also used : StandardManager(org.apache.catalina.session.StandardManager) Manager(org.apache.catalina.Manager) StandardManager(org.apache.catalina.session.StandardManager)

Aggregations

StandardManager (org.apache.catalina.session.StandardManager)5 Manager (org.apache.catalina.Manager)3 File (java.io.File)2 IOException (java.io.IOException)2 NamingException (javax.naming.NamingException)2 Container (org.apache.catalina.Container)2 LifecycleException (org.apache.catalina.LifecycleException)2 InstanceManager (org.apache.tomcat.InstanceManager)2 MalformedURLException (java.net.MalformedURLException)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 Set (java.util.Set)1 TreeMap (java.util.TreeMap)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 JarFile (java.util.jar.JarFile)1 ListenerNotFoundException (javax.management.ListenerNotFoundException)1 Notification (javax.management.Notification)1 ObjectName (javax.management.ObjectName)1