Example usage for javax.websocket Session getBasicRemote

List of usage examples for javax.websocket Session getBasicRemote

Introduction

In this page you can find the example usage for javax.websocket Session getBasicRemote.

Prototype

RemoteEndpoint.Basic getBasicRemote();

Source Link

Usage

From source file:fr.feedreader.websocket.UpdateFeed.java

public static void notifyUpdateFeed(Map<Feed, List<FeedItem>> newFeedItem, Map<Feed, Long> countUnread) {
    LogManager.getLogger().info("notification de mise  jour de flux");
    ObjectMapper mapper = new ObjectMapper();
    FeedUpdateWrapper feedUpdateWrapper = new FeedUpdateWrapper(newFeedItem, countUnread);
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        mapper.writeValue(baos, feedUpdateWrapper);
        String jsonResponse = baos.toString("UTF-8");
        availableSession.iterator();//from w w w  .ja  v  a2 s. com
        for (Iterator<Session> it = availableSession.iterator(); it.hasNext();) {
            Session session = it.next();
            try {
                session.getBasicRemote().sendText(jsonResponse);
                LogManager.getLogger().info("Envoyer  \"" + session.getId() + "\"");
            } catch (ClosedChannelException ex) {
                LogManager.getLogger().error(
                        "Session \"" + session.getId() + "\" Fermer. Exclusion de la liste des session active");
                it.remove();
            } catch (IOException ex) {
                LogManager.getLogger().error("Erreur dans l'envoi  la websocket : " + session.getId(), ex);
            }
        }
    } catch (IOException ioe) {
        LogManager.getLogger().error("Impossible de convertir les flux mis  jour en json", ioe);
    }
}

From source file:de.tuttas.websockets.ChatServer.java

public static void send(JSONObject msg, Session myself) {
    Log.d("Sende " + msg.toJSONString());
    msg.put("msg", StringUtil.escapeHtml((String) msg.get("msg")));
    for (Session s : sessions) {
        if (s != myself) {
            try {
                s.getBasicRemote().sendText(msg.toJSONString());
            } catch (IOException ex) {
                Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();//from   w w w .  jav a  2  s.  c  om
            }
        }
    }
}

From source file:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

private static Endpoint sendAndGetTextEndPoint(final String sendText, final SettableFuture<String> res) {
    return new Endpoint() {
        @Override/*from w  ww  .j av a 2s.  c o  m*/
        public void onOpen(final Session session, EndpointConfig config) {
            session.addMessageHandler(new MessageHandler.Whole<String>() {
                @Override
                public void onMessage(String text) {
                    res.set(text);
                }
            });
            try {
                session.getBasicRemote().sendText(sendText);
            } catch (IOException ignored) {
            }
        }
    };
}

From source file:org.sample.chat.ChatEndpoint.java

@OnMessage
public void message(String message, Session client) throws IOException, EncodeException {
    for (Session peer : peers) {
        peer.getBasicRemote().sendObject(message);
    }//  w  ww.j av  a2s.  c o m
}

From source file:org.qaclana.services.messagesender.MessageSender.java

@Asynchronous
public void send(@Observes SendMessage event) {
    log.sendingMessageToDestination(event.getDestination().getId(), event.getMessage().getType());

    String messageAsJson;//from  w  w  w  .j a  v  a  2  s .co m
    try {
        messageAsJson = JSON_MAPPER.writeValueAsString(event.getMessage());
    } catch (JsonProcessingException e) {
        log.failedToConvertMessageToJson(event.getMessage().toString(), e);
        return;
    }

    Session session = event.getDestination();
    try {
        session.getBasicRemote().sendText(messageAsJson);
    } catch (IOException e) {
        log.failedToSendMessageToDestination(session.getId(), e);
    }
}

From source file:org.sample.whiteboard.Whiteboard.java

@OnMessage
public void broadcastFigure(Figure figure, Session session) throws IOException, EncodeException {
    System.out.println("boradcastFigure: " + figure);
    for (Session peer : peers) {
        if (!peer.equals(session)) {
            peer.getBasicRemote().sendObject(figure);
        }//from w  w  w  . j  ava  2s  . c o  m
    }
}

From source file:org.sample.whiteboard.Whiteboard.java

@OnMessage
public void broadcastSnapshot(ByteBuffer data, Session session) throws IOException {
    System.out.println("broadcastBinary: " + data);
    for (Session peer : peers) {
        if (!peer.equals(session)) {
            peer.getBasicRemote().sendBinary(data);
        }/*from ww  w.  ja v  a 2 s .  c o m*/
    }
}

From source file:eu.agilejava.snoop.scan.SnoopClient.java

/**
 * Sends message to the WebSocket server.
 *
 * @param endpoint The server endpoint//from ww  w .ja  v a2  s.  c om
 * @param msg The message
 * @return a return message
 */
private String sendMessage(String endpoint, String msg) {

    LOGGER.config(() -> "Sending message: " + msg);

    String returnValue = "-1";
    try {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = serviceUrl + endpoint;
        Session session = container.connectToServer(this, URI.create(uri));
        session.getBasicRemote().sendText(msg != null ? msg : "");
        returnValue = session.getId();

    } catch (DeploymentException | IOException ex) {
        LOGGER.warning(ex.getMessage());
    }

    return returnValue;
}

From source file:org.sample.MyEndpoint.java

@OnMessage
public void echoBinary(ByteBuffer data, Session session) {
    System.out.println("echoBinary: " + data);
    for (byte b : data.array()) {
        System.out.print(b);//from   w w  w.jav  a  2  s. co  m
    }
    try {
        session.getBasicRemote().sendBinary(data);
    } catch (IOException ex) {
        Logger.getLogger(MyEndpoint.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.github.opensensingcity.lindt.api.QueryEndpoint.java

@OnMessage
public void handleMessage(String message, Session session) throws IOException, InterruptedException {
    appender.putSession(Thread.currentThread(), session);
    try {// w ww . j  av  a2 s. c om
        session.getBasicRemote().sendText(gson.toJson(new Response("", "", "", true)));
    } catch (IOException ex) {
        java.util.logging.Logger.getLogger(QueryEndpoint.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    }

    if (message.getBytes().length > 10 * Math.pow(2, 10)) {
        LOG.error("In this web interface request size cannot exceed 10 kB.");
        appender.removeSession(Thread.currentThread());
        return;
    }

    Model model = ModelFactory.createDefaultModel();
    try {
        Request request = gson.fromJson(message, Request.class);

        Query query = QueryFactory.create(request.query);
        RDFDataMgr.read(model, IOUtils.toInputStream(request.graph, "UTF-8"), base, Lang.TTL);
        QueryExecution ex = QueryExecutionFactory.create(query, model);

        Prologue pm = query.getPrologue();
        pm.getPrefixMapping().setNsPrefixes(model.getNsPrefixMap());

        if (query.isSelectType()) {
            String result = ResultSetFormatter.asText(ex.execSelect(), pm);
            session.getBasicRemote().sendText(gson.toJson(new Response("", result, "mappings", false)));
        } else if (query.isConstructType()) {
            StringWriter sb = new StringWriter();
            Model result = ex.execConstruct();
            result.setNsPrefixes(pm.getPrefixMapping());
            result.write(sb, "TTL", "http://example.org/");
            session.getBasicRemote().sendText(gson.toJson(new Response("", sb.toString(), "graph", false)));
        }
    } catch (IllegalArgumentException | IOException | RiotException | QueryParseException
            | UnsupportedOperationException ex) {
        LOG.error(ex.getClass().getName() + ": " + ex.getMessage());
        return;
    }
    appender.removeSession(Thread.currentThread());
}