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

The following examples show how to use org.apache.catalina.core.StandardContext#setResources() . 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: 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 2
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 3
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 4
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 5
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 6
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 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 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 9
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 10
Source File: TestVirtualWebappLoader.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartInternal() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp-3.0");
    // Must have a real docBase - just use temp
    StandardContext ctx =
        (StandardContext)tomcat.addContext("",  appDir.getAbsolutePath());

    VirtualWebappLoader loader = new VirtualWebappLoader();

    loader.setContainer(ctx);
    ctx.setLoader(loader);
    ctx.setResources(new FileDirContext());
    ctx.resourcesStart();
    File dir = new File("test/webapp-3.0-fragments/WEB-INF/lib");
    loader.setVirtualClasspath(dir.getAbsolutePath() + "/*.jar");
    loader.start();
    String[] repos = loader.getRepositories();
    assertEquals(2,repos.length);
    loader.stop();
    // ToDo: Why doesn't remove repositories?
    repos = loader.getRepositories();
    assertEquals(2, repos.length);

    // no leak
    loader.start();
    repos = loader.getRepositories();
    assertEquals(2,repos.length);

    // clear loader
    ctx.setLoader(null);
    // see tearDown()!
    tomcat.start();
}
 
Example 11
Source File: TestVirtualWebappLoader.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartInternal() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp-3.0");
    // Must have a real docBase - just use temp
    StandardContext ctx =
        (StandardContext)tomcat.addContext("",  appDir.getAbsolutePath());

    VirtualWebappLoader loader = new VirtualWebappLoader();

    loader.setContainer(ctx);
    ctx.setLoader(loader);
    ctx.setResources(new FileDirContext());
    ctx.resourcesStart();
    File dir = new File("test/webapp-3.0-fragments/WEB-INF/lib");
    loader.setVirtualClasspath(dir.getAbsolutePath() + "/*.jar");
    loader.start();
    String[] repos = loader.getRepositories();
    assertEquals(2,repos.length);
    loader.stop();
    // ToDo: Why doesn't remove repositories?
    repos = loader.getRepositories();
    assertEquals(2, repos.length);

    // no leak
    loader.start();
    repos = loader.getRepositories();
    assertEquals(2,repos.length);

    // clear loader
    ctx.setLoader(null);
    // see tearDown()!
    tomcat.start();
}
 
Example 12
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 13
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 14
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());
}
 
Example 15
Source File: TestVirtualContext.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testAdditionalWebInfClassesPaths() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0-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());
    InputStream annotatedServletClassInputStream =
        this.getClass().getResourceAsStream(
            MyAnnotatedServlet.class.getSimpleName() + ".class");
    FileOutputStream annotatedServletClassOutputStream =
        new FileOutputStream(new File(targetPackageForAnnotatedClass,
            MyAnnotatedServlet.class.getSimpleName() + ".class"));
    IOUtils.copy(annotatedServletClassInputStream, annotatedServletClassOutputStream);
    annotatedServletClassInputStream.close();
    annotatedServletClassOutputStream.close();

    VirtualWebappLoader loader = new VirtualWebappLoader(ctx.getParentClassLoader());
    loader.setVirtualClasspath("test/webapp-3.0-virtual-webapp/target/classes;" + //
        "test/webapp-3.0-virtual-library/target/classes;" + //
        additionWebInfClasses.getAbsolutePath());
    ctx.setLoader(loader);

    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.setAdditionalVirtualWebInfClasses(additionWebInfClasses.getAbsolutePath());
    VirtualDirContext resources = new VirtualDirContext();
    resources.setExtraResourcePaths("/WEB-INF/classes=" + additionWebInfClasses);
    ctx.setResources(resources);

    tomcat.start();
    assertPageContains("/test/annotatedServlet", MyAnnotatedServlet.MESSAGE);
    tomcat.stop();
    FileUtils.deleteDirectory(additionWebInfClasses);
    tempFile.delete();
}