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:cz.cvut.fel.UserSession.java

public void sendMessage(JsonObject message) throws IOException {
    log.debug("USER {}: Sending message {}", name, message);
    session.sendMessage(new TextMessage(message.toString()));
}

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

private void testExcludeEligible(Boolean excludeMe, List<Integer> exclude, List<Integer> eligible,
        List<Integer> expectedReceiver)
        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("anotherTopic");
        String json = subscribeMsg.toJson(this.jsonFactory);
        webSocketSession1.sendMessage(new TextMessage(json));
        webSocketSession2.sendMessage(new TextMessage(json));

        PublishMessage pm;/*from ww  w .  jav  a 2  s .com*/
        if (excludeMe != null) {
            pm = new PublishMessage("anotherTopic", "the test message", excludeMe);
        } else if (exclude != null) {
            Set<String> excludeSet = new HashSet<>();
            if (exclude.contains(1)) {
                excludeSet.add(result1.getWelcomeMessage().getWebSocketSessionId());
            }
            if (exclude.contains(2)) {
                excludeSet.add(result2.getWelcomeMessage().getWebSocketSessionId());
            }

            if (eligible != null) {
                Set<String> eligibleSet = new HashSet<>();
                if (eligible.contains(1)) {
                    eligibleSet.add(result1.getWelcomeMessage().getWebSocketSessionId());
                }
                if (eligible.contains(2)) {
                    eligibleSet.add(result2.getWelcomeMessage().getWebSocketSessionId());
                }

                pm = new PublishMessage("anotherTopic", "the test message", excludeSet, eligibleSet);
            } else {
                pm = new PublishMessage("anotherTopic", "the test message", excludeSet);
            }
        } else {
            pm = new PublishMessage("anotherTopic", "the test message");
        }
        webSocketSession1.sendMessage(new TextMessage(pm.toJson(this.jsonFactory)));

        if (expectedReceiver.contains(1)) {
            EventMessage event1 = (EventMessage) result1.getWampMessage();
            assertThat(event1.getTopicURI()).isEqualTo("anotherTopic");
            assertThat(event1.getEvent()).isEqualTo("the test message");
        } else {
            try {
                result1.getWampMessage();
                Assert.fail("call has to timeout");
            } catch (Exception e) {
                assertThat(e).isInstanceOf(TimeoutException.class);
            }
        }

        if (expectedReceiver.contains(2)) {
            EventMessage event2 = (EventMessage) result2.getWampMessage();
            assertThat(event2.getTopicURI()).isEqualTo("anotherTopic");
            assertThat(event2.getEvent()).isEqualTo("the test message");
        } else {
            try {
                result2.getWampMessage();
                Assert.fail("call has to timeout");
            } catch (Exception e) {
                assertThat(e).isInstanceOf(TimeoutException.class);
            }
        }

    }
}

From source file:org.kurento.tutorial.helloworld.HelloWorldRecHandler.java

private void start(final WebSocketSession session, JsonObject jsonMessage) {
    try {//from   ww  w.  j  a  va2s  . c o  m
        // 0. Repository logic
        RepositoryItemRecorder repoItem = null;
        if (repositoryClient != null) {
            try {
                Map<String, String> metadata = Collections.emptyMap();
                repoItem = repositoryClient.createRepositoryItem(metadata);
            } catch (Exception e) {
                log.warn("Unable to create kurento repository items", e);
            }
        } else {
            String now = df.format(new Date());
            String filePath = HelloWorldRecApp.REPOSITORY_SERVER_URI + now + RECORDING_EXT;
            repoItem = new RepositoryItemRecorder();
            repoItem.setId(now);
            repoItem.setUrl(filePath);
        }
        log.info("Media will be recorded {}by KMS: id={} , url={}",
                (repositoryClient == null ? "locally " : ""), repoItem.getId(), repoItem.getUrl());

        // 1. Media logic (webRtcEndpoint in loopback)
        MediaPipeline pipeline = kurento.createMediaPipeline();
        WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
        webRtcEndpoint.connect(webRtcEndpoint);
        RecorderEndpoint recorder = new RecorderEndpoint.Builder(pipeline, repoItem.getUrl())
                .withMediaProfile(MediaProfileSpecType.WEBM).build();
        webRtcEndpoint.connect(recorder);

        // 2. Store user session
        UserSession user = new UserSession(session);
        user.setMediaPipeline(pipeline);
        user.setWebRtcEndpoint(webRtcEndpoint);
        user.setRepoItem(repoItem);
        registry.register(user);

        // 3. SDP negotiation
        String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
        String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

        // 4. Gather ICE candidates
        webRtcEndpoint.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

            @Override
            public void onEvent(IceCandidateFoundEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "iceCandidate");
                response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                try {
                    synchronized (session) {
                        session.sendMessage(new TextMessage(response.toString()));
                    }
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        });

        JsonObject response = new JsonObject();
        response.addProperty("id", "startResponse");
        response.addProperty("sdpAnswer", sdpAnswer);

        synchronized (user) {
            session.sendMessage(new TextMessage(response.toString()));
        }

        webRtcEndpoint.gatherCandidates();

        recorder.record();
    } catch (Throwable t) {
        log.error("Start error", t);
        sendError(session, t.getMessage());
    }
}

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

private void getStats(WebSocketSession session) {
    try {//from  w ww  . j a va  2 s. c om
        UserSession user = users.get(session.getId());
        if (user == null) {
            return;
        }

        Map<String, Stats> wr_stats = user.getWebRtcEndpoint().getStats();
        //System.err.println("GET STATS..." + user.getWebRtcEndpoint().getStats());
        System.err.println("GET STATS..." + wr_stats);
        for (Stats s : wr_stats.values()) {
            //for (Stats s :  user.getWebRtcEndpoint().getStats().values()) {
            //System.err.println("STATS:" + s);          
            switch (s.getType()) {
            case endpoint:
                //System.err.println("STATS endpoint");
                EndpointStats end_stats = (EndpointStats) s;
                double e2eVideLatency = end_stats.getVideoE2ELatency() / 1000000;

                smart("***SMART E2E\t", e2eVideLatency, session.getId());

                JsonObject response = new JsonObject();
                response.addProperty("id", "videoE2Elatency");
                response.addProperty("message", e2eVideLatency);

                sendMessage(session, new TextMessage(response.toString()));
                break;

            //case inboundrtp:{
            //RTCInboundRTPStreamStats stats = (RTCInboundRTPStreamStats)s;
            //System.err.println(stats.getJitter());
            //}
            //break;
            //case outboundrtp:{
            //RTCOutboundRTPStreamStats stats = (RTCOutboundRTPStreamStats)s;
            //  System.err.println(stats.getRoundTripTime());

            //    JsonObject response = new JsonObject();
            //    response.addProperty("id", "videoE2Elatency");
            //    response.addProperty("message", stats.getRoundTripTime());

            // synchronized (session) {
            //    session.sendMessage(new TextMessage(response.toString()));            
            // }
            //}
            //break;

            default:
                //System.err.println("STATS DEFAULTS: " + s.getType() + "#" + s.getClass());
                break;
            }
        }
    } catch (Throwable e) {
        log.error("Exception stats", e);
    }

}

From source file:com.zb.app.websocket.api.MessagePushAPI.java

private void doSend(Long cId, Long mId, String msg) {
    Collection<WebSocketSession> set = sessionHandler.getSession(mId);
    if (Argument.isEmpty(set)) {
        logger.error(//from   w w  w  . ja  va  2s  .  c om
                "MessagePushAPI:sendPushMsg msg error:?{},cid:?{},mid:?{}is offLine!webSocketSession set is null!",
                msg, cId, mId);
    }
    for (WebSocketSession session : set) {
        if (session == null) {
            logger.error(
                    "MessagePushAPI:sendPushMsg msg error:?{},cid:?{},mid:?{}is offLine!session is null!",
                    msg, cId, mId);
        }
        try {
            session.sendMessage(new TextMessage(msg));
            logger.debug(
                    "MessagePushAPI:sendPushMsg msg success:?{},cid:?{},mid:?{},sessionId:?{}",
                    msg, cId, mId, session.getId());
        } catch (Exception e) {
            logger.error(
                    "MessagePushAPI:sendPushMsg msg error:?{},cid:?{},mid:?{},sessionId:?{}",
                    msg, cId, mId, session.getId());
        }
    }
}

From source file:org.kurento.tutorial.one2onecall.CallHandler.java

private void incomingCallResponse(final UserSession callee, JsonObject jsonMessage) throws IOException {
    String callResponse = jsonMessage.get("callResponse").getAsString();
    String from = jsonMessage.get("from").getAsString();
    final UserSession calleer = registry.getByName(from);
    String to = calleer.getCallingTo();

    if ("accept".equals(callResponse)) {
        log.debug("Accepted call from '{}' to '{}'", from, to);

        CallMediaPipeline pipeline = null;
        try {/*from  w w w.j av a  2 s .  c o m*/
            pipeline = new CallMediaPipeline(kurento);
            pipelines.put(calleer.getSessionId(), pipeline);
            pipelines.put(callee.getSessionId(), pipeline);

            callee.setWebRtcEndpoint(pipeline.getCalleeWebRtcEp());
            pipeline.getCalleeWebRtcEp()
                    .addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

                        @Override
                        public void onEvent(IceCandidateFoundEvent event) {
                            JsonObject response = new JsonObject();
                            response.addProperty("id", "iceCandidate");
                            response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                            try {
                                synchronized (callee.getSession()) {
                                    callee.getSession().sendMessage(new TextMessage(response.toString()));
                                }
                            } catch (IOException e) {
                                log.debug(e.getMessage());
                            }
                        }
                    });

            calleer.setWebRtcEndpoint(pipeline.getCallerWebRtcEp());
            pipeline.getCallerWebRtcEp()
                    .addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

                        @Override
                        public void onEvent(IceCandidateFoundEvent event) {
                            JsonObject response = new JsonObject();
                            response.addProperty("id", "iceCandidate");
                            response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                            try {
                                synchronized (calleer.getSession()) {
                                    calleer.getSession().sendMessage(new TextMessage(response.toString()));
                                }
                            } catch (IOException e) {
                                log.debug(e.getMessage());
                            }
                        }
                    });

            String calleeSdpOffer = jsonMessage.get("sdpOffer").getAsString();
            String calleeSdpAnswer = pipeline.generateSdpAnswerForCallee(calleeSdpOffer);
            JsonObject startCommunication = new JsonObject();
            startCommunication.addProperty("id", "startCommunication");
            startCommunication.addProperty("sdpAnswer", calleeSdpAnswer);

            synchronized (callee) {
                callee.sendMessage(startCommunication);
            }

            pipeline.getCalleeWebRtcEp().gatherCandidates();

            String callerSdpOffer = registry.getByName(from).getSdpOffer();
            String callerSdpAnswer = pipeline.generateSdpAnswerForCaller(callerSdpOffer);
            JsonObject response = new JsonObject();
            response.addProperty("id", "callResponse");
            response.addProperty("response", "accepted");
            response.addProperty("sdpAnswer", callerSdpAnswer);

            synchronized (calleer) {
                calleer.sendMessage(response);
            }

            pipeline.getCallerWebRtcEp().gatherCandidates();

        } catch (Throwable t) {
            log.error(t.getMessage(), t);

            if (pipeline != null) {
                pipeline.release();
            }

            pipelines.remove(calleer.getSessionId());
            pipelines.remove(callee.getSessionId());

            JsonObject response = new JsonObject();
            response.addProperty("id", "callResponse");
            response.addProperty("response", "rejected");
            calleer.sendMessage(response);

            response = new JsonObject();
            response.addProperty("id", "stopCommunication");
            callee.sendMessage(response);
        }

    } else {
        JsonObject response = new JsonObject();
        response.addProperty("id", "callResponse");
        response.addProperty("response", "rejected");
        calleer.sendMessage(response);
    }
}

From source file:com.kurento.kmf.jsonrpcconnector.client.JsonRpcClientWebSocket.java

private <P, R> Response<R> sendRequestForHelper(Request<P> request, Class<R> resultClass) throws IOException {

    connectIfNecessary();//from w  ww  .  jav a2 s.c  o  m

    Future<Response<JsonElement>> responseFuture = null;

    if (request.getId() != null) {
        responseFuture = pendingRequests.prepareResponse(request.getId());
    }

    String jsonMessage = request.toString();
    // log.info("--> {}", jsonMessage);
    synchronized (wsSession) {
        wsSession.sendMessage(new TextMessage(jsonMessage));
    }

    if (responseFuture == null) {
        return null;
    }

    try {

        // TODO Put a timeout to avoid blocking the thread when a response
        // is not sent from server
        Response<JsonElement> responseJson = responseFuture.get();

        Response<R> response = MessageUtils.convertResponse(responseJson, resultClass);

        if (response.getSessionId() != null) {
            session.setSessionId(response.getSessionId());
        }

        return response;

    } catch (InterruptedException e) {
        // TODO What to do in this case?
        throw new RuntimeException("Interrupted while waiting for a response", e);
    } catch (ExecutionException e) {
        // TODO Is there a better way to handle this?
        throw new RuntimeException("This exception shouldn't be thrown", e);
    }
}

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

@Test
public void testPublish5() 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)) {

        webSocketSession1//from   w w  w .j a  v  a 2  s . c  om
                .sendMessage(new TextMessage(new SubscribeMessage("replyTo5").toJson(this.jsonFactory)));
        webSocketSession2
                .sendMessage(new TextMessage(new SubscribeMessage("replyTo5").toJson(this.jsonFactory)));

        PublishMessage pm = new PublishMessage("incomingPublish5", "testPublish5");
        webSocketSession1.sendMessage(new TextMessage(pm.toJson(this.jsonFactory)));

        EventMessage event1 = (EventMessage) result1.getWampMessage();
        assertThat(event1.getTopicURI()).isEqualTo("replyTo5");
        assertThat(event1.getEvent()).isEqualTo("return5:testPublish5");

        EventMessage event = null;
        try {
            event = (EventMessage) result2.getWampMessage();
            Assert.fail("call has to timeout");
        } catch (Exception e) {
            assertThat(e).isInstanceOf(TimeoutException.class);
        }
        assertThat(event).isNull();
    }
}

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

public String performWebRtcNegotiation(final WebSocketSession session, String sdpOffer) {
    log.info("Starting WebRTC negotiation in session {}", sessionId);

    // Subscribe to ICE candidates
    webRtcEndpoint.addOnIceCandidateListener(new EventListener<OnIceCandidateEvent>() {
        @Override/* w  w w  . j  a v a2s. co m*/
        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()));
        }
    });

    // SDP negotiation
    String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

    // Gather ICE candidates
    webRtcEndpoint.gatherCandidates();

    return sdpAnswer;
}

From source file:org.kurento.tutorial.one2onecalladv.CallHandler.java

private void incomingCallResponse(final UserSession callee, JsonObject jsonMessage) throws IOException {
    String callResponse = jsonMessage.get("callResponse").getAsString();
    String from = jsonMessage.get("from").getAsString();
    final UserSession calleer = registry.getByName(from);
    String to = calleer.getCallingTo();
    String ClaimID = callee.getClaimID();
    String UserID = callee.getUserID();

    if ("accept".equals(callResponse)) {
        log.debug("Accepted call from '{}' to '{}'", from, to);

        CallMediaPipeline callMediaPipeline = new CallMediaPipeline(kurento, from, to);
        pipelines.put(calleer.getSessionId(), callMediaPipeline.getPipeline());
        pipelines.put(callee.getSessionId(), callMediaPipeline.getPipeline());

        callee.setWebRtcEndpoint(callMediaPipeline.getCalleeWebRtcEp());
        callMediaPipeline.getCalleeWebRtcEp()
                .addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

                    @Override//from w  w w.  ja va 2s . co  m
                    public void onEvent(IceCandidateFoundEvent event) {
                        JsonObject response = new JsonObject();
                        response.addProperty("id", "iceCandidate");
                        response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                        try {
                            synchronized (callee.getSession()) {
                                callee.getSession().sendMessage(new TextMessage(response.toString()));
                            }
                        } catch (IOException e) {
                            log.debug(e.getMessage());
                        }
                    }
                });

        String calleeSdpOffer = jsonMessage.get("sdpOffer").getAsString();
        String calleeSdpAnswer = callMediaPipeline.generateSdpAnswerForCallee(calleeSdpOffer);
        JsonObject startCommunication = new JsonObject();
        startCommunication.addProperty("id", "startCommunication");
        startCommunication.addProperty("sdpAnswer", calleeSdpAnswer);

        synchronized (callee) {
            callee.sendMessage(startCommunication);
        }

        callMediaPipeline.getCalleeWebRtcEp().gatherCandidates();

        String callerSdpOffer = registry.getByName(from).getSdpOffer();

        calleer.setWebRtcEndpoint(callMediaPipeline.getCallerWebRtcEp());
        callMediaPipeline.getCallerWebRtcEp()
                .addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

                    @Override
                    public void onEvent(IceCandidateFoundEvent event) {
                        JsonObject response = new JsonObject();
                        response.addProperty("id", "iceCandidate");
                        response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                        try {
                            synchronized (calleer.getSession()) {
                                calleer.getSession().sendMessage(new TextMessage(response.toString()));
                            }
                        } catch (IOException e) {
                            log.debug(e.getMessage());
                        }
                    }
                });

        String callerSdpAnswer = callMediaPipeline.generateSdpAnswerForCaller(callerSdpOffer);

        JsonObject response = new JsonObject();
        response.addProperty("id", "callResponse");
        response.addProperty("response", "accepted");
        response.addProperty("sdpAnswer", callerSdpAnswer);

        synchronized (calleer) {
            calleer.sendMessage(response);
        }

        callMediaPipeline.getCallerWebRtcEp().gatherCandidates();

        callMediaPipeline.record(ClaimID, UserID);

    } else {
        JsonObject response = new JsonObject();
        response.addProperty("id", "callResponse");
        response.addProperty("response", "rejected");
        calleer.sendMessage(response);
    }
}