@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);
   }
 }
Exemple #2
0
  @Test
  public void testLimits() throws DeploymentException {
    Server server = startServer(PingPongEndpoint.class);

    try {

      ClientManager client = createClient();
      final Session session =
          client.connectToServer(
              new Endpoint() {
                @Override
                public void onOpen(Session session, EndpointConfig config) {
                  // do nothing.
                }
              },
              ClientEndpointConfig.Builder.create().build(),
              getURI(PingPongEndpoint.class));

      session
          .getBasicRemote()
          .sendPing(
              ByteBuffer.wrap(
                  "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345"
                      .getBytes()));
      try {
        session
            .getBasicRemote()
            .sendPing(
                ByteBuffer.wrap(
                    "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456"
                        .getBytes()));
        fail();
      } catch (IllegalArgumentException e) {
        // ignore
      }
      session
          .getBasicRemote()
          .sendPong(
              ByteBuffer.wrap(
                  "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345"
                      .getBytes()));
      try {
        session
            .getBasicRemote()
            .sendPong(
                ByteBuffer.wrap(
                    "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456"
                        .getBytes()));
        fail();
      } catch (IllegalArgumentException e) {
        // ignore
      }

    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage(), e);
    } finally {
      stopServer(server);
    }
  }
  // onMessage will be called by WebSockets when this connection has received
  // a WebSocket message from the other side of the connection.
  // The message is derived from the WebSocket frame payloads of one, and only one, WebSocket
  // message.
  @Override
  public void onMessage(String message) {
    try {
      count++;

      if (message.toLowerCase().equals("stop")) {
        // send a WebSocket message back to the other endpoint that says we will stop.
        currentSession.getBasicRemote().sendText("OK. I will stop.");

        // Sleep to let the other side get the message before stopping - a bit kludgy, but this is
        // just a sample!
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        currentSession.close();
      } else {
        // send the message back to the other side with the iteration count.  Notice we can send
        // multiple message without having
        // to receive messages in between.
        currentSession
            .getBasicRemote()
            .sendText("From: " + this.getClass().getSimpleName() + "  Iteration count: " + count);
        currentSession.getBasicRemote().sendText(message);
      }

    } catch (IOException ex) {
      // no error processing will be done for this sample
    }
  }
  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();
  }
  @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");
  }
 @OnOpen
 public void onOpen(Session session) throws IOException {
   if (isEndpointRegistered(
           "/mbean-test",
           new EndpointClassNamePathPair(
               "/monitoredEndpoint1", MonitoredEndpoint1.class.getName()))
       && isEndpointRegistered(
           "/mbean-test",
           new EndpointClassNamePathPair(
               "/monitoredEndpoint2", MonitoredEndpoint2.class.getName()))) {
     session.getBasicRemote().sendText("OK");
     return;
   }
   session.getBasicRemote().sendText("NOK");
 }
Exemple #7
0
  @Override
  public void run() {

    try {
      while (shouldIRun) {
        Thread.sleep(crunchifyRunEveryNSeconds);
        long fileLength = crunchifyFile.length();
        if (fileLength > lastKnownPosition) {

          // Reading and writing file
          RandomAccessFile readWriteFileAccess = new RandomAccessFile(crunchifyFile, "rw");
          readWriteFileAccess.seek(lastKnownPosition);
          String crunchifyLine = null;
          while ((crunchifyLine = readWriteFileAccess.readLine()) != null) {
            for (Session s : AppLogView.sessions) {
              // s.getAsyncRemote().sendText(crunchifyLine);
              s.getBasicRemote().sendText(crunchifyLine);
            }
          }
          lastKnownPosition = readWriteFileAccess.getFilePointer();
          readWriteFileAccess.close();
        }
      }
    } catch (Exception e) {
      shouldIRun = false;
    }
  }
  /**
   * @param gd
   * @param peer
   * @throws IOException
   * @throws EncodeException
   * @throws JSONException
   */
  @OnMessage
  public void broadCastMessage(GameData gd, Session peer)
      throws IOException, EncodeException, JSONException, Exception {
    System.out.println("JSON RECEIVED");
    String gameID = gd.getJson().get("gameId").toString();
    String playername = gd.getJson().getString("playerName");

    // we may not need these lines
    GameBoard board = cache.getBoard();
    board.addPlayerToBoard(new Player(playername));
    JSONObject jSONObject = new JSONObject();
    jSONObject.put("players", board.getPlayersOnBoard());
    jSONObject.put("gameId", gameID);
    jSONObject.put("type", "notify");
    jSONObject.put("playerName", playername);
    if (board.getPlayersOnBoard().size() == 3) {
      jSONObject.put("startGame", true);
    }
    gd.setJson(jSONObject);
    System.out.println("JSON : " + gd.getJson());
    for (Session currPeer : peers) {
      currPeer.getBasicRemote().sendObject(gd);
    }
    System.out.println("JSON SENT");
  }
  @Test
  public void testEcho() throws IOException, DeploymentException, InterruptedException {
    Server server = startServer(SessionBuilderTestEndpoint.class);

    CountDownLatch messageLatch = new CountDownLatch(1);

    try {
      Session session =
          new SessionBuilder()
              .uri(getURI(SessionBuilderTestEndpoint.class))
              .messageHandler(
                  String.class,
                  message -> {
                    if (MESSAGE.equals(message)) {
                      messageLatch.countDown();
                    }
                  })
              .connect();

      session.getBasicRemote().sendText(MESSAGE);

      assertTrue(messageLatch.await(3, TimeUnit.SECONDS));
    } finally {
      stopServer(server);
    }
  }
  @Test
  public void testEncoderDecoder()
      throws IOException, DeploymentException, InterruptedException, EncodeException {
    Server server = startServer(SessionBuilderEncDecTestEndpoint.class);

    CountDownLatch messageLatch = new CountDownLatch(1);

    final ClientEndpointConfig clientEndpointConfig =
        ClientEndpointConfig.Builder.create()
            .encoders(Collections.singletonList(AClassCoder.class))
            .decoders(Collections.singletonList(AClassCoder.class))
            .build();

    try {
      Session session =
          new SessionBuilder()
              .uri(getURI(SessionBuilderEncDecTestEndpoint.class))
              .clientEndpointConfig(clientEndpointConfig)
              .messageHandler(
                  AClass.class,
                  aClass -> {
                    if (MESSAGE.equals(aClass.toString())) {
                      messageLatch.countDown();
                    }
                  })
              .connect();

      session.getBasicRemote().sendObject(new AClass());

      assertTrue(messageLatch.await(3, TimeUnit.SECONDS));
    } finally {
      stopServer(server);
    }
  }
  @Test
  public void testEchoPartial() throws IOException, DeploymentException, InterruptedException {
    Server server = startServer(SessionBuilderTestEndpoint.class);

    CountDownLatch messageLatch = new CountDownLatch(1);

    try {
      Session session =
          new SessionBuilder()
              .uri(getURI(SessionBuilderTestEndpoint.class))
              .messageHandlerPartial(
                  String.class,
                  (message, complete) -> {
                    System.out.println("partial: " + message + " " + complete);

                    if (MESSAGE.equals(message) && complete) {
                      messageLatch.countDown();
                    }
                  })
              .connect();

      session.getBasicRemote().sendText(MESSAGE);

      assertTrue(messageLatch.await(30000000, TimeUnit.SECONDS));
    } finally {
      stopServer(server);
    }
  }
 public void sendData(ResponseDTO resp, String sessionID) throws IOException, Exception {
   for (Session session : peers) {
     if (sessionID.equals(session.getId())) {
       session.getBasicRemote().sendBinary(getZippedResponse(resp));
     }
   }
 }
 @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");
 }
  @Test
  public void testBug58232() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug54807Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());

    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + "/echoBasic");

    try (Session session = wsContainer.connectToServer(client, uri); ) {
      CountDownLatch latch = new CountDownLatch(1);
      BasicText handler = new BasicText(latch);
      session.addMessageHandler(handler);
      session.getBasicRemote().sendText("echoBasic");

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

      Queue<String> messages = handler.getMessages();
      Assert.assertEquals(1, messages.size());
      for (String message : messages) {
        Assert.assertEquals("echoBasic", message);
      }
    }
  }
  private void doMaxMessageSize(String path, long size, boolean expectOpen) 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");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    Session s = connectToEchoServer(wsContainer, EndpointA.class, path);

    StringBuilder msg = new StringBuilder();
    for (long i = 0; i < size; i++) {
      msg.append('x');
    }

    s.getBasicRemote().sendText(msg.toString());

    // Wait for up to 5 seconds for session to close
    boolean open = s.isOpen();
    int count = 0;
    while (open != expectOpen && count < 50) {
      Thread.sleep(100);
      count++;
      open = s.isOpen();
    }

    Assert.assertEquals(Boolean.valueOf(expectOpen), Boolean.valueOf(s.isOpen()));
  }
  @Test
  public void testConnectToServerEndpoint() 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");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    Session wsSession =
        wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText(MESSAGE_STRING_1);

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

    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    Assert.assertEquals(MESSAGE_STRING_1, messages.peek());
  }
 @OnMessage
 public void echo(Session session, Reader input) throws IOException {
   char[] buffer = new char[128];
   try (Writer output = session.getBasicRemote().getSendWriter()) {
     int read;
     while ((read = input.read(buffer)) >= 0) output.write(buffer, 0, read);
   }
 }
 public void writeMessage(String message) {
   System.out.printf("Writing: \"%s\"%n", message);
   try {
     session.getBasicRemote().sendText(message);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemple #19
0
 @OnMessage
 public void userMessage(String message) {
   try {
     hostSession.getBasicRemote().sendText(message);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 /*core not remove*/
 public void sendToSession(Session session, Object object) {
   try {
     ObjectMapper mapper = new ObjectMapper();
     session.getBasicRemote().sendText(mapper.writeValueAsString(object));
   } catch (IOException ex) {
     this.removeDeviceBySession(session);
   }
 }
    @OnOpen
    public void onOpen(Session p) {
      try {
        p.getBasicRemote().sendText(SENT_MESSAGE);

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
 @OnOpen
 public void onOpen(Session session) {
   try {
     MyMessage message = new MyMessage("{\"apple\" : \"red\", \"banana\": \"yellow\"}");
     session.getBasicRemote().sendObject(message);
   } catch (IOException | EncodeException ex) {
     Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
  @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;
    }
  }
  @Override
  public void onMessage(String message) {
    try {
      if ("pathParams".equalsIgnoreCase(message)) {
        StringBuilder ret = new StringBuilder();
        ret.append("pathParams");
        Map<String, String> pathParams = session.getPathParameters();
        if (pathParams == null) {
          ret.append("=<null>");
        } else {
          ret.append('[').append(pathParams.size()).append(']');
          List<String> keys = new ArrayList<>();
          for (String key : pathParams.keySet()) {
            keys.add(key);
          }
          Collections.sort(keys);
          for (String key : keys) {
            String value = pathParams.get(key);
            ret.append(": '").append(key).append("'=").append(value);
          }
        }
        session.getBasicRemote().sendText(ret.toString());
        return;
      }

      if ("requestUri".equalsIgnoreCase(message)) {
        StringBuilder ret = new StringBuilder();
        ret.append("requestUri=");
        URI uri = session.getRequestURI();
        if (uri == null) {
          ret.append("=<null>");
        } else {
          ret.append(uri.toASCIIString());
        }
        session.getBasicRemote().sendText(ret.toString());
        return;
      }

      // simple echo
      session.getBasicRemote().sendText("echo:'" + message + "'");
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
 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());
     }
   }
 }
 public static void encodeCommonReply(
     Session session, String token, String username, String text) {
   if (session.isOpen()) {
     try {
       session.getBasicRemote().sendText(token + DELIMITER + username + DELIMITER + text);
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
 @OnOpen
 public void open(Session session) {
   System.out.println("Opening client Session : " + session.getId());
   try {
     session.getBasicRemote().sendText("test");
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
 private void sendTimeToAll(Session session) {
   allSessions = session.getOpenSessions();
   for (Session sess : allSessions) {
     try {
       sess.getBasicRemote().sendText("Local time: " + LocalTime.now().format(timeFormatter));
     } catch (IOException ioe) {
       System.out.println(ioe.getMessage());
     }
   }
 }
 public static synchronized void sendMsgTwoTime(String msg) {
   logger.info("msg = " + msg);
   try {
     session.getBasicRemote().sendText(msg);
     Thread.sleep(WebSocket.WEB_SOCKET_SLEEP);
     System.in.read();
   } catch (Exception e) {
     logger.error("sendMsg(String msg) error " + uri, e);
   }
   logger.info("end sendMsg(String msg)");
 }
  @OnOpen
  public void sendMessage(Session session) {

    try {
      startTime = System.currentTimeMillis();

      session.getBasicRemote().sendText(sentMessage());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }