org.apache.catalina.Context.addServletMapping()

Here are the examples of the java api org.apache.catalina.Context.addServletMapping() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

152 Examples 7

18 Source : TestWebSocketFrameClient.java
with Apache License 2.0
from wangyingjie

@Test
public void testConnectToRootEndpoint() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.clreplaced.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");
    Context ctx2 = tomcat.addContext("/foo", null);
    ctx2.addApplicationListener(TesterEchoServer.Config.clreplaced.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/");
}

18 Source : TestWsServerContainer.java
with Apache License 2.0
from wangyingjie

@Test
public void testBug54807() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug54807Config.clreplaced.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");
    tomcat.start();
    replacedert.replacedertEquals(LifecycleState.STARTED, ctx.getState());
}

18 Source : TestClose.java
with Apache License 2.0
from wangyingjie

private Tomcat startServer(final Clreplaced<? extends WsContextListener> configClreplaced) throws LifecycleException {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(configClreplaced.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");
    tomcat.start();
    return tomcat;
}

18 Source : TestCoyoteAdapter.java
with Apache License 2.0
from wangyingjie

@Test
public void testPathParamsRedirect() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase. Don't use java.io.tmpdir as it may not be
    // writable.
    File docBase = new File(getTemporaryDirectory(), "testCoyoteAdapter");
    addDeleteOnTearDown(docBase);
    if (!docBase.mkdirs() && !docBase.isDirectory()) {
        replacedert.fail("Failed to create: [" + docBase.toString() + "]");
    }
    // Create the folder that will trigger the redirect
    File foo = new File(docBase, "foo");
    addDeleteOnTearDown(foo);
    if (!foo.mkdirs() && !foo.isDirectory()) {
        replacedert.fail("Unable to create foo directory in docBase");
    }
    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());
    Tomcat.addServlet(ctx, "servlet", new PathParamServlet());
    ctx.addServletMapping("/", "servlet");
    tomcat.start();
    testPath("/", "none");
    testPath("/;jsessionid=1234", "1234");
    testPath("/foo;jsessionid=1234", "1234");
    testPath("/foo;jsessionid=1234;dummy", "1234");
    testPath("/foo;jsessionid=1234;dummy=5678", "1234");
    testPath("/foo;jsessionid=1234;=5678", "1234");
    testPath("/foo;jsessionid=1234/bar", "1234");
}

17 Source : TestAbstractHttp11Processor.java
with Apache License 2.0
from wangyingjie

@Test
public void testResponseWithErrorChunked() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctxt = tomcat.addContext("", null);
    // Add protected servlet
    Tomcat.addServlet(ctxt, "ChunkedResponseWithErrorServlet", new ResponseWithErrorServlet(true));
    ctxt.addServletMapping("/*", "ChunkedResponseWithErrorServlet");
    tomcat.start();
    String request = "GET /anything HTTP/1.1" + SimpleHttpClient.CRLF + "Host: any" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF;
    Client client = new Client(tomcat.getConnector().getLocalPort());
    client.setRequest(new String[] { request });
    client.connect();
    client.processRequest();
    // Expected response is a 200 response followed by an incomplete chunked
    // body.
    replacedertTrue(client.isResponse200());
    // There should not be an end chunk
    replacedertFalse(client.getResponseBody().endsWith("0"));
    // The last portion of text should be there
    replacedertTrue(client.getResponseBody().endsWith("line03"));
}

17 Source : TestAbstractHttp11Processor.java
with Apache License 2.0
from wangyingjie

@Test
public void testPipelining() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctxt = tomcat.addContext("", null);
    // Add protected servlet
    Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet());
    ctxt.addServletMapping("/foo", "TesterServlet");
    tomcat.start();
    String requestPart1 = "GET /foo HTTP/1.1" + SimpleHttpClient.CRLF;
    String requestPart2 = "Host: any" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF;
    final Client client = new Client(tomcat.getConnector().getLocalPort());
    client.setRequest(new String[] { requestPart1, requestPart2 });
    client.setRequestPause(1000);
    client.setUseContentLength(true);
    client.connect();
    Runnable send = new Runnable() {

        @Override
        public void run() {
            try {
                client.sendRequest();
                client.sendRequest();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    };
    Thread t = new Thread(send);
    t.start();
    // Sleep for 1500 ms which should mean the all of request 1 has been
    // sent and half of request 2
    Thread.sleep(1500);
    // Now read the first response
    client.readResponse(true);
    replacedertFalse(client.isResponse50x());
    replacedertTrue(client.isResponse200());
    replacedertEquals("OK", client.getResponseBody());
    // Read the second response. No need to sleep, read will block until
    // there is data to process
    client.readResponse(true);
    replacedertFalse(client.isResponse50x());
    replacedertTrue(client.isResponse200());
    replacedertEquals("OK", client.getResponseBody());
}

17 Source : TestCoyoteAdapter.java
with Apache License 2.0
from wangyingjie

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);
    replacedert.replacedertEquals(HttpServletResponse.SC_OK, rc);
    replacedert.replacedertEquals(expectedPathInfo, servlet.getPathInfo());
}

17 Source : ConverterApplication.java
with Apache License 2.0
from InteractiveAdvertisingBureau

private static void registerServletAndMapping(Context ctx) {
    Tomcat.addServlet(ctx, "converter", new ConverterServlet()).setLoadOnStartup(1);
    ctx.addServletMapping("/*", "converter");
}

16 Source : TestMapperWebapps.java
with Apache License 2.0
from wangyingjie

@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());
    replacedert.replacedertEquals("OK", body.toString());
}

16 Source : TestWebSocket.java
with Apache License 2.0
from wangyingjie

@Test
public void testNoUpgrade() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(new ApplicationListener(TesterEchoServer.Config.clreplaced.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("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 error response
    // No upgrade means it is not treated an as upgrade request so a 404 is
    // generated when the request reaches the Default Servlet.s
    String responseLine = client.reader.readLine();
    replacedertTrue(responseLine.startsWith("HTTP/1.1 404"));
    // Finished with the socket
    client.close();
}

16 Source : TestWebSocket.java
with Apache License 2.0
from wangyingjie

@Test
public void testNoConnection() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(new ApplicationListener(TesterEchoServer.Config.clreplaced.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("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 error response
    String responseLine = client.reader.readLine();
    replacedertTrue(responseLine.startsWith("HTTP/1.1 400"));
    // Finished with the socket
    client.close();
}

16 Source : TestWebSocket.java
with Apache License 2.0
from wangyingjie

@Test
public void testSimple() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(new ApplicationListener(TesterEchoServer.Config.clreplaced.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: keep-alive, 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();
    replacedertTrue(responseLine.startsWith("HTTP/1.1 101"));
    // Swallow the headers
    String responseHeaderLine = client.reader.readLine();
    while (!responseHeaderLine.equals("")) {
        responseHeaderLine = client.reader.readLine();
    }
    // Now we can do WebSocket
    client.sendMessage("foo", false);
    client.sendMessage("foo", true);
    replacedertEquals("foofoo", client.readMessage());
    // Finished with the socket
    client.close();
}

16 Source : TestPersistentManagerIntegration.java
with Apache License 2.0
from wangyingjie

@Test
public void backsUpOnce_56698() throws IOException, LifecycleException, InterruptedException {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.setDistributable(true);
    Tomcat.addServlet(ctx, "DummyServlet", new DummyServlet());
    ctx.addServletMapping("/dummy", "DummyServlet");
    PersistentManager manager = new PersistentManager();
    TesterStore store = new TesterStore();
    manager.setStore(store);
    manager.setMaxIdleBackup(0);
    ctx.setManager(manager);
    tomcat.start();
    String sessionId = getUrl("http://localhost:" + getPort() + "/dummy").toString();
    // Note: PersistenceManager.findSession() silently updates
    // session.lastAccessedTime, so call it only once before other work.
    Session session = manager.findSession(sessionId);
    // Wait until request processing ends, as Request.recycle() updates
    // session.lastAccessedTime via session.endAccess().
    waitWhileSessionIsActive((StandardSession) session);
    long lastAccessedTime = session.getLastAccessedTimeInternal();
    // Session should be idle at least for 0 second (maxIdleBackup)
    // to be eligible for persistence, thus no need to wait.
    // Waiting a bit, to catch changes in last accessed time of a session
    waitForClockUpdate();
    manager.processPersistenceChecks();
    replacedert.replacedertEquals(Arrays.asList(sessionId), store.getSavedIds());
    replacedert.replacedertEquals(lastAccessedTime, session.getLastAccessedTimeInternal());
    // session was not accessed, so no save will be performed
    waitForClockUpdate();
    manager.processPersistenceChecks();
    replacedert.replacedertEquals(Arrays.asList(sessionId), store.getSavedIds());
    replacedert.replacedertEquals(lastAccessedTime, session.getLastAccessedTimeInternal());
    // access session
    session.access();
    session.endAccess();
    // session was accessed, so it will be saved once again
    manager.processPersistenceChecks();
    replacedert.replacedertEquals(Arrays.asList(sessionId, sessionId), store.getSavedIds());
    // session was not accessed, so once again no save will happen
    manager.processPersistenceChecks();
    replacedert.replacedertEquals(Arrays.asList(sessionId, sessionId), store.getSavedIds());
}

16 Source : TestRequest.java
with Apache License 2.0
from wangyingjie

private void doBug56501(String deployPath, String requestPath, String expected) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext(deployPath, null);
    Tomcat.addServlet(ctx, "servlet", new Bug56501Servelet());
    ctx.addServletMapping("/*", "servlet");
    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + requestPath);
    String resultPath = res.toString();
    if (resultPath == null) {
        resultPath = "";
    }
    replacedertEquals(expected, resultPath);
}

16 Source : TestRequest.java
with Apache License 2.0
from wangyingjie

@Test
public void testBug49424NoChunking() 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() + "/");
    InputStream is = conn.getInputStream();
    replacedertNotNull(is);
}

16 Source : TestRequest.java
with Apache License 2.0
from wangyingjie

/**
 * Test case for
 * <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=38113">bug
 * 38118</a>.
 */
@Test
public void testBug38113() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    // Add the Servlet
    Tomcat.addServlet(ctx, "servlet", new EchoQueryStringServlet());
    ctx.addServletMapping("/", "servlet");
    tomcat.start();
    // No query string
    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    replacedertEquals("QueryString=null", res.toString());
    // Query string
    res = getUrl("http://localhost:" + getPort() + "/?a=b");
    replacedertEquals("QueryString=a=b", res.toString());
    // Empty string
    res = getUrl("http://localhost:" + getPort() + "/?");
    replacedertEquals("QueryString=", res.toString());
}

16 Source : TestCoyoteAdapter.java
with Apache License 2.0
from wangyingjie

private void pathParamTest(String path, String expected) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "servlet", new PathParamServlet());
    ctx.addServletMapping("/", "servlet");
    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + path);
    replacedert.replacedertEquals(expected, res.toString());
}

16 Source : TestCoyoteAdapter.java
with Apache License 2.0
from wangyingjie

private void pathParamExtenionTest(String path, String expected) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("/testapp", null);
    Tomcat.addServlet(ctx, "servlet", new PathParamServlet());
    ctx.addServletMapping("*.txt", "servlet");
    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + path);
    replacedert.replacedertEquals(expected, res.toString());
}

16 Source : TestPersistentManager.java
with Apache License 2.0
from tryandcatch

@Test
public void backsUpOnce_56698() throws IOException, LifecycleException, InterruptedException {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "DummyServlet", new DummyServlet());
    ctx.addServletMapping("/dummy", "DummyServlet");
    PersistentManager manager = new PersistentManager();
    DummyStore store = new DummyStore();
    manager.setStore(store);
    manager.setMaxIdleBackup(0);
    manager.setDistributable(true);
    ctx.setManager(manager);
    tomcat.start();
    String sessionId = getUrl("http://localhost:" + getPort() + "/dummy").toString();
    // Note: PersistenceManager.findSession() silently updates
    // session.lastAccessedTime, so call it only once before other work.
    Session session = manager.findSession(sessionId);
    // Wait until request processing ends, as Request.recycle() updates
    // session.lastAccessedTime via session.endAccess().
    waitWhileSessionIsActive((StandardSession) session);
    long lastAccessedTime = session.getLastAccessedTimeInternal();
    // Session should be idle at least for 0 second (maxIdleBackup)
    // to be eligible for persistence, thus no need to wait.
    // Waiting a bit, to catch changes in last accessed time of a session
    waitForClockUpdate();
    manager.processPersistenceChecks();
    replacedert.replacedertEquals(Arrays.asList(sessionId), store.getSavedIds());
    replacedert.replacedertEquals(lastAccessedTime, session.getLastAccessedTimeInternal());
    // session was not accessed, so no save will be performed
    waitForClockUpdate();
    manager.processPersistenceChecks();
    replacedert.replacedertEquals(Arrays.asList(sessionId), store.getSavedIds());
    replacedert.replacedertEquals(lastAccessedTime, session.getLastAccessedTimeInternal());
    // access session
    session.access();
    session.endAccess();
    // session was accessed, so it will be saved once again
    manager.processPersistenceChecks();
    replacedert.replacedertEquals(Arrays.asList(sessionId, sessionId), store.getSavedIds());
    // session was not accessed, so once again no save will happen
    manager.processPersistenceChecks();
    replacedert.replacedertEquals(Arrays.asList(sessionId, sessionId), store.getSavedIds());
}

15 Source : TestBug49158.java
with Apache License 2.0
from wangyingjie

public static void addServlets(Tomcat tomcat) {
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, path, new TestBug49158Servlet());
    ctx.addServletMapping("/" + path, path);
}

15 Source : CookiesBaseTest.java
with Apache License 2.0
from wangyingjie

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");
}

15 Source : TestTomcatClassLoader.java
with Apache License 2.0
from wangyingjie

@Test
public void testDefaultClreplacedLoader() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "ClreplacedLoaderReport", new ClreplacedLoaderReport(null));
    ctx.addServletMapping("/", "ClreplacedLoaderReport");
    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    replacedertEquals("WEBAPP,SYSTEM,OTHER,", res.toString());
}

15 Source : TestTomcatClassLoader.java
with Apache License 2.0
from wangyingjie

@Test
public void testNonDefaultClreplacedLoader() throws Exception {
    ClreplacedLoader cl = new URLClreplacedLoader(new URL[0], Thread.currentThread().getContextClreplacedLoader());
    Thread.currentThread().setContextClreplacedLoader(cl);
    Tomcat tomcat = getTomcatInstance();
    tomcat.getServer().setParentClreplacedLoader(cl);
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "ClreplacedLoaderReport", new ClreplacedLoaderReport(cl));
    ctx.addServletMapping("/", "ClreplacedLoaderReport");
    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    replacedertEquals("WEBAPP,CUSTOM,SYSTEM,OTHER,", res.toString());
}

15 Source : TestTomcat.java
with Apache License 2.0
from wangyingjie

/**
 * Start tomcat with a single context and one
 * servlet - all programmatic, no server.xml or
 * web.xml used.
 *
 * @throws Exception
 */
@Test
public void testProgrammatic() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    // You can customize the context by calling
    // its API
    Tomcat.addServlet(ctx, "myServlet", new HelloWorld());
    ctx.addServletMapping("/", "myServlet");
    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    replacedertEquals("Hello world", res.toString());
}

15 Source : TestTomcat.java
with Apache License 2.0
from wangyingjie

@Test
public void testBug53301() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    InitCount initCount = new InitCount();
    Tomcat.addServlet(ctx, "initCount", initCount);
    ctx.addServletMapping("/", "initCount");
    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    replacedertEquals("OK", res.toString());
    replacedertEquals(1, initCount.getCallCount());
}

15 Source : TestTomcat.java
with Apache License 2.0
from wangyingjie

@Test
public void testSession() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    // You can customize the context by calling
    // its API
    Tomcat.addServlet(ctx, "myServlet", new HelloWorldSession());
    ctx.addServletMapping("/", "myServlet");
    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    replacedertEquals("Hello world", res.toString());
}

15 Source : TestContextConfig.java
with Apache License 2.0
from wangyingjie

@Test
public void testBug54448and54450() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp-3.0-fragments");
    Context context = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
    Tomcat.addServlet(context, "TestServlet", "org.apache.catalina.startup.TesterServletWithAnnotations");
    context.addServletMapping("/testServlet", "TestServlet");
    tomcat.enableNaming();
    tomcat.start();
    replacedertPageContains("/test/testServlet", "envEntry1: 1 envEntry2: 2 envEntry3: 33 envEntry4: 4 envEntry5: 55 envEntry6: 66");
}

15 Source : TestContextConfig.java
with Apache License 2.0
from wangyingjie

@Test
public void testBug54379() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp-3.0-fragments");
    Context context = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
    Tomcat.addServlet(context, "TestServlet", "org.apache.catalina.startup.TesterServletWithLifeCycleMethods");
    context.addServletMapping("/testServlet", "TestServlet");
    tomcat.enableNaming();
    tomcat.start();
    replacedertPageContains("/test/testServlet", "postConstruct1()");
}

15 Source : TestRequest.java
with Apache License 2.0
from wangyingjie

@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();
    replacedertNotNull(is);
}

15 Source : TestRequest.java
with Apache License 2.0
from wangyingjie

@Test
public void testBug54984() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    root.setAllowCasualMultipartParsing(true);
    Tomcat.addServlet(root, "Bug54984", new Bug54984Servlet());
    root.addServletMapping("/", "Bug54984");
    tomcat.start();
    HttpURLConnection conn = getConnection("http://localhost:" + getPort() + "/parseParametersBeforeParseParts");
    prepareRequestBug54984(conn);
    checkResponseBug54984(conn);
    conn.disconnect();
    conn = getConnection("http://localhost:" + getPort() + "/");
    prepareRequestBug54984(conn);
    checkResponseBug54984(conn);
    conn.disconnect();
}

15 Source : TestCoyoteAdapter.java
with Apache License 2.0
from wangyingjie

@Test
public void testBug54928() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    AsyncServlet servlet = new AsyncServlet();
    Wrapper w = Tomcat.addServlet(ctx, "async", servlet);
    w.setAsyncSupported(true);
    ctx.addServletMapping("/async", "async");
    tomcat.start();
    SimpleHttpClient client = new SimpleHttpClient() {

        @Override
        public boolean isResponseBodyOK() {
            return true;
        }
    };
    String request = "GET /async HTTP/1.1" + SimpleHttpClient.CRLF + "Host: a" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF;
    client.setPort(getPort());
    client.setRequest(new String[] { request });
    client.connect();
    client.sendRequest();
    for (int i = 0; i < 10; i++) {
        String line = client.readLine();
        if (line != null && line.length() > 20) {
            log.info(line.subSequence(0, 20) + "...");
        }
    }
    client.disconnect();
    // Wait for server thread to stop
    Thread t = servlet.getThread();
    long startTime = System.nanoTime();
    t.join(5000);
    long endTime = System.nanoTime();
    log.info("Waited for servlet thread to stop for " + (endTime - startTime) / 1000000 + " ms");
    replacedert.replacedertTrue(servlet.isCompleted());
}

15 Source : TestSSOnonLoginAndBasicAuthenticator.java
with Apache License 2.0
from wangyingjie

private void setUpLogin() throws Exception {
    // No file system docBase required
    basicContext = tomcat.addContext(CONTEXT_PATH_LOGIN, null);
    basicContext.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS);
    // Add protected servlet to the context
    Tomcat.addServlet(basicContext, "TesterServlet3", new TesterServletEncodeUrl());
    basicContext.addServletMapping(URI_PROTECTED, "TesterServlet3");
    SecurityCollection collection = new SecurityCollection();
    collection.addPattern(URI_PROTECTED);
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    basicContext.addConstraint(sc);
    // Add unprotected servlet to the context
    Tomcat.addServlet(basicContext, "TesterServlet4", new TesterServletEncodeUrl());
    basicContext.addServletMapping(URI_PUBLIC, "TesterServlet4");
    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);
    basicContext.addConstraint(sc2);
    // Configure the authenticator and inherit the Realm from Engine
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("BASIC");
    basicContext.setLoginConfig(lc);
    AuthenticatorBase basicAuthenticator = new BasicAuthenticator();
    basicContext.getPipeline().addValve(basicAuthenticator);
}

15 Source : TestSSOnonLoginAndBasicAuthenticator.java
with Apache License 2.0
from wangyingjie

private void setUpNonLogin() throws Exception {
    // No file system docBase required
    nonloginContext = tomcat.addContext(CONTEXT_PATH_NOLOGIN, null);
    nonloginContext.setSessionTimeout(LONG_SESSION_TIMEOUT_MINS);
    // Add protected servlet to the context
    Tomcat.addServlet(nonloginContext, "TesterServlet1", new TesterServletEncodeUrl());
    nonloginContext.addServletMapping(URI_PROTECTED, "TesterServlet1");
    SecurityCollection collection1 = new SecurityCollection();
    collection1.addPattern(URI_PROTECTED);
    SecurityConstraint sc1 = new SecurityConstraint();
    sc1.addAuthRole(ROLE);
    sc1.addCollection(collection1);
    nonloginContext.addConstraint(sc1);
    // Add unprotected servlet to the context
    Tomcat.addServlet(nonloginContext, "TesterServlet2", new TesterServletEncodeUrl());
    nonloginContext.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);
    nonloginContext.addConstraint(sc2);
    // Configure the authenticator and inherit the Realm from Engine
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("NONE");
    nonloginContext.setLoginConfig(lc);
    AuthenticatorBase nonloginAuthenticator = new NonLoginAuthenticator();
    nonloginContext.getPipeline().addValve(nonloginAuthenticator);
}

15 Source : TestNonLoginAndBasicAuthenticator.java
with Apache License 2.0
from wangyingjie

private void setUpLogin() throws Exception {
    // No file system docBase required
    basicContext = tomcat.addContext(CONTEXT_PATH_LOGIN, null);
    basicContext.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS);
    // Add protected servlet to the context
    Tomcat.addServlet(basicContext, "TesterServlet3", new TesterServlet());
    basicContext.addServletMapping(URI_PROTECTED, "TesterServlet3");
    SecurityCollection collection = new SecurityCollection();
    collection.addPattern(URI_PROTECTED);
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    basicContext.addConstraint(sc);
    // Add unprotected servlet to the context
    Tomcat.addServlet(basicContext, "TesterServlet4", new TesterServlet());
    basicContext.addServletMapping(URI_PUBLIC, "TesterServlet4");
    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);
    basicContext.addConstraint(sc2);
    // Configure the authenticator and inherit the Realm from Engine
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("BASIC");
    basicContext.setLoginConfig(lc);
    AuthenticatorBase basicAuthenticator = new BasicAuthenticator();
    basicContext.getPipeline().addValve(basicAuthenticator);
}

15 Source : TestNonLoginAndBasicAuthenticator.java
with Apache License 2.0
from wangyingjie

private void setUpNonLogin() throws Exception {
    // No file system docBase required
    nonloginContext = tomcat.addContext(CONTEXT_PATH_NOLOGIN, null);
    nonloginContext.setSessionTimeout(LONG_SESSION_TIMEOUT_MINS);
    // Add protected servlet to the context
    Tomcat.addServlet(nonloginContext, "TesterServlet1", new TesterServlet());
    nonloginContext.addServletMapping(URI_PROTECTED, "TesterServlet1");
    SecurityCollection collection1 = new SecurityCollection();
    collection1.addPattern(URI_PROTECTED);
    SecurityConstraint sc1 = new SecurityConstraint();
    sc1.addAuthRole(ROLE);
    sc1.addCollection(collection1);
    nonloginContext.addConstraint(sc1);
    // Add unprotected servlet to the context
    Tomcat.addServlet(nonloginContext, "TesterServlet2", new TesterServlet());
    nonloginContext.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);
    nonloginContext.addConstraint(sc2);
    // Configure the authenticator and inherit the Realm from Engine
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("NONE");
    nonloginContext.setLoginConfig(lc);
    AuthenticatorBase nonloginAuthenticator = new NonLoginAuthenticator();
    nonloginContext.getPipeline().addValve(nonloginAuthenticator);
}

15 Source : ApplicationServletRegistration.java
with Apache License 2.0
from wangyingjie

@Override
public Set<String> addMapping(String... urlPatterns) {
    if (urlPatterns == null) {
        return Collections.emptySet();
    }
    Set<String> conflicts = new HashSet<String>();
    for (String urlPattern : urlPatterns) {
        String wrapperName = context.findServletMapping(urlPattern);
        if (wrapperName != null) {
            Wrapper wrapper = (Wrapper) context.findChild(wrapperName);
            if (wrapper.isOverridable()) {
                // Some Wrappers (from global and host web.xml) may be
                // overridden rather than generating a conflict
                context.removeServletMapping(urlPattern);
            } else {
                conflicts.add(urlPattern);
            }
        }
    }
    if (!conflicts.isEmpty()) {
        return conflicts;
    }
    for (String urlPattern : urlPatterns) {
        context.addServletMapping(urlPattern, wrapper.getName());
    }
    return Collections.emptySet();
}

14 Source : TestEncodingDecoding.java
with Apache License 2.0
from wangyingjie

@Test
public void testUnsupportedObject() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ProgramaticServerEndpointConfig.clreplaced.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);
        replacedert.fail("No exception thrown ");
    } catch (EncodeException e) {
    // Expected
    } catch (Throwable t) {
        replacedert.fail("Wrong exception type");
    } finally {
        session.close();
    }
}

14 Source : TestMimeHeaders.java
with Apache License 2.0
from wangyingjie

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);
}

14 Source : TestAbstractHttp11Processor.java
with Apache License 2.0
from wangyingjie

/*
     * Partially read chunked input is not swallowed when it is read during
     * async processing.
     */
@Test
public void testBug57621() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context root = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    Wrapper w = Tomcat.addServlet(root, "Bug57621", new Bug57621Servlet());
    w.setAsyncSupported(true);
    root.addServletMapping("/test", "Bug57621");
    tomcat.start();
    Bug57621Client client = new Bug57621Client();
    client.setPort(tomcat.getConnector().getLocalPort());
    client.setUseContentLength(true);
    client.connect();
    client.doRequest();
    replacedertTrue(client.getResponseLine(), client.isResponse200());
    replacedertTrue(client.isResponseBodyOK());
    // Do the request again to ensure that the remaining body was swallowed
    client.resetResponse();
    client.processRequest();
    replacedertTrue(client.isResponse200());
    replacedertTrue(client.isResponseBodyOK());
    client.disconnect();
}

14 Source : TestChunkedInputFilter.java
with Apache License 2.0
from wangyingjie

/**
 * @param expectPreplaced
 *            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 expectPreplaced, 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(expectPreplaced, 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 (expectPreplaced) {
        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 (expectPreplaced) {
        if (expectReadWholeBody) {
            replacedertNull(processException);
        }
        if (processException == null) {
            replacedertTrue(client.getResponseLine(), client.isResponse200());
            replacedertEquals(String.valueOf(expectReadCount), client.getResponseBody());
        }
        replacedertEquals(expectReadCount, servlet.getCountRead());
    } else {
        if (processException == null) {
            replacedertTrue(client.getResponseLine(), client.isResponse500());
        }
        replacedertEquals(0, servlet.getCountRead());
        replacedertTrue(servlet.getExceptionDuringRead());
    }
}

14 Source : TestWebSocket.java
with Apache License 2.0
from wangyingjie

@Test
public void testDetectWrongVersion() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(new ApplicationListener(TesterEchoServer.Config.clreplaced.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: 8" + 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();
    replacedertTrue(responseLine.startsWith("HTTP/1.1 426"));
    List<String> headerlines = new ArrayList<String>();
    String responseHeaderLine = client.reader.readLine();
    while (!responseHeaderLine.equals("")) {
        headerlines.add(responseHeaderLine);
        responseHeaderLine = client.reader.readLine();
    }
    replacedertTrue(headerlines.contains("Sec-WebSocket-Version: 13"));
    // Finished with the socket
    client.close();
}

14 Source : TestSSOnonLoginAndDigestAuthenticator.java
with Apache License 2.0
from wangyingjie

private void setUpDigest(Tomcat tomcat) throws Exception {
    // No file system docBase required
    Context ctxt = tomcat.addContext(CONTEXT_PATH_DIGEST, null);
    ctxt.setSessionTimeout(SHORT_TIMEOUT_SECS);
    // Add protected servlet
    Tomcat.addServlet(ctxt, "TesterServlet3", new TesterServlet());
    ctxt.addServletMapping(URI_PROTECTED, "TesterServlet3");
    SecurityCollection collection = new SecurityCollection();
    collection.addPattern(URI_PROTECTED);
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    ctxt.addConstraint(sc);
    // Configure the appropriate authenticator
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("DIGEST");
    ctxt.setLoginConfig(lc);
    ctxt.getPipeline().addValve(new DigestAuthenticator());
}

14 Source : TestSSOnonLoginAndDigestAuthenticator.java
with Apache License 2.0
from wangyingjie

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());
}

14 Source : Tomcat.java
with Apache License 2.0
from wangyingjie

/**
 * Static version of {@link #initWebappDefaults(String)}
 * @param ctx   The context to set the defaults for
 */
public static void initWebappDefaults(Context ctx) {
    // Default servlet
    Wrapper servlet = addServlet(ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
    servlet.setLoadOnStartup(1);
    servlet.setOverridable(true);
    // JSP servlet (by clreplaced name - to avoid loading all deps)
    servlet = addServlet(ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
    servlet.addInitParameter("fork", "false");
    servlet.setLoadOnStartup(3);
    servlet.setOverridable(true);
    // Servlet mappings
    ctx.addServletMapping("/", "default");
    ctx.addServletMapping("*.jsp", "jsp");
    ctx.addServletMapping("*.jspx", "jsp");
    // Sessions
    ctx.setSessionTimeout(30);
    // MIME mappings
    for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length; ) {
        ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++], DEFAULT_MIME_MAPPINGS[i++]);
    }
    // Welcome files
    ctx.addWelcomeFile("index.html");
    ctx.addWelcomeFile("index.htm");
    ctx.addWelcomeFile("index.jsp");
}

14 Source : 537.java
with MIT License
from masud-technope

@Test
public void testUnsupportedObject() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ProgramaticServerEndpointConfig.clreplaced.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);
        replacedert.fail("No exception thrown ");
    } catch (EncodeException e) {
    } catch (Throwable t) {
        replacedert.fail("Wrong exception type");
    } finally {
        session.close();
    }
}

14 Source : 280.java
with MIT License
from masud-technope

/**
 * @param expectPreplaced
 *            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 expectPreplaced, 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(expectPreplaced, 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 (expectPreplaced) {
        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) {
        processException = e;
    }
    if (expectPreplaced) {
        if (expectReadWholeBody) {
            replacedertNull(processException);
        }
        if (processException == null) {
            replacedertTrue(client.getResponseLine(), client.isResponse200());
            replacedertEquals(String.valueOf(expectReadCount), client.getResponseBody());
        }
        replacedertEquals(expectReadCount, servlet.getCountRead());
    } else {
        if (processException == null) {
            replacedertTrue(client.getResponseLine(), client.isResponse500());
        }
        replacedertEquals(0, servlet.getCountRead());
        replacedertTrue(servlet.getExceptionDuringRead());
    }
}

13 Source : TestWsWebSocketContainer.java
with Apache License 2.0
from wangyingjie

@Test
public void testSessionExpirySession() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.clreplaced.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");
    tomcat.start();
    // Need access to implementation methods for configuring unit tests
    WsWebSocketContainer wsContainer = (WsWebSocketContainer) ContainerProvider.getWebSocketContainer();
    // 5 second timeout
    wsContainer.setDefaultMaxSessionIdleTimeout(5000);
    wsContainer.setProcessPeriod(1);
    EndpointA endpointA = new EndpointA();
    Session s1a = connectToEchoServer(wsContainer, endpointA, TesterEchoServer.Config.PATH_BASIC);
    s1a.setMaxIdleTimeout(3000);
    Session s2a = connectToEchoServer(wsContainer, endpointA, TesterEchoServer.Config.PATH_BASIC);
    s2a.setMaxIdleTimeout(6000);
    Session s3a = connectToEchoServer(wsContainer, endpointA, TesterEchoServer.Config.PATH_BASIC);
    s3a.setMaxIdleTimeout(9000);
    // Check all three sessions are open
    Set<Session> setA = s3a.getOpenSessions();
    int expected = 3;
    while (expected > 0) {
        replacedert.replacedertEquals(expected, getOpenCount(setA));
        int count = 0;
        while (getOpenCount(setA) == expected && count < 50) {
            count++;
            Thread.sleep(100);
        }
        expected--;
    }
    replacedert.replacedertEquals(0, getOpenCount(setA));
}

13 Source : TestEncodingDecoding.java
with Apache License 2.0
from wangyingjie

@Test
public void testProgrammaticEndPoints() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ProgramaticServerEndpointConfig.clreplaced.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);
    MsgString msg1 = new MsgString();
    msg1.setData(MESSAGE_ONE);
    session.getBasicRemote().sendObject(msg1);
    // Should not take very long
    int i = 0;
    while (i < 20) {
        if (MsgStringMessageHandler.received.size() > 0 && client.received.size() > 0) {
            break;
        }
        Thread.sleep(100);
        i++;
    }
    // Check messages were received
    replacedert.replacedertEquals(1, MsgStringMessageHandler.received.size());
    replacedert.replacedertEquals(1, client.received.size());
    // Check correct messages were received
    replacedert.replacedertEquals(MESSAGE_ONE, ((MsgString) MsgStringMessageHandler.received.peek()).getData());
    replacedert.replacedertEquals(MESSAGE_ONE, new String(((MsgByte) client.received.peek()).getData()));
    session.close();
}

13 Source : TestAbstractHttp11Processor.java
with Apache License 2.0
from wangyingjie

private void doTestNon2xxResponseAndExpectation(boolean useExpectation) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "echo", new EchoBodyServlet());
    ctx.addServletMapping("/echo", "echo");
    SecurityCollection collection = new SecurityCollection("All", "");
    collection.addPattern("/*");
    SecurityConstraint constraint = new SecurityConstraint();
    constraint.addAuthRole("Any");
    constraint.addCollection(collection);
    ctx.addConstraint(constraint);
    tomcat.start();
    Non2xxResponseClient client = new Non2xxResponseClient(useExpectation);
    client.setPort(getPort());
    client.doResourceRequest("GET http://localhost:" + getPort() + "/echo HTTP/1.1", "HelloWorld");
    replacedert.replacedertTrue(client.isResponse403());
    replacedert.replacedertTrue(client.checkConnectionHeader());
}

13 Source : TestAbstractHttp11Processor.java
with Apache License 2.0
from wangyingjie

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);
    replacedertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
    if (responseBody.getLength() > 0) {
        // It will be >0 if the standard error page handlign has been
        // triggered
        replacedertFalse(responseBody.toString().contains("FAIL"));
    }
}

See More Examples