org.apache.catalina.webresources.StandardRoot Java Examples

The following examples show how to use org.apache.catalina.webresources.StandardRoot. 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: TomEEWebappClassLoader.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void setResources(final WebResourceRoot resources) {
    this.resources = resources;
    if (StandardRoot.class.isInstance(resources)) {
        final List<WebResourceSet> jars = (List<WebResourceSet>) Reflections.get(resources, "jarResources");
        if (jars != null && !jars.isEmpty()) {
            final Iterator<WebResourceSet> jarIt = jars.iterator();
            while (jarIt.hasNext()) {
                final WebResourceSet set = jarIt.next();
                if (set.getBaseUrl() == null) {
                    continue;
                }
                final File file = URLs.toFile(set.getBaseUrl());
                try {
                    if (file.exists() && (!TomEEClassLoaderEnricher.validateJarFile(file) || !jarIsAccepted(file))) {
                        // need to remove this resource
                        LOGGER.warning("Removing " + file.getAbsolutePath() + " since it is offending");
                        jarIt.remove();
                    }
                } catch (final IOException e) {
                    // ignore
                }
            }
        }
    }
}
 
Example #2
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 #3
Source File: TestWarDirContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testReservedJNDIFileNamesWithCache() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-fragments");
    // app dir is relative to server home
    StandardContext ctxt = (StandardContext) tomcat.addWebapp(
            null, "/test", appDir.getAbsolutePath());
    StandardRoot root = new StandardRoot();
    root.setCachingAllowed(true);
    ctxt.setResources(root);

    tomcat.start();

    // Should be found in resources.jar
    ByteChunk bc = getUrl("http://localhost:" + getPort() +
            "/test/'singlequote.jsp");
    Assert.assertEquals("<p>'singlequote.jsp in resources.jar</p>",
            bc.toString());

    // Should be found in file system
    bc = getUrl("http://localhost:" + getPort() +
            "/test/'singlequote2.jsp");
    Assert.assertEquals("<p>'singlequote2.jsp in file system</p>",
            bc.toString());
}
 
Example #4
Source File: TomcatServer.java    From redisson with Apache License 2.0 6 votes vote down vote up
public TomcatServer(String contextPath, int port, String appBase) throws MalformedURLException, ServletException {
    if(contextPath == null || appBase == null || appBase.length() == 0) {
        throw new IllegalArgumentException("Context path or appbase should not be null");
    }
    if(!contextPath.startsWith("/")) {
        contextPath = "/" + contextPath;
    }

    tomcat.setBaseDir("."); // location where temp dir is created
    tomcat.setPort(port);
    tomcat.getHost().setAppBase(".");

    ctx = (StandardContext) tomcat.addWebapp(contextPath, appBase);
    ctx.setDelegate(true);
    
    File additionWebInfClasses = new File("target/test-classes");
    StandardRoot resources = new StandardRoot();
    DirResourceSet webResourceSet = new DirResourceSet();
    webResourceSet.setBase(additionWebInfClasses.toString());
    webResourceSet.setWebAppMount("/WEB-INF/classes");
    resources.addPostResources(webResourceSet);
    ctx.setResources(resources);
}
 
Example #5
Source File: TomcatConfig.java    From find with MIT License 6 votes vote down vote up
@Bean
public EmbeddedServletContainerFactory servletContainer() {
    final TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();

    if(useReverseProxy) {
        tomcat.addAdditionalTomcatConnectors(createAjpConnector());
    }

    // Set the web resources cache size (this defaults to 10MB but that is too small for Find)
    tomcat.addContextCustomizers(context -> {
        final WebResourceRoot resources = new StandardRoot(context);
        resources.setCacheMaxSize(webResourcesCacheSize);
        context.setResources(resources);
    });

    tomcat.addConnectorCustomizers(connector -> {
        connector.setMaxPostSize(connectorMaxPostSize);
    });

    return tomcat;
}
 
Example #6
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 #7
Source File: Main.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static void main(String[] args) throws ServletException, LifecycleException {
	OpenTracingUtil.configureOpenTracing("RobotShop-Factory-Service");

	String webappDirLocation = "src/main/webapp/";
	Tomcat tomcat = new Tomcat();

	String webPort = System.getenv("PORT");
	if (webPort == null || webPort.isEmpty()) {
		webPort = DEFAULT_PORT;
	}

	tomcat.setPort(Integer.valueOf(webPort));

	StandardContext ctx = (StandardContext) tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());
	System.out.println("Basedir: " + new File("./" + webappDirLocation).getAbsolutePath());
	File additionWebInfClasses = new File("target/classes");
	WebResourceRoot resources = new StandardRoot(ctx);
	resources.addPreResources(
			new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
	ctx.setResources(resources);

	// Add servlet that will register Jersey REST resources
	Tomcat.addServlet(ctx, "jersey-container-servlet", resourceConfig());
	ctx.addServletMapping("/*", "jersey-container-servlet");

	tomcat.start();
	tomcat.getServer().await();
}
 
Example #8
Source File: Main.java    From heroku-identity-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String webappDirLocation = "src/main/webapp/";
        Tomcat tomcat = new Tomcat();

        //The port that we should run on can be set into an environment variable
        //Look for that variable and default to 8080 if it isn't there.
        String webPort = System.getenv("PORT");
        if(webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }

        tomcat.setPort(Integer.valueOf(webPort));

        StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
        System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath());

        // Declare an alternative location for your "WEB-INF/classes" dir
        // Servlet 3.0 annotation will work
        File additionWebInfClasses = new File("target/classes");
        WebResourceRoot resources = new StandardRoot(ctx);
        resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes",
                additionWebInfClasses.getAbsolutePath(), "/"));
        ctx.setResources(resources);

        tomcat.start();
        tomcat.getServer().await();
    }
 
Example #9
Source File: JsfTomcatApplicationListenerIT.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
public void customizeTargetTestClasses() {
	Context standardContext = mock(Context.class);
	StandardRoot webResourceRoot = new StandardRoot(standardContext);
	Mockito.when(standardContext.getResources()).thenReturn(webResourceRoot);
	Mockito.when(standardContext.getAddWebinfClassesResources()).thenReturn(Boolean.FALSE);

	String absolutePath = new File("").getAbsolutePath();
	String internalPath = METAINF_RESOURCES;

	String targetTestClassesBase = absolutePath + "/" + "build/resources/test";
	File testClassesResources = new File(targetTestClassesBase + internalPath);
	if (!testClassesResources.mkdirs()) {
		throw new RuntimeException("Could not create dir: " + testClassesResources.toString());
	}

	JsfTomcatContextCustomizer jsfTomcatContextCustomizer = new JsfTomcatContextCustomizer();
	jsfTomcatContextCustomizer.customize(standardContext);

	JsfTomcatApplicationListener jsfTomcatApplicationListener = new JsfTomcatApplicationListener(jsfTomcatContextCustomizer.getContext());

	jsfTomcatApplicationListener.onApplicationEvent(mock(ApplicationReadyEvent.class));
	if (!testClassesResources.delete()) {
		throw new RuntimeException("Could not delete dir: " + testClassesResources.toString());
	}
	assertThat(webResourceRoot.getPostResources().length)
		.isGreaterThanOrEqualTo(10);
}
 
Example #10
Source File: JsfTomcatApplicationListenerIT.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
public void customize() {
	Context standardContext = mock(Context.class);
	StandardRoot webResourceRoot = new StandardRoot(standardContext);
	Mockito.when(standardContext.getResources()).thenReturn(webResourceRoot);
	Mockito.when(standardContext.getAddWebinfClassesResources()).thenReturn(Boolean.FALSE);

	JsfTomcatContextCustomizer jsfTomcatContextCustomizer = new JsfTomcatContextCustomizer();
	jsfTomcatContextCustomizer.customize(standardContext);

	JsfTomcatApplicationListener jsfTomcatApplicationListener = new JsfTomcatApplicationListener(jsfTomcatContextCustomizer.getContext());
	jsfTomcatApplicationListener.onApplicationEvent(mock(ApplicationReadyEvent.class));
	assertThat(webResourceRoot.getPostResources().length)
		.isGreaterThanOrEqualTo(9);
}
 
Example #11
Source File: EnhancedCli.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        try (final Meecrowave meecrowave = new Meecrowave(create(args)) {

            @Override
            protected Connector createConnector() {
                return new Connector(CustomPefixHttp11NioProtocol.class.getName());
            }
        }) {
            this.instance = meecrowave;

            meecrowave.start();
            meecrowave.deployClasspath(new Meecrowave.DeploymentMeta("", null, stdCtx -> {
                stdCtx.setResources(new StandardRoot() {

                    @Override
                    protected void registerURLStreamHandlerFactory() {
                        // no-op: not supported into OSGi since there is already one and it must set a
                        // single time
                    }
                });
                stdCtx.addServletContainerInitializer(new WsSci(), null);
            }));

            doWait(meecrowave, null);
        }
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example #12
Source File: TomcatApplication.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
public static void configure(TomcatServletWebServerFactory tomcatFactory) {

        tomcatFactory.addContextCustomizers(context -> {

            StandardJarScanFilter standardJarScanFilter = new StandardJarScanFilter();
            standardJarScanFilter.setTldScan("dwr-*.jar,jstl-*.jar,spring-security-taglibs-*.jar,spring-web-*.jar,spring-webmvc-*.jar,string-*.jar,taglibs-standard-impl-*.jar,tomcat-annotations-api-*.jar,tomcat-embed-jasper-*.jar");
            standardJarScanFilter.setTldSkip("*");
            context.getJarScanner().setJarScanFilter(standardJarScanFilter);

            boolean development = (System.getProperty("airsonic.development") != null);

            // Increase the size and time before eviction of the Tomcat
            // cache so that resources aren't uncompressed too often.
            // See https://github.com/jhipster/generator-jhipster/issues/3995

            StandardRoot resources = new StandardRoot();
            if (development) {
                resources.setCachingAllowed(false);
            } else {
                resources.setCacheMaxSize(100000);
                resources.setCacheObjectMaxSize(4000);
                resources.setCacheTtl(24 * 3600 * 1000);  // 1 day, in milliseconds
            }
            context.setResources(resources);

            // Put Jasper in production mode so that JSP aren't recompiled
            // on each request.
            // See http://stackoverflow.com/questions/29653326/spring-boot-application-slow-because-of-jsp-compilation
            Container jsp = context.findChild("jsp");
            if (jsp instanceof Wrapper) {
                ((Wrapper) jsp).addInitParameter("development", Boolean.toString(development));
            }
        });
    }
 
Example #13
Source File: Main.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static void main(String[] args) throws ServletException, LifecycleException {
	OpenTracingUtil.configureOpenTracing("RobotShop-Order-Service");
	String webappDirLocation = "src/main/webapp/";
	Tomcat tomcat = new Tomcat();

	String webPort = System.getenv("PORT");
	if (webPort == null || webPort.isEmpty()) {
		webPort = DEFAULT_PORT;
	}

	tomcat.setPort(Integer.valueOf(webPort));

	StandardContext ctx = (StandardContext) tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());
	System.out.println("Basedir: " + new File("./" + webappDirLocation).getAbsolutePath());
	File additionWebInfClasses = new File("target/classes");
	WebResourceRoot resources = new StandardRoot(ctx);
	resources.addPreResources(
			new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
	ctx.setResources(resources);

	// Add servlet that will register Jersey REST resources
	Tomcat.addServlet(ctx, "jersey-container-servlet", resourceConfig());
	ctx.addServletMapping("/*", "jersey-container-servlet");

	tomcat.start();
	tomcat.getServer().await();
}
 
Example #14
Source File: Main.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static void main(String[] args) throws ServletException, LifecycleException {
	OpenTracingUtil.configureOpenTracing("RobotShop-Customer-Service");
	
	String webappDirLocation = "src/main/webapp/";
	Tomcat tomcat = new Tomcat();

	String webPort = System.getenv("PORT");
	if (webPort == null || webPort.isEmpty()) {
		webPort = DEFAULT_PORT;
	}

	tomcat.setPort(Integer.valueOf(webPort));

	StandardContext ctx = (StandardContext) tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());
	System.out.println("Basedir: " + new File("./" + webappDirLocation).getAbsolutePath());
	File additionWebInfClasses = new File("target/classes");
	WebResourceRoot resources = new StandardRoot(ctx);
	resources.addPreResources(
			new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
	ctx.setResources(resources);

	// Add servlet that will register Jersey REST resources
	Tomcat.addServlet(ctx, "jersey-container-servlet", resourceConfig());
	ctx.addServletMapping("/*", "jersey-container-servlet");

	tomcat.start();
	tomcat.getServer().await();
}
 
Example #15
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 #16
Source File: MvcConfiguration.java    From tensorboot with Apache License 2.0 5 votes vote down vote up
@Bean
public ConfigurableTomcatWebServerFactory servletContainer() {
    return new TomcatServletWebServerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            StandardRoot standardRoot = new StandardRoot(context);
            standardRoot.setCacheMaxSize(TOMCAT_RESOURCES_CACHE_SIZE);
            context.setResources(standardRoot);
            log.info(String.format("New cache size (KB): %d", context.getResources().getCacheMaxSize()));
        }
    };
}
 
Example #17
Source File: TomcatApplication.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
public static void configure(TomcatServletWebServerFactory tomcatFactory) {

        tomcatFactory.addContextCustomizers(context -> {

            StandardJarScanFilter standardJarScanFilter = new StandardJarScanFilter();
            standardJarScanFilter.setTldScan("jstl-*.jar,spring-security-taglibs-*.jar,spring-web-*.jar,spring-webmvc-*.jar,string-*.jar,taglibs-standard-impl-*.jar,tomcat-annotations-api-*.jar,tomcat-embed-jasper-*.jar");
            standardJarScanFilter.setTldSkip("*");
            context.getJarScanner().setJarScanFilter(standardJarScanFilter);

            boolean development = (System.getProperty("airsonic.development") != null);

            // Increase the size and time before eviction of the Tomcat
            // cache so that resources aren't uncompressed too often.
            // See https://github.com/jhipster/generator-jhipster/issues/3995

            StandardRoot resources = new StandardRoot();
            if (development) {
                resources.setCachingAllowed(false);
            } else {
                resources.setCacheMaxSize(100000);
                resources.setCacheObjectMaxSize(4000);
                resources.setCacheTtl(24 * 3600 * 1000);  // 1 day, in milliseconds
            }
            context.setResources(resources);

            // Put Jasper in production mode so that JSP aren't recompiled
            // on each request.
            // See http://stackoverflow.com/questions/29653326/spring-boot-application-slow-because-of-jsp-compilation
            Container jsp = context.findChild("jsp");
            if (jsp instanceof Wrapper) {
                ((Wrapper) jsp).addInitParameter("development", Boolean.toString(development));
            }
        });
    }
 
Example #18
Source File: AbstractTestTag.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp");
    Context ctx = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());

    ctx.setResources(new StandardRoot(ctx));

    // Add the JSTL (we need the TLD)
    File lib = new File("webapps/examples/WEB-INF/lib");
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/lib",
            lib.getAbsolutePath(), null, "/");

    // Configure the use of the plug-in rather than the standard impl
    File plugin = new File(
            "java/org/apache/jasper/tagplugins/jstl/tagPlugins.xml");
    Assert.assertTrue(plugin.isFile());
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/tagPlugins.xml",
            plugin.getAbsolutePath(), null, "/");

    tomcat.start();
}
 
Example #19
Source File: TestWarDirContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testReservedJNDIFileNamesNoCache() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-fragments");
    // app dir is relative to server home
    StandardContext ctxt = (StandardContext) tomcat.addWebapp(
            null, "/test", appDir.getAbsolutePath());
    StandardRoot root = new StandardRoot();
    root.setCachingAllowed(true);
    ctxt.setResources(root);
    skipTldsForResourceJars(ctxt);

    tomcat.start();

    // Should be found in resources.jar
    ByteChunk bc = getUrl("http://localhost:" + getPort() +
            "/test/'singlequote.jsp");
    Assert.assertEquals("<p>'singlequote.jsp in resources.jar</p>",
            bc.toString());

    // Should be found in file system
    bc = getUrl("http://localhost:" + getPort() +
            "/test/'singlequote2.jsp");
    Assert.assertEquals("<p>'singlequote2.jsp in file system</p>",
            bc.toString());
}
 
Example #20
Source File: TestStandardContextAliases.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testDirContextAliases() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    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, "/");


    Tomcat.addServlet(ctx, "test", new TestServlet());
    ctx.addServletMappingDecoded("/", "test");

    tomcat.start();

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

    String result = res.toString();
    if (result == null) {
        result = "";
    }

    Assert.assertTrue(result.indexOf("00-PASS") > -1);
    Assert.assertTrue(result.indexOf("01-PASS") > -1);
    Assert.assertTrue(result.indexOf("02-PASS") > -1);
}
 
Example #21
Source File: TestVirtualWebappLoader.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testStartInternal() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp");
    StandardContext ctx = (StandardContext) tomcat.addContext("",
            appDir.getAbsolutePath());


    WebappLoader loader = new WebappLoader();

    loader.setContext(ctx);
    ctx.setLoader(loader);

    ctx.setResources(new StandardRoot(ctx));
    ctx.resourcesStart();

    File f1 = new File("test/webapp-fragments/WEB-INF/lib");
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/lib",
            f1.getAbsolutePath(), null, "/");

    loader.start();
    String[] repos = loader.getLoaderRepositories();
    Assert.assertEquals(4,repos.length);
    loader.stop();

    repos = loader.getLoaderRepositories();
    Assert.assertEquals(0, repos.length);

    // no leak
    loader.start();
    repos = loader.getLoaderRepositories();
    Assert.assertEquals(4,repos.length);

    // clear loader
    ctx.setLoader(null);
    // see tearDown()!
    tomcat.start();
}
 
Example #22
Source File: ReloadingLoaderTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Before
public void initContext() throws LifecycleException {
    final OpenEjbConfiguration configuration = new OpenEjbConfiguration();
    configuration.facilities = new FacilitiesInfo();

    final CoreContainerSystem containerSystem = new CoreContainerSystem(new IvmJndiFactory());

    SystemInstance.get().setComponent(OpenEjbConfiguration.class, configuration);
    SystemInstance.get().setComponent(ContainerSystem.class, containerSystem);
    SystemInstance.get().setComponent(WebAppEnricher.class, new WebAppEnricher() {
        @Override
        public URL[] enrichment(final ClassLoader webappClassLaoder) {
            return new URL[0];
        }
    });

    parentInstance = new AtomicReference<>(ParentClassLoaderFinder.Helper.get());
    loader = new TomEEWebappClassLoader(parentInstance.get()) {
        @Override
        public ClassLoader getInternalParent() {
            return parentInstance.get();
        }

        @Override
        protected void clearReferences() {
            // no-op: this test should be reworked to support it but in real life a loader is not stopped/started
        }
    };
    loader.init();
    final StandardRoot resources = new StandardRoot();
    loader.setResources(resources);
    resources.setContext(new StandardContext() {
        @Override
        public String getDocBase() {
            final File file = new File("target/foo");
            file.mkdirs();
            return file.getAbsolutePath();
        }

        @Override
        public String getMBeanKeyProperties() {
            return "foo";
        }
    {}});
    resources.start();
    loader.start();

    info = new AppInfo();
    info.appId = "test";
    context = new AppContext(info.appId, SystemInstance.get(), loader, new IvmContext(), new IvmContext(), true);
    containerSystem.addAppContext(context);

    final WebContext webDeployment = new WebContext(context);
    webDeployment.setId(context.getId());
    webDeployment.setClassLoader(loader);
    containerSystem.addWebContext(webDeployment);
}
 
Example #23
Source File: LazyStopStandardRoot.java    From tomee with Apache License 2.0 4 votes vote down vote up
public List<String> getTrackedResources() { // IDE?
    return StandardRoot.class.cast(delegate).getTrackedResources();
}
 
Example #24
Source File: StatsServer.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static WebResourceRoot resourcesFrom(final Context context, final String path) {
    final File additionResources = new File(path);
    final WebResourceRoot resources = new StandardRoot(context);
    resources.addPreResources(new DirResourceSet(resources, "/", additionResources.getAbsolutePath(), "/"));
    return resources;
}
 
Example #25
Source File: WebServer.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    final String originalCompSystProp =
            setSystemProperty("talend.component.server.component.coordinates", componentGav);
    final String skipClasspathSystProp = setSystemProperty("component.manager.classpath.skip", "true");
    final String skipCallersSystProp = setSystemProperty("component.manager.callers.skip", "true");
    final AtomicReference<Meecrowave> ref = new AtomicReference<>();
    try {
        final CountDownLatch latch = new CountDownLatch(1);
        new Thread(() -> {
            try (final Meecrowave meecrowave = new Meecrowave(Cli.create(buildArgs()))) {
                meecrowave.start().deployClasspath(new Meecrowave.DeploymentMeta("", null, stdCtx -> {
                    stdCtx.setResources(new StandardRoot() {

                        @Override
                        protected void registerURLStreamHandlerFactory() {
                            // no-op - gradle supports to reuse the same JVM so it would be broken
                        }
                    });
                }));

                ref.set(meecrowave);
                latch.countDown();
                onOpen.forEach(it -> it.accept(meecrowave.getConfiguration()));
                meecrowave.getTomcat().getServer().await();
            } catch (final RuntimeException re) {
                latch.countDown();
                log.error(re.getMessage());
                throw re;
            }
        }, getClass().getName() + '_' + findPort()).start();
        try {
            latch.await(2, MINUTES);
        } catch (final InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
        log.info("\n\n  You can now access the UI at http://localhost:" + port + "\n\n");
        final Scanner scanner = new Scanner(System.in);
        do {
            log.info("Enter 'exit' to quit");
        } while (!shouldQuit(scanner.nextLine()));
    } finally {
        reset("talend.component.server.component.coordinates", originalCompSystProp);
        reset("component.manager.classpath.skip", skipClasspathSystProp);
        reset("component.manager.callers.skip", skipCallersSystProp);
        ofNullable(ref.get()).ifPresent(mw -> StandardServer.class.cast(mw.getTomcat().getServer()).stopAwait());
    }
}
 
Example #26
Source File: TestVirtualContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testAdditionalWebInfClassesPaths() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-virtual-webapp/src/main/webapp");
    // app dir is relative to server home
    StandardContext ctx = (StandardContext) tomcat.addWebapp(null, "/test",
        appDir.getAbsolutePath());
    File tempFile = File.createTempFile("virtualWebInfClasses", null);

    File additionWebInfClasses = new File(tempFile.getAbsolutePath() + ".dir");
    Assert.assertTrue(additionWebInfClasses.mkdirs());
    File targetPackageForAnnotatedClass =
        new File(additionWebInfClasses,
            MyAnnotatedServlet.class.getPackage().getName().replace('.', '/'));
    Assert.assertTrue(targetPackageForAnnotatedClass.mkdirs());
    try (InputStream annotatedServletClassInputStream = this.getClass().getResourceAsStream(
            MyAnnotatedServlet.class.getSimpleName() + ".class");
            FileOutputStream annotatedServletClassOutputStream = new FileOutputStream(new File(
                    targetPackageForAnnotatedClass, MyAnnotatedServlet.class.getSimpleName()
                            + ".class"));) {
        IOUtils.copy(annotatedServletClassInputStream, annotatedServletClassOutputStream);
    }

    ctx.setResources(new StandardRoot(ctx));
    File f1 = new File("test/webapp-virtual-webapp/target/classes");
    File f2 = new File("test/webapp-virtual-library/target/WEB-INF/classes");
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes",
            f1.getAbsolutePath(), null, "/");
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes",
            f2.getAbsolutePath(), null, "/");

    tomcat.start();
    // first test that without the setting on StandardContext the annotated
    // servlet is not detected
    assertPageContains("/test/annotatedServlet", MyAnnotatedServlet.MESSAGE, 404);

    tomcat.stop();

    // then test that if we configure StandardContext with the additional
    // path, the servlet is detected
    ctx.setResources(new StandardRoot(ctx));
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes",
            f1.getAbsolutePath(), null, "/");
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes",
            f2.getAbsolutePath(), null, "/");
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes",
            additionWebInfClasses.getAbsolutePath(), null, "/");

    tomcat.start();
    assertPageContains("/test/annotatedServlet", MyAnnotatedServlet.MESSAGE);
    tomcat.stop();
    FileUtils.deleteDirectory(additionWebInfClasses);
    Assert.assertTrue("Failed to clean up [" + tempFile + "]", tempFile.delete());
}