Java Code Examples for javax.websocket.WebSocketContainer#connectToServer()

The following examples show how to use javax.websocket.WebSocketContainer#connectToServer() . 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: AnnotatedServerTest.java    From wildfly-samples with MIT License 6 votes vote down vote up
@Test
    public void testEndpoint() throws IOException, ServletException, DeploymentException, InterruptedException {
        AnnotatedWebSocketServer server = new AnnotatedWebSocketServer();
        server.start();

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://localhost:8080/server";
        System.out.println("Connecting to " + uri);
        container.connectToServer(MyClient.class, URI.create(uri));

//        WebClient webClient = new WebClient();
//        TextPage page = webClient.getPage("http://localhost:8080/myapp/server");
//        assertEquals("Hello World", page.getContent());
        assertTrue(AnnotatedWebSocketServer.LATCH.await(3, TimeUnit.SECONDS));
        server.stop();
    }
 
Example 2
Source File: TestWsRemoteEndpointImplServer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@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();
}
 
Example 3
Source File: TestWsWebSocketContainer.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() 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("ftp://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
 
Example 4
Source File: TestWsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() 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("ftp://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
 
Example 5
Source File: TesterWsClientAutobahn.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private static void executeTestCase(WebSocketContainer wsc, int testCase)
        throws Exception {
    URI uri = new URI("ws://" + HOST + ":" + PORT + "/runCase?case=" +
            testCase + "&agent=" + USER_AGENT);
    TestCaseClient testCaseClient = new TestCaseClient();
    wsc.connectToServer(testCaseClient, uri);
    testCaseClient.waitForClose();
}
 
Example 6
Source File: WSTest.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Test
public void run() throws InterruptedException, DeploymentException, IOException, URISyntaxException {
	CountDownLatch cdl = new CountDownLatch(5);
	WebSocketContainer container = ContainerProvider.getWebSocketContainer();
	String wsEndpoint = String.format("ws://localhost:%d/ws-chat", CONTAINER.getConfiguration().getHttpPort());
	Session session = container.connectToServer(new ChatClient(cdl), new URI(wsEndpoint));
	assertTrue(cdl.await(20, TimeUnit.SECONDS));
	session.close();

}
 
Example 7
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 8
Source File: AsyncClient.java    From javaee8-cookbook with Apache License 2.0 5 votes vote down vote up
public void connect() {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    try {
        container.connectToServer(this, new URI(asyncServer));
    } catch (URISyntaxException | DeploymentException | IOException ex) {
        System.err.println(ex.getMessage());
    }

}
 
Example 9
Source File: TestEncodingDecoding.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsupportedObject() 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);

    // This should fail
    Object msg1 = new Object();
    try {
        session.getBasicRemote().sendObject(msg1);
        Assert.fail("No exception thrown ");
    } catch (EncodeException e) {
        // Expected
    } catch (Throwable t) {
        Assert.fail("Wrong exception type");
    } finally {
        session.close();
    }
}
 
Example 10
Source File: TestWsPingPongMessages.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPingPongMessages() 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();

    tomcat.start();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder
                    .create().build(), new URI("ws://localhost:"
                    + getPort() + TesterEchoServer.Config.PATH_ASYNC));

    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties()
            .get("endpoint");
    tep.setLatch(latch);

    PongMessageHandler handler = new PongMessageHandler(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendPing(applicationData);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    Assert.assertArrayEquals(applicationData.array(),
            (handler.getMessages().peek()).getApplicationData().array());
}
 
Example 11
Source File: TesterWsClientAutobahn.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private static int getTestCaseCount(WebSocketContainer wsc)
        throws Exception {

    URI uri = new URI("ws://" + HOST + ":" + PORT + "/getCaseCount");
    CaseCountClient caseCountClient = new CaseCountClient();
    wsc.connectToServer(caseCountClient, uri);
    return caseCountClient.getCaseCount();
}
 
Example 12
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private void doTestPerMessageDefalteClient(String msg, int count) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    Extension perMessageDeflate = new WsExtension(PerMessageDeflate.NAME);
    List<Extension> extensions = new ArrayList<Extension>(1);
    extensions.add(perMessageDeflate);

    ClientEndpointConfig clientConfig =
            ClientEndpointConfig.Builder.create().extensions(extensions).build();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientConfig,
            new URI("ws://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(count);
    BasicText handler = new BasicText(latch, msg);
    wsSession.addMessageHandler(handler);
    for (int i = 0; i < count; i++) {
        wsSession.getBasicRemote().sendText(msg);
    }

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

    Assert.assertTrue(latchResult);

    ((WsWebSocketContainer) wsContainer).destroy();
}
 
Example 13
Source File: TesterWsClientAutobahn.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private static int getTestCaseCount(WebSocketContainer wsc)
        throws Exception {

    URI uri = new URI("ws://" + HOST + ":" + PORT + "/getCaseCount");
    CaseCountClient caseCountClient = new CaseCountClient();
    wsc.connectToServer(caseCountClient, uri);
    return caseCountClient.getCaseCount();
}
 
Example 14
Source File: BadUrlTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test
public void testBadUrl() throws Exception {
  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();

  container.connectToServer(client,
      new URI(serverUri.toString() + "gateway/websocket/ws"));

  client.awaitClose(CloseReason.CloseCodes.UNEXPECTED_CONDITION.getCode(),
      1000, TimeUnit.MILLISECONDS);

  Assert.assertThat(client.close.getCloseCode().getCode(),
      CoreMatchers.is(CloseReason.CloseCodes.UNEXPECTED_CONDITION.getCode()));

}
 
Example 15
Source File: TestPojoMethodMapping.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void test() 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();

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

    Session session = wsContainer.connectToServer(client, uri);
    session.getBasicRemote().sendText("NO-OP");
    session.close();

    // Give server 20s to close. 5s should be plenty but the Gump VM is slow
    int count = 0;
    while (count < 200) {
        if (server.isClosed()) {
            break;
        }
        count++;
        Thread.sleep(100);
    }
    if (count == 50) {
        Assert.fail("Server did not process an onClose event within 5 " +
                "seconds of the client sending a close message");
    }

    // Check no errors
    List<String> errors = server.getErrors();
    for (String error : errors) {
        System.err.println(error);
    }
    Assert.assertEquals("Found errors", 0, errors.size());
}
 
Example 16
Source File: TestEncodingDecoding.java    From Tomcat7.0.67 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 17
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 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(TesterEchoServer.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://" + 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());
}
 
Example 18
Source File: TestWsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private Session connectToEchoServer(WebSocketContainer wsContainer,
        Endpoint endpoint, String path) throws Exception {
    return wsContainer.connectToServer(endpoint,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + getHostName() + ":" + getPort() + path));
}
 
Example 19
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void doTestWriteTimeoutServer(boolean setTimeoutOnContainer)
        throws Exception {

    // This will never work for BIO
    Assume.assumeFalse(
            "Skipping test. This feature will never work for BIO connector.",
            getProtocol().equals(Http11Protocol.class.getName()));

    /*
     * Note: There are all sorts of horrible uses of statics in this test
     *       because the API uses classes and the tests really need access
     *       to the instances which simply isn't possible.
     */
    timoutOnContainer = setTimeoutOnContainer;

    Tomcat tomcat = getTomcatInstance();

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

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + getHostName() + ":" + getPort() +
                    ConstantTxConfig.PATH));

    wsSession.addMessageHandler(new BlockingBinaryHandler());

    int loops = 0;
    while (loops < 15) {
        Thread.sleep(1000);
        if (!ConstantTxEndpoint.getRunning()) {
            break;
        }
        loops++;
    }

    // Check the right exception was thrown
    Assert.assertNotNull(ConstantTxEndpoint.getException());
    Assert.assertEquals(ExecutionException.class,
            ConstantTxEndpoint.getException().getClass());
    Assert.assertNotNull(ConstantTxEndpoint.getException().getCause());
    Assert.assertEquals(SocketTimeoutException.class,
            ConstantTxEndpoint.getException().getCause().getClass());

    // Check correct time passed
    Assert.assertTrue(ConstantTxEndpoint.getTimeout() >= TIMEOUT_MS);

    // Check the timeout wasn't too long
    Assert.assertTrue(ConstantTxEndpoint.getTimeout() < TIMEOUT_MS*2);
}
 
Example 20
Source File: ConnectionDroppedTest.java    From knox with Apache License 2.0 3 votes vote down vote up
@Test(expected = java.util.concurrent.TimeoutException.class)
public void testDroppedConnection() throws IOException, Exception {
  final String message = "Echo";

  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();
  javax.websocket.Session session = container.connectToServer(client,
      proxyUri);

  session.getBasicRemote().sendText(message);

  client.messageQueue.awaitMessages(1, 1000, TimeUnit.MILLISECONDS);

}