org.apache.catalina.LifecycleException Java Examples

The following examples show how to use org.apache.catalina.LifecycleException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CombinedRealm.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * 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 {
    // Start 'sub-realms' then this one
    Iterator<Realm> iter = realms.iterator();

    while (iter.hasNext()) {
        Realm realm = iter.next();
        if (realm instanceof Lifecycle) {
            try {
                ((Lifecycle) realm).start();
            } catch (LifecycleException e) {
                // If realm doesn't start can't authenticate against it
                iter.remove();
                log.error(sm.getString("combinedRealm.realmStartFail",
                        realm.getClass().getName()), e);
            }
        }
    }
    super.startInternal();
}
 
Example #2
Source File: RpsMain.java    From rock-paper-scissors-in-java with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception, LifecycleException {
    // Define a folder to hold web application contents.
    String webappDirLocation = "src/main/webapp/";
    Tomcat tomcat = new Tomcat();

    // Define port number for the web application
    String webPort = System.getenv("PORT");
    if (webPort == null || webPort.isEmpty()) {
        webPort = "8080";
    }
    // Bind the port to Tomcat server
    tomcat.setPort(Integer.valueOf(webPort));

    // Define a web application context.
    Context context = tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());

    // Define and bind web.xml file location.
    File configFile = new File(webappDirLocation + "WEB-INF/web.xml");
    context.setConfigFile(configFile.toURI().toURL());

    tomcat.start();
    logger.info("Server started at http://localhost:{}", webPort);
    tomcat.getServer().await();
}
 
Example #3
Source File: BackupManager.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #4
Source File: TestReplicatedContext.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testBug57425() throws LifecycleException, IOException {
    Tomcat tomcat = getTomcatInstance();
    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        ((StandardHost) host).setContextClass(ReplicatedContext.class.getName());
    }

    File root = new File("test/webapp-3.0");
    Context context = tomcat.addWebapp(host, "", root.getAbsolutePath());

    Tomcat.addServlet(context, "test", new AccessContextServlet());
    context.addServletMapping("/access", "test");

    tomcat.start();

    ByteChunk result = getUrl("http://localhost:" + getPort() + "/access");

    Assert.assertEquals("OK", result.toString());

}
 
Example #5
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void destroy(final StandardContext standardContext) {
    final Loader standardContextLoader = standardContext.getLoader();
    if (LazyStopLoader.class.isInstance(standardContextLoader)) {
        final Loader delegate = LazyStopLoader.class.cast(standardContextLoader).getDelegateLoader();
        if (TomEEWebappLoader.class.isInstance(delegate)) {
            final TomEEWebappLoader webappLoader = TomEEWebappLoader.class.cast(delegate);
            final ClassLoader loader = webappLoader.internalLoader();
            webappLoader.clearLoader();
            if (TomEEWebappClassLoader.class.isInstance(loader)) {
                TomEEWebappClassLoader.class.cast(loader).internalDestroy();
            }
        }
    }

    final WebResourceRoot root = standardContext.getResources();
    if (LazyStopStandardRoot.class.isInstance(root)) {
        try {
            LazyStopStandardRoot.class.cast(root).internalDestroy();
        } catch (final LifecycleException e) {
            throw new IllegalStateException(e);
        }
    }
}
 
Example #6
Source File: TestRemoteIpFilter.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private MockFilterChain testRemoteIpFilter(FilterDef filterDef, Request request)
        throws LifecycleException, IOException, ServletException {
    Tomcat tomcat = getTomcatInstance();
    Context root = tomcat.addContext("", TEMP_DIR);

    RemoteIpFilter remoteIpFilter = new RemoteIpFilter();
    filterDef.setFilterClass(RemoteIpFilter.class.getName());
    filterDef.setFilter(remoteIpFilter);
    filterDef.setFilterName(RemoteIpFilter.class.getName());
    root.addFilterDef(filterDef);

    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(RemoteIpFilter.class.getName());
    filterMap.addURLPattern("*");
    root.addFilterMap(filterMap);

    getTomcatInstance().start();

    MockFilterChain filterChain = new MockFilterChain();

    // TEST
    TesterResponse response = new TesterResponse();
    response.setRequest(request);
    remoteIpFilter.doFilter(request, response, filterChain);
    return filterChain;
}
 
Example #7
Source File: JsfTomcatApplicationListenerIT.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
@Test
public void embeddedJarWithoutAppResources2() throws LifecycleException {
	ContextMock contextMock = new ContextMock();

	File file = new File(TARGET + File.separator + TEST_CLASSES + File.separator + "test.jar");
	JarWarResourceSet jarWarResourceSet = new JarWarResourceSet(contextMock.getWebResourceRoot(),
		"/", file.getAbsolutePath(), INTERNAL_JAR, METAINF_RESOURCES);
	jarWarResourceSet.init();

	DirResourceSet dirResourceSet = new DirResourceSet(contextMock.getWebResourceRoot(),
		TEST, TEST, TEST);

	contextMock.init(dirResourceSet, jarWarResourceSet);

	callApplicationEvent(contextMock);

	assertThat(contextMock.getWebResourceRoot().getCreateWebResourceSetCalls())
		.isEqualTo(2);
}
 
Example #8
Source File: UserDatabaseRealm.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * 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 {

    try {
        Context context = getServer().getGlobalNamingContext();
        database = (UserDatabase) context.lookup(resourceName);
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        containerLog.error(sm.getString("userDatabaseRealm.lookup",
                                        resourceName),
                           e);
        database = null;
    }
    if (database == null) {
        throw new LifecycleException
            (sm.getString("userDatabaseRealm.noDatabase", resourceName));
    }

    super.startInternal();
}
 
Example #9
Source File: TomcatServerFactory.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
public static void main(String[] args) throws LifecycleException, ClientProtocolException, IOException {
    log.debug("Cwd: {}", System.getProperty("user.dir"));

    HttpsConfig httpsConfig = HttpsConfig.builder()
            .keyStore(new File("keystore/localhost/localhost.keystore.p12").getCanonicalPath())
            .keyStorePassword(STORE_PASSWORD).keyPassword(STORE_PASSWORD)
            .trustStore(new File("keystore/localhost/localhost.truststore.p12").getCanonicalPath())
            .trustStorePassword(STORE_PASSWORD).protocol("TLSv1.2").build();
    HttpsFactory httpsFactory = new HttpsFactory(httpsConfig);

    Tomcat tomcat = new TomcatServerFactory().startTomcat(httpsConfig);
    try {
        HttpClient client = httpsFactory.createSecureHttpClient();

        int port = getLocalPort(tomcat);
        HttpGet get = new HttpGet(String.format("https://localhost:%d", port));
        HttpResponse response = client.execute(get);

        String responseBody = EntityUtils.toString(response.getEntity());

        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("OK", responseBody);
    } finally {
        tomcat.stop();
    }
}
 
Example #10
Source File: StandardService.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Add a new Connector to the set of defined Connectors, and associate it
 * with this Service's Container.
 *
 * @param connector The Connector to be added
 */
@Override
public void addConnector(Connector connector) {

    synchronized (connectorsLock) {
        connector.setService(this);
        Connector results[] = new Connector[connectors.length + 1];
        System.arraycopy(connectors, 0, results, 0, connectors.length);
        results[connectors.length] = connector;
        connectors = results;

        if (getState().isAvailable()) {
            try {
                connector.start();
            } catch (LifecycleException e) {
                log.error(sm.getString(
                        "standardService.connector.startFailed",
                        connector), e);
            }
        }

        // Report this property change to interested listeners
        support.firePropertyChange("connector", null, connector);
    }

}
 
Example #11
Source File: JNDIRealm.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * 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 {

    // Check to see if the connection to the directory can be opened
    try {
        open();
    } catch (NamingException e) {
        // A failure here is not fatal as the directory may be unavailable
        // now but available later. Unavailability of the directory is not
        // fatal once the Realm has started so there is no reason for it to
        // be fatal when the Realm starts.
        containerLog.error(sm.getString("jndiRealm.open"), e);
    }

    super.startInternal();
}
 
Example #12
Source File: Connector.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
protected void destroyInternal() throws LifecycleException {
    mapperListener.destroy();

    try {
        protocolHandler.destroy();
    } catch (Exception e) {
        throw new LifecycleException
            (sm.getString
             ("coyoteConnector.protocolHandlerDestroyFailed"), e);
    }

    if (getService() != null) {
        getService().removeConnector(this);
    }

    super.destroyInternal();
}
 
Example #13
Source File: DeltaManager.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #14
Source File: TomcatBaseTest.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Make the Tomcat instance preconfigured with test/webapp available to
 * sub-classes.
 * @param addJstl Should JSTL support be added to the test webapp
 * @param start   Should the Tomcat instance be started
 *
 * @return A Tomcat instance pre-configured with the web application located
 *         at test/webapp
 *
 * @throws LifecycleException If a problem occurs while starting the
 *                            instance
 */
public Tomcat getTomcatInstanceTestWebapp(boolean addJstl, boolean start)
        throws LifecycleException {
    File appDir = new File("test/webapp");
    Context ctx = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());

    StandardJarScanner scanner = (StandardJarScanner) ctx.getJarScanner();
    StandardJarScanFilter filter = (StandardJarScanFilter) scanner.getJarScanFilter();
    filter.setTldSkip(filter.getTldSkip() + ",testclasses");
    filter.setPluggabilitySkip(filter.getPluggabilitySkip() + ",testclasses");

    if (addJstl) {
        File lib = new File("webapps/examples/WEB-INF/lib");
        ctx.setResources(new StandardRoot(ctx));
        ctx.getResources().createWebResourceSet(
                WebResourceRoot.ResourceSetType.POST, "/WEB-INF/lib",
                lib.getAbsolutePath(), null, "/");
    }

    if (start) {
        tomcat.start();
    }
    return tomcat;
}
 
Example #15
Source File: RealmBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
protected void initInternal() throws LifecycleException {

    super.initInternal();

    // We want logger as soon as possible
    if (container != null) {
        this.containerLog = container.getLogger();
    }

    x509UsernameRetriever = createUsernameRetriever(x509UsernameRetrieverClassName);
}
 
Example #16
Source File: CometConnectionManagerValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * 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 (container instanceof Context) {
        container.addLifecycleListener(this);
    }

    setState(LifecycleState.STARTING);
}
 
Example #17
Source File: JDBCAccessLogValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * 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() ;
}
 
Example #18
Source File: Main.java    From executable-embeded-tomcat-sample with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ServletException, LifecycleException, IOException {

		String hostName = "localhost";
		int port = 8080;
		String contextPath = "";

		String tomcatBaseDir = TomcatUtil.createTempDir("tomcat", port).getAbsolutePath();
		String contextDocBase = TomcatUtil.createTempDir("tomcat-docBase", port).getAbsolutePath();

		Tomcat tomcat = new Tomcat();
		tomcat.setBaseDir(tomcatBaseDir);

		tomcat.setPort(port);
		tomcat.setHostname(hostName);

		Host host = tomcat.getHost();
		Context context = tomcat.addWebapp(host, contextPath, contextDocBase, new EmbededContextConfig());

		context.setJarScanner(new EmbededStandardJarScanner());

		ClassLoader classLoader = Main.class.getClassLoader();
		context.setParentClassLoader(classLoader);

		// context load WEB-INF/web.xml from classpath
		context.addLifecycleListener(new WebXmlMountListener());

		tomcat.start();
		tomcat.getServer().await();
	}
 
Example #19
Source File: CustomWebappLoader.java    From pxf with Apache License 2.0 5 votes vote down vote up
private void addRepositories(String classpathFiles, boolean throwException) throws LifecycleException {

		for (String classpathFile : classpathFiles.split(";")) {

			String classpath = readClasspathFile(classpathFile, throwException);
			if (classpath == null) {
				continue;
			}

			ArrayList<String> classpathEntries = trimEntries(classpath.split("[\\r\\n]+"));
			LOG.info("Classpath file " + classpathFile + " has " + classpathEntries.size() + " entries");

			for (String entry : classpathEntries) {
				LOG.debug("Trying to load entry " + entry);
				int repositoriesCount = 0;
				Path pathEntry = Paths.get(entry);
				/*
				 * For each entry, we look at the parent directory and try to match each of the files
				 * inside it to the file name or pattern in the file name (the last part of the path).
				 * E.g., for path '/some/path/with/pattern*', the parent directory will be '/some/path/with/'
				 * and the file name will be 'pattern*'. Each file under that directory matching
				 * this pattern will be added to the class loader repository.
				 */
				try (DirectoryStream<Path> repositories = Files.newDirectoryStream(pathEntry.getParent(),
						pathEntry.getFileName().toString())) {
					for (Path repository : repositories) {
						if (addPathToRepository(repository, entry)) {
							repositoriesCount++;
						}
					}
				} catch (IOException e) {
					LOG.warn("Failed to load entry " + entry + ": " + e);
				}
				if (repositoriesCount == 0) {
					LOG.warn("Entry " + entry + " doesn't match any files");
				}
				LOG.debug("Loaded " + repositoriesCount + " repositories from entry " + entry);
			}
		}
	}
 
Example #20
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@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");
    Context context = tomcat.addWebapp("", root.getAbsolutePath());
    context.addLifecycleListener(listener);

    try {
        context.start();
        Assert.fail();
    } catch (LifecycleException ex) {
        // As expected
    }
    Assert.assertEquals(LifecycleState.FAILED, context.getState());

    // The second attempt
    listener.setFail(false);
    context.start();
    Assert.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");
    Assert.assertEquals("Target", result.toString());
}
 
Example #21
Source File: JAASRealm.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * 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 {

   // These need to be called after loading configuration, in case
   // useContextClassLoader appears after them in xml config
   parseClassNames(userClassNames, userClasses);
   parseClassNames(roleClassNames, roleClasses);

   super.startInternal();
}
 
Example #22
Source File: LifecycleBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private synchronized void setStateInternal(LifecycleState state, Object data, boolean check)
        throws LifecycleException {

    if (log.isDebugEnabled()) {
        log.debug(sm.getString("lifecycleBase.setState", this, state));
    }

    if (check) {
        // Must have been triggered by one of the abstract methods (assume
        // code in this class is correct)
        // null is never a valid state
        if (state == null) {
            invalidTransition("null");
            // Unreachable code - here to stop eclipse complaining about
            // a possible NPE further down the method
            return;
        }

        // Any method can transition to failed
        // startInternal() permits STARTING_PREP to STARTING
        // stopInternal() permits STOPPING_PREP to STOPPING and FAILED to
        // STOPPING
        if (!(state == LifecycleState.FAILED ||
                (this.state == LifecycleState.STARTING_PREP &&
                        state == LifecycleState.STARTING) ||
                (this.state == LifecycleState.STOPPING_PREP &&
                        state == LifecycleState.STOPPING) ||
                (this.state == LifecycleState.FAILED &&
                        state == LifecycleState.STOPPING))) {
            // No other transition permitted
            invalidTransition(state.name());
        }
    }

    this.state = state;
    String lifecycleEvent = state.getLifecycleEvent();
    if (lifecycleEvent != null) {
        fireLifecycleEvent(lifecycleEvent, data);
    }
}
 
Example #23
Source File: StandardService.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Remove the specified Connector from the set associated from this
 * Service.  The removed Connector will also be disassociated from our
 * Container.
 *
 * @param connector The Connector to be removed
 */
@Override
public void removeConnector(Connector connector) {

    synchronized (connectors) {
        int j = -1;
        for (int i = 0; i < connectors.length; i++) {
            if (connector == connectors[i]) {
                j = i;
                break;
            }
        }
        if (j < 0)
            return;
        if (connectors[j].getState().isAvailable()) {
            try {
                connectors[j].stop();
            } catch (LifecycleException e) {
                log.error(sm.getString(
                        "standardService.connector.stopFailed",
                        connectors[j]), e);
            }
        }
        connector.setService(null);
        int k = 0;
        Connector results[] = new Connector[connectors.length - 1];
        for (int i = 0; i < connectors.length; i++) {
            if (i != j)
                results[k++] = connectors[i];
        }
        connectors = results;

        // Report this property change to interested listeners
        support.firePropertyChange("connector", connector, null);
    }

}
 
Example #24
Source File: LazyValve.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void init() throws LifecycleException {
    if (instance() != null && Lifecycle.class.isInstance(delegate)) {
        Lifecycle.class.cast(delegate).init();
    } else {
        init = true;
    }
    state = LifecycleState.INITIALIZED;
}
 
Example #25
Source File: NotifyingLifecycleStateMachineTest.java    From session-managers with Apache License 2.0 5 votes vote down vote up
@Test
public void transitionStartingFailed() throws LifecycleException {
    this.lifecycleStateMachine.transition(INITIALIZING);
    this.lifecycleStateMachine.transition(INITIALIZED);
    this.lifecycleStateMachine.transition(STARTING_PREP);
    this.lifecycleStateMachine.transition(STARTING);
    assertTransition(FAILED);
}
 
Example #26
Source File: EmbeddedServer.java    From blog with MIT License 5 votes vote down vote up
public void stop() {
	try {
		tomcat.stop();
		tomcat.destroy();
		deleteDirectory(new File("target/tomcat/"));
	} catch (LifecycleException e) {
		throw new RuntimeException(e);
	}
}
 
Example #27
Source File: StandardService.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void destroyInternal() throws LifecycleException {
    mapperListener.destroy();

    // Destroy our defined Connectors
    synchronized (connectorsLock) {
        for (Connector connector : connectors) {
            try {
                connector.destroy();
            } catch (Exception e) {
                log.error(sm.getString(
                        "standardService.connector.destroyFailed", connector), e);
            }
        }
    }

    // Destroy any Executors
    for (Executor executor : findExecutors()) {
        executor.destroy();
    }

    if (engine != null) {
        engine.destroy();
    }

    super.destroyInternal();
}
 
Example #28
Source File: TestPersistentManagerIntegration.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void noSessionCreate_57637() throws IOException, LifecycleException {

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    StandardContext ctx = (StandardContext) tomcat.addContext("", null);
    ctx.setDistributable(true);

    Tomcat.addServlet(ctx, "DummyServlet", new DummyServlet());
    ctx.addServletMapping("/dummy", "DummyServlet");

    PersistentManager manager = new PersistentManager();
    TesterStore store = new TesterStore();

    manager.setStore(store);
    manager.setMaxIdleBackup(0);
    ctx.setManager(manager);
    ctx.addValve(new PersistentValve());
    tomcat.start();
    Assert.assertEquals(manager.getActiveSessions(), 0);
    Assert.assertTrue("No sessions managed", manager.getSessionIdsFull().isEmpty());
    Assert.assertEquals(
            "NO_SESSION",
            getUrl(
                    "http://localhost:" + getPort()
                            + "/dummy?no_create_session=true").toString());
    Assert.assertEquals(manager.getActiveSessions(), 0);
    Assert.assertTrue("No sessions where created", manager.getSessionIdsFull().isEmpty());
}
 
Example #29
Source File: EmbeddedServer.java    From blog with MIT License 5 votes vote down vote up
public void run() {
	try {
		tomcat.start();
	} catch (LifecycleException e) {
		throw new RuntimeException(e);
	}
	tomcat.getServer().await();
}
 
Example #30
Source File: RedissonSessionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected void stopInternal() throws LifecycleException {
    super.stopInternal();
    
    setState(LifecycleState.STOPPING);
    
    Pipeline pipeline = getEngine().getPipeline();
    synchronized (pipeline) {
        contextInUse.remove(getContext().getName());
        //remove valves when all of the RedissonSessionManagers (web apps) are not in use anymore
        if (contextInUse.isEmpty()) {
            if (updateValve != null) {
                pipeline.removeValve(updateValve);
                updateValve = null;
            }
        }
    }
    
    if (messageListener != null) {
         RTopic updatesTopic = getTopic();
         updatesTopic.removeListener(messageListener);
    }

    codecToUse = null;

    try {
        shutdownRedisson();
    } catch (Exception e) {
        throw new LifecycleException(e);
    }
    
}