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:ch.rasc.wampspring.pubsub.PubSubReplyAnnotationTest.java

@Test
public void testSubscribe1() throws InterruptedException, ExecutionException, IOException, TimeoutException {
    CompletableFutureWebSocketHandler result = new CompletableFutureWebSocketHandler(this.jsonFactory);
    try (WebSocketSession webSocketSession = startWebSocketSession(result)) {

        SubscribeMessage subscribeMsg = new SubscribeMessage("replyTo1");
        webSocketSession.sendMessage(new TextMessage(subscribeMsg.toJson(this.jsonFactory)));

        subscribeMsg = new SubscribeMessage("pubSubService.incomingSubscribe1");
        webSocketSession.sendMessage(new TextMessage(subscribeMsg.toJson(this.jsonFactory)));

        EventMessage event = (EventMessage) result.getWampMessage();
        assertThat(event.getTopicURI()).isEqualTo("replyTo1");
        assertThat(event.getEvent()).isEqualTo("returnSub1");

    }/*  w w  w.j a v  a 2 s .  co m*/
}

From source file:org.metis.push.PusherBean.java

@Override
/**//from   w  ww  . j  a  va 2 s .  com
 * This method handles an incoming message from the web socket client. 
 */
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

    if (session == null) {
        LOG.error(getBeanName() + ": null session");
        throw new Exception(getBeanName() + ":handleTextMessage, null session was received");
    }

    // the session should be in the registry
    WdsSocketSession wdsSession = getWdsSessions().get(session.getId());
    if (wdsSession == null) {
        LOG.error(getBeanName() + ":handleTextMessage, session with this id is not in registry: "
                + session.getId());
        session.close(new CloseStatus(SERVER_ERROR.getCode(),
                "ERROR, session with this id not in registry: " + session.getId()));
        return;
    }

    // some sort of message should have been received
    if (message == null) {
        LOG.error(getBeanName() + ":handleTextMessage, null message parameter");
        session.close(new CloseStatus(POLICY_VIOLATION.getCode(),
                "ERROR, session with this id gave a null message " + "parameter: " + session.getId()));
        return;
    }

    // we're supposed to receive a JSON object
    String jsonMsg = message.getPayload();

    if (jsonMsg == null) {
        LOG.error(getBeanName() + ":handleTextMessage, getPayload returns null or empty string");
        session.close(new CloseStatus(POLICY_VIOLATION.getCode(),
                "ERROR, session with this id did not return a payload: " + session.getId()));
        return;
    }

    if (jsonMsg.isEmpty()) {
        LOG.error(getBeanName() + ":handleTextMessage, getPayload returns zero-length string");
        session.close(new CloseStatus(POLICY_VIOLATION.getCode(),
                "ERROR, session with this id returns zero-length payload: " + session.getId()));
        return;
    }

    // dump the request if trace is on
    if (LOG.isTraceEnabled()) {
        LOG.trace(getBeanName() + ":***** processing new request *****");
        LOG.trace(getBeanName() + ":session id = " + session.getId());
        LOG.trace(getBeanName() + ":session remote address = " + session.getRemoteAddress().toString());
        LOG.trace(getBeanName() + ":session uri  = " + session.getUri().toString());
        LOG.trace(getBeanName() + ":session json object = " + jsonMsg);
    }

    // parse the json object
    List<Map<String, String>> jParams = null;
    try {
        jParams = Utils.parseJson(jsonMsg);
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":caught this " + "exception while parsing json object: " + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }

        session.close(new CloseStatus(SERVER_ERROR.getCode(),
                "ERROR, got this json parsing exception: " + exc.getMessage()));
        return;
    }

    if (jParams == null || jParams.isEmpty()) {
        LOG.error(getBeanName() + ":json parser returns null or " + "empty json array");
        session.close(
                new CloseStatus(SERVER_ERROR.getCode(), "ERROR, json parser returns null or empty json array"));
        return;
    }

    // if trace is on, dump the params (if any) to the log
    if (LOG.isDebugEnabled()) {
        LOG.debug(
                getBeanName() + ": handleRequestInternal, received these params: " + jParams.get(0).toString());
    }

    // get the command portion of the json message
    Map<String, String> map = jParams.get(0);
    String command = map.remove(WS_COMMAND);
    if (command == null) {
        LOG.error(getBeanName() + ":command field not present");
        session.close(POLICY_VIOLATION);
        session.close(new CloseStatus(POLICY_VIOLATION.getCode(),
                "ERROR, command string not present or improperly set: " + command));
        return;
    }

    if (!command.equals(WS_SUBSCRIBE) && !command.equals(WS_PING)) {
        LOG.error(getBeanName() + ":received this unknown command = " + command);
        session.close(POLICY_VIOLATION);
        session.close(new CloseStatus(POLICY_VIOLATION.getCode(),
                "ERROR, received this unknown command =  " + command));
        return;
    }

    // Get the SQL Job, if any, that this session is currently subscribed to
    SqlJob job = wdsSession.getMyJob();

    // if this is a ping command, return session's current subscription
    if (command.equals(WS_PING)) {
        LOG.debug(getBeanName() + ":received ping command");
        List<Map<String, Object>> response = new ArrayList<Map<String, Object>>();
        Map<String, Object> map0 = new HashMap<String, Object>();
        if (job != null) {
            LOG.debug(getBeanName() + ": client is subscribed");
            map0.put(WS_STATUS, WS_SUBSCRIBED);
            map = job.getParams();
            if (map != null && !map.isEmpty()) {
                for (String key : map.keySet()) {
                    map0.put(key, map.get(key));
                }
            }
        } else {
            LOG.debug(getBeanName() + ": client is not subscribed");
            map0.put(WS_STATUS, WS_OK);
        }
        response.add(map0);
        // send response back to client
        session.sendMessage(new TextMessage(Utils.generateJson(response)));
        return;
    }

    // find a sql statement that matches the incoming session request's
    // params
    SqlStmnt sqlStmnt = (map == null || map.isEmpty()) ? SqlStmnt.getMatch(getSqlStmnts4Get(), null)
            : SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet());

    // if getMatch could not find a match, then return error to client
    if (sqlStmnt == null) {
        LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this map: " + map.toString());
        List<Map<String, Object>> response = new ArrayList<Map<String, Object>>();
        Map<String, Object> map0 = new HashMap<String, Object>();
        if (map != null && !map.isEmpty()) {
            for (String key : map.keySet()) {
                map0.put(key, map.get(key));
            }
        }
        map0.put(WS_STATUS, WS_NOT_FOUND);
        // send response back to client
        session.sendMessage(new TextMessage(Utils.generateJson(response)));
        return;
    }

    // other than a ping, the only other command from the client is a
    // subscription command

    // Does this session already exist in one of the sql jobs? Note that the
    // client can switch subscriptions.
    if (job != null) {
        // the session pertains to a job, but does that job's map match
        // that of this session's subscription request
        if (job.isParamMatch(map)) {
            // if so, we're done
            return;
        } else {
            // else remove this session from that job - the client is
            // switching subscriptions
            job.removeSession(wdsSession.getId());
        }
    }

    mainLock.lock();
    try {
        // if we've gotten this far, the session does not pertain to a job
        // or it is a subscription change. so we now need to find an
        // existing job whose params match that of the incoming session. if
        // no job was found, then create and start one
        if (sqlStmnt.findSqlJob(map, wdsSession) == null) {
            sqlStmnt.createSqlJob(map, wdsSession);
        }
    } finally {
        mainLock.unlock();
    }
}

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

@Test
public void testSubscribe2() 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)));

        subscribeMsg = new SubscribeMessage("pubSubService.incomingSubscribe2");
        webSocketSession1.sendMessage(new TextMessage(subscribeMsg.toJson(this.jsonFactory)));

        EventMessage event = (EventMessage) result2.getWampMessage();
        assertThat(event.getTopicURI()).isEqualTo("replyTo2");
        assertThat(event.getEvent()).isEqualTo("returnSub2");

        event = null;//from  w  w  w  .  java2  s  .  co  m
        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:cn.com.inhand.devicenetworks.ap.websocket.WSDNAccessPoint.java

/**
 * ?Inbox/* www .j  a  v a2s  . c o  m*/
 *
 * @param login
 */
private void onLogin(DNMessage login, WebSocketSession session, WSDNSession wsdnsn)
        throws PacketException, IOException {
    if (login.getName().equals("login") && login.getType() == 0) {
        int result = auth(login);
        //API??
        if (result != 0) {
            List list = new ArrayList();
            list.add(new Parameter("result", "" + result));
            list.add(new Parameter("reason", ""));
            DNMessage ack = new DNMessage("login", "response", login.getTxid(), list);
            session.sendMessage(new TextMessage(new String(parser.wrap(ack))));
            list.clear();

            throw new PacketException("Failed to Login!");
        } else {
            //for debug
            if (login.getParameter("id").getValue().equals("1111")) {

                List list = new ArrayList();
                list.add(new Parameter("result", "21336"));
                list.add(new Parameter("reason", ""));
                DNMessage ack = new DNMessage("login", "response", login.getTxid(), list);
                session.sendMessage(new TextMessage(new String(parser.wrap(ack))));
                list.clear();

                throw new PacketException("The token is invalid!");
            } else {
                List list = new ArrayList();
                list.add(new Parameter("result", "0"));
                list.add(new Parameter("reason", ""));
                DNMessage ack = new DNMessage("login", "response", login.getTxid(), list);
                session.sendMessage(new TextMessage(new String(parser.wrap(ack))));
                list.clear();
                wsdnsn = new WSDNSession(login, session);
                wsdnsn.setAction(1);
                wsdnsn.setId(login.getParameter("id").getValue());
                wsdnsn.setIsLogin(true);
                wsdnsn.setAssetid(login.getParameter("asset_id").getValue());
                wsdnsn.setSn(login.getParameter("sn").getValue());
                wsdnsn.setToken(login.getParameter("access_token").getValue());

                wsdnsn.setKey(login.getParameter("key").getValue());
                wsdnsn.setId(login.getParameter("id").getValue());
                wsdnsn.setConnection_time(System.currentTimeMillis());
                wsdnsn.setLast_msg(wsdnsn.getConnection_time());

                //map
                this.cinfo.putWsdnsn(session.toString(), wsdnsn);
                try {
                    WebSocketSession oldSession = this.cinfo.getWssn(wsdnsn.getId());
                    if (oldSession != null && oldSession.isOpen()) {
                        List list1 = new ArrayList();
                        list1.add(new Parameter("result", "23010"));
                        list1.add(new Parameter("reason", "A new session is established"));
                        DNMessage logout = new DNMessage("logout", "request", "MSG_FROM_SMARTVMS-1", list1);
                        oldSession.sendMessage(new TextMessage(new String(parser.wrap(logout))));
                        oldSession.close();
                    }
                } catch (Exception e) {

                }
                this.cinfo.putWssn(wsdnsn.getId(), session);
                //this.isLogin = true;
            }
        }

    } else {
        throw new PacketException("The Packet is not a login packet!");
    }
}

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

private void play(UserSession user, final WebSocketSession session, JsonObject jsonMessage) {
    try {//from  ww w  .  ja  v a 2 s.  c  om
        // 0. Repository logic
        RepositoryItemPlayer itemPlayer = null;
        if (repositoryClient != null) {
            try {
                Date stopTimestamp = user.getStopTimestamp();
                if (stopTimestamp != null) {
                    Date now = new Date();
                    long diff = now.getTime() - stopTimestamp.getTime();
                    if (diff >= 0 && diff < REPOSITORY_DISCONNECT_TIMEOUT) {
                        log.info(
                                "Waiting for {}ms before requesting the repository read endpoint "
                                        + "(requires {}ms before upload is considered terminated "
                                        + "and only {}ms have passed)",
                                REPOSITORY_DISCONNECT_TIMEOUT - diff, REPOSITORY_DISCONNECT_TIMEOUT, diff);
                        Thread.sleep(REPOSITORY_DISCONNECT_TIMEOUT - diff);
                    }
                } else {
                    log.warn("No stop timeout was found, repository endpoint might not be ready");
                }
                itemPlayer = repositoryClient.getReadEndpoint(user.getRepoItem().getId());
            } catch (Exception e) {
                log.warn("Unable to obtain kurento repository endpoint", e);
            }
        } else {
            itemPlayer = new RepositoryItemPlayer();
            itemPlayer.setId(user.getRepoItem().getId());
            itemPlayer.setUrl(user.getRepoItem().getUrl());
        }
        log.debug("Playing from {}: id={}, url={}", (repositoryClient == null ? "disk" : "repository"),
                itemPlayer.getId(), itemPlayer.getUrl());

        // 1. Media logic
        final MediaPipeline pipeline = kurento.createMediaPipeline();
        WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
        PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline, itemPlayer.getUrl()).build();
        player.connect(webRtcEndpoint);

        // Player listeners
        player.addErrorListener(new EventListener<ErrorEvent>() {
            @Override
            public void onEvent(ErrorEvent event) {
                log.info("ErrorEvent for session '{}': {}", session.getId(), event.getDescription());
                sendPlayEnd(session, pipeline);
            }
        });
        player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
            @Override
            public void onEvent(EndOfStreamEvent event) {
                log.info("EndOfStreamEvent for session '{}'", session.getId());
                sendPlayEnd(session, pipeline);
            }
        });

        // 2. Store user session
        user.setMediaPipeline(pipeline);
        user.setWebRtcEndpoint(webRtcEndpoint);

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

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

        // 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());
                }
            }
        });

        // 5. Play recorded stream
        player.play();

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

        webRtcEndpoint.gatherCandidates();
    } catch (Throwable t) {
        log.error("Play error", t);
        sendError(session, t.getMessage());
    }
}

From source file:org.kurento.tutorial.player.PlayerFrameSaverHandler.java

private synchronized void sendMessage(WebSocketSession session, String message) {
    try {// w w w.ja v  a 2 s  . com
        session.sendMessage(new TextMessage(message));
    } catch (IOException e) {
        log.error("Exception sending message", e);
    }
}

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

public void sendPlayEnd(WebSocketSession session, MediaPipeline pipeline) {
    try {/*from www.  java  2  s.c  o m*/
        JsonObject response = new JsonObject();
        response.addProperty("id", "playEnd");
        session.sendMessage(new TextMessage(response.toString()));
    } catch (IOException e) {
        log.error("Error sending playEndOfStream message", e);
    }
    // Release pipeline
    pipeline.release();
}

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

@Test
public void testPayload() throws InterruptedException, ExecutionException, IOException, TimeoutException {
    CompletableFutureWebSocketHandler result = new CompletableFutureWebSocketHandler(this.jsonFactory);
    try (WebSocketSession webSocketSession = startWebSocketSession(result)) {

        SubscribeMessage subscribeMsg = new SubscribeMessage("payloadMethodResult");
        webSocketSession.sendMessage(new TextMessage(subscribeMsg.toJson(this.jsonFactory)));

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

        EventMessage event = (EventMessage) result.getWampMessage();
        assertThat(event.getTopicURI()).isEqualTo("payloadMethodResult");
        assertThat(event.getEvent()).isEqualTo("payloadMethod method called: payload");

    }/*from   w ww.  j  a  va2s .  c  om*/
}

From source file:com.github.mrstampy.gameboot.websocket.WebSocketSessionRegistry.java

private void sendText(String groupName, WebSocketSession wss, String message) {
    TextMessage bm = new TextMessage(message);
    try {/*www . j av a 2  s . com*/
        wss.sendMessage(bm);
        log.debug("Sent message to web socket session {} in group {}", wss.getId(), groupName);
    } catch (IOException e) {
        log.error("Unexpected exception sending message to web socket session {}", wss.getId(), e);
    }
}

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

@Test
public void testSubscribe3() throws InterruptedException, ExecutionException, IOException, TimeoutException {
    CompletableFutureWebSocketHandler result = new CompletableFutureWebSocketHandler(this.jsonFactory);
    try (WebSocketSession webSocketSession = startWebSocketSession(result)) {

        SubscribeMessage subscribeMsg = new SubscribeMessage("replyTo3");
        webSocketSession.sendMessage(new TextMessage(subscribeMsg.toJson(this.jsonFactory)));

        subscribeMsg = new SubscribeMessage("incomingSub3");
        webSocketSession.sendMessage(new TextMessage(subscribeMsg.toJson(this.jsonFactory)));

        EventMessage event = (EventMessage) result.getWampMessage();
        assertThat(event.getTopicURI()).isEqualTo("replyTo3");
        assertThat(event.getEvent()).isEqualTo("returnSub3");

    }// www  . j  a v a2  s .  c o m
}