Example usage for javax.websocket Session getAsyncRemote

List of usage examples for javax.websocket Session getAsyncRemote

Introduction

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

Prototype

RemoteEndpoint.Async getAsyncRemote();

Source Link

Usage

From source file:com.rotty3000.websocket.demo.WebsocketEndpoint.java

@Override
public void onOpen(Session session, EndpointConfig config) {
    Async remote = session.getAsyncRemote();

    session.addMessageHandler(new MessageHandler.Whole<String>() {

        public void onMessage(String text) {
            try {
                JSONObject jsonObject = new JSONObject(text);

                if (!jsonObject.has("file")) {
                    remote.sendText("[ERROR] No log file specified!");

                    return;
                }//w  ww.j  av a  2  s  . co m

                String fileName = jsonObject.getString("file");

                Path filePath = Paths.get(fileName);
                File file = filePath.toFile();

                if (!file.exists() || !file.canRead()) {
                    remote.sendText("[ERROR] The file [" + fileName + "] cannot be found!");

                    return;
                }

                int lines = 0;
                if (jsonObject.has("lines")) {
                    lines = jsonObject.getInt("lines");
                }

                remote.sendText(
                        "[CON] Here come the logs for [" + fileName + "] with [" + lines + "] of history.");

                logReader = new LogReader(remote, file, lines);

                logReader.start();
            } catch (Exception e) {
                remote.sendText("[ERROR] " + e.getMessage());
            }
        }

    });
}

From source file:com.josue.ws.web.server.MessageDispatcher.java

private void sendAllExceptSender(MessageRequestWrapper wrapper) {
    Iterator<Session> sessions = store.getSessions(wrapper.getMap());
    while (sessions.hasNext()) {
        Session onlineSession = sessions.next();
        if (!onlineSession.equals(wrapper.getSession())) {
            onlineSession.getAsyncRemote().sendText(wrapper.getOriginalMessage());
        }/*  w w w . j av  a  2  s  .com*/
    }
}

From source file:com.mycompany.wolf.Game.java

public void rooms(Session session) {
    List roomInfos = rooms.values().stream()
            .map(room -> ImmutableMap.of("roomId", room.roomId, "count", room.count()))
            .collect(Collectors.toCollection(LinkedList::new));
    Map<String, Object> resp = ImmutableMap.of("code", "listRoomsResp", "properties", roomInfos);
    String json = JsonUtils.toString(resp);
    session.getAsyncRemote().sendText(json);
}

From source file:com.mycompany.wolf.Room.java

public void seerForecasts(Session session, String forecastedPlayerId) {
    final String playerId = getPlayerId(session);
    if (SEER.equals(session.getUserProperties().get("role")) && !dead.contains(playerId)
            && !seerForcastings.containsKey(playerId) //???
    ) {/* w  ww .  j  av  a2s  .c  o  m*/
        seerForcastings.put(playerId, new SeerForcasting(forecastedPlayerId));
        Session forecastedSession = sessions.stream()
                .filter(s -> Objects.equals(getPlayerId(s), forecastedPlayerId)).findAny().orElse(null);
        Map<String, Object> forecastResp = ImmutableMap.of("code", "seerForecastResp", "properties",
                ImmutableMap.of("playerId", forecastedPlayerId, "role",
                        forecastedSession.getUserProperties().get("role")));
        String forecastRespJson = JsonUtils.toString(forecastResp);
        session.getAsyncRemote().sendText(forecastRespJson);
    }
}

From source file:org.b3log.symphony.processor.channel.ArticleChannel.java

/**
 * Notifies the specified article heat message to browsers.
 *
 * @param message the specified message, for example      <pre>
 * {/*w w w  .  j  a  v  a  2  s.c o m*/
 *     "articleId": "",
 *     "operation": "" // "+"/"-"
 * }
 * </pre>
 */
public static void notifyHeat(final JSONObject message) {
    message.put(Common.TYPE, Article.ARTICLE_T_HEAT);

    final String msgStr = message.toString();

    for (final Session session : SESSIONS) {
        final String viewingArticleId = (String) Channels.getHttpParameter(session, Article.ARTICLE_T_ID);
        if (Strings.isEmptyOrNull(viewingArticleId)
                || !viewingArticleId.equals(message.optString(Article.ARTICLE_T_ID))) {
            continue;
        }

        if (session.isOpen()) {
            session.getAsyncRemote().sendText(msgStr);
        }
    }
}

From source file:org.b3log.symphony.processor.channel.ArticleChannel.java

/**
 * Notifies the specified comment message to browsers.
 *
 * @param message the specified message, for example      <pre>
 * {//from   w  ww  . ja v  a  2 s  .c om
 *     "articleId": "",
 *     "commentId": "",
 *     "commentAuthorName": "",
 *     "commentAuthorThumbnailURL": "",
 *     "commentCreateTime": "", // yyyy-MM-dd HH:mm
 *     "commentContent": "",
 *     commentThankLabel": "",
 *     "thankLabel": "",
 *     "thankedLabel": "",
 *     "timeAgo": ""
 * }
 * </pre>
 */
public static void notifyComment(final JSONObject message) {
    message.put(Common.TYPE, Comment.COMMENT);

    final String msgStr = message.toString();

    final LatkeBeanManager beanManager = LatkeBeanManagerImpl.getInstance();
    final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class);
    final ArticleRepository articleRepository = beanManager.getReference(ArticleRepository.class);

    for (final Session session : SESSIONS) {
        final String viewingArticleId = (String) Channels.getHttpParameter(session, Article.ARTICLE_T_ID);
        if (Strings.isEmptyOrNull(viewingArticleId)
                || !viewingArticleId.equals(message.optString(Article.ARTICLE_T_ID))) {
            continue;
        }

        final int articleType = Integer.valueOf(Channels.getHttpParameter(session, Article.ARTICLE_TYPE));

        try {
            if (Article.ARTICLE_TYPE_C_DISCUSSION == articleType) {
                final JSONObject user = (JSONObject) Channels.getHttpSessionAttribute(session, User.USER);
                if (null == user) {
                    continue;
                }

                final String userName = user.optString(User.USER_NAME);
                final String userId = user.optString(Keys.OBJECT_ID);
                final String userRole = user.optString(User.USER_ROLE);

                final JSONObject article = articleRepository.get(viewingArticleId);
                final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
                if (!userId.equals(articleAuthorId)) {
                    final String articleContent = article.optString(Article.ARTICLE_CONTENT);
                    final Set<String> userNames = userQueryService.getUserNames(articleContent);

                    boolean invited = false;
                    for (final String inviteUserName : userNames) {
                        if (inviteUserName.equals(userName)) {
                            invited = true;

                            break;
                        }
                    }

                    if (Role.ADMIN_ROLE.equals(userRole)) {
                        invited = true;
                    }

                    if (!invited) {
                        continue; // next session
                    }
                }
            }

            if (session.isOpen()) {
                session.getAsyncRemote().sendText(msgStr);
            }
        } catch (final Exception e) {
            LOGGER.log(Level.ERROR, "Notify comment error", e);
        }
    }
}

From source file:org.b3log.symphony.processor.channel.ArticleListChannel.java

/**
 * Notifies the specified article heat message to browsers.
 *
 * @param message the specified message, for example      <pre>
 * {//w  ww .  j a v  a 2s  .co m
 *     "articleId": "",
 *     "operation": "" // "+"/"-"
 * }
 * </pre>
 */
public static void notifyHeat(final JSONObject message) {
    final String articleId = message.optString(Article.ARTICLE_T_ID);
    final String msgStr = message.toString();

    synchronized (SESSIONS) {
        for (final Map.Entry<Session, String> entry : SESSIONS.entrySet()) {
            final Session session = entry.getKey();
            final String articleIds = entry.getValue();

            if (!StringUtils.contains(articleIds, articleId)) {
                continue;
            }

            if (session.isOpen()) {
                session.getAsyncRemote().sendText(msgStr);
            }
        }
    }
}

From source file:org.b3log.symphony.processor.channel.ChatRoomChannel.java

/**
 * Called when the socket connection with the browser is established.
 *
 * @param session session//w w  w. j  a  v  a  2  s . co  m
 */
@OnOpen
public void onConnect(final Session session) {
    SESSIONS.add(session);

    synchronized (SESSIONS) {
        final Iterator<Session> i = SESSIONS.iterator();
        while (i.hasNext()) {
            final Session s = i.next();

            if (s.isOpen()) {
                final String msgStr = new JSONObject().put(Common.ONLINE_CHAT_CNT, SESSIONS.size())
                        .put(Common.TYPE, "online").toString();
                s.getAsyncRemote().sendText(msgStr);
            }
        }
    }
}

From source file:org.b3log.symphony.processor.channel.ChatRoomChannel.java

/**
 * Notifies the specified chat message to browsers.
 *
 * @param message the specified message, for example      <pre>
 * {/*from   ww w  .j  av a  2  s  .c o  m*/
 *     "userName": "",
 *     "content": ""
 * }
 * </pre>
 */
public static void notifyChat(final JSONObject message) {
    message.put(Common.TYPE, "msg");
    final String msgStr = message.toString();

    synchronized (SESSIONS) {
        final Iterator<Session> i = SESSIONS.iterator();
        while (i.hasNext()) {
            final Session session = i.next();

            if (session.isOpen()) {
                session.getAsyncRemote().sendText(msgStr);
            }
        }
    }
}

From source file:org.b3log.symphony.processor.channel.ChatRoomChannel.java

/**
 * Removes the specified session.// ww  w  .jav a  2  s. com
 *
 * @param session the specified session
 */
private void removeSession(final Session session) {
    SESSIONS.remove(session);

    synchronized (SESSIONS) {
        final Iterator<Session> i = SESSIONS.iterator();
        while (i.hasNext()) {
            final Session s = i.next();

            if (s.isOpen()) {
                final String msgStr = new JSONObject().put(Common.ONLINE_CHAT_CNT, SESSIONS.size())
                        .put(Common.TYPE, "online").toString();
                s.getAsyncRemote().sendText(msgStr);
            }
        }
    }
}