Esempio n. 1
0
  private void unjoinChat() {
    if (thisSession.getUserProperties().containsKey("USER")) {
      LOG.debug("unjoinChat(): " + thisSession.getUserProperties().get("USER"));

      sessionService.removeOnSessionDestroyedListener(callback);

      if (isHttpSessionValid) {
        int sessionIdleTime =
            (int) ((System.currentTimeMillis() - httpSession.getLastAccessedTime()) / 1000);
        LOG.debug("Max idle timeout: " + (sessionIdleTime + defaultSessionTimeout));
        httpSession.setMaxInactiveInterval(sessionIdleTime + defaultSessionTimeout);
      }

      int userNb = usersLoggedIn.decrementAndGet();

      Message infoMsg = new Message();

      infoMsg.TYPE = "INFO";
      infoMsg.SUBTYPE = "JOIN";
      infoMsg.INFO_MSG = thisSession.getUserProperties().get("USER") + " has left the building";
      infoMsg.STATS_MSG = userNb + " User" + (userNb > 1 ? "s " : " ") + "online!";
      infoMsg.USER_LIST = buildUserList(false);

      thisSession.getUserProperties().clear();

      broadcastMessage(infoMsg, false);
    }
  }
Esempio n. 2
0
  private void handleChat(final Message clientMsg) {
    Message broadcastMsg;

    if (clientMsg.SUBTYPE.equals("MSG")) {

      lastActivityTime = System.currentTimeMillis();

      ChatMsg chatMsg = new ChatMsg();
      broadcastMsg = clientMsg;
      // You can't trust nobody ;)
      chatMsg.MSG = clientMsg.CHAT_MSG.MSG.replace("<", "&lt;").replace("&", "&amp;");
      chatMsg.COLOR = (String) thisSession.getUserProperties().get("COLOR");
      chatMsg.FROM = (String) thisSession.getUserProperties().get("USER");

      ChatLog logMsg = new ChatLog();
      logMsg.setDate(new Date(lastActivityTime));
      logMsg.setUser(chatMsg.FROM);
      logMsg.setMessage(chatMsg.MSG);

      try {
        chatLogRepository.insert(logMsg);
      } catch (Exception e) {
        LOG.error(e.getMessage());
      }

      broadcastMsg.CHAT_MSG = chatMsg;
      broadcastMessage(broadcastMsg, true);
    }
  }
 @OnMessage
 public void setAktionId(Long aktionId, Session session) {
   logger.info("Client " + session.getId() + " hat Aktion " + aktionId + " ausgewählt.");
   try {
     List<Spende> result = new LinkedList<>();
     try {
       result = spendeListProvider.getSpendeList(aktionId);
     } catch (NotFoundException e) {
       session
           .getBasicRemote()
           .sendText("Die Aktion mit der ID: " + aktionId + " ist nicht verfügbar");
     } catch (WebApplicationException e) {
       logger.log(
           Level.SEVERE,
           "Die Spendenliste für Aktion mit ID: "
               + aktionId
               + " konnte nicht abgerufen werden. Läuft der JBoss?",
           e);
       session.getBasicRemote().sendText("Fehler beim Abruf der initialen Spendenliste.");
     }
     session.getUserProperties().put(AKTION_ID, aktionId);
     for (Spende spende : result) {
       logger.info("Sende " + spende + " an Client " + session.getId());
       session.getBasicRemote().sendObject(spende);
     }
     session.getBasicRemote().sendText("Aktion geändert zu: " + aktionId);
   } catch (IOException | EncodeException e) {
     logger.log(Level.INFO, "Keine Verbindung zu Client: " + session, e);
   }
 }
Esempio n. 4
0
  private String[] buildUserList(final boolean includeThis) {
    List<String> userList = new ArrayList<>();

    LOG.debug("buildUserList(): " + thisSession.getOpenSessions().size());

    for (Session session : thisSession.getOpenSessions()) {
      if (!includeThis && thisSession.equals(session)) {
        continue;
      }
      String userName = (String) session.getUserProperties().get("USER");
      String userColor = (String) session.getUserProperties().get("COLOR");
      userList.add(userColor + "*" + userName);
    }

    return (userList.size() == 0) ? null : userList.toArray(new String[userList.size()]);
  }
Esempio n. 5
0
 private void updateUserList() {
   List<String> usernames = new ArrayList<>();
   for (Session s : session.getOpenSessions()) {
     String uname = (String) s.getUserProperties().get(USERNAME_KEY);
     usernames.add(uname);
   }
   this.endpointConfig.getUserProperties().put(USERNAMES_KEY, usernames);
 }
  @OnClose
  public void handleClose(Session userSession) {
    String username = (String) userSession.getUserProperties().get("username");
    if (username != null) {
      System.out.println("User '" + username + "' closed connection.");
    }

    chatroomUsers.remove(userSession);
  }
Esempio n. 7
0
  private void joinChat() {
    String userColor;

    sessionService.addOnSessionDestroyedListener(callback);

    defaultSessionTimeout = httpSession.getMaxInactiveInterval();
    httpSession.setMaxInactiveInterval(0);
    lastActivityTime = System.currentTimeMillis();

    String username = ((User) authToken.getPrincipal()).getUsername();
    LOG.debug("joinChat() user: "******"USER", username);

    int userNb = usersLoggedIn.incrementAndGet();
    // If a user is active more than once, give him the same color:
    if (userColorMap.containsKey(username)) {
      userColor = userColorMap.get(username);
    } else {
      userColor = PEER_COLORS[userNb % PEER_COLOR_NB];
      userColorMap.put(username, userColor);
    }

    thisSession.getUserProperties().put("COLOR", userColor);

    Message joinMsg = new Message();
    joinMsg.TYPE = "JOIN";
    joinMsg.SUBTYPE = "JOIN";
    joinMsg.USER_LIST = buildUserList(true);
    joinMsg.STATS_MSG = userNb + " User" + (userNb > 1 ? "s " : " ") + "online!";

    sendMessage(joinMsg);

    Message infoMsg = new Message();
    infoMsg.TYPE = "INFO";
    infoMsg.SUBTYPE = "JOIN";
    infoMsg.INFO_MSG = username + " has entered the building";
    infoMsg.STATS_MSG = userNb + " User" + (userNb > 1 ? "s " : " ") + "online!";
    infoMsg.USER_LIST = buildUserList(true);

    broadcastMessage(infoMsg, false);
  }
 @OnMessage
 public String onMessage(String unscrambledWord, Session session) {
   switch (unscrambledWord) {
     case "start":
       logger.info("Starting the game by sending first word");
       String scrambledWord = WordRepository.getInstance().getRandomWord().getScrambledWord();
       session.getUserProperties().put("scrambledWord", scrambledWord);
       return scrambledWord;
     case "quit":
       logger.info("Quitting the game");
       try {
         session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "Game finished"));
       } catch (IOException e) {
         throw new RuntimeException(e);
       }
   }
   String scrambledWord = (String) session.getUserProperties().get("scrambledWord");
   return checkLastWordAndSendANewWord(scrambledWord, unscrambledWord, session);
 }
  @OnMessage
  public void handleMessage(String message, Session userSession) throws IOException {
    String username = (String) userSession.getUserProperties().get("username");
    if (username == null) {
      userSession.getUserProperties().put("username", message);
      userSession
          .getBasicRemote()
          .sendText(buildJsonData("System", "You are now connected as '" + message + "'"));
      System.out.println("User '" + message + "' is connected.");
    } else {
      System.out.println("Server: " + username + " said '" + message + "'");

      // Sends a message to each user in the chatroom
      Iterator<Session> iterator = chatroomUsers.iterator();
      while (iterator.hasNext()) {
        iterator.next().getBasicRemote().sendText(buildJsonData(username, message));
      }
    }
  }
  @Test
  public void testHandleMessageWithParams() throws Exception {
    when(player1Session.getBasicRemote()).thenReturn(player1Basic);
    when(player1Session.getUserProperties()).thenReturn(userProperties);
    when(player2Session.getBasicRemote()).thenReturn(player2Basic);
    when(userProperties.get(TicTacToeEndpoint.GAME_PROPERTY_KEY)).thenReturn(game);

    handler.handleMessage(player1Session, TicTacToeMessage.GAME_HAS_WINNER, "1", "2", "3");

    verify(player1Basic).sendText("p4 1 2 3");
    verify(player2Basic).sendText("p4 1 2 3");
  }
Esempio n. 11
0
 @OnMessage
 public void onMessage(final Session session, final String chatMessage) {
   String room = (String) session.getUserProperties().get("room");
   try {
     for (Session s : session.getOpenSessions()) {
       if (s.isOpen()) {
         s.getBasicRemote().sendText(chatMessage);
       }
     }
   } catch (IOException e) {
     log.log(Level.WARNING, "onMessage failed", e);
   }
 }
  @Test(expected = UnhandledMessageException.class)
  public void testHandleMessageSendFailure() throws Exception {
    when(player1Session.getBasicRemote()).thenReturn(player1Basic);
    when(player1Session.getUserProperties()).thenReturn(userProperties);
    when(player2Session.getBasicRemote()).thenReturn(player2Basic);
    when(userProperties.get(TicTacToeEndpoint.GAME_PROPERTY_KEY)).thenReturn(game);
    doThrow(new IOException()).when(player2Basic).sendText("p4");

    try {
      handler.handleMessage(player1Session, TicTacToeMessage.GAME_HAS_WINNER);
    } catch (UnhandledMessageException e) {
      verify(player1Basic).sendText("p4");
      verify(player2Basic).sendText("p4");

      assertThat(e.getCause(), is(instanceOf(IOException.class)));
      throw e;
    }
  }
  /**
   * Note how this helper method uses both websockets session information and the WordRepository and
   * Word helper classes.
   *
   * @param scrambledWord
   * @param unscrambledWord
   * @param session
   * @return
   */
  private String checkLastWordAndSendANewWord(
      String scrambledWord, String unscrambledWord, Session session) {
    WordRepository repository = WordRepository.getInstance();
    Word word = repository.getWord(scrambledWord);

    String nextScrambledWord = repository.getRandomWord().getScrambledWord();

    session.getUserProperties().put("scrambledWord", nextScrambledWord);

    String correctUnscrambledWord = word.getUnscrambbledWord();

    if (word == null || !correctUnscrambledWord.equals(unscrambledWord)) {
      return String.format(
          "You guessed it wrong. Correct answer %s. Try the next one .. %s",
          correctUnscrambledWord, nextScrambledWord);
    }
    return String.format("You guessed it right. Try the next word ...  %s", nextScrambledWord);
  }
    @OnMessage
    public String getHeaders(Session session, String headerKey) {
      StringBuilder response = new StringBuilder();

      response.append("Request Header [").append(headerKey).append("]: ");
      @SuppressWarnings("unchecked")
      Map<String, List<String>> headers =
          (Map<String, List<String>>) session.getUserProperties().get("request-headers");
      if (headers == null) {
        response.append("<no headers found in session.getUserProperties()>");
      } else {
        List<String> values = headers.get(headerKey);
        if (values == null) {
          response.append("<header not found>");
        } else {
          response.append(QuoteUtil.join(values, ","));
        }
      }

      return response.toString();
    }
Esempio n. 15
0
  @OnOpen
  public void onOpen(Session session) {
    LOG.debug("@OnOpen: " + session.getId());
    thisSession = session;

    if (thisSession.getUserPrincipal() != null) {
      authToken = (UsernamePasswordAuthenticationToken) thisSession.getUserPrincipal();
      if (authToken.isAuthenticated()) {
        isHttpSessionValid = true;
        httpSession = (HttpSession) thisSession.getUserProperties().get("httpSession");
        httpSessionId = httpSession.getId();
        LOG.debug("HTTP Session id: " + httpSessionId);
        if (httpSession.getAttribute("CHAT_OPEN") != null) {
          activeClose(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "ALREADY_OPEN"));
        } else {
          httpSession.setAttribute("CHAT_OPEN", true);
        }
        return;
      }
    }

    activeClose(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Unauthorized"));
  }
Esempio n. 16
0
  private void broadcastTranscriptUpdate() {
    String v = this.transcript.getRec();
    String g;
    if (c.equals(v)) {
      for (Session nextSession : session.getOpenSessions()) {

        ChatUpdateMessage cdm =
            new ChatUpdateMessage(
                this.transcript.getLastUsername(),
                this.transcript.getLastMessage(),
                this.transcript.getRec());

        try {
          nextSession.getBasicRemote().sendObject(cdm);
        } catch (IOException | EncodeException ex) {
          System.out.println("Error updating a client : " + ex.getMessage());
        }
      }
    } else {
      for (Session nextSession : session.getOpenSessions()) {
        String check = this.transcript.getRec();
        ChatUpdateMessage cdm =
            new ChatUpdateMessage(
                this.transcript.getLastUsername(),
                this.transcript.getLastMessage(),
                this.transcript.getRec());
        g = (String) nextSession.getUserProperties().get(USERNAME_KEY);
        if (v.equals(g)) {
          try {
            nextSession.getBasicRemote().sendObject(cdm);
          } catch (IOException | EncodeException ex) {
            System.out.println("Error updating a client : " + ex.getMessage());
          }
        }
      }
    }
  }
Esempio n. 17
0
    @OnMessage
    public void onMessage(Session session, String msg) throws IOException {

      if (started) {
        return;
      }
      synchronized (this) {
        if (started) {
          return;
        } else {
          started = true;
        }
      }

      System.out.println("Received " + msg + ", now sending data");

      session
          .getUserProperties()
          .put(
              org.apache.tomcat.websocket.Constants.BLOCKING_SEND_TIMEOUT_PROPERTY,
              Long.valueOf(SEND_TIME_OUT_MILLIS));

      Basic remote = session.getBasicRemote();
      remote.setBatchingAllowed(true);

      for (int i = 0; i < MESSAGE_COUNT; i++) {
        remote.sendText(MESSAGE);
        if (i % (MESSAGE_COUNT * 0.4) == 0) {
          remote.setBatchingAllowed(false);
          remote.setBatchingAllowed(true);
        }
      }

      // Flushing should happen automatically on session close
      session.close();
    }
Esempio n. 18
0
 public ECCKeyPair getServerIdentity() {
   return (ECCKeyPair) session.getUserProperties().get(SERVER_IDENTITY_ATT_NAME);
 }
Esempio n. 19
0
 public String getClientIdentity() {
   return (String) session.getUserProperties().get(CLIENT_IDENTITY_ATT_NAME);
 }
Esempio n. 20
0
 public void setClientIdentity(String clientIdentity) {
   session.getUserProperties().put(CLIENT_IDENTITY_ATT_NAME, clientIdentity);
 }
Esempio n. 21
0
 public Boolean getPendingPongMsg() {
   return (Boolean) session.getUserProperties().get(PENDING_PONG_MSG_ATT_NAME);
 }
Esempio n. 22
0
 public void setPendingPongMsg(Boolean pending) {
   session.getUserProperties().put(PENDING_PONG_MSG_ATT_NAME, pending);
 }
Esempio n. 23
0
 private String getCurrentUsername() {
   return (String) session.getUserProperties().get(USERNAME_KEY);
 }
Esempio n. 24
0
 private void registerUser(String username) {
   System.out.println("Inside registration");
   session.getUserProperties().put(USERNAME_KEY, username);
   this.updateUserList();
 }
  /**
   * (non-javadoc)
   *
   * @see PackageProcessor#processingPackage(Session, Package)
   */
  @Override
  public void processingPackage(Session session, Package packageReceived) {

    LOG.info("Processing new package received");

    String channelIdentityPrivateKey = getChannel().getChannelIdentity().getPrivateKey();
    String destinationIdentityPublicKey =
        (String) session.getUserProperties().get(HeadersAttName.CPKI_ATT_HEADER_NAME);
    NodeProfile nodeProfile = null;
    AddNodeToCatalogMsjRespond addNodeToCatalogMsjRespond = null;

    try {

      AddNodeToCatalogMsgRequest messageContent =
          AddNodeToCatalogMsgRequest.parseContent(packageReceived.getContent());

      /*
       * Create the method call history
       */
      methodCallsHistory(
          getGson().toJson(messageContent.getNodeProfile()), destinationIdentityPublicKey);

      /*
       * Validate if content type is the correct
       */
      if (messageContent.getMessageContentType() == MessageContentType.JSON) {

        /*
         * Obtain the profile of the node
         */
        nodeProfile = messageContent.getNodeProfile();

        if (exist(nodeProfile)) {

          /*
           * Notify the node already exist
           */
          addNodeToCatalogMsjRespond =
              new AddNodeToCatalogMsjRespond(
                  CheckInProfileMsjRespond.STATUS.FAIL,
                  "The node profile already exist",
                  nodeProfile.getIdentityPublicKey());

        } else {

          /*
           * Insert NodesCatalog into data base
           */
          insertNodesCatalog(nodeProfile);

          /*
           * Insert NodesCatalogTransaction into data base
           */
          insertNodesCatalogTransaction(nodeProfile);

          /*
           * Insert NodesCatalogTransactionsPendingForPropagation into data base
           */
          insertNodesCatalogTransactionsPendingForPropagation(nodeProfile);

          /*
           * If all ok, respond whit success message
           */
          addNodeToCatalogMsjRespond =
              new AddNodeToCatalogMsjRespond(
                  CheckInProfileMsjRespond.STATUS.SUCCESS,
                  CheckInProfileMsjRespond.STATUS.SUCCESS.toString(),
                  nodeProfile.getIdentityPublicKey());
        }

        Package packageRespond =
            Package.createInstance(
                addNodeToCatalogMsjRespond.toJson(),
                packageReceived.getNetworkServiceTypeSource(),
                PackageType.ADD_NODE_TO_CATALOG_RESPOND,
                channelIdentityPrivateKey,
                destinationIdentityPublicKey);

        /*
         * Send the respond
         */
        session.getAsyncRemote().sendObject(packageRespond);
      }

    } catch (Exception exception) {

      try {

        LOG.error(exception.getMessage());

        /*
         * Respond whit fail message
         */
        addNodeToCatalogMsjRespond =
            new AddNodeToCatalogMsjRespond(
                AddNodeToCatalogMsjRespond.STATUS.FAIL,
                exception.getLocalizedMessage(),
                nodeProfile.getIdentityPublicKey());
        Package packageRespond =
            Package.createInstance(
                addNodeToCatalogMsjRespond.toJson(),
                packageReceived.getNetworkServiceTypeSource(),
                PackageType.ADD_NODE_TO_CATALOG_RESPOND,
                channelIdentityPrivateKey,
                destinationIdentityPublicKey);

        /*
         * Send the respond
         */
        session.getAsyncRemote().sendObject(packageRespond);

      } catch (Exception e) {
        LOG.error(e.getMessage());
      }
    }
  }
  private void doBufferTest(
      boolean isTextBuffer, boolean isServerBuffer, boolean isTextMessage, boolean pass)
      throws Exception {

    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(
        new ApplicationListener(TesterEchoServer.Config.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    if (isServerBuffer) {
      if (isTextBuffer) {
        ctx.addParameter(
            org.apache.tomcat.websocket.server.Constants
                .TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM,
            "1024");
      } else {
        ctx.addParameter(
            org.apache.tomcat.websocket.server.Constants
                .BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM,
            "1024");
      }
    } else {
      if (isTextBuffer) {
        wsContainer.setDefaultMaxTextMessageBufferSize(1024);
      } else {
        wsContainer.setDefaultMaxBinaryMessageBufferSize(1024);
      }
    }

    tomcat.start();

    Session wsSession =
        wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_BASIC));
    BasicHandler<?> handler;
    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties().get("endpoint");
    tep.setLatch(latch);
    if (isTextMessage) {
      handler = new BasicText(latch);
    } else {
      handler = new BasicBinary(latch);
    }

    wsSession.addMessageHandler(handler);
    if (isTextMessage) {
      wsSession.getBasicRemote().sendText(MESSAGE_TEXT_4K);
    } else {
      wsSession.getBasicRemote().sendBinary(ByteBuffer.wrap(MESSAGE_BINARY_4K));
    }

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    Queue<?> messages = handler.getMessages();
    if (pass) {
      Assert.assertEquals(1, messages.size());
      if (isTextMessage) {
        Assert.assertEquals(MESSAGE_TEXT_4K, messages.peek());
      } else {
        Assert.assertEquals(ByteBuffer.wrap(MESSAGE_BINARY_4K), messages.peek());
      }
    } else {
      // When the message exceeds the buffer size, the WebSocket is
      // closed. The endpoint ensures that the latch is cleared when the
      // WebSocket closes. However, the session isn't marked as closed
      // until after the onClose() method completes so there is a small
      // window where this test could fail. Therefore, wait briefly to
      // give the session a chance to complete the close process.
      for (int i = 0; i < 500; i++) {
        if (!wsSession.isOpen()) {
          break;
        }
        Thread.sleep(10);
      }
      Assert.assertFalse(wsSession.isOpen());
    }
  }
Esempio n. 27
0
 @OnOpen
 public void open(final Session session, @PathParam("room") final String room) {
   log.info("session openend and bound to room: " + room);
   session.getUserProperties().put("room", room);
 }
Esempio n. 28
0
 public void setServerIdentity(ECCKeyPair serverIdentity) {
   session.getUserProperties().put(SERVER_IDENTITY_ATT_NAME, serverIdentity);
 }