/** * 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 { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.stopped", getName())); setState(LifecycleState.STOPPING); // Expire all active sessions if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.expireSessions", getName())); Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { DeltaSession session = (DeltaSession) sessions[i]; if (!session.isValid()) continue; try { session.expire(true, isExpireSessionsOnShutdown()); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } // Require a new random number generator if we are restarted super.stopInternal(); }
/** * Test JNDI is available to ServletContextListeners. */ @Test public void testBug49132() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required org.apache.catalina.Context ctx = tomcat.addContext("", null); // Enable JNDI - it is disabled by default tomcat.enableNaming(); ContextEnvironment environment = new ContextEnvironment(); environment.setType(BUG49132_VALUE.getClass().getName()); environment.setName(BUG49132_NAME); environment.setValue(BUG49132_VALUE); ctx.getNamingResources().addEnvironment(environment); ctx.addApplicationListener(Bug49132Listener.class.getName()); tomcat.start(); assertEquals(LifecycleState.STARTED, ctx.getState()); }
/** * Stop this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. * * This will disconnect the cluster communication channel and stop the * listener thread. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("backupManager.stopped", getName())); setState(LifecycleState.STOPPING); if (sessions instanceof LazyReplicatedMap) { LazyReplicatedMap<String,Session> map = (LazyReplicatedMap<String,Session>)sessions; map.breakdown(); } super.stopInternal(); }
@Override public void declareRoles(String... roleNames) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { // TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException(sm.getString("applicationContext.addRole.ise", getContextPath())); } if (roleNames == null) { throw new IllegalArgumentException(sm.getString("applicationContext.roles.iae", getContextPath())); } for (String role : roleNames) { if (role == null || "".equals(role)) { throw new IllegalArgumentException(sm.getString("applicationContext.role.iae", getContextPath())); } context.addSecurityRole(role); } }
/** * Prepare for the beginning of active use of the public methods of 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 void startInternal() throws LifecycleException { // Create a MessageDigest instance for credentials, if desired if (digest != null) { try { md = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); } } setState(LifecycleState.STARTING); }
/** * Start Cluster 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 void startInternal() throws LifecycleException { if (log.isInfoEnabled()) log.info("Cluster is about to start"); try { checkDefaults(); registerClusterValve(); channel.addMembershipListener(this); channel.addChannelListener(this); if (channel instanceof GroupChannel) ((GroupChannel) channel).setName(getClusterName() + "-Channel"); channel.start(channelStartOptions); if (clusterDeployer != null) clusterDeployer.start(); registerMember(channel.getLocalMember(false)); } catch (Exception x) { log.error("Unable to start cluster.", x); throw new LifecycleException(x); } setState(LifecycleState.STARTING); }
/** * Add a new welcome file to the set recognized by this Context. * * @param name * New welcome file name */ @Override public void addWelcomeFile(String name) { synchronized (welcomeFilesLock) { // Welcome files from the application deployment descriptor // completely replace those from the default conf/web.xml file if (replaceWelcomeFiles) { fireContainerEvent(CLEAR_WELCOME_FILES_EVENT, null); welcomeFiles = new String[0]; setReplaceWelcomeFiles(false); } String results[] = new String[welcomeFiles.length + 1]; for (int i = 0; i < welcomeFiles.length; i++) results[i] = welcomeFiles[i]; results[welcomeFiles.length] = name; welcomeFiles = results; } if (this.getState().equals(LifecycleState.STARTED)) fireContainerEvent(ADD_WELCOME_FILE_EVENT, name); }
/** * Create a message and send it * * @param serverId * the server instance id * @param serverName * the server name * @param destAddr * the JGroups destination address @return * {@link JGroupsStateReporter} for chaining purposes */ private void sendMsg(final String serverId, final String serverName, final Address destAddr) { messagingService.init(); try { final Address channelAddress = messagingService.getChannel().getAddress(); msgBuilder = new JGroupsServerInfoMessageBuilder().setServerId(serverId).setServerName(serverName) .setState(state).setSrcAddress(channelAddress).setDestAddress(destAddr); } catch (final Exception e) { throw new JGroupsStateReporterException("Failed to create message!", e); } messagingService.send(msgBuilder.build()); // send the // state // details // immediately if (LifecycleState.STOPPED.equals(state) || LifecycleState.DESTROYED.equals(state)) { LOGGER.info("State {} received, destroying messaging service...", state); messagingService.destroy(); } }
/** * Stop nested components ({@link Service}s) and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. * * @exception LifecycleException * if this component detects a fatal error that needs to be * reported */ @Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); fireLifecycleEvent(CONFIGURE_STOP_EVENT, null); // Stop our defined Services for (int i = 0; i < services.length; i++) { services[i].stop(); } globalNamingResources.stop(); stopAwait(); }
@Test public void testWebappLoaderStartFail() throws Exception { // Test that if WebappLoader start() fails and if the cause of // the failure is gone, the context can be started without // a need to redeploy it. // Set up a container Tomcat tomcat = getTomcatInstance(); tomcat.start(); // To not start Context automatically, as we have to configure it first ((ContainerBase) tomcat.getHost()).setStartChildren(false); FailingWebappLoader loader = new FailingWebappLoader(); File root = new File("test/webapp-3.0"); Context context = tomcat.addWebapp("", root.getAbsolutePath()); context.setLoader(loader); try { context.start(); fail(); } catch (LifecycleException ex) { // As expected } assertEquals(LifecycleState.FAILED, context.getState()); // The second attempt loader.setFail(false); context.start(); assertEquals(LifecycleState.STARTED, context.getState()); // Using a test from testBug49922() to check that the webapp is running ByteChunk result = getUrl("http://localhost:" + getPort() + "/bug49922/target"); assertEquals("Target", result.toString()); }
@Test public void testWebappListenerConfigureFail() throws Exception { // Test that if LifecycleListener on webapp fails during // configure_start event and if the cause of the failure is gone, // the context can be started without a need to redeploy it. // Set up a container Tomcat tomcat = getTomcatInstance(); tomcat.start(); // To not start Context automatically, as we have to configure it first ((ContainerBase) tomcat.getHost()).setStartChildren(false); FailingLifecycleListener listener = new FailingLifecycleListener(); File root = new File("test/webapp-3.0"); Context context = tomcat.addWebapp("", root.getAbsolutePath()); context.addLifecycleListener(listener); try { context.start(); fail(); } catch (LifecycleException ex) { // As expected } assertEquals(LifecycleState.FAILED, context.getState()); // The second attempt listener.setFail(false); context.start(); assertEquals(LifecycleState.STARTED, context.getState()); // Using a test from testBug49922() to check that the webapp is running ByteChunk result = getUrl("http://localhost:" + getPort() + "/bug49922/target"); assertEquals("Target", result.toString()); }
@Test public void testDeploymentXmlExternalDirXmlFTT() throws Exception { File dir = createDirInExternal(true); createXmlInConfigBaseForExternal(dir); doTestDeployment(false, true, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); }
@Override public synchronized void lifecycleEvent(final LifecycleEvent event) { final LifecycleState lifecycleState = event.getLifecycle().getState(); // h2 tcp server if (h2TcpServerService == null) { h2TcpServerService = new H2TcpServerServiceImpl(tcpServerParam); } if (LifecycleState.STARTING_PREP.equals(lifecycleState) && !h2TcpServerService.isServerRunning()) { LOGGER.info("Initializing H2 tcp server on Tomcat lifecycle: " + lifecycleState); h2TcpServerService.startServer(); } else if (LifecycleState.DESTROYING.equals(lifecycleState) && h2TcpServerService.isServerRunning()) { LOGGER.info("Destroying H2 tcp server on Tomcat lifecycle: " + lifecycleState); h2TcpServerService.stopServer(); } // h2 web server try { if (h2WebServerService == null) { h2WebServerService = new H2WebServerServiceImpl(webServerParam); } if (LifecycleState.STARTING_PREP.equals(lifecycleState) && !h2WebServerService.isServerRunning()) { LOGGER.info("Initializing H2 web server on Tomcat lifecycle: " + lifecycleState); h2WebServerService.startServer(); } else if (LifecycleState.DESTROYING.equals(lifecycleState) && h2WebServerService.isServerRunning()) { LOGGER.info("Destroying H2 web server on Tomcat lifecycle: " + lifecycleState); h2WebServerService.stopServer(); } } catch (final DbServerServiceException e) { LOGGER.log(Level.SEVERE, "Failed to start H2 Web Server! Continuing without it.", e); } }
/** * Stop an existing server instance. */ public void stop() { try { // Remove the ShutdownHook first so that server.stop() // doesn't get invoked twice if (useShutdownHook) { Runtime.getRuntime().removeShutdownHook(shutdownHook); // If JULI is being used, re-enable JULI's shutdown to ensure // log messages are not lost LogManager logManager = LogManager.getLogManager(); if (logManager instanceof ClassLoaderLogManager) { ((ClassLoaderLogManager) logManager).setUseShutdownHook( true); } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This will fail on JDK 1.2. Ignoring, as Tomcat can run // fine without the shutdown hook. } // Shut down the server try { Server s = getServer(); LifecycleState state = s.getState(); if (LifecycleState.STOPPING_PREP.compareTo(state) <= 0 && LifecycleState.DESTROYED.compareTo(state) >= 0) { // Nothing to do. stop() was already called } else { s.stop(); s.destroy(); } } catch (LifecycleException e) { log.error("Catalina.stop", e); } }
/** * Prepare for the beginning of active use of the public methods of 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 void startInternal() throws LifecycleException { // Create a MessageDigest instance for credentials, if desired if (digest != null) { try { md = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new LifecycleException(sm.getString("realmBase.algorithm", digest), e); } } setState(LifecycleState.STARTING); }
@Test public void testDeploymentXmlExternalDirXmlFFT() throws Exception { File dir = createDirInExternal(true); createXmlInConfigBaseForExternal(dir); doTestDeployment(false, false, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); }
/** * 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 { if (log.isDebugEnabled()) log.debug("Stopping"); setState(LifecycleState.STOPPING); if (getStore() != null && saveOnRestart) { unload(); } else { // Expire all active sessions Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { StandardSession session = (StandardSession) sessions[i]; if (!session.isValid()) continue; session.expire(); } } if (getStore() != null && getStore() instanceof Lifecycle) ((Lifecycle)getStore()).stop(); // Require a new random number generator if we are restarted super.stopInternal(); }
@Override public void setContainer(Container container) { if (this.container == container) { // NO-OP return; } if (!getState().equals(LifecycleState.NEW)) { throw new IllegalStateException(sm.getString("managerBase.setContextNotNew")); } Container oldContainer = this.container; this.container = container; // TODO - delete the line below in Tomcat 9 onwards support.firePropertyChange("container", oldContainer, this.container); }
/** * Begin processing requests via this Connector. * * @exception LifecycleException if a fatal startup error occurs */ @Override protected void startInternal() throws LifecycleException { // Validate settings before starting if (getPort() < 0) { throw new LifecycleException(sm.getString( "coyoteConnector.invalidPort", Integer.valueOf(getPort()))); } setState(LifecycleState.STARTING); try { protocolHandler.start(); } catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); } mapperListener.start(); }
/** * 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 { try { open(); } catch (SQLException e) { throw new LifecycleException(e); } setState(LifecycleState.STARTING); }
/** * 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 { setState(LifecycleState.STOPPING); close() ; }
@Test public void testDeploymentXmlExternalWarXmlFFT() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(false, false, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, true); }
/** * 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 { try { open() ; } catch (SQLException e) { throw new LifecycleException(e); } setState(LifecycleState.STARTING); }
/** * 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 { semaphore = new Semaphore(concurrency, fairness); setState(LifecycleState.STARTING); }
/** * 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 { super.startInternal(); if (store == null) log.error("No Store configured, persistence disabled"); else if (store instanceof Lifecycle) ((Lifecycle) store).start(); setState(LifecycleState.STARTING); }
@Test public void testBug54807() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); ctx.addApplicationListener(Bug54807Config.class.getName()); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); Assert.assertEquals(LifecycleState.STARTED, ctx.getState()); }
@Test public void testDeploymentXmlExternalWarXmlTTF() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(true, true, false, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); }
@Override public void setComment(String comment) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationSessionCookieConfig.ise", "comment", context.getPath())); } this.comment = comment; }
@Override public <T extends EventListener> void addListener(T t) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString("applicationContext.addListener.ise", getContextPath())); } boolean match = false; if (t instanceof ServletContextAttributeListener || t instanceof ServletRequestListener || t instanceof ServletRequestAttributeListener || t instanceof HttpSessionAttributeListener) { context.addApplicationEventListener(t); match = true; } if (t instanceof HttpSessionListener || (t instanceof ServletContextListener && newServletContextListenerAllowed)) { // Add listener directly to the list of instances rather than to // the list of class names. context.addApplicationLifecycleListener(t); match = true; } if (match) return; if (t instanceof ServletContextListener) { throw new IllegalArgumentException( sm.getString("applicationContext.addListener.iae.sclNotAllowed", t.getClass().getName())); } else { throw new IllegalArgumentException( sm.getString("applicationContext.addListener.iae.wrongType", t.getClass().getName())); } }
/** * @throws IllegalStateException * if the context has already been initialised * @throws IllegalArgumentException * If SSL is requested in combination with anything else or if * an unsupported tracking mode is requested */ @Override public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.setSessionTracking.ise", getContextPath())); } // Check that only supported tracking modes have been requested for (SessionTrackingMode sessionTrackingMode : sessionTrackingModes) { if (!supportedSessionTrackingModes.contains(sessionTrackingMode)) { throw new IllegalArgumentException(sm.getString("applicationContext.setSessionTracking.iae.invalid", sessionTrackingMode.toString(), getContextPath())); } } // Check SSL has not be configured with anything else if (sessionTrackingModes.contains(SessionTrackingMode.SSL)) { if (sessionTrackingModes.size() > 1) { throw new IllegalArgumentException( sm.getString("applicationContext.setSessionTracking.iae.ssl", getContextPath())); } } this.sessionTrackingModes = sessionTrackingModes; }
public String getStatus() { int port = this.getTomcat().getPort(); Bootstrap b = BootstrapManager.getBoostrap(port); if (null == b) { return not_loaded; } if (!getXMLFile().exists()) return not_loaded; List<Context> cs = b.listContexts(); for (Context c : cs) { boolean match = this.nameMatch(c); if (match) { LifecycleState status = c.getState(); // System.out.println(status); switch (status) { case FAILED: case STOPPED: return failed; case STARTED: return loaded; default: return loading; } } } if (this.getTomcat().getStatus().equals(Bootstrap.status_starting) || this.getTomcat().getStatus().equals(Bootstrap.status_started)) return loading; return not_loaded; }
@Override public <T extends EventListener> void addListener(T t) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.addListener.ise", getContextPath())); } boolean match = false; if (t instanceof ServletContextAttributeListener || t instanceof ServletRequestListener || t instanceof ServletRequestAttributeListener || t instanceof HttpSessionAttributeListener) { context.addApplicationEventListener(t); match = true; } if (t instanceof HttpSessionListener || (t instanceof ServletContextListener && newServletContextListenerAllowed)) { // Add listener directly to the list of instances rather than to // the list of class names. context.addApplicationLifecycleListener(t); match = true; } if (match) return; if (t instanceof ServletContextListener) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.sclNotAllowed", t.getClass().getName())); } else { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", t.getClass().getName())); } }
/** * Dismantle Tomcat with index. * @param index The tomcat index. */ public void dismantle(int index) { try { if (tomcats[index].getServer() != null && tomcats[index].getServer().getState() != LifecycleState.DESTROYED) { if (tomcats[index].getServer().getState() != LifecycleState.STOPPED) { tomcats[index].stop(); } tomcats[index].destroy(); } } catch (LifecycleException e) { System.out.println("Exception shutting down Testing Tomcat (this may happen a lot): " + e.getMessage()); } }
/** * Remove the specified welcome file name from the list recognized * by this Context. * * @param name Name of the welcome file to be removed */ @Override public void removeWelcomeFile(String name) { synchronized (welcomeFilesLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < welcomeFiles.length; i++) { if (welcomeFiles[i].equals(name)) { n = i; break; } } if (n < 0) return; // Remove the specified welcome file int j = 0; String results[] = new String[welcomeFiles.length - 1]; for (int i = 0; i < welcomeFiles.length; i++) { if (i != n) results[j++] = welcomeFiles[i]; } welcomeFiles = results; } // Inform interested listeners if(this.getState().equals(LifecycleState.STARTED)) fireContainerEvent(REMOVE_WELCOME_FILE_EVENT, name); }
@Test public void testDeploymentXmlExternalWarXmlTTT() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(true, true, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, true); }
private void addChildInternal(Container child) { if( log.isDebugEnabled() ) log.debug("Add child " + child + " " + this); synchronized(children) { if (children.get(child.getName()) != null) throw new IllegalArgumentException("addChild: Child name '" + child.getName() + "' is not unique"); child.setParent(this); // May throw IAE children.put(child.getName(), child); } // Start child // Don't do this inside sync block - start can be a slow process and // locking the children object can cause problems elsewhere try { if ((getState().isAvailable() || LifecycleState.STARTING_PREP.equals(getState())) && startChildren) { child.start(); } } catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException("ContainerBase.addChild: start: " + e); } finally { fireContainerEvent(ADD_CHILD_EVENT, child); } }
/** * Stop associated {@link ClassLoader} 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 void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("webappLoader.stopping")); setState(LifecycleState.STOPPING); // Remove context attributes as appropriate if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); servletContext.removeAttribute(Globals.CLASS_PATH_ATTR); } // Throw away our current class loader if (classLoader != null) { ((Lifecycle) classLoader).stop(); DirContextURLStreamHandler.unbind(classLoader); } try { StandardContext ctx=(StandardContext)container; String contextName = ctx.getName(); if (!contextName.startsWith("/")) { contextName = "/" + contextName; } ObjectName cloname = new ObjectName (MBeanUtils.getDomain(ctx) + ":type=WebappClassLoader,context=" + contextName + ",host=" + ctx.getParent().getName()); Registry.getRegistry(null, null).unregisterComponent(cloname); } catch (Exception e) { log.error("LifecycleException ", e); } classLoader = null; }
@Override public void setDomain(String domain) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationSessionCookieConfig.ise", "domain name", context.getPath())); } this.domain = domain; }
@Override public void setPath(String path) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException(sm.getString( "applicationSessionCookieConfig.ise", "path", context.getPath())); } this.path = path; }