// encoders/decoders per session
  @Test
  public void testProgrammatic() throws DeploymentException {

    final Server server =
        startServer(MyApplicationConfiguration.class, ServerDeployApplicationConfig.class);

    try {
      messageLatch = new CountDownLatch(1);

      ClientManager serviceClient = ClientManager.createClient();

      testViaServiceEndpoint(serviceClient, ServiceEndpoint.class, POSITIVE, "Cleanup");

      WebSocketContainer client = ContainerProvider.getWebSocketContainer();
      Session session =
          client.connectToServer(
              ClientEndpoint.class,
              ClientEndpointConfig.Builder.create().build(),
              getURI("/myEndpoint"));

      messageLatch.await(5, TimeUnit.SECONDS);

      testViaServiceEndpoint(serviceClient, ServiceEndpoint.class, POSITIVE, "FirstClient");

      messageLatch = new CountDownLatch(1);
      session.getBasicRemote().sendText("test");
      messageLatch.await(5, TimeUnit.SECONDS);

      testViaServiceEndpoint(serviceClient, ServiceEndpoint.class, POSITIVE, "FirstClient");

      session.close();

      testViaServiceEndpoint(serviceClient, ServiceEndpoint.class, POSITIVE, "FirstClientClosed");

      messageLatch = new CountDownLatch(1);
      session =
          client.connectToServer(
              ClientEndpoint.class,
              ClientEndpointConfig.Builder.create().build(),
              getURI("/myEndpoint"));
      messageLatch.await(5, TimeUnit.SECONDS);

      testViaServiceEndpoint(serviceClient, ServiceEndpoint.class, POSITIVE, "SecondClient");

      session.close();

      testViaServiceEndpoint(serviceClient, ServiceEndpoint.class, POSITIVE, "SecondClientClosed");
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(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
    }
  }
  /**
   * Sends the given status on the given WebSocket connection and closes the connection.
   *
   * @param session The outbound WebSocket connection to close.
   * @param guac_status The status to send.
   */
  private void closeConnection(Session session, GuacamoleStatus guac_status) {

    try {
      CloseCode code = CloseReason.CloseCodes.getCloseCode(guac_status.getWebSocketCode());
      String message = Integer.toString(guac_status.getGuacamoleStatusCode());
      session.close(new CloseReason(code, message));
    } catch (IOException e) {
      logger.debug("Unable to close WebSocket connection.", e);
    }
  }
 @OnClose
 public void onClose(Session session, @PathParam("username") String username) {
   try {
     client.remove(session);
     user.remove(URLEncoder.encode(username, "UTF-8"));
     session.close();
   } catch (Exception e) {
     // do nothing
   }
 }
Beispiel #5
0
 private void activeClose(CloseReason reason) {
   try {
     if (thisSession.isOpen()) {
       LOG.debug("Closing connection to peer: " + thisSession.getId());
       thisSession.close(reason);
     }
   } catch (IOException e) {
     LOG.error(e);
   }
 }
 private void disconnectImpl() {
   if (websocketSession != null) {
     try {
       websocketSession.close();
     } catch (IOException ex) {
       // ignored.
     } finally {
       websocketSession = null;
     }
   }
 }
Beispiel #7
0
 /**
  * Send message to the service endpoint and compare the received result with the specified one.
  *
  * @param client client used to send the message.
  * @param serviceEndpoint endpoint to which the message will be sent.
  * @param expectedResult expected reply.
  * @param message message to be sent.
  * @throws DeploymentException
  * @throws IOException
  * @throws InterruptedException
  */
 protected void testViaServiceEndpoint(
     ClientManager client, Class<?> serviceEndpoint, final String expectedResult, String message)
     throws DeploymentException, IOException, InterruptedException {
   final MyServiceClientEndpoint myServiceClientEndpoint = new MyServiceClientEndpoint();
   final Session serviceSession =
       client.connectToServer(myServiceClientEndpoint, getURI(serviceEndpoint));
   serviceSession.getBasicRemote().sendText(message);
   assertTrue(myServiceClientEndpoint.latch.await(1, TimeUnit.SECONDS));
   assertEquals(expectedResult, myServiceClientEndpoint.receivedMessage);
   serviceSession.close();
 }
Beispiel #8
0
 public synchronized void putNewSession(String sid, Session session) {
   Session other = this.savedSessionMap.get(sid);
   if (other != null && other.isOpen()) {
     try {
       other.close();
     } catch (IOException ex) {
       this.logger.error("websocket-close sid:{} error:{}", sid, ex.getMessage());
     }
   }
   this.savedSessionMap.put(sid, session);
   this.logger.debug("websocket-session add new sid:{}", sid);
 }
 @OnError
 public void onError(Session session, Throwable t) {
   try {
     System.out.println(" --------------------------------------------------------------------- ");
     System.out.println(" WsCommunicationsTyrusCloudClientChannel - Starting method onError");
     t.printStackTrace();
     clientConnection.close(
         new CloseReason(CloseReason.CloseCodes.PROTOCOL_ERROR, t.getMessage()));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 protected void disconnect(String reason) {
   Session wsSession = _wsSession;
   _wsSession = null;
   if (wsSession != null && wsSession.isOpen()) {
     logger.debug("Closing websocket session {}", wsSession);
     try {
       wsSession.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, reason));
     } catch (IOException x) {
       logger.trace("Could not close websocket session " + wsSession, x);
     }
   }
 }
Beispiel #11
0
  @Test
  public void testErrorOnClose() {
    Server server = new Server(OnCloseErrorTestEndpoint.class);

    try {
      server.start();
      final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();

      messageLatch = new CountDownLatch(1);
      ClientManager client = ClientManager.createClient();
      final Session session =
          client.connectToServer(
              new TestEndpointAdapter() {
                @Override
                public EndpointConfig getEndpointConfig() {
                  return cec;
                }

                @Override
                public void onOpen(Session session) {
                  session.addMessageHandler(new TestTextMessageHandler(this));
                }

                @Override
                public void onMessage(String message) {
                  // do nothing
                }
              },
              cec,
              new URI("ws://localhost:8025/websockets/tests/close"));

      // TODO: is this really needed? Cannot we somehow force underlying protocol impl to connect
      // immediately
      // TODO: after connectToServer call?
      messageLatch.await(1, TimeUnit.SECONDS);
      session.close();

      // TODO: is this really needed? Cannot we somehow force underlying protocol impl to connect
      // immediately
      // TODO: after close call?
      messageLatch.await(1, TimeUnit.SECONDS);

      assertTrue(OnCloseErrorTestEndpoint.session != null);
      assertTrue(OnCloseErrorTestEndpoint.throwable != null);
      assertEquals("testException", OnCloseErrorTestEndpoint.throwable.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage(), e);
    } finally {
      server.stop();
    }
  }
Beispiel #12
0
  @Test
  public void testAllMethods()
      throws IOException, DeploymentException, InterruptedException, EncodeException {
    Server server = startServer(SessionBuilderEncDecTestEndpoint.class);

    CountDownLatch messageLatch = new CountDownLatch(1);
    CountDownLatch onOpenLatch = new CountDownLatch(1);
    CountDownLatch onCloseLatch = new CountDownLatch(1);
    CountDownLatch onErrorLatch = 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();
                    }
                  })
              .onOpen((session1, endpointConfig) -> onOpenLatch.countDown())
              .onError((session1, throwable) -> onErrorLatch.countDown())
              .onClose(
                  (session1, closeReason) -> {
                    onCloseLatch.countDown();
                    throw new RuntimeException("onErrorTrigger");
                  })
              .connect();

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

      assertTrue(onOpenLatch.await(3, TimeUnit.SECONDS));
      assertTrue(messageLatch.await(3, TimeUnit.SECONDS));

      session.close();

      assertTrue(onCloseLatch.await(3, TimeUnit.SECONDS));
      assertTrue(onErrorLatch.await(3, TimeUnit.SECONDS));

    } finally {
      stopServer(server);
    }
  }
  public void closeConnection() {

    try {

      System.out.println(" WsCommunicationsTyrusCloudClientChannel - close connection");
      clientConnection.close(
          new CloseReason(
              CloseReason.CloseCodes.NORMAL_CLOSURE,
              "The cloud client close the connection, intentionally."));
      raiseClientConnectionCloseNotificationEvent();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @Test
  public void testGetOpenSessions() 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 s1a =
        connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC);
    Session s2a =
        connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC);
    Session s3a =
        connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC);

    Session s1b =
        connectToEchoServer(wsContainer, EndpointB.class, TesterEchoServer.Config.PATH_BASIC);
    Session s2b =
        connectToEchoServer(wsContainer, EndpointB.class, TesterEchoServer.Config.PATH_BASIC);

    Set<Session> setA = s3a.getOpenSessions();
    Assert.assertEquals(3, setA.size());
    Assert.assertTrue(setA.remove(s1a));
    Assert.assertTrue(setA.remove(s2a));
    Assert.assertTrue(setA.remove(s3a));

    s1a.close();

    setA = s3a.getOpenSessions();
    Assert.assertEquals(2, setA.size());
    Assert.assertFalse(setA.remove(s1a));
    Assert.assertTrue(setA.remove(s2a));
    Assert.assertTrue(setA.remove(s3a));

    Set<Session> setB = s1b.getOpenSessions();
    Assert.assertEquals(2, setB.size());
    Assert.assertTrue(setB.remove(s1b));
    Assert.assertTrue(setB.remove(s2b));
  }
 @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);
 }
Beispiel #16
0
 @Override
 protected void shutdown(String reason) {
   Session session;
   synchronized (this) {
     session = _session;
     close();
   }
   if (session != null) {
     if (logger.isDebugEnabled())
       logger.debug("Closing ({}) websocket session {}", reason, session);
     try {
       // Limits of the WebSocket APIs, otherwise an exception is thrown.
       reason = reason.substring(0, Math.min(reason.length(), 30));
       session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, reason));
     } catch (Throwable x) {
       logger.trace("Could not close websocket session " + session, x);
     }
   }
 }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    XDIAddress parent = XDIAddress.create(req.getParameter("parent"));
    String parentSecretToken = req.getParameter("parentSecretToken");
    XDIAddress child1 = XDIAddress.create(req.getParameter("child1"));
    XDIAddress child2 = XDIAddress.create(req.getParameter("child2"));

    Connection connection =
        CynjaCloudChat.connectionService.blockConnection(parent, parentSecretToken, child1, child2);

    Session[] sessions = CynjaCloudChat.sessionService.getSessions(connection);

    for (Session session : sessions) {

      session.close(new CloseReason(CloseCodes.VIOLATED_POLICY, "Connection has been blocked."));
    }
  }
Beispiel #18
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();
    }
  @Override
  public void run() {

    final Semaphore sem = new Semaphore(0);
    final List<String> logs = new ArrayList<String>();
    final Map<String, List<String>> logsToSync = new HashMap<String, List<String>>();
    final List<Session> sessions = new ArrayList<Session>();

    GenericWebsocketClient gwc =
        new GenericWebsocketClient(
            new WebsocketClient() {
              @Override
              public void onOpen(final Session session, EndpointConfig config) {
                try {
                  sessions.add(session);
                  String sid = session.getId();
                  List<String> sl = Collections.synchronizedList(new ArrayList<String>(logs));
                  logsToSync.put(sid, sl);

                  for (String id : sl) {
                    AttLog log = attLogsManager.findById(id);
                    String json = attLogSerializer.toJson(log);
                    String cmdJson = "attLog;" + json;

                    logger.info(cmdJson);
                    session.getBasicRemote().sendText(cmdJson);
                  }

                } catch (Exception e) {
                  logger.log(Level.SEVERE, e.getMessage(), e);
                  sem.release();
                }
              }

              @Override
              public void onClose(Session s, CloseReason reason) {
                logger.info("onClose");
                sem.release();
              }

              @Override
              public void onMessage(String m, Session session) {
                logger.info("onMessage " + m);

                String sid = session.getId();
                List<String> sl = logsToSync.get(sid);

                String cmd = "OK;delete;";
                if (m.startsWith(cmd)) {

                  String id = m.substring(cmd.length());
                  try {
                    attLogsManager.remove(id);
                    if (sl != null) {
                      sl.remove(id);
                    }

                    if (sl == null || sl.size() <= 0) {
                      sem.release();
                    }

                  } catch (AttLogException e) {
                    logger.log(Level.SEVERE, e.getMessage(), e);
                    sem.release();
                  }
                }
              }
            });

    final URI uri =
        URI.create("ws://" + serverData.getIp() + ":" + serverData.getPort() + serverData.getUrl());

    while (true) {

      // busco a ver si existen logs a ser sincronizados.
      logs.clear();
      try {
        List<String> ls = attLogsManager.findAll();

        if (ls != null && ls.size() > 0) {

          logs.addAll(ls);
          sem.drainPermits();

          logger.info("connecting to : " + uri.toString());
          ContainerProvider.getWebSocketContainer().connectToServer(gwc, uri);

          try {
            sem.acquire();

          } catch (InterruptedException e1) {
            e1.printStackTrace();
          }
        }

      } catch (DeploymentException | AttLogException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);

      } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);

      } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
      }

      // limpio todas las sesiones que hayan quedado habiertas.
      for (Session s : sessions) {
        try {
          if (s.isOpen()) {
            s.close();
          }
        } catch (IOException e) {
        }
      }
      sessions.clear();
      logsToSync.clear();
      logs.clear();

      try {
        // espero a que alguien marque o hasta que se cumpla el sleep.
        MutualExclusion.using[MutualExclusion.NEED_ATTLOGS_SYNC].tryAcquire(
            sleep, TimeUnit.MILLISECONDS);

      } catch (InterruptedException e) {

      }
    }
  }