Java Code Examples for org.apache.catalina.core.StandardContext#addLifecycleListener()

The following examples show how to use org.apache.catalina.core.StandardContext#addLifecycleListener() . 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: TestContextConfig.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void doTestOverrideDefaultServletWithSCI(String servletName)
        throws Exception{

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp");
    StandardContext ctxt = (StandardContext) tomcat.addContext(null,
            "/test", appDir.getAbsolutePath());
    ctxt.setDefaultWebXml(new File("conf/web.xml").getAbsolutePath());
    ctxt.addLifecycleListener(new ContextConfig());

    ctxt.addServletContainerInitializer(
            new CustomDefaultServletSCI(servletName), null);

    tomcat.start();

    assertPageContains("/test", "OK - Custom default Servlet");
}
 
Example 2
Source File: TestContextConfig.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void doTestOverrideDefaultServletWithSCI(String servletName)
        throws Exception{

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0");
    StandardContext ctxt = (StandardContext) tomcat.addContext(null,
            "/test", appDir.getAbsolutePath());
    ctxt.setDefaultWebXml(new File("conf/web.xml").getAbsolutePath());
    ctxt.addLifecycleListener(new ContextConfig());

    ctxt.addServletContainerInitializer(
            new CustomDefaultServletSCI(servletName), null);

    tomcat.start();

    assertPageContains("/test", "OK - Custom default Servlet");
}
 
Example 3
Source File: DubboApplicationContextInitializerTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpringContextLoaderListenerInWebXml() throws Exception {
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/test-classes");
    tomcat.setPort(12345);
    StandardContext context = new StandardContext();
    context.setName("test");
    context.setDocBase("test");
    context.setPath("/test");
    context.addLifecycleListener(new ContextConfig());
    tomcat.getHost().addChild(context);
    tomcat.start();
    // there should be 1 application listener
    Assert.assertEquals(1, context.getApplicationLifecycleListeners().length);
    // the first one should be Spring's built in ContextLoaderListener.
    Assert.assertTrue(context.getApplicationLifecycleListeners()[0] instanceof ContextLoaderListener);
    tomcat.stop();
    tomcat.destroy();
}
 
Example 4
Source File: DubboApplicationContextInitializerTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoListenerInWebXml() throws Exception {
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/test-classes");
    tomcat.setPort(12345);
    StandardContext context = new StandardContext();
    context.setName("test2");
    context.setDocBase("test2");
    context.setPath("/test2");
    context.addLifecycleListener(new ContextConfig());
    tomcat.getHost().addChild(context);
    tomcat.start();
    // there should be 1 application listener
    Assert.assertEquals(1, context.getApplicationLifecycleListeners().length);
    // the first one should be Spring's built in ContextLoaderListener.
    Assert.assertTrue(context.getApplicationLifecycleListeners()[0] instanceof ContextLoaderListener);
    tomcat.stop();
    tomcat.destroy();
}
 
Example 5
Source File: DubboApplicationContextInitializerTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetadataComplete() throws Exception {
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/test-classes");
    tomcat.setPort(12345);
    StandardContext context = new StandardContext();
    context.setName("test3");
    context.setDocBase("test3");
    context.setPath("/test3");
    context.addLifecycleListener(new ContextConfig());
    tomcat.getHost().addChild(context);
    tomcat.start();
    // there should be no application listeners
    Assert.assertEquals(0, context.getApplicationLifecycleListeners().length);
    tomcat.stop();
    tomcat.destroy();
}
 
Example 6
Source File: TestContextConfig.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void doTestOverrideDefaultServletWithSCI(String servletName)
        throws Exception{

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0");
    StandardContext ctxt = (StandardContext) tomcat.addContext(null,
            "/test", appDir.getAbsolutePath());
    ctxt.setDefaultWebXml(new File("conf/web.xml").getAbsolutePath());
    ctxt.addLifecycleListener(new ContextConfig());

    ctxt.addServletContainerInitializer(
            new CustomDefaultServletSCI(servletName), null);

    tomcat.start();

    assertPageContains("/test", "OK - Custom default Servlet");
}
 
Example 7
Source File: TestWebappServiceLoader.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWebapp() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp-3.0-fragments-empty-absolute-ordering");
    StandardContext ctxt = (StandardContext) tomcat.addContext(null, "/test", appDir.getAbsolutePath());
    ctxt.addLifecycleListener(new ContextConfig());
    tomcat.start();

    WebappServiceLoader<ServletContainerInitializer> loader =
            new WebappServiceLoader<ServletContainerInitializer>(ctxt);
    @SuppressWarnings("unused")
    Collection<ServletContainerInitializer> initializers = loader.load(ServletContainerInitializer.class);
}
 
Example 8
Source File: TestWebappServiceLoader.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testWebapp() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp-3.0-fragments-empty-absolute-ordering");
    StandardContext ctxt = (StandardContext) tomcat.addContext(null, "/test", appDir.getAbsolutePath());
    ctxt.addLifecycleListener(new ContextConfig());
    tomcat.start();

    WebappServiceLoader<ServletContainerInitializer> loader =
            new WebappServiceLoader<ServletContainerInitializer>(ctxt);
    @SuppressWarnings("unused")
    Collection<ServletContainerInitializer> initializers = loader.load(ServletContainerInitializer.class);
}
 
Example 9
Source File: SpringBootTomcatPlusIT.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public void onDeployUAVApp(Object... args) {
    
    if(UAVServer.ServerVendor.SPRINGBOOT!=UAVServer.instance().getServerInfo(CaptureConstants.INFO_APPSERVER_VENDOR)) {
        return;
    }
    
    Tomcat tomcat=(Tomcat) args[0];
    String mofRoot=(String) args[1];
    
    //add uavApp
    StandardContext context=new StandardContext();
    context.setName("com.creditease.uav");
    context.setPath("/com.creditease.uav");
    context.setDocBase(mofRoot + "/com.creditease.uav");
    context.addLifecycleListener(new Tomcat.FixContextListener());
    tomcat.getHost().addChild(context);
    
    //add default servlet
    Wrapper servlet = context.createWrapper();
    servlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
    servlet.setName("default");
    context.addChild(servlet);    
    servlet.setOverridable(true);
    context.addServletMapping("/", "default");
    
    //init webapp classloader
    context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));
    context.setDelegate(true);
    
    //after tomcat8, skip jarscan
    Object obj=ReflectionHelper.newInstance("org.apache.tomcat.util.scan.StandardJarScanner", Thread.currentThread().getContextClassLoader());
    if(obj!=null) {
        ReflectionHelper.invoke("org.apache.tomcat.util.scan.StandardJarScanner", obj, "setScanAllFiles", new Class<?>[]{Boolean.class}, new Object[] { false}, Thread.currentThread().getContextClassLoader());
        ReflectionHelper.invoke("org.apache.tomcat.util.scan.StandardJarScanner", obj, "setScanClassPath", new Class<?>[]{Boolean.class}, new Object[] { false}, Thread.currentThread().getContextClassLoader());
        ReflectionHelper.invoke("org.apache.tomcat.util.scan.StandardJarScanner", obj, "setScanAllDirectories", new Class<?>[]{Boolean.class}, new Object[] { false}, Thread.currentThread().getContextClassLoader());            
        
        context.setJarScanner((JarScanner) obj);      
    }        
}
 
Example 10
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
@Override
protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
    if (host.getState() == LifecycleState.NEW) {
        super.prepareContext(host, initializers);
    } else {
        File documentRoot = getValidDocumentRoot();
        StandardContext context = new StandardContext();
        if (documentRoot != null) {
            context.setResources(new StandardRoot(context));
        }
        context.setName(getContextPath());
        context.setDisplayName(getDisplayName());
        context.setPath(getContextPath());
        File docBase = (documentRoot != null) ? documentRoot : createTempDir("tomcat-docbase");
        context.setDocBase(docBase.getAbsolutePath());
        context.addLifecycleListener(new Tomcat.FixContextListener());
        context.setParentClassLoader(Thread.currentThread().getContextClassLoader());
        resetDefaultLocaleMapping(context);
        addLocaleMappings(context);
        context.setUseRelativeRedirects(false);
        configureTldSkipPatterns(context);
        WebappLoader loader = new WebappLoader(context.getParentClassLoader());
        loader
            .setLoaderClass("com.alipay.sofa.ark.web.embed.tomcat.ArkTomcatEmbeddedWebappClassLoader");
        loader.setDelegate(true);
        context.setLoader(loader);
        if (isRegisterDefaultServlet()) {
            addDefaultServlet(context);
        }
        if (shouldRegisterJspServlet()) {
            addJspServlet(context);
            addJasperInitializer(context);
        }
        context.addLifecycleListener(new StaticResourceConfigurer(context));
        ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);
        context.setParent(host);
        configureContext(context, initializersToUse);
        host.addChild(context);
    }
}
 
Example 11
Source File: Bootstrap.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        final String confDir = System.getProperty("bistoury.conf");
        if (Strings.isNullOrEmpty(confDir)) {
            throw new RuntimeException("请在JVM参数中配置项目配置文件目录,即bistoury.conf");
        }
        DynamicConfig config = DynamicConfigLoader.load("server.properties");

        int port = config.getInt("tomcat.port");
        System.setProperty("bistoury.tomcat.port", String.valueOf(port));

        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.setBaseDir(config.getString("tomcat.basedir"));
        tomcat.getHost().setAutoDeploy(false);

        final String webappDirLocation = getWebappDirLocation();

        StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());

        String contextPath = "";
        ctx.setPath(contextPath);
        ctx.addLifecycleListener(new Tomcat.FixContextListener());
        ctx.setName("bistoury-ui");
        tomcat.getHost().addChild(ctx);

        log(webappDirLocation, confDir);

        logger.info("Server配置加载完成,正在启动中...");
        tomcat.start();
        tomcat.getServer().await();
    } catch (Exception e) {
        logger.error("Server启动失败...", e);
    }
}
 
Example 12
Source File: MBeanFactory.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new StandardContext.
 *
 * @param parent MBean Name of the associated parent component
 * @param path The context path for this Context
 * @param docBase Document base directory (or WAR) for this Context
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createStandardContext(String parent, 
                                    String path,
                                    String docBase,
                                    boolean xmlValidation,
                                    boolean xmlNamespaceAware,
                                    boolean tldValidation,
                                    boolean tldNamespaceAware)
    throws Exception {

    // Create a new StandardContext instance
    StandardContext context = new StandardContext();
    path = getPathStr(path);
    context.setPath(path);
    context.setDocBase(docBase);
    context.setXmlValidation(xmlValidation);
    context.setXmlNamespaceAware(xmlNamespaceAware);
    context.setTldValidation(tldValidation);
    context.setTldNamespaceAware(tldNamespaceAware);
    
    ContextConfig contextConfig = new ContextConfig();
    context.addLifecycleListener(contextConfig);

    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    ObjectName deployer = new ObjectName(pname.getDomain()+
                                         ":type=Deployer,host="+
                                         pname.getKeyProperty("host"));
    if(mserver.isRegistered(deployer)) {
        String contextName = context.getName();
        mserver.invoke(deployer, "addServiced",
                       new Object [] {contextName},
                       new String [] {"java.lang.String"});
        String configPath = (String)mserver.getAttribute(deployer,
                                                         "configBaseName");
        String baseName = context.getBaseName();
        File configFile = new File(new File(configPath), baseName+".xml");
        if (configFile.isFile()) {
            context.setConfigFile(configFile.toURI().toURL());
        }
        mserver.invoke(deployer, "manageApp",
                       new Object[] {context},
                       new String[] {"org.apache.catalina.Context"});
        mserver.invoke(deployer, "removeServiced",
                       new Object [] {contextName},
                       new String [] {"java.lang.String"});
    } else {
        log.warn("Deployer not found for "+pname.getKeyProperty("host"));
        Service service = getService(pname);
        Engine engine = (Engine) service.getContainer();
        Host host = (Host) engine.findChild(pname.getKeyProperty("host"));
        host.addChild(context);
    }

    // Return the corresponding MBean name
    return context.getObjectName().toString();

}
 
Example 13
Source File: SamlAuthenticatorValve.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void initInternal() {
    StandardContext standardContext = (StandardContext) context;
    standardContext.addLifecycleListener(this);
}
 
Example 14
Source File: MBeanFactory.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new StandardContext.
 *
 * @param parent MBean Name of the associated parent component
 * @param path The context path for this Context
 * @param docBase Document base directory (or WAR) for this Context
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createStandardContext(String parent, 
                                    String path,
                                    String docBase,
                                    boolean xmlValidation,
                                    boolean xmlNamespaceAware,
                                    boolean tldValidation,
                                    boolean tldNamespaceAware)
    throws Exception {

    // Create a new StandardContext instance
    StandardContext context = new StandardContext();
    path = getPathStr(path);
    context.setPath(path);
    context.setDocBase(docBase);
    context.setXmlValidation(xmlValidation);
    context.setXmlNamespaceAware(xmlNamespaceAware);
    context.setTldValidation(tldValidation);
    context.setTldNamespaceAware(tldNamespaceAware);
    
    ContextConfig contextConfig = new ContextConfig();
    context.addLifecycleListener(contextConfig);

    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    ObjectName deployer = new ObjectName(pname.getDomain()+
                                         ":type=Deployer,host="+
                                         pname.getKeyProperty("host"));
    if(mserver.isRegistered(deployer)) {
        String contextName = context.getName();
        mserver.invoke(deployer, "addServiced",
                       new Object [] {contextName},
                       new String [] {"java.lang.String"});
        String configPath = (String)mserver.getAttribute(deployer,
                                                         "configBaseName");
        String baseName = context.getBaseName();
        File configFile = new File(new File(configPath), baseName+".xml");
        if (configFile.isFile()) {
            context.setConfigFile(configFile.toURI().toURL());
        }
        mserver.invoke(deployer, "manageApp",
                       new Object[] {context},
                       new String[] {"org.apache.catalina.Context"});
        mserver.invoke(deployer, "removeServiced",
                       new Object [] {contextName},
                       new String [] {"java.lang.String"});
    } else {
        log.warn("Deployer not found for "+pname.getKeyProperty("host"));
        Service service = getService(pname);
        Engine engine = (Engine) service.getContainer();
        Host host = (Host) engine.findChild(pname.getKeyProperty("host"));
        host.addChild(context);
    }

    // Return the corresponding MBean name
    return context.getObjectName().toString();

}
 
Example 15
Source File: SamlAuthenticatorValve.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void initInternal() {
    StandardContext standardContext = (StandardContext) context;
    standardContext.addLifecycleListener(this);
}
 
Example 16
Source File: SamlAuthenticatorValve.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws LifecycleException {
    StandardContext standardContext = (StandardContext) context;
    standardContext.addLifecycleListener(this);
    super.start();
}
 
Example 17
Source File: KeycloakAuthenticatorValve.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void initInternal() {
    StandardContext standardContext = (StandardContext) context;
    standardContext.addLifecycleListener(this);
}
 
Example 18
Source File: KeycloakAuthenticatorValve.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws LifecycleException {
    StandardContext standardContext = (StandardContext) context;
    standardContext.addLifecycleListener(this);
    super.start();
}
 
Example 19
Source File: Embedded.java    From Tomcat7.0.67 with Apache License 2.0 2 votes vote down vote up
/**
 * Create, configure, and return a Context that will process all
 * HTTP requests received from one of the associated Connectors,
 * and directed to the specified context path on the virtual host
 * to which this Context is connected.
 * <p>
 * After you have customized the properties, listeners, and Valves
 * for this Context, you must attach it to the corresponding Host
 * by calling:
 * <pre>
 *   host.addChild(context);
 * </pre>
 * which will also cause the Context to be started if the Host has
 * already been started.
 *
 * @param path Context path of this application ("" for the default
 *  application for this host, must start with a slash otherwise)
 * @param docBase Absolute pathname to the document base directory
 *  for this web application
 *
 * @exception IllegalArgumentException if an invalid parameter
 *  is specified
 */
public Context createContext(String path, String docBase) {

    if( log.isDebugEnabled() )
        log.debug("Creating context '" + path + "' with docBase '" +
                   docBase + "'");

    StandardContext context = new StandardContext();

    context.setDocBase(docBase);
    context.setPath(path);

    ContextConfig config = new ContextConfig();
    config.setCustomAuthenticators(authenticators);
    context.addLifecycleListener(config);

    return (context);

}
 
Example 20
Source File: Embedded.java    From tomcatsrc with Apache License 2.0 2 votes vote down vote up
/**
 * Create, configure, and return a Context that will process all
 * HTTP requests received from one of the associated Connectors,
 * and directed to the specified context path on the virtual host
 * to which this Context is connected.
 * <p>
 * After you have customized the properties, listeners, and Valves
 * for this Context, you must attach it to the corresponding Host
 * by calling:
 * <pre>
 *   host.addChild(context);
 * </pre>
 * which will also cause the Context to be started if the Host has
 * already been started.
 *
 * @param path Context path of this application ("" for the default
 *  application for this host, must start with a slash otherwise)
 * @param docBase Absolute pathname to the document base directory
 *  for this web application
 *
 * @exception IllegalArgumentException if an invalid parameter
 *  is specified
 */
public Context createContext(String path, String docBase) {

    if( log.isDebugEnabled() )
        log.debug("Creating context '" + path + "' with docBase '" +
                   docBase + "'");

    StandardContext context = new StandardContext();

    context.setDocBase(docBase);
    context.setPath(path);

    ContextConfig config = new ContextConfig();
    config.setCustomAuthenticators(authenticators);
    context.addLifecycleListener(config);

    return (context);

}