Example usage for org.springframework.web.socket.sockjs.client SockJsClient SockJsClient

List of usage examples for org.springframework.web.socket.sockjs.client SockJsClient SockJsClient

Introduction

In this page you can find the example usage for org.springframework.web.socket.sockjs.client SockJsClient SockJsClient.

Prototype

public SockJsClient(List<Transport> transports) 

Source Link

Document

Create a SockJsClient with the given transports.

Usage

From source file:ch.rasc.wampspring.demo.client.CallClientSockJs.java

public static void main(String[] args) throws InterruptedException {

    List<Transport> transports = new ArrayList<>(2);
    transports.add(new WebSocketTransport(new StandardWebSocketClient()));
    transports.add(new RestTemplateXhrTransport());
    WebSocketClient webSocketClient = new SockJsClient(transports);

    JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper());

    CountDownLatch latch = new CountDownLatch(10_000);
    TestTextWebSocketHandler handler = new TestTextWebSocketHandler(jsonFactory, latch);

    Long[] start = new Long[1];
    ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler,
            "ws://localhost:8080/wampOverSockJS");
    future.addCallback(wss -> {// w w w.j  a va  2 s .co  m
        start[0] = System.currentTimeMillis();
        for (int i = 0; i < 10_000; i++) {

            CallMessage callMessage = new CallMessage(UUID.randomUUID().toString(), "testService.sum", i,
                    i + 1);
            try {
                wss.sendMessage(new TextMessage(callMessage.toJson(jsonFactory)));
            } catch (Exception e) {
                System.out.println("ERROR SENDING CALLMESSAGE" + e);
                latch.countDown();
            }
        }

    }, t -> {
        System.out.println("DO HANDSHAKE ERROR: " + t);
        System.exit(1);
    });

    if (!latch.await(3, TimeUnit.MINUTES)) {
        System.out.println("SOMETHING WENT WRONG");
    }

    System.out.println((System.currentTimeMillis() - start[0]) / 1000 + " seconds");
    System.out.println("SUCCESS: " + handler.getSuccess());
    System.out.println("ERROR  : " + handler.getError());
}

From source file:org.tommy.stationery.moracle.core.client.load.StompWebSocketLoadTestClient.java

public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
        host = args[0];// w  ww.  ja  v  a  2  s. c  om
    }

    int port = 59984;
    if (args.length > 1) {
        port = Integer.valueOf(args[1]);
    }

    String url = "http://" + host + ":" + port + "/home";
    logger.debug("Sending warm-up HTTP request to " + url);
    HttpStatus status = new RestTemplate().getForEntity(url, Void.class).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    Executor executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    org.eclipse.jetty.websocket.client.WebSocketClient jettyClient = new WebSocketClient(executor);
    JettyWebSocketClient webSocketClient = new JettyWebSocketClient(jettyClient);
    webSocketClient.start();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
        URI uri = new URI("ws://" + host + ":" + port + "/stomp");
        WebSocketStompClient stompClient = new WebSocketStompClient(uri, null, sockJsClient);
        stompClient.setMessageConverter(new StringMessageConverter());

        logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
        StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
        stopWatch.start();

        List<ConsumerStompMessageHandler> consumers = new ArrayList<>();
        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            consumers.add(new ConsumerStompMessageHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch,
                    messageLatch, disconnectLatch, failure));
            stompClient.connect(consumers.get(i));
        }

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users connected, remaining: " + connectLatch.getCount());
        }
        if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users subscribed, remaining: " + subscribeLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users ");
        stopWatch.start();

        ProducerStompMessageHandler producer = new ProducerStompMessageHandler(BROADCAST_MESSAGE_COUNT,
                failure);
        stompClient.connect(producer);

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            for (ConsumerStompMessageHandler consumer : consumers) {
                if (consumer.messageCount.get() < consumer.expectedMessageCount) {
                    logger.debug(consumer);
                }
            }
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all handlers received every message, remaining: " + messageLatch.getCount());
        }

        producer.session.disconnect();
        if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        System.out.println("\nPress any key to exit...");
        System.in.read();
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        webSocketClient.stop();
        jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
}

From source file:ymanv.forex.SockJsClientTest.java

private static void startSockJs(WebSocketHandler eh) throws Exception {
    List<Transport> transports = new ArrayList<>(2);
    transports.add(new WebSocketTransport(createWebSocketClient()));
    transports.add(new RestTemplateXhrTransport());

    SockJsClient sockJsClient = new SockJsClient(transports);

    sockJsClient.doHandshake(eh, URL).get();
}

From source file:ch.rasc.wampspring.config.SockJsTest.java

@Override
protected WebSocketClient createWebSocketClient() {
    List<Transport> transports = new ArrayList<>(2);
    transports.add(new WebSocketTransport(new StandardWebSocketClient()));
    transports.add(new RestTemplateXhrTransport());
    return new SockJsClient(transports);
}

From source file:de.metas.ui.web.vaadin.window.RestProxyWindowModel.java

public RestProxyWindowModel() {
    super();/*from   w  w  w  .ja v a2  s  . c  o m*/
    VaadinClientApplication.autowire(this);

    // WebSocket connection
    {
        final List<Transport> transports = new ArrayList<>(1);
        transports.add(new WebSocketTransport(new StandardWebSocketClient()));
        final WebSocketClient transport = new SockJsClient(transports);
        final WebSocketStompClient stompClient = new WebSocketStompClient(transport);

        stompClient.setMessageConverter(new MappingJackson2MessageConverter());
        stompClient.setTaskScheduler(taskScheduler); // for heartbeats, receipts

        final String url = "ws://127.0.0.1:8080" + WebSocketConfig.ENDPOINT;
        final StompSessionHandler handler = new RestProxyWindowModel_StompSessionHandler();
        futureWebSocketSession = stompClient.connect(url, handler);
    }
}

From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java

@BeforeClass
public static void setup() throws Exception {

    System.setProperty("spring.profiles.active", "test.tomcat");

    port = SocketUtils.findAvailableTcpPort();

    server = new TomcatWebSocketTestServer(port);
    server.deployConfig(TestDispatcherServletInitializer.class);
    server.start();/*from ww  w  . j  a  va 2 s.  c  o  m*/

    webSocketUri = "ws://localhost:" + port + "/composite/websocket";

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(new StandardWebSocketClient()));
    RestTemplateXhrTransport xhrTransport = new RestTemplateXhrTransport(new RestTemplate());
    xhrTransport.setRequestHeaders(headers);
    transports.add(xhrTransport);

    sockJsClient = new SockJsClient(transports);

}

From source file:com.codeveo.lago.bot.stomp.client.AbstractHttpLagoBot.java

protected void setupAndSignInClient(String lagoUrl, String botUsername, String botPassword,
        LagoRequestHelper requestHelper) throws Exception {
    try {// w w  w  . j ava 2 s  . c  o m
        if (requestHelper == null) {
            throw new Exception("Request helper must not be null");
        }

        if (!(requestHelper instanceof HttpLagoRequestHelper)) {
            throw new Exception("Requires instance of '" + HttpLagoRequestHelper.class.getSimpleName()
                    + "' not '" + requestHelper.getClass().getSimpleName() + "'");
        }

        HttpLagoRequestHelper httpRequestHelper = (HttpLagoRequestHelper) requestHelper;

        lagoBot = new RLagoBot(null, null, botUsername, botPassword);

        Builder builder = new AsyncHttpClientConfig.Builder();
        Realm realm = new Realm.RealmBuilder().setPrincipal(botUsername).setPassword(botPassword)
                .setUsePreemptiveAuth(true).setScheme(AuthScheme.BASIC).build();
        builder.setRealm(realm).build();

        asyncHttpClient = new AsyncHttpClient(builder.build());

        Pair<Integer, String> statusWithCookieOrFaultJSON = HttpLagoRequestHelper.signIn(lagoUrl, botUsername,
                botPassword);

        int statusCode = statusWithCookieOrFaultJSON.getLeft();

        if (statusCode == HttpStatus.CREATED.value()) {
            cookie = statusWithCookieOrFaultJSON.getRight();

            /* websocket headers */
            wsHeaders.add("Cookie", cookie);
        } else {
            String faultJSON = statusWithCookieOrFaultJSON.getRight();

            if (faultJSON != null) {
                RFault fault = objectMapper.readValue(faultJSON, RFault.class);

                if (fault != null) {
                    throw new Exception("Error occured during authentication (HTTP status code: " + statusCode
                            + ", Error code: " + fault.getErrorCode() + ", Message: '" + fault.getMessage()
                            + "')");
                }
            }

            throw new Exception("Error occured during authentication (HTTP status code: " + statusCode);
        }

        if (cookie == null) {
            throw new Exception("Bot '" + botUsername + "' could not sign in");
        }

        /* setup request helper */
        httpRequestHelper.setAsyncHttpClient(asyncHttpClient).setCookie(cookie).setObjectMapper(objectMapper)
                .setServerUrl(lagoUrl);
        this.httpLagoRequestHelper = httpRequestHelper;

        String wsLagoUrl = toWsUrl(lagoUrl);
        URI uri = new URI(wsLagoUrl + WebServiceUserDesc.WS_PATH);

        LagoStompMessageHandler messageListener = new LagoStompMessageHandler(lagoBot, queue);

        List<Transport> transports = new ArrayList<>();
        transports.add(new WebSocketTransport(new StandardWebSocketClient()));
        RestTemplateXhrTransport xhrTransport = new RestTemplateXhrTransport(new RestTemplate());
        xhrTransport.setRequestHeaders(wsHeaders);
        transports.add(xhrTransport);

        sockJsClient = new SockJsClient(transports);
        stompClient = new WebSocketStompClient(uri, wsHeaders, sockJsClient);
        stompClient.setMessageConverter(converter);
        stompClient.connect(messageListener);

        taskExecutor.submit(new StompMessageListener());
    } catch (Exception e) {
        if (cookie != null) {
            httpLagoRequestHelper.signOut();
        }

        throw new Exception("Error occured while initializing lago bot", e);
    }
}

From source file:org.appverse.web.framework.backend.frontfacade.websocket.IntegrationWebsocketTest.java

@BeforeClass
public static void setup() throws Exception {

    // Since test classpath includes both embedded Tomcat and Jetty we need to
    // set a Spring profile explicitly to bypass WebSocket engine detection.
    // See {@link org.springframework.samples.portfolio.config.WebSocketConfig}

    // This test is not supported with Jetty because it doesn't seem to support
    // deployment withspecific ServletContainerInitializer's at for testing

    System.setProperty("spring.profiles.active", "test.tomcat");

    port = SocketUtils.findAvailableTcpPort();

    server = new TomcatWebSocketTestServer(port);
    server.deployConfig(TestDispatcherServletInitializer.class, WebSecurityInitializer.class);
    server.start();/*from ww  w  . j av a  2  s. c om*/

    loginAndSaveJsessionIdCookie("fabrice", "fab123", headers);

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(new StandardWebSocketClient()));
    RestTemplateXhrTransport xhrTransport = new RestTemplateXhrTransport(new RestTemplate());
    xhrTransport.setRequestHeaders(headers);
    transports.add(xhrTransport);

    sockJsClient = new SockJsClient(transports);
}

From source file:org.springframework.samples.portfolio.web.load.StompWebSocketLoadTestClient.java

public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
        host = args[0];//from www . j a  va 2s .c  o m
    }

    int port = 37232;
    if (args.length > 1) {
        port = Integer.valueOf(args[1]);
    }

    String homeUrl = "http://{host}:{port}/home";
    logger.debug("Sending warm-up HTTP request to " + homeUrl);
    HttpStatus status = new RestTemplate().getForEntity(homeUrl, Void.class, host, port).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<>();

    StandardWebSocketClient webSocketClient = new StandardWebSocketClient();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.afterPropertiesSet();

        String stompUrl = "ws://{host}:{port}/stomp";
        WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
        stompClient.setMessageConverter(new StringMessageConverter());
        stompClient.setTaskScheduler(taskScheduler);
        stompClient.setDefaultHeartbeat(new long[] { 0, 0 });

        logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
        StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
        stopWatch.start();

        List<ConsumerStompSessionHandler> consumers = new ArrayList<>();
        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            consumers.add(new ConsumerStompSessionHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch,
                    messageLatch, disconnectLatch, failure));
            stompClient.connect(stompUrl, consumers.get(i), host, port);
        }

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all users connected, remaining: " + connectLatch.getCount());
        }
        if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all users subscribed, remaining: " + subscribeLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users ");
        stopWatch.start();

        ProducerStompSessionHandler producer = new ProducerStompSessionHandler(BROADCAST_MESSAGE_COUNT,
                failure);
        stompClient.connect(stompUrl, producer, host, port);
        stompClient.setTaskScheduler(taskScheduler);

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
            for (ConsumerStompSessionHandler consumer : consumers) {
                if (consumer.messageCount.get() < consumer.expectedMessageCount) {
                    logger.debug(consumer);
                }
            }
        }
        if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
            fail("Not all handlers received every message, remaining: " + messageLatch.getCount());
        }

        producer.session.disconnect();
        if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        System.out.println("\nPress any key to exit...");
        System.in.read();
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
}