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

The following examples show how to use org.apache.catalina.startup.Tomcat#addContext() . 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: TestApplicationContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testCrossContextSetAttribute() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx2 = tomcat.addContext("/second", null);
    GetAttributeServlet getAttributeServlet = new GetAttributeServlet();
    Tomcat.addServlet(ctx2, "getAttributeServlet", getAttributeServlet);
    ctx2.addServletMappingDecoded("/test", "getAttributeServlet");

    // No file system docBase required
    Context ctx1 = tomcat.addContext("/first", null);
    ctx1.setCrossContext(true);
    SetAttributeServlet setAttributeServlet = new SetAttributeServlet("/test", "/second");
    Tomcat.addServlet(ctx1, "setAttributeServlet", setAttributeServlet);
    ctx1.addServletMappingDecoded("/test", "setAttributeServlet");

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/first/test", bc, null);

    Assert.assertEquals(200, rc);
    Assert.assertEquals("01-PASS", bc.toString());
}
 
Example 2
Source File: TestRequest.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Test case for {@link Request#login(String, String)} and
 * {@link Request#logout()}.
 */
@Test
public void testLoginLogout() throws Exception{
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    LoginConfig config = new LoginConfig();
    config.setAuthMethod("BASIC");
    ctx.setLoginConfig(config);
    ctx.getPipeline().addValve(new BasicAuthenticator());

    Tomcat.addServlet(ctx, "servlet", new LoginLogoutServlet());
    ctx.addServletMapping("/", "servlet");

    MapRealm realm = new MapRealm();
    realm.addUser(LoginLogoutServlet.USER, LoginLogoutServlet.PWD);
    ctx.setRealm(realm);

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    assertEquals(LoginLogoutServlet.OK, res.toString());
}
 
Example 3
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void doTestAsyncRequestURI(String uri) throws Exception{
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Servlet servlet = new AsyncRequestUriServlet();
    Wrapper wrapper1 = Tomcat.addServlet(ctx, "bug57559", servlet);
    wrapper1.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/", "bug57559");

    tomcat.start();

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

    Assert.assertEquals(uri, body.toString());
}
 
Example 4
Source File: JCacheFilterTest.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilter() throws Exception
{
    Hello.COUNTER.set(0);
    final Tomcat tomcat = new Tomcat();
    tomcat.setPort(0);
    try {
        tomcat.getEngine();
        tomcat.start();
        final Context ctx = tomcat.addContext("/sample", docBase.getAbsolutePath());
        Tomcat.addServlet(ctx, "hello", Hello.class.getName());
        ctx.addServletMapping("/", "hello");
        addJcsFilter(ctx);
        StandardContext.class.cast(ctx).filterStart();

        final URL url = new URL("http://localhost:" + tomcat.getConnector().getLocalPort() + "/sample/");
        assertEquals("hello", IOUtils.toString(url.openStream()));
        assertEquals(1, Hello.COUNTER.get());

        assertEquals("hello", IOUtils.toString(url.openStream()));
        assertEquals(1, Hello.COUNTER.get());
    } finally {
        stop(tomcat);
    }
}
 
Example 5
Source File: TestMapperWebapps.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testContextRoot_Bug53339() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    tomcat.enableNaming();

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

    Tomcat.addServlet(ctx, "Bug53356", new Bug53356Servlet());
    ctx.addServletMapping("", "Bug53356");

    tomcat.start();

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

    Assert.assertEquals("OK", body.toString());
}
 
Example 6
Source File: TestSwallowAbortedUploads.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private synchronized void init(int status, boolean swallow)
        throws Exception {
    if (init)
        return;

    Tomcat tomcat = getTomcatInstance();
    context = tomcat.addContext("", TEMP_DIR);
    AbortedPOSTServlet servlet = new AbortedPOSTServlet();
    servlet.setStatus(status);
    Tomcat.addServlet(context, servletName,
                      servlet);
    context.addServletMapping(URI, servletName);
    context.setSwallowAbortedUploads(swallow);

    tomcat.start();

    setPort(tomcat.getConnector().getLocalPort());

    init = true;
}
 
Example 7
Source File: TestAbstractHttp11Processor.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testChunking11NoContentLength() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    Tomcat.addServlet(ctxt, "NoContentLengthFlushingServlet",
            new NoContentLengthFlushingServlet());
    ctxt.addServletMapping("/test", "NoContentLengthFlushingServlet");

    tomcat.start();

    ByteChunk responseBody = new ByteChunk();
    Map<String,List<String>> responseHeaders =
            new HashMap<String,List<String>>();
    int rc = getUrl("http://localhost:" + getPort() + "/test", responseBody,
            responseHeaders);

    assertEquals(HttpServletResponse.SC_OK, rc);
    assertTrue(responseHeaders.containsKey("Transfer-Encoding"));
    List<String> encodings = responseHeaders.get("Transfer-Encoding");
    assertEquals(1, encodings.size());
    assertEquals("chunked", encodings.get(0));
}
 
Example 8
Source File: TestStandardContext.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testTldListener() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    File docBase = new File("test/webapp-3.0");
    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());

    // Start the context
    tomcat.start();

    // Stop the context
    ctx.stop();

    String log = TesterTldListener.getLog();
    Assert.assertTrue(log, log.contains("PASS-01"));
    Assert.assertTrue(log, log.contains("PASS-02"));
    Assert.assertFalse(log, log.contains("FAIL"));
}
 
Example 9
Source File: CookiesBaseTest.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
public static void addServlets(Tomcat tomcat) {
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Tomcat.addServlet(ctx, "invalid", new CookieServlet("na;me", "value"));
    ctx.addServletMapping("/invalid", "invalid");
    Tomcat.addServlet(ctx, "null", new CookieServlet(null, "value"));
    ctx.addServletMapping("/null", "null");
    Tomcat.addServlet(ctx, "blank", new CookieServlet("", "value"));
    ctx.addServletMapping("/blank", "blank");
    Tomcat.addServlet(ctx, "invalidFwd",
            new CookieServlet("na/me", "value"));
    ctx.addServletMapping("/invalidFwd", "invalidFwd");
    Tomcat.addServlet(ctx, "invalidStrict",
            new CookieServlet("na?me", "value"));
    ctx.addServletMapping("/invalidStrict", "invalidStrict");
    Tomcat.addServlet(ctx, "valid", new CookieServlet("name", "value"));
    ctx.addServletMapping("/valid", "valid");
    Tomcat.addServlet(ctx, "switch", new CookieServlet("name", "val?ue"));
    ctx.addServletMapping("/switch", "switch");

}
 
Example 10
Source File: TestWsPingPongMessages.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPingPongMessages() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider
            .getWebSocketContainer();

    tomcat.start();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder
                    .create().build(), new URI("ws://localhost:"
                    + getPort() + TesterEchoServer.Config.PATH_ASYNC));

    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties()
            .get("endpoint");
    tep.setLatch(latch);

    PongMessageHandler handler = new PongMessageHandler(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendPing(applicationData);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    Assert.assertArrayEquals(applicationData.array(),
            (handler.getMessages().peek()).getApplicationData().array());
}
 
Example 11
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug49567() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Bug49567Servlet servlet = new Bug49567Servlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    // Call the servlet once
    ByteChunk bc = getUrl("http://localhost:" + getPort() + "/");
    assertEquals("OK", bc.toString());

    // Give the async thread a chance to finish (but not too long)
    int counter = 0;
    while (!servlet.isDone() && counter < 10) {
        Thread.sleep(1000);
        counter++;
    }

    assertEquals("1false2true3true4true5false", servlet.getResult());

    // Check the access log
    alv.validateAccessLog(1, 200, Bug49567Servlet.THREAD_SLEEP_TIME,
            Bug49567Servlet.THREAD_SLEEP_TIME + REQUEST_TIME);
}
 
Example 12
Source File: TestWsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointNoHost() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC));
}
 
Example 13
Source File: TestAbstractAjpProcessor.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void test304WithBody() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "bug55453", new Tester304WithBodyServlet());
    ctx.addServletMapping("/", "bug55453");

    tomcat.start();

    SimpleAjpClient ajpClient = new SimpleAjpClient();
    ajpClient.setPort(getPort());
    ajpClient.connect();

    validateCpong(ajpClient.cping());

    TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
    forwardMessage.end();

    TesterAjpMessage responseHeaders =
            ajpClient.sendMessage(forwardMessage, null);

    // Expect 2 messages: headers, end
    validateResponseHeaders(responseHeaders, 304, "Not Modified");
    validateResponseEnd(ajpClient.readMessage(), true);

    // Double check the connection is still open
    validateCpong(ajpClient.cping());

    ajpClient.disconnect();
}
 
Example 14
Source File: TestPojoEndpointBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug54716() throws Exception {
    TestUtil.generateMask();
    // Set up utility classes
    Bug54716 server = new Bug54716();
    SingletonConfigurator.setInstance(server);
    ServerConfigListener.setPojoClazz(Bug54716.class);

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ServerConfigListener.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();


    tomcat.start();

    Client client = new Client();
    URI uri = new URI("ws://localhost:" + getPort() + "/");

    wsContainer.connectToServer(client, uri);

    // Server should close the connection after the exception on open.
    boolean closed = client.waitForClose(5);
    Assert.assertTrue("Server failed to close connection", closed);
}
 
Example 15
Source File: TestWebSocketFrameClient.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testConnectToBasicEndpoint() throws Exception {

    Tomcat tomcat = getTomcatInstance();
    Context ctx = tomcat.addContext(URI_PROTECTED, null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    SecurityCollection collection = new SecurityCollection();
    collection.addPatternDecoded("/");
    String utf8User = "test";
    String utf8Pass = "123\u00A3"; // pound sign

    tomcat.addUser(utf8User, utf8Pass);
    tomcat.addRole(utf8User, ROLE);

    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    ctx.addConstraint(sc);

    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("BASIC");
    ctx.setLoginConfig(lc);

    AuthenticatorBase basicAuthenticator = new org.apache.catalina.authenticator.BasicAuthenticator();
    ctx.getPipeline().addValve(basicAuthenticator);

    tomcat.start();

    ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
    clientEndpointConfig.getUserProperties().put(Constants.WS_AUTHENTICATION_USER_NAME, utf8User);
    clientEndpointConfig.getUserProperties().put(Constants.WS_AUTHENTICATION_PASSWORD, utf8Pass);

    echoTester(URI_PROTECTED, clientEndpointConfig);

}
 
Example 16
Source File: TestAbortedUpload.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void configureAndStartWebApplication() throws LifecycleException {
    Tomcat tomcat = getTomcatInstance();

    // Retain '/simple' url-pattern since it enables code re-use
    Context ctxt = tomcat.addContext("", null);
    Tomcat.addServlet(ctxt, "abort", new AbortServlet());
    ctxt.addServletMappingDecoded("/simple", "abort");

    tomcat.start();
}
 
Example 17
Source File: TestWsWebSocketContainer.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointNoHost() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC));
}
 
Example 18
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void doTestBug51197(boolean threaded, boolean customError) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    AsyncErrorServlet asyncErrorServlet =
        new AsyncErrorServlet(HttpServletResponse.SC_BAD_REQUEST, threaded);
    Wrapper wrapper =
        Tomcat.addServlet(ctx, "asyncErrorServlet", asyncErrorServlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/asyncErrorServlet", "asyncErrorServlet");

    if (customError) {
        CustomErrorServlet customErrorServlet = new CustomErrorServlet();
        Tomcat.addServlet(ctx, "customErrorServlet", customErrorServlet);
        ctx.addServletMapping("/customErrorServlet", "customErrorServlet");

        ErrorPage ep = new ErrorPage();
        ep.setLocation("/customErrorServlet");

        ctx.addErrorPage(ep);
    }

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/asyncErrorServlet");

    ByteChunk res = new ByteChunk();
    int rc = getUrl(url.toString(), res, null);

    assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);

    // SRV 10.9.2 - Handling an error is entirely the application's
    // responsibility when an error occurs on an application thread.
    // Calling sendError() followed by complete() and expecting the standard
    // error page mechanism to kick in could be viewed as handling the error
    String responseBody = res.toString();
    Assert.assertNotNull(responseBody);
    assertTrue(responseBody.length() > 0);
    if (customError) {
        assertTrue(responseBody, responseBody.contains(CustomErrorServlet.ERROR_MESSAGE));
    } else {
        assertTrue(responseBody, responseBody.contains(AsyncErrorServlet.ERROR_MESSAGE));
    }

    // Without this test may complete before access log has a chance to log
    // the request
    Thread.sleep(REQUEST_TIME);

    // Check the access log
    alv.validateAccessLog(1, HttpServletResponse.SC_BAD_REQUEST, 0,
            REQUEST_TIME);
}
 
Example 19
Source File: TestWebappClassLoaderThreadLocalMemoryLeak.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testThreadLocalLeak1() throws Exception {

    Tomcat tomcat = getTomcatInstance();
    // Need to make sure we see a leak for the right reasons
    tomcat.getServer().addLifecycleListener(
            new JreMemoryLeakPreventionListener());

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

    Tomcat.addServlet(ctx, "leakServlet1",
            "org.apache.tomcat.unittest.TesterLeakingServlet1");
    ctx.addServletMappingDecoded("/leak1", "leakServlet1");

    tomcat.start();

    Executor executor = tomcat.getConnector().getProtocolHandler().getExecutor();
    ((ThreadPoolExecutor) executor).setThreadRenewalDelay(-1);

    // Configure logging filter to check leak message appears
    TesterLogValidationFilter f = TesterLogValidationFilter.add(null,
            "The web application [ROOT] created a ThreadLocal with key of", null,
            "org.apache.catalina.loader.WebappClassLoaderBase");

    // Need to force loading of all web application classes via the web
    // application class loader
    loadClass("TesterCounter",
            (WebappClassLoaderBase) ctx.getLoader().getClassLoader());
    loadClass("TesterLeakingServlet1",
            (WebappClassLoaderBase) ctx.getLoader().getClassLoader());

    // This will trigger the ThreadLocal creation
    int rc = getUrl("http://localhost:" + getPort() + "/leak1",
            new ByteChunk(), null);

    // Make sure request is OK
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    // Destroy the context
    ctx.stop();
    tomcat.getHost().removeChild(ctx);
    ctx = null;

    // Make sure we have a memory leak
    String[] leaks = ((StandardHost) tomcat.getHost())
            .findReloadedContextMemoryLeaks();
    Assert.assertNotNull(leaks);
    Assert.assertTrue(leaks.length > 0);

    // Make sure the message was logged
    Assert.assertEquals(1, f.getMessageCount());
}
 
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();
}