Search in sources :

Example 26 with DefaultServlet

use of org.apache.catalina.servlets.DefaultServlet in project tomcat70 by apache.

the class TestWebSocket method testKey.

@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();
    Assert.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();
    }
    Assert.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));
    Assert.assertEquals(source, accept);
    sha1Helper.reset();
    sha1Helper.update("TOD".getBytes(B2CConverter.ISO_8859_1));
    source = Base64.encode(sha1Helper.digest(WS_ACCEPT));
    Assert.assertFalse(source.equals(accept));
    // Finished with the socket
    client.close();
}
Also used : InitialContext(javax.naming.InitialContext) Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) TesterEchoServer(org.apache.tomcat.websocket.TesterEchoServer) ApplicationListener(org.apache.catalina.deploy.ApplicationListener) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) MessageDigest(java.security.MessageDigest) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 27 with DefaultServlet

use of org.apache.catalina.servlets.DefaultServlet in project tomcat by apache.

the class TestRewriteValve method doTestRewrite.

private void doTestRewrite(String config, String request, String expectedURI, String expectedQueryString, String expectedAttributeValue) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    RewriteValve rewriteValve = new RewriteValve();
    ctx.getPipeline().addValve(rewriteValve);
    rewriteValve.setConfiguration(config);
    Tomcat.addServlet(ctx, "snoop", new SnoopServlet());
    ctx.addServletMappingDecoded("/a/%5A", "snoop");
    ctx.addServletMappingDecoded("/c/*", "snoop");
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");
    tomcat.start();
    ByteChunk res = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + request, res, null);
    res.setCharset(StandardCharsets.UTF_8);
    if (expectedURI == null) {
        // Rewrite is expected to fail. Probably because invalid characters
        // were written into the request target
        Assert.assertEquals(400, rc);
    } else {
        String body = res.toString();
        RequestDescriptor requestDesc = SnoopResult.parse(body);
        String requestURI = requestDesc.getRequestInfo("REQUEST-URI");
        Assert.assertEquals(expectedURI, requestURI);
        if (expectedQueryString != null) {
            String queryString = requestDesc.getRequestInfo("REQUEST-QUERY-STRING");
            Assert.assertEquals(expectedQueryString, queryString);
        }
        if (expectedAttributeValue != null) {
            String attributeValue = requestDesc.getAttribute("X-Test");
            Assert.assertEquals(expectedAttributeValue, attributeValue);
        }
    }
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) DefaultServlet(org.apache.catalina.servlets.DefaultServlet)

Example 28 with DefaultServlet

use of org.apache.catalina.servlets.DefaultServlet in project tomcat by apache.

the class TestWsRemoteEndpoint method doTestWriter.

private void doTestWriter(Class<?> clazz, boolean useWriter, String testMessage) 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.addServletMappingDecoded("/", "default");
    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    tomcat.start();
    Session wsSession;
    URI uri = new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC);
    if (Endpoint.class.isAssignableFrom(clazz)) {
        @SuppressWarnings("unchecked") Class<? extends Endpoint> endpointClazz = (Class<? extends Endpoint>) clazz;
        wsSession = wsContainer.connectToServer(endpointClazz, Builder.create().build(), uri);
    } else {
        wsSession = wsContainer.connectToServer(clazz, uri);
    }
    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties().get("endpoint");
    tep.setLatch(latch);
    AsyncHandler<?> handler;
    if (useWriter) {
        handler = new AsyncText(latch);
    } else {
        handler = new AsyncBinary(latch);
    }
    wsSession.addMessageHandler(handler);
    if (useWriter) {
        Writer w = wsSession.getBasicRemote().getSendWriter();
        for (int i = 0; i < 8; i++) {
            w.write(testMessage);
        }
        w.close();
    } else {
        OutputStream s = wsSession.getBasicRemote().getSendStream();
        for (int i = 0; i < 8; i++) {
            s.write(testMessage.getBytes(StandardCharsets.UTF_8));
        }
        s.close();
    }
    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    List<String> results = new ArrayList<>();
    if (useWriter) {
        @SuppressWarnings("unchecked") List<String> messages = (List<String>) handler.getMessages();
        results.addAll(messages);
    } else {
        // Take advantage of the fact that the message uses characters that
        // are represented as a single UTF-8 byte so won't be split across
        // binary messages
        @SuppressWarnings("unchecked") List<ByteBuffer> messages = (List<ByteBuffer>) handler.getMessages();
        for (ByteBuffer message : messages) {
            byte[] bytes = new byte[message.limit()];
            message.get(bytes);
            results.add(new String(bytes, StandardCharsets.UTF_8));
        }
    }
    int offset = 0;
    int i = 0;
    for (String result : results) {
        if (testMessage.length() == 0) {
            Assert.assertEquals(0, result.length());
        } else {
            // First may be a fragment
            Assert.assertEquals(SEQUENCE.substring(offset, S_LEN), result.substring(0, S_LEN - offset));
            i = S_LEN - offset;
            while (i + S_LEN < result.length()) {
                if (!SEQUENCE.equals(result.substring(i, i + S_LEN))) {
                    Assert.fail();
                }
                i += S_LEN;
            }
            offset = result.length() - i;
            if (!SEQUENCE.substring(0, offset).equals(result.substring(i))) {
                Assert.fail();
            }
        }
    }
}
Also used : AsyncText(org.apache.tomcat.websocket.TesterMessageCountClient.AsyncText) Tomcat(org.apache.catalina.startup.Tomcat) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) URI(java.net.URI) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) TesterAnnotatedEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterAnnotatedEndpoint) Endpoint(jakarta.websocket.Endpoint) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) ArrayList(java.util.ArrayList) List(java.util.List) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) Context(org.apache.catalina.Context) WebSocketContainer(jakarta.websocket.WebSocketContainer) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) TesterAnnotatedEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterAnnotatedEndpoint) Endpoint(jakarta.websocket.Endpoint) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) AsyncBinary(org.apache.tomcat.websocket.TesterMessageCountClient.AsyncBinary) Writer(java.io.Writer) Session(jakarta.websocket.Session)

Example 29 with DefaultServlet

use of org.apache.catalina.servlets.DefaultServlet in project tomcat by apache.

the class TestWsRemoteEndpoint method doTestWriterError.

private void doTestWriterError(Class<?> clazz) 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.addServletMappingDecoded("/", "default");
    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    tomcat.start();
    Session wsSession;
    URI uri = new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_WRITER_ERROR);
    if (Endpoint.class.isAssignableFrom(clazz)) {
        @SuppressWarnings("unchecked") Class<? extends Endpoint> endpointClazz = (Class<? extends Endpoint>) clazz;
        wsSession = wsContainer.connectToServer(endpointClazz, Builder.create().build(), uri);
    } else {
        wsSession = wsContainer.connectToServer(clazz, uri);
    }
    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties().get("endpoint");
    tep.setLatch(latch);
    AsyncHandler<?> handler;
    handler = new AsyncText(latch);
    wsSession.addMessageHandler(handler);
    // This should trigger the error
    wsSession.getBasicRemote().sendText("Start");
    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    @SuppressWarnings("unchecked") List<String> messages = (List<String>) handler.getMessages();
    Assert.assertEquals(0, messages.size());
}
Also used : Context(org.apache.catalina.Context) AsyncText(org.apache.tomcat.websocket.TesterMessageCountClient.AsyncText) Tomcat(org.apache.catalina.startup.Tomcat) WebSocketContainer(jakarta.websocket.WebSocketContainer) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) TesterAnnotatedEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterAnnotatedEndpoint) Endpoint(jakarta.websocket.Endpoint) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) ArrayList(java.util.ArrayList) List(java.util.List) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) Session(jakarta.websocket.Session)

Example 30 with DefaultServlet

use of org.apache.catalina.servlets.DefaultServlet in project tomcat by apache.

the class TestWsSessionSuspendResume method test.

@Test
public void test() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Config.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() + Config.PATH));
    CountDownLatch latch = new CountDownLatch(2);
    wsSession.addMessageHandler(String.class, message -> {
        Assert.assertTrue("[echo, echo, echo]".equals(message));
        latch.countDown();
    });
    for (int i = 0; i < 8; i++) {
        wsSession.getBasicRemote().sendText("echo");
    }
    boolean latchResult = latch.await(30, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    wsSession.close();
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) WebSocketContainer(jakarta.websocket.WebSocketContainer) ServerEndpointConfig(jakarta.websocket.server.ServerEndpointConfig) ClientEndpointConfig(jakarta.websocket.ClientEndpointConfig) TesterEndpointConfig(org.apache.tomcat.websocket.server.TesterEndpointConfig) EndpointConfig(jakarta.websocket.EndpointConfig) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) ClientEndpointConfig(jakarta.websocket.ClientEndpointConfig) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) Endpoint(jakarta.websocket.Endpoint) Session(jakarta.websocket.Session) Test(org.junit.Test)

Aggregations

DefaultServlet (org.apache.catalina.servlets.DefaultServlet)93 Context (org.apache.catalina.Context)91 Tomcat (org.apache.catalina.startup.Tomcat)91 Test (org.junit.Test)70 URI (java.net.URI)59 Session (jakarta.websocket.Session)39 WebSocketContainer (jakarta.websocket.WebSocketContainer)36 Session (javax.websocket.Session)30 WebSocketContainer (javax.websocket.WebSocketContainer)27 TesterProgrammaticEndpoint (org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint)27 CountDownLatch (java.util.concurrent.CountDownLatch)24 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)24 ClientEndpointConfig (jakarta.websocket.ClientEndpointConfig)23 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)19 TesterEndpoint (org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint)19 BasicText (org.apache.tomcat.websocket.TesterMessageCountClient.BasicText)18 Endpoint (jakarta.websocket.Endpoint)15 ServerEndpoint (jakarta.websocket.server.ServerEndpoint)15 ServerEndpoint (javax.websocket.server.ServerEndpoint)14 Endpoint (javax.websocket.Endpoint)13