Java Code Examples for javax.websocket.ContainerProvider#getWebSocketContainer()

The following examples show how to use javax.websocket.ContainerProvider#getWebSocketContainer() . 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: LibertySessionWrapper.java    From rogue-cloud with Apache License 2.0 6 votes vote down vote up
private void connect(String url) {
	// Don't try to connect if we have already disposed of the session, or the client instance
	if (disposed || LibertyClientInstance.getInstance().isDisposed()) {
		log.interesting("Ignoring connect as instance of wrapper is disposed ["+disposed+","+LibertyClientInstance.getInstance().isDisposed()+"]", parent.getLogContext());
		return;
	}

	log.interesting("Attempting to connect", parent.getLogContext());
	final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
	//
	// ClientManager client = ClientManager.createClient();

	WebSocketContainer c = ContainerProvider.getWebSocketContainer();
	c.setDefaultMaxTextMessageBufferSize(1024 * 1024);
	c.setDefaultMaxSessionIdleTimeout(2 * TimeUnit.MILLISECONDS.convert(RCSharedConstants.MAX_ROUND_LENGTH_IN_NANOS, TimeUnit.NANOSECONDS));
	try {
		c.connectToServer(this.hce, cec, new URI(url));
		// Wait for the endpoint to call us on success or failure.
	} catch (DeploymentException | IOException | URISyntaxException e) {
		errorOccurred(null);
	}

}
 
Example 2
Source File: TesterWsClientAutobahn.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        WebSocketContainer wsc = ContainerProvider.getWebSocketContainer();

        int testCaseCount = getTestCaseCount(wsc);
        System.out.println("There are " + testCaseCount + " test cases");
        for (int testCase = 1; testCase <= testCaseCount; testCase++) {
            if (testCase % 50 == 0) {
                System.out.println(testCase);
            } else {
                System.out.print('.');
            }
            try {
                executeTestCase(wsc, testCase);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                t.printStackTrace();
            }

        }
        System.out.println("Testing complete");
        updateReports(wsc);
    }
 
Example 3
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 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: WebsocketClient.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public WebsocketClient(String uri, final String sessionID, MessageHandler.Whole<String> messageHandler)
    throws IOException {

// add session ID so the request gets through LAMS security
Builder configBuilder = ClientEndpointConfig.Builder.create();
configBuilder.configurator(new Configurator() {
    @Override
    public void beforeRequest(Map<String, List<String>> headers) {
	headers.put("Cookie", Arrays.asList("JSESSIONID=" + sessionID));
    }
});
ClientEndpointConfig clientConfig = configBuilder.build();
this.websocketEndpoint = new WebsocketEndpoint(messageHandler);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
    container.connectToServer(websocketEndpoint, clientConfig, new URI(uri));
} catch (DeploymentException | URISyntaxException e) {
    throw new IOException("Error while connecting to websocket server", e);
}
   }
 
Example 5
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 6
Source File: WebsocketLauncher.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
public static boolean startUp(BinanceDexClientEndpoint endpoint){
    try {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        container.setDefaultMaxBinaryMessageBufferSize(128000000);
        container.setDefaultMaxTextMessageBufferSize(128000000);
        container.connectToServer(endpoint,new URI(endpoint.getUrl()));
        return true;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: StockExchangeNotifier.java    From blog-tutorials with MIT License 5 votes vote down vote up
@PostConstruct
public void init() {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    try {
        this.session = container.connectToServer(StockExchangeClient.class,
                new URI("ws://localhost:9080/stocks"));
    } catch (DeploymentException | IOException | URISyntaxException e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: TestWsPingPongMessages.java    From Tomcat8-Source-Read with MIT License 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.addServletMappingDecoded("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider
            .getWebSocketContainer();

    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 9
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private void doMaxMessageSize(String path, long size, boolean expectOpen)
        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();

    Session s = connectToEchoServer(wsContainer, new EndpointA(), path);

    StringBuilder msg = new StringBuilder();
    for (long i = 0; i < size; i++) {
        msg.append('x');
    }

    s.getBasicRemote().sendText(msg.toString());

    // Wait for up to 5 seconds for session to close
    boolean open = s.isOpen();
    int count = 0;
    while (open != expectOpen && count < 50) {
        Thread.sleep(100);
        count++;
        open = s.isOpen();
    }

    Assert.assertEquals(Boolean.valueOf(expectOpen),
            Boolean.valueOf(s.isOpen()));
}
 
Example 10
Source File: AbstractWebsocketClientEndpoint.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Connect.
 *
 * @throws DeploymentException the deployment exception
 * @throws IOException         Signals that an I/O exception has occurred.
 */
public void connect() throws DeploymentException, IOException {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    LOGGER.info("Connecting to " + endpointURI);

    container.connectToServer(this, endpointURI);
}
 
Example 11
Source File: TestPojoEndpointBase.java    From Tomcat8-Source-Read with MIT License 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.addServletMappingDecoded("/", "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 12
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 13
Source File: TestEncodingDecoding.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
@Ignore // TODO Investigate why this test fails
public void testBatchedEndPoints() throws Exception {
    // Set up utility classes
    BatchedServer server = new BatchedServer();
    SingletonConfigurator.setInstance(server);
    ServerConfigListener.setPojoClazz(BatchedServer.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.addServletMappingDecoded("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    StringClient client = new StringClient();
    URI uri = new URI("ws://localhost:" + getPort() + PATH_BATCHED_EP);
    Session session = wsContainer.connectToServer(client, uri);

    session.getBasicRemote().sendText(MESSAGE_ONE);

    // Should not take very long
    int i = 0;
    while (i++ < 20) {
        if (server.received.size() > 0 && client.received.size() > 0) {
            break;
        }
        i++;
        Thread.sleep(100);
    }

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

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

    Assert.assertNull(server.t);
}
 
Example 14
Source File: TestPojoMethodMapping.java    From Tomcat8-Source-Read with MIT License 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.addServletMappingDecoded("/", "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 15
Source File: TestWebSocketFrameClientSSL.java    From Tomcat8-Source-Read with MIT License 4 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(TesterFirehoseServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    TesterSupport.initSsl(tomcat);

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().build();

    clientEndpointConfig.getUserProperties().put(
            Constants.SSL_CONTEXT_PROPERTY, createSSLContext());

    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);
    }
}
 
Example 16
Source File: TestCloseBug58624.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testOnErrorNotCalledWhenClosingConnection() throws Throwable {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug58624ServerConfig.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Bug58624ClientEndpoint client = new Bug58624ClientEndpoint();
    URI uri = new URI("ws://localhost:" + getPort() + Bug58624ServerConfig.PATH);

    Session session = wsContainer.connectToServer(client, uri);

    // Wait for session to open on the server
    int count = 0;
    while (count < 50 && Bug58624ServerEndpoint.getOpenSessionCount() == 0) {
        count++;
        Thread.sleep(100);
    }
    Assert.assertNotEquals(0,  Bug58624ServerEndpoint.getOpenSessionCount());

    // Now close the session
    session.close();

    // Wait for session to close on the server
    count = 0;
    while (count < 50 && Bug58624ServerEndpoint.getOpenSessionCount() > 0) {
        count++;
        Thread.sleep(100);
    }
    Assert.assertEquals(0,  Bug58624ServerEndpoint.getOpenSessionCount());

    // Ensure no errors were reported on the server
    Assert.assertEquals(0,  Bug58624ServerEndpoint.getErrorCount());

    if (client.getError() != null) {
        throw client.getError();
    }
}
 
Example 17
Source File: FHIRServerTestBase.java    From FHIR with Apache License 2.0 4 votes vote down vote up
/**
 * Creates and returns an "endpoint" to be used to receive notifications via a
 * websocket.
 */
protected FHIRNotificationServiceClientEndpoint getWebsocketClientEndpoint() {
    try {
        FHIRNotificationServiceClientEndpoint endpoint = new FHIRNotificationServiceClientEndpoint();
        ClientEndpointConfig config = ClientEndpointConfig.Builder.create().configurator(new Configurator() {
            @Override
            public void beforeRequest(Map<String, List<String>> headers) {
                String userpw = getFhirUser() + ":" + getFhirPassword();
                String encoding = Base64.getEncoder().encodeToString(userpw.getBytes());
                List<String> values = new ArrayList<String>();
                values.add("Basic " + encoding);
                headers.put("Authorization", values);
            }
        }).build();

        String webSocketURL = getWebSocketURL();
        if (webSocketURL.startsWith("wss")) {
            String tsLoc = getAbsoluteFilename(getTsLocation());
            if (tsLoc == null) {
                throw new FileNotFoundException("Truststore file not found: " + getTsLocation());
            }

            String ksLoc = getAbsoluteFilename(getKsLocation());
            if (ksLoc == null) {
                throw new FileNotFoundException("Keystore file not found: " + getKsLocation());
            }

            System.getProperties().put(SslContextConfigurator.KEY_STORE_FILE, ksLoc);
            System.getProperties().put(SslContextConfigurator.KEY_STORE_PASSWORD, getKsPassword());
            System.getProperties().put(SslContextConfigurator.TRUST_STORE_FILE, tsLoc);
            System.getProperties().put(SslContextConfigurator.TRUST_STORE_PASSWORD, getTsPassword());

            final SslContextConfigurator defaultConfig = new SslContextConfigurator();
            defaultConfig.retrieve(System.getProperties());
            SslEngineConfigurator sslEngineConfigurator = new SslEngineConfigurator(defaultConfig, true, false,
                    false);
            sslEngineConfigurator.setHostVerificationEnabled(false);
            config.getUserProperties().put(PROPNAME_SSL_ENGINE_CONFIGURATOR, sslEngineConfigurator);

        }
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        Session session = container.connectToServer(endpoint, config, new URI(webSocketURL));

        // Add a Delay
        int count = 10;
        while ( !session.isOpen() && count > 0) {
            System.out.println(">>> " + count + " waiting");
            Thread.sleep(1000l);
            count--;
        }

        endpoint.setSession(session);
        return endpoint;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 18
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetOpenSessions() 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();

    EndpointA endpointA = new EndpointA();
    Session s1a = connectToEchoServer(wsContainer, endpointA,
            TesterEchoServer.Config.PATH_BASIC);
    Session s2a = connectToEchoServer(wsContainer, endpointA,
            TesterEchoServer.Config.PATH_BASIC);
    Session s3a = connectToEchoServer(wsContainer, endpointA,
            TesterEchoServer.Config.PATH_BASIC);

    EndpointB endpointB = new EndpointB();
    Session s1b = connectToEchoServer(wsContainer, endpointB,
            TesterEchoServer.Config.PATH_BASIC);
    Session s2b = connectToEchoServer(wsContainer, endpointB,
            TesterEchoServer.Config.PATH_BASIC);

    Set<Session> setA = s3a.getOpenSessions();
    Assert.assertEquals(3, setA.size());
    Assert.assertTrue(setA.remove(s1a));
    Assert.assertTrue(setA.remove(s2a));
    Assert.assertTrue(setA.remove(s3a));

    s1a.close();

    setA = s3a.getOpenSessions();
    Assert.assertEquals(2, setA.size());
    Assert.assertFalse(setA.remove(s1a));
    Assert.assertTrue(setA.remove(s2a));
    Assert.assertTrue(setA.remove(s3a));

    Set<Session> setB = s1b.getOpenSessions();
    Assert.assertEquals(2, setB.size());
    Assert.assertTrue(setB.remove(s1b));
    Assert.assertTrue(setB.remove(s2b));
}
 
Example 19
Source File: StandardWebSocketClient.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Default constructor that calls
 * {@code ContainerProvider.getWebSocketContainer()} to obtain a (new)
 * {@link WebSocketContainer} instance.
 */
public StandardWebSocketClient() {
	this(ContainerProvider.getWebSocketContainer());
}
 
Example 20
Source File: StandardWebSocketClient.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Default constructor that calls {@code ContainerProvider.getWebSocketContainer()}
 * to obtain a (new) {@link WebSocketContainer} instance. Also see constructor
 * accepting existing {@code WebSocketContainer} instance.
 */
public StandardWebSocketClient() {
	this.webSocketContainer = ContainerProvider.getWebSocketContainer();
}