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

The following examples show how to use org.apache.catalina.core.StandardContext#setName() . 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: 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 2
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 3
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 4
Source File: InMemoryRealmTest.java    From oryx with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticate() throws Exception {
  InMemoryRealm realm = new InMemoryRealm();
  StandardContext ctx = new StandardContext();
  ctx.setName("OryxTest");
  realm.setContainer(ctx);
  realm.start();

  realm.addUser("foo", "bar");
  Principal authPrincipal = realm.authenticate("foo", "bar");
  assertNotNull(authPrincipal);
  assertEquals("foo", authPrincipal.getName());
  assertNull(realm.authenticate("foo", "baz"));
  assertNull(realm.authenticate("bar", "foo"));
  assertEquals("bar", realm.getPassword("foo"));
  assertEquals("foo", realm.getPrincipal("foo").getName());
}
 
Example 5
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) throws Exception {
    try {
        final String confDir = System.getProperty("bistoury.conf");
        if (Strings.isNullOrEmpty(confDir)) {
            throw new RuntimeException("请在JVM参数中配置项目配置文件目录,即bistoury.conf");
        }

        DynamicConfig<LocalDynamicConfig> 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-proxy");
        tomcat.getHost().addChild(ctx);

        log(webappDirLocation, confDir);

        logger.info("Server配置加载完成,正在启动中...");
        tomcat.start();
        tomcat.getServer().await();
    } catch (Exception e) {
        logger.error("Server启动失败...", e);
    }
}
 
Example 6
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 7
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 8
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 9
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
private static Context createNewContext(final ClassLoader classLoader, String authMethod, String transportGuarantee, final String realmName, final String name) {
    String path = name;
    if (path == null) {
        path = "/";
    }
    if (!path.startsWith("/")) {
        path = "/" + path;
    }

    final StandardContext context = new IgnoredStandardContext();
    context.setPath(path);
    context.setDocBase("");
    context.setParentClassLoader(classLoader);
    context.setDelegate(true);
    context.setName(name);
    ((TomcatWebAppBuilder) SystemInstance.get().getComponent(WebAppBuilder.class)).initJ2EEInfo(context);

    // Configure security
    if (authMethod != null) {
        authMethod = authMethod.toUpperCase();
    }
    if (transportGuarantee != null) {
        transportGuarantee = transportGuarantee.toUpperCase();
    }
    if (authMethod == null || "NONE".equals(authMethod)) { //NOPMD
        // ignore none for now as the  NonLoginAuthenticator seems to be completely hosed
    } else if ("BASIC".equals(authMethod) || "DIGEST".equals(authMethod) || "CLIENT-CERT".equals(authMethod)) {

        //Setup a login configuration
        final LoginConfig loginConfig = new LoginConfig();
        loginConfig.setAuthMethod(authMethod);
        loginConfig.setRealmName(realmName);
        context.setLoginConfig(loginConfig);

        //Setup a default Security Constraint
        final String securityRole = SystemInstance.get().getProperty(TOMEE_JAXWS_SECURITY_ROLE_PREFIX + name, "default");
        for (final String role : securityRole.split(",")) {
            final SecurityCollection collection = new SecurityCollection();
            collection.addMethod("GET");
            collection.addMethod("POST");
            collection.addPattern("/*");
            collection.setName(role);

            final SecurityConstraint sc = new SecurityConstraint();
            sc.addAuthRole("*");
            sc.addCollection(collection);
            sc.setAuthConstraint(true);
            sc.setUserConstraint(transportGuarantee);

            context.addConstraint(sc);
            context.addSecurityRole(role);
        }

        //Set the proper authenticator
        if ("BASIC".equals(authMethod)) {
            context.addValve(new BasicAuthenticator());
        } else if ("DIGEST".equals(authMethod)) {
            context.addValve(new DigestAuthenticator());
        } else if ("CLIENT-CERT".equals(authMethod)) {
            context.addValve(new SSLAuthenticator());
        } else if ("NONE".equals(authMethod)) {
            context.addValve(new NonLoginAuthenticator());
        }

        context.getPipeline().addValve(new OpenEJBValve());

    } else {
        throw new IllegalArgumentException("Invalid authMethod: " + authMethod);
    }

    return context;
}
 
Example 10
Source File: TomcatHessianRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
private static Context createNewContext(final ClassLoader classLoader, final String rAuthMethod, final String rTransportGuarantee, final String realmName, final String name) {
    String path = name;
    if (path == null) {
        path = "/";
    }
    if (!path.startsWith("/")) {
        path = "/" + path;
    }

    final StandardContext context = new IgnoredStandardContext();
    context.setPath(path);
    context.setDocBase("");
    context.setParentClassLoader(classLoader);
    context.setDelegate(true);
    context.setName(name);
    TomcatWebAppBuilder.class.cast(SystemInstance.get().getComponent(WebAppBuilder.class)).initJ2EEInfo(context);

    // Configure security
    String authMethod = rAuthMethod;
    if (authMethod != null) {
        authMethod = authMethod.toUpperCase();
    }
    String transportGuarantee = rTransportGuarantee;
    if (transportGuarantee != null) {
        transportGuarantee = transportGuarantee.toUpperCase();
    }
    if (authMethod != null & !"NONE".equals(authMethod)) {
        if ("BASIC".equals(authMethod) || "DIGEST".equals(authMethod) || "CLIENT-CERT".equals(authMethod)) {

            //Setup a login configuration
            final LoginConfig loginConfig = new LoginConfig();
            loginConfig.setAuthMethod(authMethod);
            loginConfig.setRealmName(realmName);
            context.setLoginConfig(loginConfig);

            //Setup a default Security Constraint
            final String securityRole = SystemInstance.get().getProperty(TOMEE_HESSIAN_SECURITY_ROLE_PREFIX + name, "default");
            for (final String role : securityRole.split(",")) {
                final SecurityCollection collection = new SecurityCollection();
                collection.addMethod("GET");
                collection.addMethod("POST");
                collection.addPattern("/*");
                collection.setName(role);

                final SecurityConstraint sc = new SecurityConstraint();
                sc.addAuthRole("*");
                sc.addCollection(collection);
                sc.setAuthConstraint(true);
                sc.setUserConstraint(transportGuarantee);

                context.addConstraint(sc);
                context.addSecurityRole(role);
            }
        }

        //Set the proper authenticator
        switch (authMethod) {
            case "BASIC":
                context.addValve(new BasicAuthenticator());
                break;
            case "DIGEST":
                context.addValve(new DigestAuthenticator());
                break;
            case "CLIENT-CERT":
                context.addValve(new SSLAuthenticator());
                break;
            case "NONE":
                context.addValve(new NonLoginAuthenticator());
                break;
        }

        context.getPipeline().addValve(new OpenEJBValve());
    } else {
        throw new IllegalArgumentException("Invalid authMethod: " + authMethod);
    }

    return context;
}