Java Code Examples for org.apache.catalina.Context#addServletMapping()

The following examples show how to use org.apache.catalina.Context#addServletMapping() . 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: TestMimeHeaders.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void setupHeadersTest(Tomcat tomcat) {
    Context ctx = tomcat.addContext("", getTemporaryDirectory()
            .getAbsolutePath());
    Tomcat.addServlet(ctx, "servlet", new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override
        public void service(ServletRequest req, ServletResponse res)
                throws ServletException, IOException {
            res.setContentType("text/plain; charset=ISO-8859-1");
            res.getWriter().write("OK");
        }
    });
    ctx.addServletMapping("/", "servlet");

    alv = new HeaderCountLogValve();
    tomcat.getHost().getPipeline().addValve(alv);
}
 
Example 2
Source File: TestAbstractHttp11Processor.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void doTestBug53677(boolean flush) throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

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

    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_INTERNAL_SERVER_ERROR, rc);
    if (responseBody.getLength() > 0) {
        // It will be >0 if the standard error page handlign has been
        // triggered
        assertFalse(responseBody.toString().contains("FAIL"));
    }
}
 
Example 3
Source File: TestCoyoteAdapter.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void doTestUriDecoding(String path, String encoding,
        String expectedPathInfo) throws Exception{

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    tomcat.getConnector().setURIEncoding(encoding);

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

    PathInfoServlet servlet = new PathInfoServlet();
    Tomcat.addServlet(ctx, "servlet", servlet);
    ctx.addServletMapping("/*", "servlet");

    tomcat.start();

    int rc = getUrl("http://localhost:" + getPort() + path,
            new ByteChunk(), null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    Assert.assertEquals(expectedPathInfo, servlet.getPathInfo());
}
 
Example 4
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 5
Source File: ServiceDispatcherTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void beforeTest(ServiceHandler serviceHandler) throws Exception {
  MetadataParser parser = new MetadataParser();
  parser.parseAnnotations(true);
  parser.useLocalCoreVocabularies(true);
  parser.implicitlyLoadCoreVocabularies(true);
  ServiceMetadata metadata = parser.buildServiceMetadata(new FileReader("src/test/resources/trippin.xml"));

  File baseDir = new File(System.getProperty("java.io.tmpdir"));
  tomcat.setBaseDir(baseDir.getAbsolutePath());
  tomcat.getHost().setAppBase(baseDir.getAbsolutePath());
  Context cxt = tomcat.addContext("/trippin", baseDir.getAbsolutePath());
  Tomcat.addServlet(cxt, "trippin", new SampleODataServlet(serviceHandler, metadata));
  cxt.addServletMapping("/*", "trippin");
  tomcat.setPort(TOMCAT_PORT);
  tomcat.start();
}
 
Example 6
Source File: TestWebSocketFrameClient.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnectToRootEndpoint() 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");
    Context ctx2 = tomcat.addContext("/foo", null);
    ctx2.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx2, "default", new DefaultServlet());
    ctx2.addServletMapping("/", "default");

    tomcat.start();

    echoTester("");
    echoTester("/");
    // FIXME: The ws client doesn't handle any response other than the upgrade,
    // which may or may not be allowed. In that case, the server will return
    // a redirect to the root of the webapp to avoid possible broken relative
    // paths.
    // echoTester("/foo");
    echoTester("/foo/");
}
 
Example 7
Source File: TestSSOnonLoginAndDigestAuthenticator.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private void setUpNonLogin(Tomcat tomcat) throws Exception {

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

        // Add protected servlet
        Tomcat.addServlet(ctxt, "TesterServlet1", new TesterServlet());
        ctxt.addServletMapping(URI_PROTECTED, "TesterServlet1");
        SecurityCollection collection1 = new SecurityCollection();
        collection1.addPattern(URI_PROTECTED);
        SecurityConstraint sc1 = new SecurityConstraint();
        sc1.addAuthRole(ROLE);
        sc1.addCollection(collection1);
        ctxt.addConstraint(sc1);

        // Add unprotected servlet
        Tomcat.addServlet(ctxt, "TesterServlet2", new TesterServlet());
        ctxt.addServletMapping(URI_PUBLIC, "TesterServlet2");
        SecurityCollection collection2 = new SecurityCollection();
        collection2.addPattern(URI_PUBLIC);
        SecurityConstraint sc2 = new SecurityConstraint();
        // do not add a role - which signals access permitted without one
        sc2.addCollection(collection2);
        ctxt.addConstraint(sc2);

        // Configure the appropriate authenticator
        LoginConfig lc = new LoginConfig();
        lc.setAuthMethod("NONE");
        ctxt.setLoginConfig(lc);
        ctxt.getPipeline().addValve(new NonLoginAuthenticator());
    }
 
Example 8
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 9
Source File: TestKeepAliveCount.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private synchronized void init() {
    if (init) return;

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "Simple", new SimpleServlet());
    root.addServletMapping("/test", "Simple");
    tomcat.getConnector().setProperty("maxKeepAliveRequests", "5");
    tomcat.getConnector().setProperty("soTimeout", "20000");
    tomcat.getConnector().setProperty("keepAliveTimeout", "50000");
    init = true;
}
 
Example 10
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncContextListenerClearing() throws Exception {
    resetTracker();

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Servlet stage1 = new DispatchingServletTracking("/stage2", true);
    Wrapper wrapper1 = Tomcat.addServlet(ctx, "stage1", stage1);
    wrapper1.setAsyncSupported(true);
    ctx.addServletMapping("/stage1", "stage1");

    Servlet stage2 = new DispatchingServletTracking("/stage3", false);
    Wrapper wrapper2 = Tomcat.addServlet(ctx, "stage2", stage2);
    wrapper2.setAsyncSupported(true);
    ctx.addServletMapping("/stage2", "stage2");

    Servlet stage3 = new NonAsyncServlet();
    Tomcat.addServlet(ctx, "stage3", stage3);
    ctx.addServletMapping("/stage3", "stage3");

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

    tomcat.start();

    getUrl("http://localhost:" + getPort()+ "/stage1");

    assertEquals("doGet-startAsync-doGet-startAsync-onStartAsync-NonAsyncServletGet-onComplete-", getTrack());

    // Check the access log
    alv.validateAccessLog(1, 200, 0, REQUEST_TIME);
}
 
Example 11
Source File: TestPojoEndpointBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnOpenPojoMethod() throws Exception {
    // Set up utility classes
    OnOpenServerEndpoint server = new OnOpenServerEndpoint();
    SingletonConfigurator.setInstance(server);
    ServerConfigListener.setPojoClazz(OnOpenServerEndpoint.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() + "/");

    Session session = wsContainer.connectToServer(client, uri);

    client.waitForClose(5);
    Assert.assertTrue(session.isOpen());
}
 
Example 12
Source File: TestWsPingPongMessages.java    From tomcatsrc 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 13
Source File: TestInternalInputBuffer.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private Exception doRequest() {

            Tomcat tomcat = getTomcatInstance();

            Context root = tomcat.addContext("", TEMP_DIR);
            Tomcat.addServlet(root, "Bug48839", new Bug48839Servlet());
            root.addServletMapping("/test", "Bug48839");

            try {
                tomcat.start();
                setPort(tomcat.getConnector().getLocalPort());

                // Open connection
                connect();

                String[] request = new String[1];
                request[0] =
                    "GET http://localhost:8080/test HTTP/1.1" + CRLF +
                    "X-Bug48839: abcd" + CRLF +
                    "\tefgh" + CRLF +
                    "Connection: close" + CRLF +
                    CRLF;

                setRequest(request);
                processRequest(); // blocks until response has been read

                // Close the connection
                disconnect();
            } catch (Exception e) {
                return e;
            }
            return null;
        }
 
Example 14
Source File: TestCookiesAllowNameOnly.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private void doRequest() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    Context root = tomcat.addContext("", TEMP_DIR);
    Tomcat.addServlet(root, "Simple", new SimpleServlet());
    root.addServletMapping("/test", "Simple");

    tomcat.start();
    // Open connection
    setPort(tomcat.getConnector().getLocalPort());
    connect();

    String[] request = new String[1];
    request[0] =
        "GET /test HTTP/1.0" + CRLF +
        "Cookie: " + COOKIE_WITH_NAME_ONLY_1 + CRLF +
        "Cookie: " + COOKIE_WITH_NAME_ONLY_2 + CRLF + CRLF;
    setRequest(request);
    processRequest(true); // blocks until response has been read
    String response = getResponseBody();

    // Close the connection
    disconnect();
    reset();
    tomcat.stop();
    // Need the extra equals since cookie 1 is just the name
    assertEquals(COOKIE_WITH_NAME_ONLY_1 + "=" +
            COOKIE_WITH_NAME_ONLY_2, response);
}
 
Example 15
Source File: TestEncodingDecoding.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsupportedObject() throws Exception{
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ProgramaticServerEndpointConfig.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() + PATH_PROGRAMMATIC_EP);
    Session session = wsContainer.connectToServer(client, uri);

    // This should fail
    Object msg1 = new Object();
    try {
        session.getBasicRemote().sendObject(msg1);
        Assert.fail("No exception thrown ");
    } catch (EncodeException e) {
        // Expected
    } catch (Throwable t) {
        Assert.fail("Wrong exception type");
    } finally {
        session.close();
    }
}
 
Example 16
Source File: TestRequest.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug49424WithChunking() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet());
    root.addServletMapping("/", "Bug37794");
    tomcat.start();

    HttpURLConnection conn = getConnection("http://localhost:" + getPort() + "/");
    conn.setChunkedStreamingMode(8 * 1024);
    InputStream is = conn.getInputStream();
    assertNotNull(is);
}
 
Example 17
Source File: TestApplicationContext.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug57190() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Context foo1 = new StandardContext();
    foo1.setName("/foo##1");
    foo1.setPath("/foo");
    foo1.setWebappVersion("1");
    foo1.setDocBase(System.getProperty("java.io.tmpdir"));
    foo1.addLifecycleListener(new FixContextListener());
    foo1.addLifecycleListener(new SetIdListener("foo1"));
    tomcat.getHost().addChild(foo1);

    Context foo2 = new StandardContext();
    foo2.setName("/foo##2");
    foo2.setPath("/foo");
    foo2.setWebappVersion("2");
    foo2.setDocBase(System.getProperty("java.io.tmpdir"));
    foo2.addLifecycleListener(new FixContextListener());
    foo2.addLifecycleListener(new SetIdListener("foo2"));
    tomcat.getHost().addChild(foo2);

    // No file system docBase required
    Context bar = tomcat.addContext("/bar", null);
    bar.addLifecycleListener(new SetIdListener("bar"));

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addLifecycleListener(new SetIdListener("ROOT"));
    ctx.setCrossContext(true);

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

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    String body = res.toString();

    Assert.assertTrue(body, body.contains("01-bar"));
    Assert.assertTrue(body, body.contains("02-foo2"));
    Assert.assertTrue(body, body.contains("03-foo1"));
    Assert.assertTrue(body, body.contains("04-foo2"));
    Assert.assertTrue(body, body.contains("05-foo2"));
    Assert.assertTrue(body, body.contains("06-ROOT"));
    Assert.assertTrue(body, body.contains("07-ROOT"));
    Assert.assertTrue(body, body.contains("08-foo2"));
    Assert.assertTrue(body, body.contains("09-ROOT"));
}
 
Example 18
Source File: TestWebSocket.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testKey() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(new ApplicationListener(
            TesterEchoServer.Config.class.getName(), false));

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

    tomcat.start();

    WebSocketClient client= new WebSocketClient(getPort());

    // Send the WebSocket handshake
    client.writer.write("GET " + TesterEchoServer.Config.PATH_BASIC + " HTTP/1.1" + CRLF);
    client.writer.write("Host: foo" + CRLF);
    client.writer.write("Upgrade: websocket" + CRLF);
    client.writer.write("Connection: upgrade" + CRLF);
    client.writer.write("Sec-WebSocket-Version: 13" + CRLF);
    client.writer.write("Sec-WebSocket-Key: TODO" + CRLF);
    client.writer.write(CRLF);
    client.writer.flush();

    // Make sure we got an upgrade response
    String responseLine = client.reader.readLine();
    assertTrue(responseLine.startsWith("HTTP/1.1 101"));

    String accept = null;
    String responseHeaderLine = client.reader.readLine();
    while (!responseHeaderLine.equals("")) {
        if(responseHeaderLine.startsWith("Sec-WebSocket-Accept: ")) {
            accept = responseHeaderLine.substring(responseHeaderLine.indexOf(':')+2);
            break;
        }
        responseHeaderLine = client.reader.readLine();
    }
    assertTrue(accept != null);
    MessageDigest sha1Helper = MessageDigest.getInstance("SHA1");
    sha1Helper.reset();
    sha1Helper.update("TODO".getBytes(B2CConverter.ISO_8859_1));
    String source = Base64.encode(sha1Helper.digest(WS_ACCEPT));
    assertEquals(source,accept);

    sha1Helper.reset();
    sha1Helper.update("TOD".getBytes(B2CConverter.ISO_8859_1));
    source = Base64.encode(sha1Helper.digest(WS_ACCEPT));
    assertFalse(source.equals(accept));
    // Finished with the socket
    client.close();
}
 
Example 19
Source File: HttpCommonsTest.java    From raml-tester with Apache License 2.0 4 votes vote down vote up
@Override
protected void init(Context ctx) {
    Tomcat.addServlet(ctx, "app", new TestServlet());
    ctx.addServletMapping("/*", "app");
}
 
Example 20
Source File: TestChunkedInputFilter.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * @param expectPass
 *            If the servlet is expected to process the request
 * @param expectReadWholeBody
 *            If the servlet is expected to fully read the body and reliably
 *            deliver a response
 * @param chunks
 *            Text of chunks
 * @param readLimit
 *            Do not read more than this many bytes
 * @param expectReadCount
 *            Expected count of read bytes
 * @throws Exception
 *             Unexpected
 */
private void doTestChunkSize(boolean expectPass,
        boolean expectReadWholeBody, String chunks, int readLimit,
        int expectReadCount) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    BodyReadServlet servlet = new BodyReadServlet(expectPass, readLimit);
    Tomcat.addServlet(ctx, "servlet", servlet);
    ctx.addServletMapping("/", "servlet");

    tomcat.start();

    String request = "POST /echo-params.jsp HTTP/1.1"
            + SimpleHttpClient.CRLF + "Host: any" + SimpleHttpClient.CRLF
            + "Transfer-encoding: chunked" + SimpleHttpClient.CRLF
            + "Content-Type: text/plain" + SimpleHttpClient.CRLF;
    if (expectPass) {
        request += "Connection: close" + SimpleHttpClient.CRLF;
    }
    request += SimpleHttpClient.CRLF + chunks + "0" + SimpleHttpClient.CRLF
            + SimpleHttpClient.CRLF;

    TrailerClient client = new TrailerClient(tomcat.getConnector()
            .getLocalPort());
    client.setRequest(new String[] { request });

    Exception processException = null;
    client.connect();
    try {
        client.processRequest();
    } catch (Exception e) {
        // Socket was probably closed before client had a chance to read
        // response
        processException = e;
    }
    if (expectPass) {
        if (expectReadWholeBody) {
            assertNull(processException);
        }
        if (processException == null) {
            assertTrue(client.getResponseLine(), client.isResponse200());
            assertEquals(String.valueOf(expectReadCount),
                    client.getResponseBody());
        }
        assertEquals(expectReadCount, servlet.getCountRead());
    } else {
        if (processException == null) {
            assertTrue(client.getResponseLine(), client.isResponse500());
        }
        assertEquals(0, servlet.getCountRead());
        assertTrue(servlet.getExceptionDuringRead());
    }
}