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

The following examples show how to use org.apache.catalina.core.StandardContext#setParentClassLoader() . 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: TomcatServer.java    From doodle with Apache License 2.0 6 votes vote down vote up
public TomcatServer(Configuration configuration) {
    try {
        this.tomcat = new Tomcat();
        tomcat.setBaseDir(configuration.getDocBase());
        tomcat.setPort(configuration.getServerPort());

        File root = getRootFolder(configuration);
        File webContentFolder = new File(root.getAbsolutePath(), configuration.getResourcePath());
        if (!webContentFolder.exists()) {
            webContentFolder = Files.createTempDirectory("default-doc-base").toFile();
        }

        log.info("Tomcat:configuring app with basedir: [{}]", webContentFolder.getAbsolutePath());
        StandardContext ctx = (StandardContext) tomcat.addWebapp(configuration.getContextPath(), webContentFolder.getAbsolutePath());
        ctx.setParentClassLoader(this.getClass().getClassLoader());

        WebResourceRoot resources = new StandardRoot(ctx);
        ctx.setResources(resources);

        tomcat.addServlet(configuration.getContextPath(), "dispatcherServlet", new DispatcherServlet()).setLoadOnStartup(0);
        ctx.addServletMappingDecoded("/*", "dispatcherServlet");
    } catch (Exception e) {
        log.error("初始化Tomcat失败", e);
        throw new RuntimeException(e);
    }
}
 
Example 2
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 3
Source File: TomcatCustomServer.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
protected void init(final String contextRoot, final String resourceBase) throws ServletException, IOException {
    final Path basePath = Files.createTempDirectory(DEFAULT_TOMCAT_BASE_TEMP_DIR);
    setBaseDir(basePath.toString());

    if (StringUtils.isNotEmpty(resourceBase)) {
        this.resourceBase = resourceBase;
    }

    initExecutor();
    initConnector();

    final ContextConfig conf = new ContextConfig();
    final StandardContext ctx = (StandardContext) this.addWebapp(getHost(), contextRoot, new File(this.resourceBase).getAbsolutePath(), conf);
    createGlobalXml();
    conf.setDefaultWebXml(globalWebXml.getAbsolutePath());

    for (LifecycleListener listen : ctx.findLifecycleListeners()) {
        if (listen instanceof DefaultWebXmlListener) {
            ctx.removeLifecycleListener(listen);
        }
    }

    ctx.setParentClassLoader(TomcatCustomServer.class.getClassLoader());

    //Disable TLD scanning by default
    if (System.getProperty(Constants.SKIP_JARS_PROPERTY) == null && System.getProperty(Constants.SKIP_JARS_PROPERTY) == null) {
        LOGGER.debug("disabling TLD scanning");
        StandardJarScanFilter jarScanFilter = (StandardJarScanFilter) ctx.getJarScanner().getJarScanFilter();
        jarScanFilter.setTldSkip("*");
    }
}
 
Example 4
Source File: StatsServer.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    // Register and map the dispatcher servlet
    final File base = new File(System.getProperty("java.io.tmpdir"));

    final Tomcat server = new Tomcat();
    server.setPort(8686);
    server.setBaseDir(base.getAbsolutePath());

    final StandardContext context = (StandardContext)server.addWebapp("/", base.getAbsolutePath());
    context.setConfigFile(StatsServer.class.getResource("/META-INF/context.xml"));
    context.addApplicationListener(ContextLoaderListener.class.getName());
    context.setAddWebinfClassesResources(true);
    context.setResources(resourcesFrom(context, "target/classes"));
    context.setParentClassLoader(Thread.currentThread().getContextClassLoader());

    final Wrapper cxfServlet = Tomcat.addServlet(context, "cxfServlet", new CXFServlet());
    cxfServlet.setAsyncSupported(true);
    context.addServletMappingDecoded("/rest/*", "cxfServlet");

    final Context staticContext = server.addWebapp("/static", base.getAbsolutePath());
    Tomcat.addServlet(staticContext, "cxfStaticServlet", new DefaultServlet());
    staticContext.addServletMappingDecoded("/static/*", "cxfStaticServlet");
    staticContext.setResources(resourcesFrom(staticContext, "target/classes/web-ui"));
    staticContext.setParentClassLoader(Thread.currentThread().getContextClassLoader());

    server.start();
    server.getServer().await();
}
 
Example 5
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 6
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;
}