Java Code Examples for org.apache.catalina.startup.Tomcat#setPort()

The following examples show how to use org.apache.catalina.startup.Tomcat#setPort() . 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: HeartbeatTest.java    From TeaStore with Apache License 2.0 6 votes vote down vote up
/**
 * Setup the test by deploying an embedded tomcat and adding the rest endpoints.
 * @throws Throwable Throws uncaught throwables for test to fail.
 */
@Before
public void setup() throws Throwable {
	registryTomcat = new Tomcat();
	registryTomcat.setPort(3000);
	registryTomcat.setBaseDir(testWorkingDir);
	Context context = registryTomcat.addWebapp(CONTEXT, testWorkingDir);
	context.addApplicationListener(RegistryStartup.class.getName());
	ResourceConfig restServletConfig = new ResourceConfig();
	restServletConfig.register(RegistryREST.class);
	restServletConfig.register(Registry.class);
	ServletContainer restServlet = new ServletContainer(restServletConfig);
	registryTomcat.addServlet(CONTEXT, "restServlet", restServlet);
	context.addServletMappingDecoded("/rest/*", "restServlet");
	registryTomcat.start();
}
 
Example 2
Source File: ServerTest.java    From raml-tester with Apache License 2.0 6 votes vote down vote up
@Before
public void initImpl() throws LifecycleException, ServletException {
    if (!inited.contains(getClass())) {
        inited.add(getClass());
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();

        tomcat = new Tomcat();
        tomcat.setPort(PORT);
        tomcat.setBaseDir(".");
        final Context ctx = tomcat.addWebapp("", "src/test");
        ctx.setJarScanner(NO_SCAN);
        ((Host) ctx.getParent()).setAppBase("");

        init(ctx);

        tomcat.start();
    }
}
 
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: AuthenticatorTestCase.java    From registry with Apache License 2.0 6 votes vote down vote up
protected void startTomcat() throws Exception {
    tomcat = new Tomcat();
    File base = new File(System.getProperty("java.io.tmpdir"));
    org.apache.catalina.Context ctx =
            tomcat.addContext("/foo", base.getAbsolutePath());
    FilterDef fd = new FilterDef();
    fd.setFilterClass(TestFilter.class.getName());
    fd.setFilterName("TestFilter");
    FilterMap fm = new FilterMap();
    fm.setFilterName("TestFilter");
    fm.addURLPattern("/*");
    fm.addServletName("/bar");
    ctx.addFilterDef(fd);
    ctx.addFilterMap(fm);
    tomcat.addServlet(ctx, "/bar", TestServlet.class.getName());
    ctx.addServletMapping("/bar", "/bar");
    host = "localhost";
    port = getLocalPort();
    tomcat.setHostname(host);
    tomcat.setPort(port);
    tomcat.start();
}
 
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: StrutsOneIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context =
            tomcat.addWebapp("", new File("src/test/resources/struts1").getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(ExecuteActionInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    int statusCode = asyncHttpClient.prepareGet("http://localhost:" + port + "/hello.do")
            .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }

    tomcat.stop();
    tomcat.destroy();
}
 
Example 7
Source File: TestTomcatThreadMetrics.java    From metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testTomcatThreadMetrics() {
    Tomcat tomcat = new Tomcat();
    tomcat.setPort(22222);
    tomcat.addContext("", "/tmp");
    tomcat.addServlet("", "testServlet", TestServlet.class.getName());
    MetricManager.register("tomcat", MetricName.build("middleware.tomcat.thread"), new ThreadGaugeSet());
    try {
        tomcat.start();
    } catch (LifecycleException e) {
        e.printStackTrace();
    }

    MetricRegistry registry = MetricManager.getIMetricManager().getMetricRegistryByGroup("tomcat");
    Assert.assertNotNull(registry.getGauges().get(MetricName.build("middleware.tomcat.thread.busy_count")));
    Assert.assertNotNull(registry.getGauges().get(MetricName.build("middleware.tomcat.thread.total_count")));
    Assert.assertNotNull(registry.getGauges().get(MetricName.build("middleware.tomcat.thread.min_pool_size")));
    Assert.assertNotNull(registry.getGauges().get(MetricName.build("middleware.tomcat.thread.max_pool_size")));
    Assert.assertNotNull(registry.getGauges().get(MetricName.build("middleware.tomcat.thread.thread_pool_queue_size")));
}
 
Example 8
Source File: UnmanagedTomcatServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    // Prepare Tomcat instances.
    tomcatWithWebApp = new Tomcat();
    tomcatWithWebApp.setPort(0);
    tomcatWithWebApp.setBaseDir("build" + File.separatorChar +
                                "tomcat-" + UnmanagedTomcatServiceTest.class.getSimpleName() + "-1");

    tomcatWithWebApp.addWebapp("", WebAppContainerTest.webAppRoot().getAbsolutePath());
    TomcatUtil.engine(tomcatWithWebApp.getService(), "foo").setName("tomcatWithWebApp");

    tomcatWithoutWebApp = new Tomcat();
    tomcatWithoutWebApp.setPort(0);
    tomcatWithoutWebApp.setBaseDir("build" + File.separatorChar +
                                   "tomcat-" + UnmanagedTomcatServiceTest.class.getSimpleName() + "-2");
    assertThat(TomcatUtil.engine(tomcatWithoutWebApp.getService(), "bar")).isNotNull();

    // Start the Tomcats.
    tomcatWithWebApp.start();
    tomcatWithoutWebApp.start();

    // Bind them to the Server.
    sb.serviceUnder("/empty/", TomcatService.of(new Connector(), "someHost"))
      .serviceUnder("/some-webapp-nohostname/",
                    TomcatService.of(tomcatWithWebApp.getConnector()))
      .serviceUnder("/no-webapp/", TomcatService.of(tomcatWithoutWebApp))
      .serviceUnder("/some-webapp/", TomcatService.of(tomcatWithWebApp));
}
 
Example 9
Source File: TomcatHttpServer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public TomcatHttpServer(URL url, final HttpHandler handler) {
        super(url, handler);

        this.url = url;
        DispatcherServlet.addHttpHandler(url.getPort(), handler);
        String baseDir = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
        tomcat = new Tomcat();
        tomcat.setBaseDir(baseDir);
        tomcat.setPort(url.getPort());
        tomcat.getConnector().setProperty(
                "maxThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS)));
//        tomcat.getConnector().setProperty(
//                "minSpareThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS)));

        tomcat.getConnector().setProperty(
                "maxConnections", String.valueOf(url.getParameter(Constants.ACCEPTS_KEY, -1)));

        tomcat.getConnector().setProperty("URIEncoding", "UTF-8");
        tomcat.getConnector().setProperty("connectionTimeout", "60000");

        tomcat.getConnector().setProperty("maxKeepAliveRequests", "-1");
        tomcat.getConnector().setProtocol("org.apache.coyote.http11.Http11NioProtocol");

        Context context = tomcat.addContext("/", baseDir);
        Tomcat.addServlet(context, "dispatcher", new DispatcherServlet());
        context.addServletMapping("/*", "dispatcher");
        ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext());

        try {
            tomcat.start();
        } catch (LifecycleException e) {
            throw new IllegalStateException("Failed to start tomcat server at " + url.getAddress(), e);
        }
    }
 
Example 10
Source File: Main.java    From executable-embeded-tomcat-sample with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ServletException, LifecycleException, IOException {

		String hostName = "localhost";
		int port = 8080;
		String contextPath = "";

		String tomcatBaseDir = TomcatUtil.createTempDir("tomcat", port).getAbsolutePath();
		String contextDocBase = TomcatUtil.createTempDir("tomcat-docBase", port).getAbsolutePath();

		Tomcat tomcat = new Tomcat();
		tomcat.setBaseDir(tomcatBaseDir);

		tomcat.setPort(port);
		tomcat.setHostname(hostName);

		Host host = tomcat.getHost();
		Context context = tomcat.addWebapp(host, contextPath, contextDocBase, new EmbededContextConfig());

		context.setJarScanner(new EmbededStandardJarScanner());

		ClassLoader classLoader = Main.class.getClassLoader();
		context.setParentClassLoader(classLoader);

		// context load WEB-INF/web.xml from classpath
		context.addLifecycleListener(new WebXmlMountListener());

		tomcat.start();
		tomcat.getServer().await();
	}
 
Example 11
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 12
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 13
Source File: AbstractTomcatServer.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void run() {
    server = new Tomcat();
    server.setPort(port);
    server.getConnector();

    try {
        base = Files.createTempDirectory("tmp-");
        server.setBaseDir(base.toString());

        if (resourcePath == null) {
            final Context context = server.addContext("", base.toString());
            final Wrapper cxfServlet = Tomcat.addServlet(context, "cxfServlet", new CXFNonSpringJaxrsServlet());
            cxfServlet.addInitParameter("jaxrs.serviceClasses", BookStore.class.getName());
            cxfServlet.addInitParameter("jaxrs.providers", String.join(",",
                JacksonJsonProvider.class.getName(),
                BookStoreResponseFilter.class.getName()
            ));
            cxfServlet.setAsyncSupported(true);
            context.addServletMappingDecoded("/rest/*", "cxfServlet");
        } else {
            server.getHost().setAppBase(base.toString());
            server.getHost().setAutoDeploy(true);
            server.getHost().setDeployOnStartup(true);
            server.addWebapp(contextPath, getClass().getResource(resourcePath).toURI().getPath().toString());
        }

        server.start();
    } catch (final Exception ex) {
        ex.printStackTrace();
        fail(ex.getMessage());
    }
}
 
Example 14
Source File: TokenExpiryTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static void initRp() {
    try {
        rpServer = new Tomcat();
        rpServer.setPort(0);
        String currentDir = new File(".").getCanonicalPath();
        rpServer.setBaseDir(currentDir + File.separator + "target");

        rpServer.getHost().setAppBase("tomcat/rp/webapps");
        rpServer.getHost().setAutoDeploy(true);
        rpServer.getHost().setDeployOnStartup(true);

        Connector httpsConnector = new Connector();
        httpsConnector.setPort(Integer.parseInt(rpHttpsPort));
        httpsConnector.setSecure(true);
        httpsConnector.setScheme("https");
        httpsConnector.setAttribute("keyAlias", "mytomidpkey");
        httpsConnector.setAttribute("keystorePass", "tompass");
        httpsConnector.setAttribute("keystoreFile", "test-classes/server.jks");
        httpsConnector.setAttribute("truststorePass", "tompass");
        httpsConnector.setAttribute("truststoreFile", "test-classes/server.jks");
        // httpsConnector.setAttribute("clientAuth", "false");
        httpsConnector.setAttribute("clientAuth", "want");
        httpsConnector.setAttribute("sslProtocol", "TLS");
        httpsConnector.setAttribute("SSLEnabled", true);

        rpServer.getService().addConnector(httpsConnector);

        rpServer.addWebapp("/fedizhelloworld", "cxfWebappExpiry");

        rpServer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 15
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 16
Source File: FederationTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static void initIdp() {
    try {
        idpServer = new Tomcat();
        idpServer.setPort(0);
        String currentDir = new File(".").getCanonicalPath();
        idpServer.setBaseDir(currentDir + File.separator + "target");

        idpServer.getHost().setAppBase("tomcat/idp/webapps");
        idpServer.getHost().setAutoDeploy(true);
        idpServer.getHost().setDeployOnStartup(true);

        Connector httpsConnector = new Connector();
        httpsConnector.setPort(Integer.parseInt(idpHttpsPort));
        httpsConnector.setSecure(true);
        httpsConnector.setScheme("https");
        httpsConnector.setAttribute("keyAlias", "mytomidpkey");
        httpsConnector.setAttribute("keystorePass", "tompass");
        httpsConnector.setAttribute("keystoreFile", "test-classes/server.jks");
        httpsConnector.setAttribute("truststorePass", "tompass");
        httpsConnector.setAttribute("truststoreFile", "test-classes/server.jks");
        httpsConnector.setAttribute("clientAuth", "want");
        // httpsConnector.setAttribute("clientAuth", "false");
        httpsConnector.setAttribute("sslProtocol", "TLS");
        httpsConnector.setAttribute("SSLEnabled", true);

        idpServer.getService().addConnector(httpsConnector);

        idpServer.addWebapp("/fediz-idp-sts", "fediz-idp-sts");
        idpServer.addWebapp("/fediz-idp", "fediz-idp");

        idpServer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 17
Source File: AbstractTomcatMetricsTest.java    From tomcat_exporter with Apache License 2.0 5 votes vote down vote up
public static void setUpTomcat(String dataSourceFactory) throws LifecycleException, ServletException {
    // create a tomcat instance
    tomcat = new Tomcat();
    tomcat.setBaseDir(".");
    tomcat.setPort(0);
    tomcat.enableNaming();

    // create a context with our test servlet
    Context ctx = tomcat.addContext(CONTEXT_PATH, new File(".").getAbsolutePath());
    Tomcat.addServlet(ctx, SERVLET_NAME, new TestServlet());
    ctx.addServletMappingDecoded("/*", SERVLET_NAME);

    // add our metrics filter
    FilterDef def = new FilterDef();
    def.setFilterClass(TomcatServletMetricsFilter.class.getName());
    def.setFilterName("metricsFilter");
    def.addInitParameter("buckets",".01, .05, .1, .25, .5, 1, 2.5, 5, 10, 30");
    ctx.addFilterDef(def);
    FilterMap map = new FilterMap();
    map.setFilterName("metricsFilter");
    map.addURLPattern("/*");
    ctx.addFilterMap(map);

    // create a datasource
    ContextResource resource = new ContextResource();
    resource.setName("jdbc/db");
    resource.setAuth("Container");
    resource.setType("javax.sql.DataSource");
    resource.setScope("Sharable");
    resource.setProperty("name", "foo");
    resource.setProperty("factory", dataSourceFactory);
    resource.setProperty("driverClassName", "org.h2.Driver");
    resource.setProperty("url", "jdbc:h2:mem:dummy");
    resource.setProperty("jdbcInterceptors", "nl.nlighten.prometheus.tomcat.TomcatJdbcInterceptor(logFailed=true,logSlow=true,threshold=0,buckets=.01|.05|.1|1|10,slowQueryBuckets=1|10|30)");
    ctx.getNamingResources().addResource(resource);

    // start instance
    tomcat.init();
    tomcat.start();
}
 
Example 18
Source File: SpringTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private static Tomcat startServer(boolean idp, String port)
    throws ServletException, LifecycleException, IOException {
    Tomcat server = new Tomcat();
    server.setPort(0);
    String currentDir = new File(".").getCanonicalPath();
    String baseDir = currentDir + File.separator + "target";
    server.setBaseDir(baseDir);

    if (idp) {
        server.getHost().setAppBase("tomcat/idp/webapps");
    } else {
        server.getHost().setAppBase("tomcat/rp/webapps");
    }
    server.getHost().setAutoDeploy(true);
    server.getHost().setDeployOnStartup(true);

    Connector httpsConnector = new Connector();
    httpsConnector.setPort(Integer.parseInt(port));
    httpsConnector.setSecure(true);
    httpsConnector.setScheme("https");
    httpsConnector.setAttribute("keyAlias", "mytomidpkey");
    httpsConnector.setAttribute("keystorePass", "tompass");
    httpsConnector.setAttribute("keystoreFile", "test-classes/server.jks");
    httpsConnector.setAttribute("truststorePass", "tompass");
    httpsConnector.setAttribute("truststoreFile", "test-classes/server.jks");
    httpsConnector.setAttribute("clientAuth", "want");
    // httpsConnector.setAttribute("clientAuth", "false");
    httpsConnector.setAttribute("sslProtocol", "TLS");
    httpsConnector.setAttribute("SSLEnabled", true);

    server.getService().addConnector(httpsConnector);

    if (idp) {
        File stsWebapp = new File(baseDir + File.separator + server.getHost().getAppBase(), "fediz-idp-sts");
        server.addWebapp("/fediz-idp-sts", stsWebapp.getAbsolutePath());

        File idpWebapp = new File(baseDir + File.separator + server.getHost().getAppBase(), "fediz-idp");
        server.addWebapp("/fediz-idp", idpWebapp.getAbsolutePath());
    } else {
        File rpWebapp = new File(baseDir + File.separator + server.getHost().getAppBase(),
                                 "fediz-systests-webapps-spring");
        server.addWebapp("/fedizhelloworld", rpWebapp.getAbsolutePath());
        server.addWebapp("/fedizhelloworldspringnoreqvalidation", rpWebapp.getAbsolutePath());
    }

    server.start();

    return server;
}
 
Example 19
Source File: TomcatServer.java    From athena-rest with Apache License 2.0 4 votes vote down vote up
private void initTomcat() {
	serverStatus = ServerStatus.STARTING;

	tomcat = new Tomcat();
	tomcat.setPort(port);

	// Changed it to use NIO due to poor performance in burdon test
	Connector connector = new Connector(Utils.getStringProperty(properties, "web.connectorProtocol"));

	
	connector.setURIEncoding("UTF-8");
	connector.setPort(port);
	connector.setUseBodyEncodingForURI(true);
	connector.setAsyncTimeout(Utils.getIntegerValue(properties,
			WEB_ASYNC_TIMEOUT, DEFAULT_ASYNC_TIMEOUT));
	connector.setAttribute("minProcessors", Utils.getIntegerValue(
			properties, WEB_MIN_PROCESSORS, DEFAULT_MIN_PROCESSORS));
	connector.setAttribute("maxProcessors", Utils.getIntegerValue(
			properties, WEB_MAX_PROCESSORS, DEFAULT_MAX_PROCESSORS));
	connector.setAttribute("acceptCount", Utils.getIntegerValue(properties,
			WEB_ACCEPT_COUNT, DEFAULT_ACCEPT_COUNT));
	connector.setAttribute("minSpareThreads", Utils.getIntegerValue(
			properties, WEB_MIN_SPARE_THREADS, DEFAULT_MIN_SPARE_THREADS));
	connector.setAttribute("maxThreads", Utils.getIntegerValue(properties,
			WEB_MAX_THREADS, DEFAULT_MAX_THREADS));
	connector.setRedirectPort(Utils.getIntegerValue(properties,
			WEB_REDIRECT_PORT, DEFAULT_WEB_REDIRECT_PORT));
	
	if (this.minThreads != -1 && this.maxThreads != -1) {
		connector.setAttribute("minThreads", minThreads);
		connector.setAttribute("maxThreads", maxThreads);
	}

	Service tomcatService = tomcat.getService();
	tomcatService.addConnector(connector);
	tomcat.setConnector(connector);

	Context context = null;
	try {
		context = tomcat.addWebapp(contextPath,
				new File(webappPath).getAbsolutePath());
	} catch (ServletException e) {
		log.error("Failed to add webapp + " + webappPath, e);

		exit();
	}
	context.setLoader(new WebappLoader(Thread.currentThread()
			.getContextClassLoader()));

	String extraResourcePaths = properties
			.getProperty(WEB_EXTRA_RESOURCE_PATHS);
	if (!StringUtils.isBlank(extraResourcePaths)) {
		VirtualDirContext virtualDirContext = new VirtualDirContext();
		virtualDirContext.setExtraResourcePaths(extraResourcePaths);
		context.setResources(virtualDirContext);
	}

	StandardServer server = (StandardServer) tomcat.getServer();
	AprLifecycleListener listener = new AprLifecycleListener();
	server.addLifecycleListener(listener);
}
 
Example 20
Source File: JspRenderIT.java    From glowroot with Apache License 2.0 3 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context =
            tomcat.addContext("", new File("src/test/resources").getAbsolutePath());

    WebappLoader webappLoader = new WebappLoader(RenderJspInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    Tomcat.addServlet(context, "hello", new ForwardingServlet());
    context.addServletMapping("/hello", "hello");
    Tomcat.addServlet(context, "jsp", new JspServlet());
    context.addServletMapping("*.jsp", "jsp");

    tomcat.start();
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    int statusCode = asyncHttpClient.prepareGet("http://localhost:" + port + "/hello")
            .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
    tomcat.stop();
    tomcat.destroy();
}