void processNewUser(NewUserMessage message) {
    String newUsername = this.validateUsername(message.getUsername());
    NewUserMessage uMessage = new NewUserMessage(newUsername);
    try {
      session.getBasicRemote().sendObject(uMessage);
    } catch (IOException | EncodeException ioe) {
      System.out.println(
          "Error signing " + message.getUsername() + " into chat : " + ioe.getMessage());
    }
    this.registerUser(newUsername);

    try {
      ResultSet rs = null, ds = null;
      String z, x;
      String url1 = "jdbc:mysql://localhost:3306/chat";
      Connection conn1 = DriverManager.getConnection(url1, "root", "root");
      Statement st1 = conn1.createStatement();
      Statement st2 = conn1.createStatement();
      String myQuery = "SELECT Message,Recepient FROM Log WHERE User = '******'";
      System.out.println(myQuery);
      rs =
          st1.executeQuery("SELECT Message,Recepient FROM Log WHERE User = '******';");
      while (rs.next()) {
        z = rs.getString("Message");
        x = rs.getString("Recepient");
        ChatUpdateMessage cdm1 = new ChatUpdateMessage(newUsername, z, x);
        try {
          session.getBasicRemote().sendObject(cdm1);
        } catch (IOException | EncodeException ex) {
          System.out.println("Error updating a client : " + ex.getMessage());
        }
      }

      ds =
          st2.executeQuery("SELECT Message,User FROM Log WHERE Recepient = '" + newUsername + "';");
      while (ds.next()) {
        z = ds.getString("Message");
        x = ds.getString("User");
        ChatUpdateMessage cdm2 = new ChatUpdateMessage(x, z, newUsername);
        try {
          session.getBasicRemote().sendObject(cdm2);
        } catch (IOException | EncodeException ex) {
          System.out.println("Error updating a client : " + ex.getMessage());
        }
      }

    } catch (Exception e) {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
    }

    this.broadcastUserListUpdate();
  }
 @OnMessage
 public void handleMessage(String message, Session session) throws IOException {
   if (!message.equals("ping")) {
     throw new IllegalArgumentException("Invalid message received: " + message);
   }
   session.getBasicRemote().sendText("pong");
 }
 private void broadcastUserListUpdate() {
   UserListUpdateMessage ulum = new UserListUpdateMessage(this.getUserList());
   for (Session nextSession : session.getOpenSessions()) {
     try {
       nextSession.getBasicRemote().sendObject(ulum);
     } catch (IOException | EncodeException ex) {
       System.out.println("Error updating a client : " + ex.getMessage());
     }
   }
 }
 /**
  * When a user sends a message to the server, this method will intercept the message and allow us
  * to react to it. For now the message is read as a String.
  */
 @OnMessage
 public void onMessage(String message, Session session) {
   Logger logger = LogManager.getFormatterLogger(EchoService.class);
   logger.info("Message from " + session.getId() + ": " + message);
   try {
     session.getBasicRemote().sendText(message);
   } catch (IOException ex) {
     ex.printStackTrace();
     logger.error(ex.getMessage(), ex);
   }
 }
Beispiel #5
0
  @OnOpen
  public void onOpen(Session session) {
    try {
      // add new user to list of users
      sessionList.add(session);

      // send new user their session id
      session.getBasicRemote().sendText("{\"sessionId\":\"" + session.getId() + "\"}");

    } catch (IOException e) {
    }
  }
Beispiel #6
0
  private boolean processWatchKey(WatchKey watchKey) {
    for (WatchEvent<?> event : watchKey.pollEvents()) {
      if (StandardWatchEventKinds.OVERFLOW == event.kind()) continue;
      try {
        session.getBasicRemote().sendObject(((Path) event.context()).toFile());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return watchKey.reset();
  }
  @OnOpen
  public void onOpen(Session session) {
    try {
      User person = new User();
      person.setName("john");
      person.setSurname("smith");
      person.setEmail("*****@*****.**");

      session.getBasicRemote().sendObject(person);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #8
0
  @OnOpen
  public void setMonitor(@PathParam("directory") String directory, Session s) {
    System.out.printf("Watch for %s%n", directory);
    try {
      watchService = FileSystems.getDefault().newWatchService();
      session = s;
      Path p = new File(directory).toPath();
      p.register(
          watchService,
          StandardWatchEventKinds.ENTRY_CREATE,
          StandardWatchEventKinds.ENTRY_DELETE,
          StandardWatchEventKinds.ENTRY_MODIFY);
      session.getBasicRemote().sendText("Registered " + p);
      pollThr = new Thread(this);
      pollThr.start();
    } catch (IOException e) {
      try {
        session.getBasicRemote().sendText("Can't setup watcher :" + e);
      } catch (IOException e2) {

      }
    }
  }
  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());
          }
        }
      }
    }
  }
 /**
  * @OnOpen allows us to intercept the creation of a new session. The session class allows us to
  * send data to the user. In the method onOpen, we'll let the user know that the handshake was
  * successful.
  */
 @OnOpen
 public void onOpen(Session session) {
   Logger logger = LogManager.getFormatterLogger(EchoService.class);
   logger.info(session.getId() + " has opened a connection");
   logger.info("MaxBinaryMessageBufferSize %d", session.getMaxBinaryMessageBufferSize());
   logger.info("MaxIdleTimeout %d", session.getMaxIdleTimeout());
   logger.info("MaxTextMessageBufferSize %d", session.getMaxTextMessageBufferSize());
   logger.info("Open sessions size %d", session.getOpenSessions().size());
   logger.info("Protocol %s", session.getProtocolVersion());
   logger.info("QueryString %s", session.getQueryString());
   try {
     session.getBasicRemote().sendText("Connection Established");
   } catch (IOException ex) {
     ex.printStackTrace();
     logger.error(ex.getMessage(), ex);
   }
 }
  @OnMessage
  public void message(
      @PathParam("gameidentifier") String gameIdentifier, String message, Session client)
      throws IOException, EncodeException {

    JsonObject jsonObj = Json.createReader(new StringReader(message)).readObject();
    String command = jsonObj.getString("command");

    if (command.equals("getPlayers")) {
      JsonArrayBuilder arrayBuilder = getCouchStorage().playersList(gameIdentifier);
      JsonObjectBuilder objectBuilder =
          Json.createObjectBuilder().add("players", arrayBuilder).add("command", "loadPlayers");
      client.getBasicRemote().sendText(objectBuilder.build().toString());
    } else if (command.equals("addPlayer")) {

      String playerUUID = jsonObj.getString("playerID");
      Point position =
          new Point(jsonObj.getJsonNumber("positionX"), jsonObj.getJsonNumber("positionY"));

      getCouchStorage().addPlayer(playerUUID, position, gameIdentifier);

      JsonObjectBuilder objectBuilderForAdd =
          Json.createObjectBuilder()
              .add("command", "addedPlayer")
              .add(
                  "data",
                  Json.createObjectBuilder()
                      .add("PlayerID", playerUUID)
                      .add("positionX", position.getPointX())
                      .add("positionY", position.getPointY()));
      String jsonString = objectBuilderForAdd.build().toString();

      for (Session peer : client.getOpenSessions()) {
        peer.getBasicRemote().sendText(jsonString);
      }
    } else if (command.equals("movePlayer")) {
      JsonObject jsonMoveData =
          Json.createReader(new StringReader(message)).readObject().getJsonObject("data");
      JsonObjectBuilder objectBuilder =
          Json.createObjectBuilder().add("command", "playerMoved").add("data", jsonMoveData);

      String playerId = jsonMoveData.getString("PlayerID");
      Point position =
          new Point(
              jsonMoveData.getJsonNumber("positionX"), jsonMoveData.getJsonNumber("positionY"));
      Point targetPosition =
          new Point(
              jsonMoveData.getJsonNumber("targetPositionX"),
              jsonMoveData.getJsonNumber("targetPositionY"));
      int direction = jsonMoveData.getInt("direction");

      getCouchStorage().updatePlayer(playerId, position, direction, targetPosition);

      String jsonString = objectBuilder.build().toString();
      for (Session peer : client.getOpenSessions()) {
        peer.getBasicRemote().sendText(jsonString);
      }
    } else if (command.equals("synchronize")) {
      JsonArray items =
          Json.createReader(new StringReader(message)).readObject().getJsonArray("data");
      getCouchStorage().synchronizePlayers(items);
      JsonArrayBuilder arrayBuilder = getCouchStorage().playersList(gameIdentifier);
      JsonObjectBuilder objectBuilder =
          Json.createObjectBuilder().add("players", arrayBuilder).add("command", "synchronize");
      String jsonString = objectBuilder.build().toString();

      for (Session peer : client.getOpenSessions()) {
        peer.getBasicRemote().sendText(jsonString);
      }
    }
  }