use of org.apache.catalina.Lifecycle in project tomcat by apache.
the class StandardContext method destroyInternal.
/** Destroy needs to clean up the context completely.
*
* The problem is that undoing all the config in start() and restoring
* a 'fresh' state is impossible. After stop()/destroy()/init()/start()
* we should have the same state as if a fresh start was done - i.e
* read modified web.xml, etc. This can only be done by completely
* removing the context object and remapping a new one, or by cleaning
* up everything.
*
* XXX Should this be done in stop() ?
*
*/
@Override
protected void destroyInternal() throws LifecycleException {
// have been set so the notification can't be created
if (getObjectName() != null) {
// Send j2ee.object.deleted notification
Notification notification = new Notification("j2ee.object.deleted", this.getObjectName(), sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
if (namingResources != null) {
namingResources.destroy();
}
Loader loader = getLoader();
if (loader instanceof Lifecycle) {
((Lifecycle) loader).destroy();
}
Manager manager = getManager();
if (manager instanceof Lifecycle) {
((Lifecycle) manager).destroy();
}
if (resources != null) {
resources.destroy();
}
super.destroyInternal();
}
use of org.apache.catalina.Lifecycle 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);
}
}
use of org.apache.catalina.Lifecycle in project tomcat by apache.
the class ManagerBase method startInternal.
@Override
protected void startInternal() throws LifecycleException {
// nulls.
while (sessionCreationTiming.size() < TIMING_STATS_CACHE_SIZE) {
sessionCreationTiming.add(null);
}
while (sessionExpirationTiming.size() < TIMING_STATS_CACHE_SIZE) {
sessionExpirationTiming.add(null);
}
/* Create sessionIdGenerator if not explicitly configured */
SessionIdGenerator sessionIdGenerator = getSessionIdGenerator();
if (sessionIdGenerator == null) {
sessionIdGenerator = new StandardSessionIdGenerator();
setSessionIdGenerator(sessionIdGenerator);
}
sessionIdGenerator.setJvmRoute(getJvmRoute());
if (sessionIdGenerator instanceof SessionIdGeneratorBase) {
SessionIdGeneratorBase sig = (SessionIdGeneratorBase) sessionIdGenerator;
sig.setSecureRandomAlgorithm(getSecureRandomAlgorithm());
sig.setSecureRandomClass(getSecureRandomClass());
sig.setSecureRandomProvider(getSecureRandomProvider());
}
if (sessionIdGenerator instanceof Lifecycle) {
((Lifecycle) sessionIdGenerator).start();
} else {
// Force initialization of the random number generator
if (log.isDebugEnabled())
log.debug("Force random number initialization starting");
sessionIdGenerator.generateSessionId();
if (log.isDebugEnabled())
log.debug("Force random number initialization completed");
}
}
use of org.apache.catalina.Lifecycle in project tomee by apache.
the class LazyValve method instance.
private Valve instance() {
if (delegate == null) {
synchronized (this) {
if (delegate == null) {
final Object instance;
ClassLoader cl = loader();
if (cl == null) {
return null;
}
final Class<?> clazz;
try {
clazz = cl.loadClass(delegateClassName);
} catch (final ClassNotFoundException e) {
throw new TomEERuntimeException(e);
}
try {
final ObjectRecipe recipe = new ObjectRecipe(clazz);
recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
recipe.allow(Option.FIELD_INJECTION);
recipe.allow(Option.PRIVATE_PROPERTIES);
if (properties != null) {
final Properties props = new PropertiesAdapter().unmarshal(properties.trim().replaceAll("\\p{Space}*(\\p{Alnum}*)=", "\n$1="));
recipe.setAllProperties(props);
}
instance = recipe.create();
} catch (final Exception e) {
throw new TomEERuntimeException(e);
}
delegate = Valve.class.cast(instance);
delegate.setNext(next);
if (Contained.class.isInstance(delegate)) {
Contained.class.cast(delegate).setContainer(container);
}
if (Lifecycle.class.isInstance(delegate)) {
if (init) {
try {
final Lifecycle lifecycle = Lifecycle.class.cast(delegate);
for (final LifecycleListener listener : lifecycleListeners) {
lifecycle.addLifecycleListener(listener);
}
lifecycle.init();
if (start) {
lifecycle.start();
}
} catch (final LifecycleException e) {
// no-op
}
}
}
if (ClusterValve.class.isInstance(delegate)) {
ClusterValve.class.cast(delegate).setCluster(cluster);
}
}
}
}
return delegate;
}
use of org.apache.catalina.Lifecycle in project tomcat by apache.
the class StandardEngineSF method storeChildren.
/**
* Store the specified Engine properties.
*
* @param aWriter
* PrintWriter to which we are storing
* @param indent
* Number of spaces to indent this element
* @param aEngine
* Object whose properties are being stored
*
* @exception Exception
* if an exception occurs while storing
*/
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aEngine, StoreDescription parentDesc) throws Exception {
if (aEngine instanceof StandardEngine) {
StandardEngine engine = (StandardEngine) aEngine;
// Store nested <Listener> elements
LifecycleListener[] listeners = ((Lifecycle) engine).findLifecycleListeners();
storeElementArray(aWriter, indent, listeners);
// Store nested <Realm> element
Realm realm = engine.getRealm();
Realm parentRealm = null;
// TODO is this case possible? (see it a old Server 5.0 impl)
if (engine.getParent() != null) {
parentRealm = engine.getParent().getRealm();
}
if (realm != parentRealm) {
storeElement(aWriter, indent, realm);
}
// Store nested <Valve> elements
Valve[] valves = engine.getPipeline().getValves();
if (valves != null && valves.length > 0) {
List<Valve> engineValves = new ArrayList<>();
for (int i = 0; i < valves.length; i++) {
if (!(valves[i] instanceof ClusterValve))
engineValves.add(valves[i]);
}
storeElementArray(aWriter, indent, engineValves.toArray());
}
// store all <Cluster> elements
Cluster cluster = engine.getCluster();
if (cluster != null) {
storeElement(aWriter, indent, cluster);
}
// store all <Host> elements
Container[] children = engine.findChildren();
storeElementArray(aWriter, indent, children);
}
}
Aggregations