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:cn.com.inhand.devicenetworks.ap.mq.rabbitmq.DelivingNoticeConsumer.java

public void listen(Message message) {
    String str = new String(message.getBody());
    System.out.println("===============recv:" + message);
    try {/*from   www  . j a va 2  s  .  c o  m*/
        DNMessage msg = parser.unwrap(str.getBytes());
        if (msg != null) {
            Parameter param = msg.getParameter("id");
            if (param != null) {
                String id = param.getValue();
                WebSocketSession ws = this.cinfo.getWssn(id);
                if (ws != null) {
                    ws.sendMessage(new TextMessage(str));
                } else {
                    //???Websocket AP?AP?AP???
                    //?
                    //                        List list = new ArrayList();
                    //                        list.add(new Parameter("result", "30005"));
                    //                        list.add(new Parameter("reason", "The asset is offline."));
                    //                        list.add(msg.getParameter("id"));
                    //                        list.add(msg.getParameter("transcation_id"));
                    //                        list.add(msg.getParameter("asset_id"));
                    //                        DNMessage ack = new DNMessage(msg.getName(), "response", msg.getTxid(), list);
                    //
                    //                        MessageProperties properties =message.getMessageProperties();
                    ////                        properties.setCorrelationId(correlationId);
                    //        
                    //                        producer.sendMessage(new String(parser.wrap(msg)));
                    //                        logger.info("The asset[" + asset_id + "] is not online, return a offline ack to source. msg=" + ack.toString());
                    //                        System.out.println("The asset[" + asset_id + "] is not online, return a offline ack to source. msg=" + ack.toString());
                    //                         //?rabbitmq rpc
                    //--------------------------------

                }
            } else {
                //??
            }
        }
    } catch (Exception e) {
        logger.warning(e.getLocalizedMessage());
    }
}

From source file:cn.com.inhand.devicenetworks.ap.mq.rabbitmq.TaskNotificationConsumer.java

public void listen(String message) {

    try {/* www . j a v  a2  s  .  c  o  m*/
        DNMessage msg = parser.unwrap(message.getBytes());
        if (msg != null) {
            Parameter param = msg.getParameter("id");
            if (param != null) {
                String id = param.getValue();
                WebSocketSession ws = this.cinfo.getWssn(id);
                if (ws != null) {
                    ws.sendMessage(new TextMessage(message));
                } else {
                    //???Websocket AP?AP?AP???
                    //?
                    //                         List list = new ArrayList();
                    //                         list.add(new Parameter("result","30005"));
                    //                         list.add(new Parameter("reason","The asset is offline."));
                    //                         DNMessage ack = new DNMessage(msg.getName(),"response",msg.getTxid(),list);
                    //                         
                    //                         logger.info("The asset["+asset_id+"] is not online, return a offline ack to source. msg="+ack.toString());
                    //                          System.out.println("The asset["+asset_id+"] is not online, return a offline ack to source. msg="+ack.toString());
                    //                         //?rabbitmq rpc
                    //                         //--------------------------------
                }
            } else {
                //??
            }
        }
    } catch (Exception e) {
        logger.warning(e.getLocalizedMessage());
    }
}

From source file:com.kurento.kmf.jsonrpcconnector.internal.ws.WebSocketServerSession.java

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

    Future<Response<JsonElement>> responseFuture = null;

    if (request.getId() != null) {
        responseFuture = pendingRequests.prepareResponse(request.getId());
    }/*from w  w w . j  a v a  2s  .  c  om*/

    try {
        synchronized (wsSession) {
            wsSession.sendMessage(new TextMessage(JsonUtils.toJson(request)));
        }
    } catch (Exception e) {
        LOG.error("Exception while sending message '{}' to websocket with native sessionId '{}': {}",
                JsonUtils.toJson(request), wsSession.getId(), e);
        // TODO Implement retries if possible
        return null;
    }

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

    Response<JsonElement> responseJsonObject;
    try {
        responseJsonObject = responseFuture.get();
    } 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);
    }

    return MessageUtils.convertResponse(responseJsonObject, resultClass);
}

From source file:org.bitcoinrt.spring.websocket.ClientMtgoxWebSocketHandler.java

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    logger.debug("New message: " + message);

    String channel = JsonPath.compile("$.channel").read(message.getPayload());

    String primary = null;/*from  w w w  . j av  a  2s .com*/
    try {
        primary = JsonPath.compile("$.trade.primary").read(message.getPayload());
    } catch (Exception ex) {
        // ignore
    }

    if (MTGOX_TRADES_CHANNEL.equals(channel) && "Y".equals(primary)) {
        JSONObject trade = JsonPath.compile("$.trade").read(message.getPayload());
        logger.info("Broadcasting Trade: {}", trade);
        serverWebSocketSessionsStore.sendToAll(new TextMessage(message.getPayload()));
    } else {
        // ignore any non-trade messages that might slip in before our
        // op:unsubscribes sent above have been handled; also ignore any
        // 'non-primary' trades. see
        // https://en.bitcoin.it/wiki/MtGox/API/HTTP/v1#Multi_currency_trades
        logger.debug("Ignoring Message: {}", message);
    }
}

From source file:com.nts.alphamaleWeb.handler.RecordReplayWSHandler.java

public void onCatchExecutionResult(String resultLogJson) {

    if (this.session == null) {
        log.debug("session is empty");
        return;/*  w w w .  j  ava2s . c  o  m*/
    }
    if (StringUtils.isEmpty(resultLogJson)) {
        log.debug("session is empty");
        return;
    }
    try {
        TextMessage msg = new TextMessage(resultLogJson);
        this.session.sendMessage(msg);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:ymanv.forex.websocket.RatesWebSocketHandler.java

@Subscribe
public void send(RatesUpdatedEvent event) throws IOException {
    if (sessions.isEmpty()) {
        return;//from w  ww .  ja va2s .  c  o m
    }

    String txt = serializeRates(event.getRates());

    for (WebSocketSession wss : new CopyOnWriteArrayList<>(sessions)) {
        wss.sendMessage(new TextMessage(txt));
    }
}

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

public String startSession(final WebSocketSession session, String sdpOffer) {
    // One KurentoClient instance per session (reserving points per session)
    Properties properties = new Properties();
    properties.add("loadPoints", POINTS_PER_SESSION);
    kurentoClient = KurentoClient.create(properties);
    log.info("Created kurentoClient (session {})", sessionId);

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

    webRtcEndpoint = new WebRtcEndpoint.Builder(mediaPipeline).build();
    FaceOverlayFilter faceOverlayFilter = new FaceOverlayFilter.Builder(mediaPipeline).build();
    faceOverlayFilter.setOverlayedImage("http://files.kurento.org/img/mario-wings.png", -0.35F, -1.2F, 1.6F,
            1.6F);//w w  w .j  a  va  2s . co m
    webRtcEndpoint.connect(faceOverlayFilter);
    faceOverlayFilter.connect(webRtcEndpoint);

    // WebRTC negotiation
    webRtcEndpoint.addOnIceCandidateListener(new EventListener<OnIceCandidateEvent>() {
        @Override
        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:eu.nubomedia.tutorial.magicmirror.MagicMirrorHandler.java

private void start(final WebSocketSession session, JsonObject jsonMessage) {
    // User session
    String sessionId = session.getId();
    UserSession user = new UserSession(sessionId, this);
    users.put(sessionId, user);/* w  w w  .  jav a 2s.  c  o  m*/

    // Media logic for magic mirror
    String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
    String sdpAnswer = user.startSession(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:com.devicehive.websockets.AbstractWebSocketHandler.java

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    logger.debug("Session id {} ", session.getId());
    session = sessionMonitor.getSession(session.getId());
    JsonObject request = new JsonParser().parse(message.getPayload()).getAsJsonObject();
    JsonObject response = webSocketResponseBuilder.buildResponse(request, session);
    session.sendMessage(new TextMessage(response.toString()));
}

From source file:org.kurento.demo.CrowdDetectorHandler.java

private void start(final WebSocketSession session, JsonObject jsonMessage) throws IOException {

    updateFeed(jsonMessage);/*  w  w  w .j  a  va2 s  .  c  om*/

    if (this.pipeline.getPlayerEndpoint() == null) {
        try {
            JsonObject response = new JsonObject();
            response.addProperty("id", "noPlayer");
            session.sendMessage(new TextMessage(response.toString()));
        } catch (IOException a) {
            log.error("Exception sending message", a);
        }
        return;
    }

    if (!this.pipeline.isPlaying()) {
        try {
            JsonObject response = new JsonObject();
            response.addProperty("id", "noPlaying");
            session.sendMessage(new TextMessage(response.toString()));
        } catch (IOException a) {
            log.error("Exception sending message", a);
        }
        return;
    }

    MediaPipeline mediaPipeline = this.pipeline.getPipeline();

    WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(mediaPipeline).build();

    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.debug(e.getMessage());
            }
        }
    });

    this.pipeline.setWebRtcEndpoint(session.getId(), webRtcEndpoint);

    this.pipeline.getCrowdDetectorFilter().connect(webRtcEndpoint);

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

    // Sending response back to client
    JsonObject response = new JsonObject();
    response.addProperty("id", "startResponse");
    response.addProperty("sdpAnswer", sdpAnswer);
    response.addProperty("feedUrl", this.pipeline.getFeedUrl());
    response.addProperty("rois", gson.toJson(this.pipeline.getRois()));
    synchronized (session) {
        session.sendMessage(new TextMessage(response.toString()));
    }
    webRtcEndpoint.gatherCandidates();
}