Search in sources :

Example 56 with Session

use of javax.websocket.Session in project undertow by undertow-io.

the class AnnotatedEndpointTest method testCloseReason.

@Test
public void testCloseReason() throws Exception {
    MessageEndpoint.reset();
    Session session = deployment.connectToServer(AnnotatedClientEndpoint.class, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/chat/Bob"));
    Assert.assertEquals("hi Bob (protocol=foo)", AnnotatedClientEndpoint.message());
    session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Foo!"));
    Assert.assertEquals("CLOSED", AnnotatedClientEndpoint.message());
    CloseReason cr = MessageEndpoint.getReason();
    Assert.assertEquals(CloseReason.CloseCodes.VIOLATED_POLICY.getCode(), cr.getCloseCode().getCode());
    Assert.assertEquals("Foo!", cr.getReasonPhrase());
}
Also used : CloseReason(javax.websocket.CloseReason) URI(java.net.URI) Session(javax.websocket.Session) UndertowSession(io.undertow.websockets.jsr.UndertowSession) Test(org.junit.Test)

Example 57 with Session

use of javax.websocket.Session in project tomee by apache.

the class ClasspathAsWebappTest method run.

@Test
public void run() throws MalformedURLException {
    MyInitializer.found = null;
    MyBean.VALUE = null;
    try (final Container container = new Container(new Configuration().http(NetworkUtil.getNextAvailablePort()).property("openejb.container.additional.exclude", "org.apache.tomee.embedded.").property("openejb.additional.include", "tomee-").user("tomee", "tomeepwd").loginConfig(new LoginConfigBuilder().basic()).securityConstaint(new SecurityConstaintBuilder().addAuthRole("**").authConstraint(true).addCollection("api", "/api/resource2/"))).deployPathsAsWebapp(JarLocation.jarLocation(MyInitializer.class)).inject(this)) {
        // Servlet (initializer, servlet)
        assertNotNull(MyInitializer.found);
        final Iterator<Class<?>> it = MyInitializer.found.iterator();
        while (it.hasNext()) {
            // ThreadStackRule defines one for instance
            final Class<?> next = it.next();
            if (next.getEnclosingClass() != null && !Modifier.isStatic(next.getModifiers())) {
                it.remove();
            }
        }
        assertEquals(1, MyInitializer.found.size());
        assertEquals(Task1.class, MyInitializer.found.iterator().next());
        try {
            assertEquals("Servlet!", IO.slurp(new URL("http://localhost:" + container.getConfiguration().getHttpPort() + "/s")));
        } catch (final IOException e) {
            fail(e.getMessage());
        }
        try {
            assertEquals("WebServlet", IO.slurp(new URL("http://localhost:" + container.getConfiguration().getHttpPort() + "/w")));
        } catch (final IOException e) {
            fail(e.getMessage());
        }
        // JSP
        try {
            assertEquals("JSP", IO.slurp(new URL("http://localhost:" + container.getConfiguration().getHttpPort() + "/?test=JSP")).trim());
        } catch (final IOException e) {
            fail(e.getMessage());
        }
        // CDI
        assertNotNull(bean);
        assertNull(bean.value());
        MyBean.VALUE = "cdi";
        assertEquals("cdi", bean.value());
        // EJB
        MyBean.VALUE = "ejb";
        assertEquals("ejb", anEjb.run());
        // JAXRS
        try {
            assertEquals("jaxrs", IO.slurp(new URL("http://localhost:" + container.getConfiguration().getHttpPort() + "/api/resource")));
        } catch (final IOException e) {
            fail(e.getMessage());
        }
        // JAXRS + servlet security
        try {
            final URL url = new URL("http://localhost:" + container.getConfiguration().getHttpPort() + "/api/resource2/");
            final HttpURLConnection c = HttpURLConnection.class.cast(url.openConnection());
            c.setRequestProperty("Authorization", "Basic " + printBase64Binary("tomee:tomeepwd".getBytes()));
            assertEquals("tomee", IO.slurp(c.getInputStream()));
            c.disconnect();
        } catch (final IOException e) {
            fail(e.getMessage());
        }
        try {
            assertEquals("tomee", IO.slurp(new URL("http://tomee:tomeepwd@localhost:" + container.getConfiguration().getHttpPort() + "/api/resource2/")));
            fail("should have been not authorized");
        } catch (final IOException e) {
        // ok
        }
        // WebSocket
        final WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
        try {
            WebSocketClient.message = null;
            final WebSocketClient webSocketClient = new WebSocketClient();
            final Session session = webSocketContainer.connectToServer(webSocketClient, new URI("ws://localhost:" + container.getConfiguration().getHttpPort() + "/ws"));
            webSocketClient.latch.await(20, TimeUnit.SECONDS);
            session.close();
            assertEquals("websocket", WebSocketClient.message);
        } catch (final Exception e) {
            fail(e.getMessage());
        }
    }
}
Also used : WebSocketContainer(javax.websocket.WebSocketContainer) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) ServletException(javax.servlet.ServletException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) WebSocketContainer(javax.websocket.WebSocketContainer) HttpURLConnection(java.net.HttpURLConnection) Session(javax.websocket.Session) Test(org.junit.Test)

Example 58 with Session

use of javax.websocket.Session in project tomcat by apache.

the class TestShutdown method testShutdownBufferedMessages.

@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));
}
Also used : Context(org.apache.catalina.Context) BasicText(org.apache.tomcat.websocket.TesterMessageCountClient.BasicText) Tomcat(org.apache.catalina.startup.Tomcat) WebSocketContainer(javax.websocket.WebSocketContainer) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) ServerEndpoint(javax.websocket.server.ServerEndpoint) Session(javax.websocket.Session) Test(org.junit.Test) WebSocketBaseTest(org.apache.tomcat.websocket.WebSocketBaseTest)

Example 59 with Session

use of javax.websocket.Session in project tomcat by apache.

the class TestWsRemoteEndpointImplServer method testClientDropsConnection.

/*
     * https://bz.apache.org/bugzilla/show_bug.cgi?id=58624
     *
     * This test requires three breakpoints to be set. Two in this file (marked
     * A & B with comments) and one (C) at the start of
     * WsRemoteEndpointImplServer.doWrite().
     *
     * With the breakpoints in place, run this test.
     * Once breakpoints A & B are reached, progress the thread at breakpoint A
     * one line to close the connection.
     * Once breakpoint C is reached, allow the thread at breakpoint B to
     * continue.
     * Then allow the thread at breakpoint C to continue.
     *
     * In the failure mode, the thread at breakpoint B will not progress past
     * the call to sendObject(). If the issue is fixed, the thread at breakpoint
     * B will continue past sendObject() and terminate with a TimeoutException.
     */
@Test
public void testClientDropsConnection() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug58624Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");
    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    tomcat.start();
    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + Bug58624Config.PATH);
    Session session = wsContainer.connectToServer(client, uri);
    // Break point A required on following line
    session.close();
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) WebSocketContainer(javax.websocket.WebSocketContainer) SimpleClient(org.apache.tomcat.websocket.pojo.TesterUtil.SimpleClient) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) URI(java.net.URI) Session(javax.websocket.Session) WebSocketBaseTest(org.apache.tomcat.websocket.WebSocketBaseTest) Test(org.junit.Test)

Example 60 with Session

use of javax.websocket.Session in project tomcat by apache.

the class TestWsSubprotocols method testWsSubprotocols.

@Test
public void testWsSubprotocols() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    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();
    tomcat.start();
    Session wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().preferredSubprotocols(Arrays.asList("sp3")).build(), new URI("ws://localhost:" + getPort() + SubProtocolsEndpoint.PATH_BASIC));
    Assert.assertTrue(wsSession.isOpen());
    if (wsSession.getNegotiatedSubprotocol() != null) {
        Assert.assertTrue(wsSession.getNegotiatedSubprotocol().isEmpty());
    }
    wsSession.close();
    SubProtocolsEndpoint.recycle();
    wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().preferredSubprotocols(Arrays.asList("sp2")).build(), new URI("ws://localhost:" + getPort() + SubProtocolsEndpoint.PATH_BASIC));
    Assert.assertTrue(wsSession.isOpen());
    Assert.assertEquals("sp2", wsSession.getNegotiatedSubprotocol());
    // Client thread might move faster than server. Wait for upto 5s for the
    // subProtocols to be set
    int count = 0;
    while (count < 50 && SubProtocolsEndpoint.subprotocols == null) {
        count++;
        Thread.sleep(100);
    }
    Assert.assertNotNull(SubProtocolsEndpoint.subprotocols);
    Assert.assertArrayEquals(new String[] { "sp1", "sp2" }, SubProtocolsEndpoint.subprotocols.toArray(new String[2]));
    wsSession.close();
    SubProtocolsEndpoint.recycle();
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) WebSocketContainer(javax.websocket.WebSocketContainer) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) EndpointConfig(javax.websocket.EndpointConfig) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) TesterEndpointConfig(org.apache.tomcat.websocket.server.TesterEndpointConfig) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) URI(java.net.URI) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) ServerEndpoint(javax.websocket.server.ServerEndpoint) Session(javax.websocket.Session) Test(org.junit.Test)

Aggregations

Session (javax.websocket.Session)115 Test (org.junit.Test)92 URI (java.net.URI)73 WebSocketContainer (javax.websocket.WebSocketContainer)42 Endpoint (javax.websocket.Endpoint)39 CountDownLatch (java.util.concurrent.CountDownLatch)34 Context (org.apache.catalina.Context)31 DefaultServlet (org.apache.catalina.servlets.DefaultServlet)31 Tomcat (org.apache.catalina.startup.Tomcat)31 EndpointConfig (javax.websocket.EndpointConfig)29 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)27 UndertowSession (io.undertow.websockets.jsr.UndertowSession)25 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)23 ServerEndpoint (javax.websocket.server.ServerEndpoint)20 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)16 IOException (java.io.IOException)16 AnnotatedClientEndpoint (io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint)15 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)15 AtomicReference (java.util.concurrent.atomic.AtomicReference)15 FrameChecker (io.undertow.websockets.utils.FrameChecker)14