Example usage for org.springframework.web.socket TextMessage TextMessage

List of usage examples for org.springframework.web.socket TextMessage TextMessage

Introduction

In this page you can find the example usage for org.springframework.web.socket TextMessage TextMessage.

Prototype

public TextMessage(byte[] payload) 

Source Link

Document

Create a new text WebSocket message from the given byte[].

Usage

From source file:org.acruxsource.sandbox.spring.jmstows.websocket.ChatHandler.java

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    logger.info("New incoming message: " + message.getPayload());

    StringReader stringReader = new StringReader(message.getPayload());
    JsonReader jsonReader = Json.createReader(stringReader);
    JsonObject chatMessageObject = jsonReader.readObject();

    if (chatMessageObject.getJsonString("name") != null && chatMessageObject.getJsonString("message") != null) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setName(chatMessageObject.getJsonString("name").getString());
        chatMessage.setMessage(chatMessageObject.getJsonString("message").getString());
        jmsMessageSender.sendMessage("websocket.out", chatMessage);
    } else {//from   w  w  w .  ja va  2  s.c om
        session.sendMessage(new TextMessage("Empty name or message"));
    }
}

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

private void sendInternal(Message<byte[]> message) {
    byte[] bytes = this.encoder.encode(message);
    try {//from   w w  w . j  a v  a2s. com
        this.webSocketSession.sendMessage(new TextMessage(new String(bytes, UTF_8)));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

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

@Test
public void testPubSub() throws InterruptedException, ExecutionException, TimeoutException, IOException {

    CompletableFutureWebSocketHandler result = new CompletableFutureWebSocketHandler(this.jsonFactory);
    try (WebSocketSession webSocketSession = startWebSocketSession(result)) {
        SubscribeMessage subscribeMsg = new SubscribeMessage("/topic");
        webSocketSession.sendMessage(new TextMessage(subscribeMsg.toJson(this.jsonFactory)));

        PublishMessage pm = new PublishMessage("/topic", "payload");
        webSocketSession.sendMessage(new TextMessage(pm.toJson(this.jsonFactory)));

        EventMessage event = (EventMessage) result.getWampMessage();
        assertThat(event.getTopicURI()).isEqualTo("/topic");
        assertThat(event.getEvent()).isEqualTo("payload");

        result.reset();/*w w w .  ja v  a 2  s .  c  o  m*/

        UnsubscribeMessage unsubscribeMsg = new UnsubscribeMessage("/topic");
        webSocketSession.sendMessage(new TextMessage(unsubscribeMsg.toJson(this.jsonFactory)));

        try {
            pm = new PublishMessage("/topic", "payload2");
            webSocketSession.sendMessage(new TextMessage(pm.toJson(this.jsonFactory)));

            event = (EventMessage) result.getWampMessage();
            Assert.fail("call shoud timeout");
        } catch (Exception e) {
            assertThat(e).isInstanceOf(TimeoutException.class);
        }
    }

}

From source file:eu.nubomedia.tutorial.repository.RepositoryHandler.java

private void start(WebSocketSession session, JsonObject jsonMessage) {
    // User session
    String sessionId = session.getId();
    UserSession user = new UserSession(sessionId, repositoryClient, this);
    users.put(sessionId, user);//from   w ww . j  a v a2s . c o m

    // Media logic for recording
    String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
    String sdpAnswer = user.startRecording(session, sdpOffer);

    // Response message
    JsonObject response = new JsonObject();
    response.addProperty("id", "startResponse");
    response.addProperty("sdpAnswer", sdpAnswer);
    sendMessage(session, new TextMessage(response.toString()));
}

From source file:fi.vtt.nubomedia.armodule.UserSession.java

public String startSession(final WebSocketSession session, String sdpOffer, JsonObject jsonMessage) {
    System.err.println("ME USER SESSION START SESSION");

    // One KurentoClient instance per session
    kurentoClient = KurentoClient.create();
    log.info("Created kurentoClient (session {})", sessionId);

    // Media logic (pipeline and media elements connectivity)
    mediaPipeline = kurentoClient.createMediaPipeline();
    log.info("Created Media Pipeline {} (session {})", mediaPipeline.getId(), session.getId());

    mediaPipeline.setLatencyStats(true);
    log.info("Media Pipeline {} latencyStants set{}", mediaPipeline.getId(), mediaPipeline.getLatencyStats());

    webRtcEndpoint = new WebRtcEndpoint.Builder(mediaPipeline).build();
    handler.createPipeline(this, jsonMessage);

    // WebRTC negotiation
    webRtcEndpoint.addOnIceCandidateListener(new EventListener<OnIceCandidateEvent>() {
        @Override/*ww w.  j a v a2s.com*/
        public void onEvent(OnIceCandidateEvent event) {
            JsonObject response = new JsonObject();
            response.addProperty("id", "iceCandidate");
            response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
            handler.sendMessage(session, new TextMessage(response.toString()));
        }
    });
    String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);
    webRtcEndpoint.gatherCandidates();

    return sdpAnswer;
}

From source file:fi.vtt.nubomedia.armodule.BaseHandler.java

private void start(final WebSocketSession session, JsonObject jsonMessage) {
    try {/* w  w w . j av a2s  .  c  o m*/
        UserSession user = new UserSession(session.getId(), this);
        users.put(session.getId(), user);

        try {
            out = new PrintWriter("smart.txt");
        } catch (Throwable t) {
            t.printStackTrace();
        }
        String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
        String sdpAnswer = user.startSession(session, sdpOffer, jsonMessage);

        JsonObject response = new JsonObject();
        response.addProperty("id", "startResponse");
        response.addProperty("sdpAnswer", sdpAnswer);
        sendMessage(session, new TextMessage(response.toString()));
    } catch (Throwable t) {
        t.printStackTrace();
        error(session, t.getMessage());
    }
}

From source file:ch.rasc.wampspring.testsupport.BaseWampTest.java

protected WampMessage sendAuthenticatedMessage(WampMessage msg) throws Exception {
    CompletableFutureWebSocketHandler result = new CompletableFutureWebSocketHandler(this.jsonFactory);

    WebSocketClient webSocketClient = createWebSocketClient();
    try (WebSocketSession webSocketSession = webSocketClient.doHandshake(result, wampEndpointUrl()).get()) {

        result.getWelcomeMessage();/* w  ww.j  a  v a  2  s. co  m*/
        authenticate(result, webSocketSession);
        webSocketSession.sendMessage(new TextMessage(msg.toJson(this.jsonFactory)));

        return result.getWampMessage();
    }
}

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

/**
 * Handle incoming WebSocket messages from clients.
 *///w  w  w.j  a  v  a2s.c o  m
@Override
public void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> webSocketMessage,
        MessageChannel outputChannel) {

    Assert.isInstanceOf(TextMessage.class, webSocketMessage);
    WampMessage wampMessage = null;
    try {
        wampMessage = WampMessage.fromJson(session, this.jsonFactory,
                ((TextMessage) webSocketMessage).getPayload());
    } catch (Throwable ex) {
        if (logger.isErrorEnabled()) {
            logger.error("Failed to parse " + webSocketMessage + " in session " + session.getId() + ".", ex);
        }
        return;
    }

    try {
        WampSessionContextHolder.setAttributesFromMessage(wampMessage);
        outputChannel.send(wampMessage);
    } catch (Throwable ex) {
        logger.error("Failed to send client message to application via MessageChannel" + " in session "
                + session.getId() + ".", ex);

        if (wampMessage != null && wampMessage instanceof CallMessage) {

            CallErrorMessage callErrorMessage = new CallErrorMessage((CallMessage) wampMessage, "",
                    ex.toString());

            try {
                String json = callErrorMessage.toJson(this.jsonFactory);
                session.sendMessage(new TextMessage(json));
            } catch (Throwable t) {
                // Could be part of normal workflow (e.g. browser tab closed)
                logger.debug("Failed to send error to client.", t);
            }

        }
    } finally {
        WampSessionContextHolder.resetAttributes();
    }
}

From source file:ch.rasc.wampspring.pubsub.PubSubReplyAnnotationTest.java

@Test
public void testPublish2() throws InterruptedException, ExecutionException, IOException, TimeoutException {

    CompletableFutureWebSocketHandler result1 = new CompletableFutureWebSocketHandler(this.jsonFactory);
    CompletableFutureWebSocketHandler result2 = new CompletableFutureWebSocketHandler(this.jsonFactory);

    try (WebSocketSession webSocketSession1 = startWebSocketSession(result1);
            WebSocketSession webSocketSession2 = startWebSocketSession(result2)) {

        SubscribeMessage subscribeMsg = new SubscribeMessage("replyTo2");
        webSocketSession1.sendMessage(new TextMessage(subscribeMsg.toJson(this.jsonFactory)));
        webSocketSession2.sendMessage(new TextMessage(subscribeMsg.toJson(this.jsonFactory)));

        PublishMessage pm = new PublishMessage("pubSubService.incomingPublish2", "testPublish2");
        webSocketSession1.sendMessage(new TextMessage(pm.toJson(this.jsonFactory)));

        EventMessage event = (EventMessage) result2.getWampMessage();
        assertThat(event.getTopicURI()).isEqualTo("replyTo2");
        assertThat(event.getEvent()).isEqualTo("return2:testPublish2");

        event = null;//  w w  w  .  j av  a2 s . com
        try {
            event = (EventMessage) result1.getWampMessage();
            Assert.fail("call has to timeout");
        } catch (Exception e) {
            assertThat(e).isInstanceOf(TimeoutException.class);
        }
        assertThat(event).isNull();
    }

}

From source file:org.opencron.server.websocket.TerminalHandler.java

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    super.handleTextMessage(session, message);
    try {/*from  w  w w. j a  v a 2s . c  om*/
        getClient(session, null);
        if (this.terminalClient != null) {
            if (!terminalClient.isClosed()) {
                terminalClient.write(message.getPayload());
            } else {
                session.close();
            }
        }
    } catch (Exception e) {
        session.sendMessage(new TextMessage("Sorry! Opencron Terminal was closed, please try again. "));
        terminalClient.disconnect();
        session.close();
    }
}