Search in sources :

Example 71 with DefaultServlet

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

the class TestAuthenticatorBaseCorsPreflight method test.

@Test
public void test() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp");
    Context ctx = tomcat.addContext("", appDir.getAbsolutePath());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");
    LoginConfig loginConfig = new LoginConfig();
    loginConfig.setAuthMethod("BASIC");
    ctx.setLoginConfig(loginConfig);
    BasicAuthenticator basicAuth = new BasicAuthenticator();
    basicAuth.setAllowCorsPreflight(allowCorsPreflight.toString());
    ctx.getPipeline().addValve(basicAuth);
    Realm realm = new NullRealm();
    ctx.setRealm(realm);
    SecurityCollection securityCollection = new SecurityCollection();
    securityCollection.addPattern("/*");
    SecurityConstraint constraint = new SecurityConstraint();
    constraint.setAuthConstraint(true);
    constraint.addCollection(securityCollection);
    ctx.addConstraint(constraint);
    // For code coverage
    FilterDef otherFilter = new FilterDef();
    otherFilter.setFilterName("other");
    otherFilter.setFilterClass(AddDefaultCharsetFilter.class.getName());
    FilterMap otherMap = new FilterMap();
    otherMap.setFilterName("other");
    otherMap.addURLPatternDecoded("/other");
    ctx.addFilterDef(otherFilter);
    ctx.addFilterMap(otherMap);
    FilterDef corsFilter = new FilterDef();
    corsFilter.setFilterName("cors");
    corsFilter.setFilterClass(CorsFilter.class.getName());
    corsFilter.addInitParameter(CorsFilter.PARAM_CORS_ALLOWED_ORIGINS, ALLOWED_ORIGIN);
    corsFilter.addInitParameter(CorsFilter.PARAM_CORS_ALLOWED_METHODS, ALLOWED_METHOD);
    FilterMap corsFilterMap = new FilterMap();
    corsFilterMap.setFilterName("cors");
    corsFilterMap.addURLPatternDecoded(filterMapping);
    ctx.addFilterDef(corsFilter);
    ctx.addFilterMap(corsFilterMap);
    tomcat.start();
    Map<String, List<String>> reqHead = new HashMap<>();
    if (origin != null) {
        List<String> values = new ArrayList<>();
        if (SAME_ORIGIN.equals(origin)) {
            values.add(origin + ":" + getPort());
        } else {
            values.add(origin);
        }
        reqHead.put(CorsFilter.REQUEST_HEADER_ORIGIN, values);
    }
    if (accessControl != null) {
        List<String> values = new ArrayList<>();
        values.add(accessControl);
        reqHead.put(CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD, values);
    }
    ByteChunk out = new ByteChunk();
    int rc = methodUrl("http://localhost:" + getPort() + "/target", out, 300000, reqHead, null, method, false);
    if (allow) {
        Assert.assertEquals(200, rc);
    } else {
        Assert.assertEquals(403, rc);
    }
}
Also used : Context(org.apache.catalina.Context) CorsFilter(org.apache.catalina.filters.CorsFilter) Tomcat(org.apache.catalina.startup.Tomcat) FilterDef(org.apache.tomcat.util.descriptor.web.FilterDef) HashMap(java.util.HashMap) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) ArrayList(java.util.ArrayList) NullRealm(org.apache.catalina.realm.NullRealm) AddDefaultCharsetFilter(org.apache.catalina.filters.AddDefaultCharsetFilter) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) ArrayList(java.util.ArrayList) List(java.util.List) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) File(java.io.File) NullRealm(org.apache.catalina.realm.NullRealm) Realm(org.apache.catalina.Realm) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 72 with DefaultServlet

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

the class TestWsWebSocketContainer method testSessionExpiryOnUserPropertyReadIdleTimeout.

@Test
public void testSessionExpiryOnUserPropertyReadIdleTimeout() 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");
    tomcat.start();
    // Need access to implementation methods for configuring unit tests
    WsWebSocketContainer wsContainer = (WsWebSocketContainer) ContainerProvider.getWebSocketContainer();
    wsContainer.setDefaultMaxSessionIdleTimeout(90000);
    wsContainer.setProcessPeriod(1);
    EndpointA endpointA = new EndpointA();
    Session s1a = connectToEchoServer(wsContainer, endpointA, TesterEchoServer.Config.PATH_BASIC);
    s1a.setMaxIdleTimeout(90000);
    s1a.getUserProperties().put(Constants.READ_IDLE_TIMEOUT_MS, Long.valueOf(5000));
    // maxIdleTimeout is 90s but the readIdleTimeout is 5s. The session
    // should get closed after 5 seconds as nothing is read on it.
    // First confirm the session has been opened.
    Assert.assertEquals(1, s1a.getOpenSessions().size());
    // Now wait for it to close. Allow up to 30s as some CI systems are slow
    // but that is still well under the 90s configured for the session.
    int count = 0;
    while (count < 300 && s1a.isOpen()) {
        count++;
        Thread.sleep(100);
    }
    Assert.assertFalse(s1a.isOpen());
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) ClientEndpointConfig(jakarta.websocket.ClientEndpointConfig) EndpointConfig(jakarta.websocket.EndpointConfig) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) Endpoint(jakarta.websocket.Endpoint) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) Session(jakarta.websocket.Session) Test(org.junit.Test)

Example 73 with DefaultServlet

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

the class TestWsWebSocketContainer method testSessionExpiryOnUserPropertyWriteIdleTimeout.

@Test
public void testSessionExpiryOnUserPropertyWriteIdleTimeout() 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");
    tomcat.start();
    // Need access to implementation methods for configuring unit tests
    WsWebSocketContainer wsContainer = (WsWebSocketContainer) ContainerProvider.getWebSocketContainer();
    wsContainer.setDefaultMaxSessionIdleTimeout(90000);
    wsContainer.setProcessPeriod(1);
    EndpointA endpointA = new EndpointA();
    Session s1a = connectToEchoServer(wsContainer, endpointA, TesterEchoServer.Config.PATH_BASIC);
    s1a.setMaxIdleTimeout(90000);
    s1a.getUserProperties().put(Constants.WRITE_IDLE_TIMEOUT_MS, Long.valueOf(5000));
    // maxIdleTimeout is 90s but the writeIdleTimeout is 5s. The session
    // should get closed after 5 seconds as nothing is written on it.
    // First confirm the session has been opened.
    Assert.assertEquals(1, s1a.getOpenSessions().size());
    // Now wait for it to close. Allow up to 30s as some CI systems are slow
    // but that is still well under the 90s configured for the session.
    int count = 0;
    while (count < 300 && s1a.isOpen()) {
        count++;
        Thread.sleep(100);
    }
    Assert.assertFalse(s1a.isOpen());
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) ClientEndpointConfig(jakarta.websocket.ClientEndpointConfig) EndpointConfig(jakarta.websocket.EndpointConfig) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) Endpoint(jakarta.websocket.Endpoint) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) Session(jakarta.websocket.Session) Test(org.junit.Test)

Example 74 with DefaultServlet

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

the class TestWsWebSocketContainer method testConnectToServerEndpoint.

@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.addServletMappingDecoded("/", "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();
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) WebSocketContainer(jakarta.websocket.WebSocketContainer) ClientEndpointConfig(jakarta.websocket.ClientEndpointConfig) EndpointConfig(jakarta.websocket.EndpointConfig) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) BasicText(org.apache.tomcat.websocket.TesterMessageCountClient.BasicText) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) Session(jakarta.websocket.Session) Test(org.junit.Test)

Example 75 with DefaultServlet

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

the class TestWsWebSocketContainer method doBufferTest.

private void doBufferTest(boolean isTextBuffer, boolean isServerBuffer, boolean isTextMessage, boolean pass) 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();
    if (isServerBuffer) {
        if (isTextBuffer) {
            ctx.addParameter(org.apache.tomcat.websocket.server.Constants.TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM, "1024");
        } else {
            ctx.addParameter(org.apache.tomcat.websocket.server.Constants.BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM, "1024");
        }
    } else {
        if (isTextBuffer) {
            wsContainer.setDefaultMaxTextMessageBufferSize(1024);
        } else {
            wsContainer.setDefaultMaxBinaryMessageBufferSize(1024);
        }
    }
    tomcat.start();
    Session wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_BASIC));
    BasicHandler<?> handler;
    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties().get("endpoint");
    tep.setLatch(latch);
    if (isTextMessage) {
        handler = new BasicText(latch);
    } else {
        handler = new BasicBinary(latch);
    }
    wsSession.addMessageHandler(handler);
    try {
        if (isTextMessage) {
            wsSession.getBasicRemote().sendText(MESSAGE_TEXT_4K);
        } else {
            wsSession.getBasicRemote().sendBinary(ByteBuffer.wrap(MESSAGE_BINARY_4K));
        }
    } catch (IOException ioe) {
    // Some messages sends are expected to fail. Assertions further on
    // in this method will check for the correct behaviour so ignore any
    // exception here.
    }
    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    Queue<?> messages = handler.getMessages();
    if (pass) {
        Assert.assertEquals(1, messages.size());
        if (isTextMessage) {
            Assert.assertEquals(MESSAGE_TEXT_4K, messages.peek());
        } else {
            Assert.assertEquals(ByteBuffer.wrap(MESSAGE_BINARY_4K), messages.peek());
        }
    } else {
        // give the session a chance to complete the close process.
        for (int i = 0; i < 500; i++) {
            if (!wsSession.isOpen()) {
                break;
            }
            Thread.sleep(10);
        }
        Assert.assertFalse(wsSession.isOpen());
    }
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) WebSocketContainer(jakarta.websocket.WebSocketContainer) ClientEndpointConfig(jakarta.websocket.ClientEndpointConfig) EndpointConfig(jakarta.websocket.EndpointConfig) BasicBinary(org.apache.tomcat.websocket.TesterMessageCountClient.BasicBinary) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) Endpoint(jakarta.websocket.Endpoint) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) BasicText(org.apache.tomcat.websocket.TesterMessageCountClient.BasicText) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) Session(jakarta.websocket.Session)

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