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

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

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    Context ctxt = tomcat.addWebapp(
            null, "/examples", appDir.getAbsolutePath());
    ctxt.addApplicationListener(WsContextListener.class.getName());

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() +
            "/examples/jsp/jsp2/el/basic-arithmetic.jsp");
    String text = res.toString();
    Assert.assertTrue(text, text.indexOf("<td>${(1==2) ? 3 : 4}</td>") > 0);
}
 
Example 2
Source File: TomcatHttpServer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void initServer() throws Exception {
	this.tomcatServer = new Tomcat();
	this.tomcatServer.setBaseDir(baseDir);
	this.tomcatServer.setHostname(getHost());
	this.tomcatServer.setPort(getPort());

	ServletHttpHandlerAdapter servlet = initServletAdapter();

	File base = new File(System.getProperty("java.io.tmpdir"));
	Context rootContext = tomcatServer.addContext(this.contextPath, base.getAbsolutePath());
	Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet).setAsyncSupported(true);
	rootContext.addServletMappingDecoded(this.servletMapping, "httpHandlerServlet");
	if (wsListener != null) {
		rootContext.addApplicationListener(wsListener.getName());
	}
}
 
Example 3
Source File: TestListener.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Check that a {@link ServletContextListener} cannot install a
 * {@link javax.servlet.ServletContainerInitializer}.
 * @throws Exception
 */
@Test
public void testServletContextListener() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    // SCL2 pretends to be in web.xml, and tries to install a
    // ServletContainerInitializer.
    context.addApplicationListener(SCL2.class.getName());
    tomcat.start();

    //check that the ServletContainerInitializer wasn't initialized.
    assertFalse(SCL3.initialized);
}
 
Example 4
Source File: TomcatHttpServer.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void initServer() throws Exception {
	this.tomcatServer = new Tomcat();
	this.tomcatServer.setBaseDir(baseDir);
	this.tomcatServer.setHostname(getHost());
	this.tomcatServer.setPort(getPort());

	ServletHttpHandlerAdapter servlet = initServletAdapter();

	File base = new File(System.getProperty("java.io.tmpdir"));
	Context rootContext = tomcatServer.addContext(this.contextPath, base.getAbsolutePath());
	Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet).setAsyncSupported(true);
	rootContext.addServletMappingDecoded(this.servletMapping, "httpHandlerServlet");
	if (wsListener != null) {
		rootContext.addApplicationListener(wsListener.getName());
	}
}
 
Example 5
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 6
Source File: HeartbeatTest.java    From TeaStore with Apache License 2.0 6 votes vote down vote up
/**
 * Setup the test by deploying an embedded tomcat and adding the rest endpoints.
 * @throws Throwable Throws uncaught throwables for test to fail.
 */
@Before
public void setup() throws Throwable {
	registryTomcat = new Tomcat();
	registryTomcat.setPort(3000);
	registryTomcat.setBaseDir(testWorkingDir);
	Context context = registryTomcat.addWebapp(CONTEXT, testWorkingDir);
	context.addApplicationListener(RegistryStartup.class.getName());
	ResourceConfig restServletConfig = new ResourceConfig();
	restServletConfig.register(RegistryREST.class);
	restServletConfig.register(Registry.class);
	ServletContainer restServlet = new ServletContainer(restServletConfig);
	registryTomcat.addServlet(CONTEXT, "restServlet", restServlet);
	context.addServletMappingDecoded("/rest/*", "restServlet");
	registryTomcat.start();
}
 
Example 7
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 8
Source File: MdwServletContainerFactory.java    From mdw with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(Context context) {
    context.addApplicationListener("org.apache.tomcat.websocket.server.WsContextListener");
    context.addErrorPage(new ErrorPage() {
        @Override
        public int getErrorCode() {
            return 404;
        }

        @Override
        public String getLocation() {
            return "/404";
        }
    });
    context.addErrorPage(new ErrorPage() {
        @Override
        public int getErrorCode() {
            return 500;
        }

        @Override
        public String getLocation() {
            return "/error";
        }
    });

    // CORS access is wide open
    FilterDef corsFilter = new FilterDef();
    corsFilter.setFilterName("CorsFilter");
    corsFilter.setFilterClass("org.apache.catalina.filters.CorsFilter");
    corsFilter.addInitParameter("cors.allowed.methods", "GET,POST,PUT,DELETE,HEAD,OPTIONS");
    corsFilter.addInitParameter("cors.allowed.headers", "Authorization,Content-Type,X-Requested-With,Accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Accept-Encoding,Accept-Language,Cache-Control,Connection,Host,Pragma,Referer,User-Agent");
    corsFilter.addInitParameter("cors.allowed.origins", "*");
    context.addFilterDef(corsFilter);
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(corsFilter.getFilterName());
    filterMap.addURLPattern("/api/*");
    filterMap.addURLPattern("/services/AppSummary");
    context.addFilterMap(filterMap);
}
 
Example 9
Source File: TestWsServerContainer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug58232() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug54807Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());

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

    try (Session session = wsContainer.connectToServer(client, uri);) {
        CountDownLatch latch = new CountDownLatch(1);
        BasicText handler = new BasicText(latch);
        session.addMessageHandler(handler);
        session.getBasicRemote().sendText("echoBasic");

        boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
        Assert.assertTrue(latchResult);

        Queue<String> messages = handler.getMessages();
        Assert.assertEquals(1, messages.size());
        for (String message : messages) {
            Assert.assertEquals("echoBasic", message);
        }
    }
}
 
Example 10
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 11
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectToServerEndpoint() 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();
    // Set this artificially small to trigger
    // https://bz.apache.org/bugzilla/show_bug.cgi?id=57054
    wsContainer.setDefaultMaxBinaryMessageBufferSize(64);
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText(MESSAGE_STRING_1);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    Assert.assertEquals(MESSAGE_STRING_1, messages.peek());

    ((WsWebSocketContainer) wsContainer).destroy();
}
 
Example 12
Source File: TestShutdown.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testShutdownBufferedMessages() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(EchoBufferedConfig.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("ws://localhost:" + getPort() + "/test"));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText("Hello");

    int count = 0;
    while (count < 10 && EchoBufferedEndpoint.messageCount.get() == 0) {
        Thread.sleep(200);
        count++;
    }
    Assert.assertNotEquals("Message not received by server",
            EchoBufferedEndpoint.messageCount.get(), 0);

    tomcat.stop();

    Assert.assertTrue("Latch expired waiting for message", latch.await(10, TimeUnit.SECONDS));
}
 
Example 13
Source File: TestEncodingDecoding.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testProgrammaticEndPoints() 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);

    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
    Assert.assertEquals(1, MsgStringMessageHandler.received.size());
    Assert.assertEquals(1, client.received.size());

    // Check correct messages were received
    Assert.assertEquals(MESSAGE_ONE,
            ((MsgString) MsgStringMessageHandler.received.peek()).getData());
    Assert.assertEquals(MESSAGE_ONE,
            new String(((MsgByte) client.received.peek()).getData()));
    session.close();
}
 
Example 14
Source File: TestWebSocket.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@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.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: 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();
    assertTrue(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();
    }

    assertTrue(headerlines.contains("Sec-WebSocket-Version: 13"));
    // Finished with the socket
    client.close();
}
 
Example 15
Source File: TestWebSocket.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@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.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: 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();
    assertTrue(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();
    }

    assertTrue(headerlines.contains("Sec-WebSocket-Version: 13"));
    // Finished with the socket
    client.close();
}
 
Example 16
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 17
Source File: TestEncodingDecoding.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testAnnotatedEndPoints() throws Exception {
    // Set up utility classes
    Server server = new Server();
    SingletonConfigurator.setInstance(server);
    ServerConfigListener.setPojoClazz(Server.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() + PATH_ANNOTATED_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 (server.received.size() > 0 && client.received.size() > 0) {
            break;
        }
        Thread.sleep(100);
    }

    // Check messages were received
    Assert.assertEquals(1, server.received.size());
    Assert.assertEquals(1, client.received.size());

    // Check correct messages were received
    Assert.assertEquals(MESSAGE_ONE,
            ((MsgString) server.received.peek()).getData());
    Assert.assertEquals(MESSAGE_ONE,
            ((MsgString) client.received.peek()).getData());
    session.close();

    // Should not take very long but some failures have been seen
    i = testEvent(MsgStringEncoder.class.getName()+":init", 0);
    i = testEvent(MsgStringDecoder.class.getName()+":init", i);
    i = testEvent(MsgByteEncoder.class.getName()+":init", i);
    i = testEvent(MsgByteDecoder.class.getName()+":init", i);
    i = testEvent(MsgStringEncoder.class.getName()+":destroy", i);
    i = testEvent(MsgStringDecoder.class.getName()+":destroy", i);
    i = testEvent(MsgByteEncoder.class.getName()+":destroy", i);
    i = testEvent(MsgByteDecoder.class.getName()+":destroy", i);
}
 
Example 18
Source File: TomcatServer.java    From pippo with Apache License 2.0 4 votes vote down vote up
@Override
public void start() {
    if (StringUtils.isNullOrEmpty(pippoFilterPath)) {
        pippoFilterPath = "/*";
    }

    tomcat = createTomcat();
    tomcat.setBaseDir(getSettings().getBaseFolder());

    if (getSettings().getKeystoreFile() == null) {
        enablePlainConnector(tomcat);
    } else {
        enableSSLConnector(tomcat);
    }

    File docBase = new File(System.getProperty("java.io.tmpdir"));
    Context context = tomcat.addContext(getSettings().getContextPath(), docBase.getAbsolutePath());
    context.setAllowCasualMultipartParsing(true);
    PippoServlet pippoServlet = new PippoServlet();
    pippoServlet.setApplication(getApplication());

    Wrapper wrapper = context.createWrapper();
    String name = "pippoServlet";

    wrapper.setName(name);
    wrapper.setLoadOnStartup(1);
    wrapper.setServlet(pippoServlet);
    context.addChild(wrapper);
    context.addServletMapping(pippoFilterPath, name);

    // inject application as context attribute
    context.getServletContext().setAttribute(PIPPO_APPLICATION, getApplication());

    // add initializers
    context.addApplicationListener(PippoServletContextListener.class.getName());

    // add listeners
    listeners.forEach(listener -> context.addApplicationListener(listener.getName()));

    String version = tomcat.getClass().getPackage().getImplementationVersion();
    log.info("Starting Tomcat Server {} on port {}", version, getSettings().getPort());

    try {
        tomcat.start();
    } catch (LifecycleException e) {
        log.error("Unable to launch Tomcat", e);
        throw new PippoRuntimeException(e);
    }

    if (!getApplication().getPippoSettings().isTest()) {
        tomcat.getServer().await();
    }
}
 
Example 19
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private void doTestTimeoutErrorDispatch(Boolean asyncError,
        ErrorPageAsyncMode mode) throws Exception {
    resetTracker();
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    TimeoutServlet timeout = new TimeoutServlet(null, null);
    Wrapper w1 = Tomcat.addServlet(ctx, "time", timeout);
    w1.setAsyncSupported(true);
    ctx.addServletMapping("/async", "time");

    NonAsyncServlet nonAsync = new NonAsyncServlet();
    Wrapper w2 = Tomcat.addServlet(ctx, "nonAsync", nonAsync);
    w2.setAsyncSupported(true);
    ctx.addServletMapping("/error/nonasync", "nonAsync");

    AsyncErrorPage asyncErrorPage = new AsyncErrorPage(mode);
    Wrapper w3 = Tomcat.addServlet(ctx, "asyncErrorPage", asyncErrorPage);
    w3.setAsyncSupported(true);
    ctx.addServletMapping("/error/async", "asyncErrorPage");

    if (asyncError != null) {
        ErrorPage ep = new ErrorPage();
        ep.setErrorCode(500);
        if (asyncError.booleanValue()) {
            ep.setLocation("/error/async");
        } else {
            ep.setLocation("/error/nonasync");
        }

        ctx.addErrorPage(ep);
    }

    ctx.addApplicationListener(TrackingRequestListener.class.getName());

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);
    TesterAccessLogValve alvGlobal = new TesterAccessLogValve();
    tomcat.getHost().getPipeline().addValve(alvGlobal);

    tomcat.start();
    ByteChunk res = new ByteChunk();
    try {
        getUrl("http://localhost:" + getPort() + "/async", res, null);
    } catch (IOException ioe) {
        // Ignore - expected for some error conditions
    }

    StringBuilder expected = new StringBuilder();
    expected.append("requestInitialized-TimeoutServletGet-");
    if (asyncError != null) {
        if (asyncError.booleanValue()) {
            expected.append("AsyncErrorPageGet-");
            if (mode == ErrorPageAsyncMode.NO_COMPLETE){
                expected.append("NoOp-");
            } else if (mode == ErrorPageAsyncMode.COMPLETE) {
                expected.append("Complete-");
            } else if (mode == ErrorPageAsyncMode.DISPATCH) {
                expected.append("Dispatch-NonAsyncServletGet-");
            }
        } else {
            expected.append("NonAsyncServletGet-");
        }
    }
    expected.append("requestDestroyed");

    // Request may complete before listener has finished processing so wait
    // up to 5 seconds for the right response
    String expectedTrack = expected.toString();
    int count = 0;
    while (!expectedTrack.equals(getTrack()) && count < 100) {
        Thread.sleep(50);
        count ++;
    }
    Assert.assertEquals(expectedTrack, getTrack());

    // Check the access log
    alvGlobal.validateAccessLog(1, 500, TimeoutServlet.ASYNC_TIMEOUT,
            TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN +
            REQUEST_TIME);
    alv.validateAccessLog(1, 500, TimeoutServlet.ASYNC_TIMEOUT,
            TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN +
            REQUEST_TIME);
}
 
Example 20
Source File: TestWebSocketFrameClientSSL.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testConnectToServerEndpointSSL() throws Exception {

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


    TesterSupport.initSsl(tomcat);

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().build();
    URL truststoreUrl = this.getClass().getClassLoader().getResource(
            "org/apache/tomcat/util/net/ca.jks");
    File truststoreFile = new File(truststoreUrl.toURI());
    clientEndpointConfig.getUserProperties().put(
            WsWebSocketContainer.SSL_TRUSTSTORE_PROPERTY,
            truststoreFile.getAbsolutePath());
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("wss://localhost:" + getPort() +
                    TesterFirehoseServer.Config.PATH));
    CountDownLatch latch =
            new CountDownLatch(TesterFirehoseServer.MESSAGE_COUNT);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText("Hello");

    System.out.println("Sent Hello message, waiting for data");

    // Ignore the latch result as the message count test below will tell us
    // if the right number of messages arrived
    handler.getLatch().await(TesterFirehoseServer.WAIT_TIME_MILLIS,
            TimeUnit.MILLISECONDS);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(
            TesterFirehoseServer.MESSAGE_COUNT, messages.size());
    for (String message : messages) {
        Assert.assertEquals(TesterFirehoseServer.MESSAGE, message);
    }
}