Esempio n. 1
0
  @Test(expected = javax.websocket.DeploymentException.class)
  public void testDuplicatePaths_03() throws Exception {
    WsServerContainer sc = new WsServerContainer(new TesterServletContext());

    ServerEndpointConfig configA =
        ServerEndpointConfig.Builder.create(Object.class, "/a/b/{var1}").build();
    ServerEndpointConfig configB =
        ServerEndpointConfig.Builder.create(Object.class, "/a/b/{var2}").build();

    sc.addEndpoint(configA);
    sc.addEndpoint(configB);
  }
Esempio n. 2
0
  @Test
  public void testSpecExample4() throws Exception {
    WsServerContainer sc = new WsServerContainer(new TesterServletContext());

    ServerEndpointConfig configA =
        ServerEndpointConfig.Builder.create(Object.class, "/{var1}/d").build();
    ServerEndpointConfig configB =
        ServerEndpointConfig.Builder.create(Object.class, "/b/{var2}").build();

    sc.addEndpoint(configA);
    sc.addEndpoint(configB);

    Assert.assertEquals(configB, sc.findMapping("/b/d").getConfig());
  }
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    ServerContainer container =
        (ServerContainer) sce.getServletContext().getAttribute(ServerContainer.class.getName());

    try {
      container.addEndpoint(
          ServerEndpointConfig.Builder.create(PongMessageEndpoint.class, "/ping").build());
      container.addEndpoint(
          ServerEndpointConfig.Builder.create(PongMessageEndpoint.class, "/pong").build());
    } catch (DeploymentException e) {
      throw new RuntimeException("Unable to add endpoint via config file", e);
    }
  }
  @org.junit.Test
  public void testBinaryWithByteBufferAsync() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<Throwable>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();

    class TestEndPoint extends Endpoint {
      @Override
      public void onOpen(final Session session, EndpointConfig config) {
        connected.set(true);
        session.addMessageHandler(
            new MessageHandler.Partial<ByteBuffer>() {
              @Override
              public void onMessage(ByteBuffer message, boolean last) {
                Assert.assertTrue(last);
                ByteBuffer buf = ByteBuffer.allocate(message.remaining());
                buf.put(message);
                buf.flip();
                try {
                  session.getBasicRemote().sendBinary(buf);
                } catch (IOException e) {
                  e.printStackTrace();
                  cause.set(e);
                  latch.setException(e);
                }
              }
            });
      }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE);
    builder.start(
        HttpClient.create(DefaultServer.getWorker(), OptionMap.EMPTY),
        new ByteBufferSlicePool(100, 100));

    builder.addEndpoint(
        ServerEndpointConfig.Builder.create(TestEndPoint.class, "/")
            .configurator(new InstanceConfigurator(new TestEndPoint()))
            .build());
    deployServlet(builder);

    WebSocketTestClient client =
        new WebSocketTestClient(
            getVersion(),
            new URI(
                "ws://"
                    + DefaultServer.getHostAddress("default")
                    + ":"
                    + DefaultServer.getHostPort("default")
                    + "/"));
    client.connect();
    client.send(
        new BinaryWebSocketFrame(ChannelBuffers.wrappedBuffer(payload)),
        new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();
    Assert.assertNull(cause.get());
    client.destroy();
  }
  @org.junit.Test
  public void testCloseFrame() throws Exception {
    final int code = 1000;
    final String reasonText = "TEST";
    final AtomicReference<CloseReason> reason = new AtomicReference<CloseReason>();
    ByteBuffer payload = ByteBuffer.allocate(reasonText.length() + 2);
    payload.putShort((short) code);
    payload.put(reasonText.getBytes("UTF-8"));
    payload.flip();

    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();
    final AtomicInteger closeCount = new AtomicInteger();

    class TestEndPoint extends Endpoint {
      @Override
      public void onOpen(final Session session, EndpointConfig config) {
        connected.set(true);
      }

      @Override
      public void onClose(Session session, CloseReason closeReason) {
        closeCount.incrementAndGet();
        reason.set(closeReason);
      }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE);
    builder.start(
        HttpClient.create(DefaultServer.getWorker(), OptionMap.EMPTY),
        new ByteBufferSlicePool(100, 100));

    builder.addEndpoint(
        ServerEndpointConfig.Builder.create(TestEndPoint.class, "/")
            .configurator(new InstanceConfigurator(new TestEndPoint()))
            .build());
    deployServlet(builder);

    WebSocketTestClient client =
        new WebSocketTestClient(
            getVersion(),
            new URI(
                "ws://"
                    + DefaultServer.getHostAddress("default")
                    + ":"
                    + DefaultServer.getHostPort("default")
                    + "/"));
    client.connect();
    client.send(
        new CloseWebSocketFrame(code, reasonText),
        new FrameChecker(CloseWebSocketFrame.class, payload.array(), latch));
    latch.getIoFuture().get();
    Assert.assertEquals(code, reason.get().getCloseCode().getCode());
    Assert.assertEquals(reasonText, reason.get().getReasonPhrase());
    Assert.assertEquals(1, closeCount.get());
    client.destroy();
  }
Esempio n. 6
0
 public static void launchSessionEndpoint(
     ServletContext context, String path, String actorSystemKey) {
   ServerContainer container =
       (ServerContainer) context.getAttribute("javax.websocket.server.ServerContainer");
   try {
     container.addEndpoint(
         ServerEndpointConfig.Builder.create(SessionEndpoint.class, path)
             .configurator(new SessionEndpointConfigurator(actorSystemKey))
             .build());
   } catch (DeploymentException ex) {
     ex.printStackTrace();
   }
 }
  @org.junit.Test
  public void testTextByFuture() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Future<Void>> sendResult = new AtomicReference<Future<Void>>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();

    class TestEndPoint extends Endpoint {
      @Override
      public void onOpen(final Session session, EndpointConfig config) {
        connected.set(true);
        session.addMessageHandler(
            new MessageHandler.Whole<String>() {
              @Override
              public void onMessage(String message) {
                sendResult.set(session.getAsyncRemote().sendText(message));
              }
            });
      }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE);
    builder.start(
        HttpClient.create(DefaultServer.getWorker(), OptionMap.EMPTY),
        new ByteBufferSlicePool(100, 100));
    builder.addEndpoint(
        ServerEndpointConfig.Builder.create(TestEndPoint.class, "/")
            .configurator(new InstanceConfigurator(new TestEndPoint()))
            .build());
    deployServlet(builder);

    WebSocketTestClient client =
        new WebSocketTestClient(
            getVersion(),
            new URI(
                "ws://"
                    + DefaultServer.getHostAddress("default")
                    + ":"
                    + DefaultServer.getHostPort("default")
                    + "/"));
    client.connect();
    client.send(
        new TextWebSocketFrame(ChannelBuffers.wrappedBuffer(payload)),
        new FrameChecker(TextWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();

    sendResult.get();

    client.destroy();
  }
 @Override
 public void contextInitialized(ServletContextEvent sce) {
   super.contextInitialized(sce);
   ServerContainer sc =
       (ServerContainer)
           sce.getServletContext()
               .getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
   try {
     sc.addEndpoint(ServerEndpointConfig.Builder.create(ConstantTxEndpoint.class, PATH).build());
     if (TestWsWebSocketContainer.timoutOnContainer) {
       sc.setAsyncSendTimeout(TIMEOUT_MS);
     }
   } catch (DeploymentException e) {
     throw new IllegalStateException(e);
   }
 }
Esempio n. 9
0
  @Before
  public void prepare() throws Exception {
    server = new Server();
    connector = new ServerConnector(server);
    server.addConnector(connector);

    ServletContextHandler context = new ServletContextHandler(server, "/", true, false);
    ServerContainer container = WebSocketServerContainerInitializer.configureContext(context);
    ServerEndpointConfig config =
        ServerEndpointConfig.Builder.create(ServerTextStreamer.class, PATH).build();
    container.addEndpoint(config);

    server.start();

    wsClient = ContainerProvider.getWebSocketContainer();
    server.addBean(wsClient, true);
  }
Esempio n. 10
0
    @Override
    public void contextInitialized(ServletContextEvent sce) {
      super.contextInitialized(sce);

      ServerContainer sc =
          (ServerContainer)
              sce.getServletContext()
                  .getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);

      ServerEndpointConfig sec =
          ServerEndpointConfig.Builder.create(TesterEchoServer.Basic.class, "/{param}").build();

      try {
        sc.addEndpoint(sec);
      } catch (DeploymentException e) {
        throw new RuntimeException(e);
      }
    }
  /**
   * Provides the equivalent of {@link #addEndpoint(ServerEndpointConfig)} for publishing plain old
   * java objects (POJOs) that have been annotated as WebSocket endpoints.
   *
   * @param pojo The annotated POJO
   */
  @Override
  public void addEndpoint(Class<?> pojo) throws DeploymentException {

    ServerEndpoint annotation = pojo.getAnnotation(ServerEndpoint.class);
    if (annotation == null) {
      throw new DeploymentException(
          sm.getString("serverContainer.missingAnnotation", pojo.getName()));
    }
    String path = annotation.value();

    // Validate encoders
    validateEncoders(annotation.encoders());

    // Method mapping
    PojoMethodMapping methodMapping = new PojoMethodMapping(pojo, annotation.decoders(), path);

    // ServerEndpointConfig
    ServerEndpointConfig sec;
    Class<? extends Configurator> configuratorClazz = annotation.configurator();
    Configurator configurator = null;
    if (!configuratorClazz.equals(Configurator.class)) {
      try {
        configurator = annotation.configurator().newInstance();
      } catch (InstantiationException | IllegalAccessException e) {
        throw new DeploymentException(
            sm.getString(
                "serverContainer.configuratorFail",
                annotation.configurator().getName(),
                pojo.getClass().getName()),
            e);
      }
    }
    sec =
        ServerEndpointConfig.Builder.create(pojo, path)
            .decoders(Arrays.asList(annotation.decoders()))
            .encoders(Arrays.asList(annotation.encoders()))
            .subprotocols(Arrays.asList(annotation.subprotocols()))
            .configurator(configurator)
            .build();
    sec.getUserProperties().put(PojoEndpointServer.POJO_METHOD_MAPPING_KEY, methodMapping);

    addEndpoint(sec);
  }
Esempio n. 12
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public Task<Void> start() {

    // Ensuring that jersey will use singletons from the orbit container.
    ServiceLocator locator = Injections.createLocator();
    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    final List<Class<?>> classes = new ArrayList<>(providers);
    if (container != null) {
      classes.addAll(container.getClasses());
      for (final Class<?> c : container.getClasses()) {
        if (c.isAnnotationPresent(Singleton.class)) {
          Injections.addBinding(
              Injections.newFactoryBinder(
                      new Factory() {
                        @Override
                        public Object provide() {
                          return container.get(c);
                        }

                        @Override
                        public void dispose(final Object instance) {}
                      })
                  .to(c),
              dc);
        }
      }
    }
    dc.commit();

    final ResourceConfig resourceConfig = new ResourceConfig();

    // installing jax-rs classes known by the orbit container.
    for (final Class c : classes) {
      if (c.isAnnotationPresent(javax.ws.rs.Path.class)
          || c.isAnnotationPresent(javax.ws.rs.ext.Provider.class)) {
        resourceConfig.register(c);
      }
    }

    final WebAppContext webAppContext = new WebAppContext();
    final ProtectionDomain protectionDomain = EmbeddedHttpServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    logger.info(location.toExternalForm());
    webAppContext.setInitParameter("useFileMappedBuffer", "false");
    webAppContext.setWar(location.toExternalForm());
    // this sets the default service locator to one that bridges to the orbit container.
    webAppContext.getServletContext().setAttribute(ServletProperties.SERVICE_LOCATOR, locator);
    webAppContext.setContextPath("/*");
    webAppContext.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    final ContextHandler resourceContext = new ContextHandler();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[] {"index.html"});
    resourceHandler.setBaseResource(Resource.newClassPathResource("/web"));

    resourceContext.setHandler(resourceHandler);
    resourceContext.setInitParameter("useFileMappedBuffer", "false");
    final ContextHandlerCollection contexts = new ContextHandlerCollection();

    contexts.setHandlers(
        new Handler[] {
          wrapHandlerWithMetrics(resourceContext, "resourceContext"),
          wrapHandlerWithMetrics(webAppContext, "webAppContext")
        });

    server = new Server(port);
    server.setHandler(contexts);
    try {
      /// Initialize javax.websocket layer
      final ServerContainer serverContainer =
          WebSocketServerContainerInitializer.configureContext(webAppContext);

      for (Class c : classes) {
        if (c.isAnnotationPresent(ServerEndpoint.class)) {
          final ServerEndpoint annotation = (ServerEndpoint) c.getAnnotation(ServerEndpoint.class);

          final ServerEndpointConfig serverEndpointConfig =
              ServerEndpointConfig.Builder.create(c, annotation.value())
                  .configurator(
                      new ServerEndpointConfig.Configurator() {
                        @Override
                        public <T> T getEndpointInstance(final Class<T> endpointClass)
                            throws InstantiationException {
                          return container.get(endpointClass);
                        }
                      })
                  .build();

          serverContainer.addEndpoint(serverEndpointConfig);
        }
      }
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }

    try {
      server.start();
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }
    return Task.done();
  }
  @org.junit.Test
  public void testBinaryWithByteBufferByCompletion() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<SendResult> sendResult = new AtomicReference<SendResult>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();
    final FutureResult latch2 = new FutureResult();

    class TestEndPoint extends Endpoint {
      @Override
      public void onOpen(final Session session, EndpointConfig config) {
        connected.set(true);
        session.addMessageHandler(
            new MessageHandler.Whole<ByteBuffer>() {
              @Override
              public void onMessage(ByteBuffer message) {
                ByteBuffer buf = ByteBuffer.allocate(message.remaining());
                buf.put(message);
                buf.flip();
                session
                    .getAsyncRemote()
                    .sendBinary(
                        buf,
                        new SendHandler() {
                          @Override
                          public void onResult(SendResult result) {
                            sendResult.set(result);
                            if (result.getException() != null) {
                              latch2.setException(new IOException(result.getException()));
                            } else {
                              latch2.setResult(null);
                            }
                          }
                        });
              }
            });
      }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE);
    builder.start(
        HttpClient.create(DefaultServer.getWorker(), OptionMap.EMPTY),
        new ByteBufferSlicePool(100, 100));

    builder.addEndpoint(
        ServerEndpointConfig.Builder.create(TestEndPoint.class, "/")
            .configurator(new InstanceConfigurator(new TestEndPoint()))
            .build());
    deployServlet(builder);

    WebSocketTestClient client =
        new WebSocketTestClient(
            getVersion(),
            new URI(
                "ws://"
                    + DefaultServer.getHostAddress("default")
                    + ":"
                    + DefaultServer.getHostPort("default")
                    + "/"));
    client.connect();
    client.send(
        new BinaryWebSocketFrame(ChannelBuffers.wrappedBuffer(payload)),
        new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();
    latch2.getIoFuture().get();

    SendResult result = sendResult.get();
    Assert.assertNotNull(result);
    Assert.assertNull(result.getException());

    client.destroy();
  }
 public WicketServerEndpointConfig() {
   this.delegate =
       ServerEndpointConfig.Builder.create(WicketEndpoint.class, WICKET_WEB_SOCKET_PATH).build();
 }