コード例 #1
0
ファイル: BasicWSRouteTest.java プロジェクト: frtj/camelwss
  @Test
  public void happyTest() throws Exception {
    BasicWSRoute route = context.getRegistry().lookup("basicRoute", BasicWSRoute.class);

    AsyncHttpClient c = new AsyncHttpClient();

    WebSocket websocket =
        c.prepareGet("ws:" + route.getConnectionUri())
            .execute(
                new WebSocketUpgradeHandler.Builder()
                    .addWebSocketListener(
                        new WebSocketTextListener() {
                          @Override
                          public void onMessage(String message) {
                            received.add(message);
                            System.out.println("received --> " + message);
                            latch.countDown();
                          }

                          @Override
                          public void onFragment(String fragment, boolean last) {}

                          @Override
                          public void onOpen(WebSocket websocket) {}

                          @Override
                          public void onClose(WebSocket websocket) {}

                          @Override
                          public void onError(Throwable t) {
                            t.printStackTrace();
                          }
                        })
                    .build())
            .get();

    // Jackson
    ObjectMapper mapper = new ObjectMapper();
    WsMessage info = new WsMessage();
    info.setHeader("woot");
    info.setContent("hest");

    websocket.sendTextMessage(mapper.writeValueAsString(info));
    assertTrue(latch.await(10, TimeUnit.SECONDS));

    assertEquals(1, received.size());
    WsMessage result = mapper.readValue(received.get(0), WsMessage.class);
    assertTrue(result.getContent().startsWith("pong:"));

    websocket.close();
    c.close();
  }
コード例 #2
0
ファイル: PlexConnector.java プロジェクト: juri8/openhab
 /** Closes the web socket connection */
 public void close() {
   if (webSocket != null) {
     running = false;
     webSocket.close();
     webSocket = null;
   }
 }
コード例 #3
0
ファイル: PlexConnector.java プロジェクト: juri8/openhab
  /**
   * Check if the connection to the Plex server is active
   *
   * @return true if an active connection to the Plex server exists, false otherwise
   */
  public boolean isConnected() {
    if (webSocket == null || !webSocket.isOpen()) {
      return false;
    }

    return connected;
  }
コード例 #4
0
  @Test
  public void testWSHttpCall() throws Exception {
    AsyncHttpClient c = new AsyncHttpClient();

    WebSocket websocket =
        c.prepareGet("ws://127.0.0.1:" + port + "/echo")
            .execute(
                new WebSocketUpgradeHandler.Builder()
                    .addWebSocketListener(
                        new WebSocketTextListener() {
                          @Override
                          public void onMessage(String message) {}

                          @Override
                          public void onFragment(String fragment, boolean last) {}

                          @Override
                          public void onOpen(WebSocket websocket) {}

                          @Override
                          public void onClose(WebSocket websocket) {}

                          @Override
                          public void onError(Throwable t) {
                            t.printStackTrace();
                          }
                        })
                    .build())
            .get();

    MockEndpoint result = getMockEndpoint("mock:result");
    result.expectedBodiesReceived("Test");

    websocket.sendTextMessage("Test");

    result.assertIsSatisfied();

    websocket.close();
    c.close();
  }
コード例 #5
0
 public void sendMessage(byte[] message) {
   websocket.sendMessage(message);
 }
コード例 #6
0
 public void sendTextMessage(String message) {
   websocket.sendTextMessage(message);
 }
コード例 #7
0
 public void close() {
   websocket.close();
   client.close();
 }
コード例 #8
0
ファイル: BaseTest.java プロジェクト: juansarabia/atmosphere
  @Test(timeOut = 60000, enabled = true)
  public void onResumeWithTimerTest() {
    logger.info("{}: running test: onResumeWithTimerTest", getClass().getSimpleName());

    final AtomicBoolean onResume = new AtomicBoolean();
    final CountDownLatch eventReceived = new CountDownLatch(1);
    final CountDownLatch suspended = new CountDownLatch(1);
    final AtomicReference<AtmosphereResource> resource = new AtomicReference<AtmosphereResource>();

    final CountDownLatch latch = new CountDownLatch(1);
    atmoServlet
        .framework()
        .addAtmosphereHandler(
            ROOT,
            new AbstractHttpAtmosphereHandler() {

              public void onRequest(final AtmosphereResource r) throws IOException {
                r.addEventListener(
                    new WebSocketEventListenerAdapter() {

                      @Override
                      public void onSuspend(AtmosphereResourceEvent event) {
                        logger.trace("{}", event);
                        suspended.countDown();
                      }

                      @Override
                      public void onResume(AtmosphereResourceEvent event) {
                        onResume.set(true);
                        eventReceived.countDown();
                      }
                    });

                if (suspended.getCount() != 0) {
                  resource.set(r.suspend());
                } else {
                  try {
                    suspended.await(5, TimeUnit.SECONDS);
                  } catch (InterruptedException e) {
                    e.printStackTrace();
                  }
                  String message = r.getRequest().getReader().readLine();
                  r.getBroadcaster().broadcast(message);
                  new Timer()
                      .schedule(
                          new TimerTask() {
                            @Override
                            public void run() {
                              resource.get().resume();
                            }
                          },
                          2000);
                }
              }

              public void onStateChange(AtmosphereResourceEvent event) throws IOException {
                if (event.isSuspended()) {
                  event.getResource().write(event.getMessage().toString().getBytes());
                }
              }
            },
            BroadcasterFactory.getDefault().get(DefaultBroadcaster.class, "suspend"));

    AsyncHttpClient c = new AsyncHttpClient();
    try {
      final AtomicReference<String> response = new AtomicReference<String>(null);
      WebSocket w =
          c.prepareGet(urlTarget).execute(new WebSocketUpgradeHandler.Builder().build()).get();
      w.addWebSocketListener(
              new WebSocketTextListener() {

                @Override
                public void onMessage(String message) {
                  response.set(message);
                  latch.countDown();
                }

                @Override
                public void onFragment(String fragment, boolean last) {
                  fail();
                }

                @Override
                public void onOpen(WebSocket websocket) {}

                @Override
                public void onClose(WebSocket websocket) {
                  latch.countDown();
                }

                @Override
                public void onError(Throwable t) {
                  t.printStackTrace();
                  fail(t.getMessage());
                }
              })
          .sendTextMessage("echo");

      try {
        latch.await(20, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
        fail(e.getMessage());
      }

      eventReceived.await(10, TimeUnit.SECONDS);
      assertNotNull(response.get());
      assertEquals(response.get(), "echo");
      assertTrue(onResume.get());

    } catch (Exception e) {
      logger.error("test failed", e);
      fail(e.getMessage());
    }
    c.close();
  }
コード例 #9
0
ファイル: BaseTest.java プロジェクト: juansarabia/atmosphere
  @Test(timeOut = 60000, enabled = true)
  public void sessionTest() {
    logger.info("{}: running test: sessionTest", getClass().getSimpleName());

    final AtomicReference<HttpSession> session = new AtomicReference<HttpSession>();
    final AtomicReference<HttpSession> sessionOnPost = new AtomicReference<HttpSession>();

    final CountDownLatch latch = new CountDownLatch(1);
    atmoServlet
        .framework()
        .addAtmosphereHandler(
            ROOT,
            new AbstractHttpAtmosphereHandler() {

              boolean isSuspended = false;

              public void onRequest(AtmosphereResource r) throws IOException {
                if (!isSuspended) {
                  session.set(r.suspend().session(true));
                  isSuspended = true;
                } else {
                  String message = r.getRequest().getReader().readLine();
                  r.getBroadcaster().broadcast(message);
                }
              }

              public void onStateChange(AtmosphereResourceEvent event) throws IOException {
                if (event.isSuspended()) {
                  sessionOnPost.set(event.getResource().session());
                  event.getResource().write(event.getMessage().toString().getBytes());
                }
              }
            },
            BroadcasterFactory.getDefault().get(DefaultBroadcaster.class, "suspend"));

    AsyncHttpClient c = new AsyncHttpClient();
    try {
      final AtomicReference<String> response = new AtomicReference<String>(null);
      WebSocket w =
          c.prepareGet(urlTarget).execute(new WebSocketUpgradeHandler.Builder().build()).get();
      w.addWebSocketListener(
              new WebSocketTextListener() {

                @Override
                public void onMessage(String message) {
                  response.set(message);
                  latch.countDown();
                }

                @Override
                public void onFragment(String fragment, boolean last) {
                  fail();
                }

                @Override
                public void onOpen(WebSocket websocket) {}

                @Override
                public void onClose(WebSocket websocket) {
                  latch.countDown();
                }

                @Override
                public void onError(Throwable t) {
                  t.printStackTrace();
                  fail(t.getMessage());
                }
              })
          .sendTextMessage("echo");

      try {
        latch.await(20, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
        fail(e.getMessage());
      }

      assertNotNull(response.get());
      assertEquals(response.get(), "echo");
      assertEquals(session.get().getId(), sessionOnPost.get().getId());

    } catch (Exception e) {
      logger.error("test failed", e);
      fail(e.getMessage());
    }
    c.close();
  }