javax.websocket.server.ServerEndpointConfig Java Examples

The following examples show how to use javax.websocket.server.ServerEndpointConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestWsRemoteEndpointImplServer.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);

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

    List<Class<? extends Encoder>> encoders = new ArrayList<Class<? extends Encoder>>();
    encoders.add(Bug58624Encoder.class);
    ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(
            Bug58624Endpoint.class, PATH).encoders(encoders).build();

    try {
        sc.addEndpoint(sec);
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: TestWsServerContainer.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpecExample3() throws Exception {
    WsServerContainer sc =
            new WsServerContainer(new TesterServletContext());

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

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

    Assert.assertEquals(configB, sc.findMapping("/a/b/c").getConfig());
    Assert.assertEquals(configA, sc.findMapping("/a/d/c").getConfig());
    Assert.assertEquals(configC, sc.findMapping("/a/x/y").getConfig());
}
 
Example #3
Source File: MyApp.java    From dropwizard-websockets with MIT License 6 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws InvalidKeySpecException, NoSuchAlgorithmException, ServletException, DeploymentException {
    environment.lifecycle().addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {

        @Override
        public void lifeCycleStarted(LifeCycle event) {
            cdl.countDown();
        }
    });
    environment.jersey().register(new MyResource());
    environment.healthChecks().register("alive", new HealthCheck() {
        @Override
        protected HealthCheck.Result check() throws Exception {
            return HealthCheck.Result.healthy();
        }
    });

    // Using ServerEndpointConfig lets you inject objects to the websocket endpoint:
    final ServerEndpointConfig config = ServerEndpointConfig.Builder.create(EchoServer.class, "/extends-ws").build();
    // config.getUserProperties().put(Environment.class.getName(), environment);
    // Then you can get it from the Session object
    // - obj = session.getUserProperties().get("objectName");            
    websocketBundle.addEndpoint(config);
}
 
Example #4
Source File: TestWsRemoteEndpointImplServer.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);

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

    List<Class<? extends Encoder>> encoders = new ArrayList<Class<? extends Encoder>>();
    encoders.add(Bug58624Encoder.class);
    ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(
            Bug58624Endpoint.class, PATH).encoders(encoders).build();

    try {
        sc.addEndpoint(sec);
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: ExamplesConfig.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public Set<ServerEndpointConfig> getEndpointConfigs(
        Set<Class<? extends Endpoint>> scanned) {

    Set<ServerEndpointConfig> result = new HashSet<>();

    if (scanned.contains(EchoEndpoint.class)) {
        result.add(ServerEndpointConfig.Builder.create(
                EchoEndpoint.class,
                "/websocket/echoProgrammatic").build());
    }

    if (scanned.contains(DrawboardEndpoint.class)) {
        result.add(ServerEndpointConfig.Builder.create(
                DrawboardEndpoint.class,
                "/websocket/drawboard").build());
    }

    return result;
}
 
Example #6
Source File: ServerEndpointExporter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Actually register the endpoints. Called by {@link #afterSingletonsInstantiated()}.
 */
protected void registerEndpoints() {
	Set<Class<?>> endpointClasses = new LinkedHashSet<>();
	if (this.annotatedEndpointClasses != null) {
		endpointClasses.addAll(this.annotatedEndpointClasses);
	}

	ApplicationContext context = getApplicationContext();
	if (context != null) {
		String[] endpointBeanNames = context.getBeanNamesForAnnotation(ServerEndpoint.class);
		for (String beanName : endpointBeanNames) {
			endpointClasses.add(context.getType(beanName));
		}
	}

	for (Class<?> endpointClass : endpointClasses) {
		registerEndpoint(endpointClass);
	}

	if (context != null) {
		Map<String, ServerEndpointConfig> endpointConfigMap = context.getBeansOfType(ServerEndpointConfig.class);
		for (ServerEndpointConfig endpointConfig : endpointConfigMap.values()) {
			registerEndpoint(endpointConfig);
		}
	}
}
 
Example #7
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #8
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
@Ignore("UT3 - P4")
public void testPingPong() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final CompletableFuture<?> latch = new CompletableFuture<>();

    class TestEndPoint extends Endpoint {
        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getEventLoopSupplier(), Collections.EMPTY_LIST, false, false);

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

    WebSocketTestClient client = new WebSocketTestClient(new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new PingWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(PongWebSocketFrame.class, payload, latch));
    latch.get(10, TimeUnit.SECONDS);
    Assert.assertNull(cause.get());
    client.destroy();
}
 
Example #9
Source File: TesterEndpointConfig.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);

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

    try {
        ServerEndpointConfig sec = getServerEndpointConfig();
        if (sec == null) {
            sc.addEndpoint(getEndpointClass());
        } else {
            sc.addEndpoint(sec);
        }
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: ExamplesConfig.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
public Set<ServerEndpointConfig> getEndpointConfigs(
        Set<Class<? extends Endpoint>> scanned) {

    Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>();

    if (scanned.contains(EchoEndpoint.class)) {
        result.add(ServerEndpointConfig.Builder.create(
                EchoEndpoint.class,
                "/websocket/echoProgrammatic").build());
    }

    if (scanned.contains(DrawboardEndpoint.class)) {
        result.add(ServerEndpointConfig.Builder.create(
                DrawboardEndpoint.class,
                "/websocket/drawboard").build());
    }

    return result;
}
 
Example #11
Source File: TestWsServerContainer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testSpecExample3() throws Exception {
    WsServerContainer sc = new WsServerContainer(new TesterServletContext());

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

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

    Assert.assertEquals(configB, sc.findMapping("/a/b/c").getConfig());
    Assert.assertEquals(configA, sc.findMapping("/a/d/c").getConfig());
    Assert.assertEquals(configC, sc.findMapping("/a/x/y").getConfig());
}
 
Example #12
Source File: TestWsServerContainer.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #13
Source File: TestClose.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@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(
            getEndpointClass(), PATH).build();

    try {
        sc.addEndpoint(sec);
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
Source File: SaslTest.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
@Override
protected void registerWebSocketEndpoints(final ServerContainer container) {
  try {
    container.addEndpoint(ServerEndpointConfig.Builder
        .create(
            WSEndpoint.class,
            WSEndpoint.class.getAnnotation(ServerEndpoint.class).value()
        ).build());
  } catch (DeploymentException e) {
    fail("Invalid test");
  }
}
 
Example #15
Source File: ServerApplication.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void initialize(final Bootstrap<AppConfig> bootstrap) {
  // This bootstrap will replace ${...} values in YML configuration with environment
  // variable values. Without it, all values in the YML configuration are treated as literals.
  bootstrap.setConfigurationSourceProvider(
      new SubstitutingSourceProvider(
          bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(false)));

  // From: https://www.dropwizard.io/0.7.1/docs/manual/jdbi.html
  // By adding the JdbiExceptionsBundle to your application, Dropwizard will automatically unwrap
  // ant thrown SQLException or DBIException instances. This is critical for debugging, since
  // otherwise only the common wrapper exception’s stack trace is logged.
  bootstrap.addBundle(new JdbiExceptionsBundle());
  bootstrap.addBundle(new RateLimitBundle(new InMemoryRateLimiterFactory()));

  // Note, websocket endpoint is instantiated dynamically on every new connection and does
  // not allow for constructor injection. To inject objects, we use 'userProperties' of the
  // socket configuration that can then be retrieved from a websocket session.
  gameConnectionWebsocket =
      ServerEndpointConfig.Builder.create(
              GameConnectionWebSocket.class, WebsocketPaths.GAME_CONNECTIONS)
          .build();

  playerConnectionWebsocket =
      ServerEndpointConfig.Builder.create(
              PlayerConnectionWebSocket.class, WebsocketPaths.PLAYER_CONNECTIONS)
          .build();

  bootstrap.addBundle(new WebsocketBundle(gameConnectionWebsocket, playerConnectionWebsocket));
}
 
Example #16
Source File: TestWsServerContainer.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test(expected = javax.websocket.DeploymentException.class)
public void testDuplicatePaths_02() throws Exception {
    WsServerContainer sc =
            new WsServerContainer(new TesterServletContext());

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

    sc.addEndpoint(configA);
    sc.addEndpoint(configB);
}
 
Example #17
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBinaryWithByteArray() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final CompletableFuture<?> latch = new CompletableFuture<>();
    class TestEndPoint extends Endpoint {
        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
            session.addMessageHandler(new MessageHandler.Whole<byte[]>() {
                @Override
                public void onMessage(byte[] message) {
                    session.getAsyncRemote().sendBinary(ByteBuffer.wrap(message.clone()));
                }
            });
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getEventLoopSupplier(), Collections.EMPTY_LIST, false, false);
    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());

    deployServlet(builder);

    WebSocketTestClient client = new WebSocketTestClient(new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    latch.get();
    Assert.assertNull(cause.get());
    client.destroy();
}
 
Example #18
Source File: TestWsServerContainer.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #19
Source File: WebSocketTunnelModule.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
@Override
public void configureServlets() {

    logger.info("Loading JSR-356 WebSocket support...");

    // Get container
    ServerContainer container = (ServerContainer) getServletContext().getAttribute("javax.websocket.server.ServerContainer"); 
    if (container == null) {
        logger.warn("ServerContainer attribute required by JSR-356 is missing. Cannot load JSR-356 WebSocket support.");
        return;
    }

    Provider<TunnelRequestService> tunnelRequestServiceProvider = getProvider(TunnelRequestService.class);

    // Build configuration for WebSocket tunnel
    ServerEndpointConfig config =
            ServerEndpointConfig.Builder.create(RestrictedGuacamoleWebSocketTunnelEndpoint.class, "/websocket-tunnel")
                                        .configurator(new RestrictedGuacamoleWebSocketTunnelEndpoint.Configurator(tunnelRequestServiceProvider))
                                        .subprotocols(Arrays.asList(new String[]{"guacamole"}))
                                        .build();

    try {

        // Add configuration to container
        container.addEndpoint(config);

    }
    catch (DeploymentException e) {
        logger.error("Unable to deploy WebSocket tunnel.", e);
    }

}
 
Example #20
Source File: TestWsServerContainer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #21
Source File: CamelWebSocketJSR356Recorder.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public void configureWebsocketEndpoints(WebSocketDeploymentInfo deploymentInfo, CamelWebSocketJSR356Config config) {
    List<String> endpointPaths = config.serverEndpointPaths.orElseGet(Collections::emptyList);
    for (String path : endpointPaths) {
        CamelServerEndpoint endpoint = new CamelServerEndpoint();
        ServerEndpointConfig.Builder builder = ServerEndpointConfig.Builder.create(CamelServerEndpoint.class, path);
        builder.configurator(new CamelWebSocketJSR356EndpointConfigurator(endpoint));
        deploymentInfo.addEndpoint(builder.build());
    }
}
 
Example #22
Source File: TestWsServerContainer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test(expected = DeploymentException.class)
public void testDuplicatePaths02() throws Exception {
    WsServerContainer sc = new WsServerContainer(new TesterServletContext());

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

    sc.addEndpoint(configA);
    sc.addEndpoint(configB);
}
 
Example #23
Source File: PojoEndpointServer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {

    ServerEndpointConfig sec = (ServerEndpointConfig) endpointConfig;

    Object pojo;
    try {
        pojo = sec.getConfigurator().getEndpointInstance(
                sec.getEndpointClass());
    } catch (InstantiationException e) {
        throw new IllegalArgumentException(sm.getString(
                "pojoEndpointServer.getPojoInstanceFail",
                sec.getEndpointClass().getName()), e);
    }
    setPojo(pojo);

    @SuppressWarnings("unchecked")
    Map<String,String> pathParameters =
            (Map<String, String>) sec.getUserProperties().get(
                    POJO_PATH_PARAM_KEY);
    setPathParameters(pathParameters);

    PojoMethodMapping methodMapping =
            (PojoMethodMapping) sec.getUserProperties().get(
                    POJO_METHOD_MAPPING_KEY);
    setMethodMapping(methodMapping);

    doOnOpen(session, endpointConfig);
}
 
Example #24
Source File: ServerContainerInitializeListener.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
protected ServerEndpointConfig createServerEndpointConfig(ServletContext servletContext) {
    final List<Class<? extends Encoder>> encoders = new LinkedList<>();
    final List<Class<? extends Decoder>> decoders = new LinkedList<>();
    encoders.add(OutputMessageEncoder.class);
    decoders.add(InputMessageDecoder.class);
    final ServerEndpointConfig endpointConfig = create(WSConnectionImpl.class, "/ws")
            .configurator(createConfigurator()).encoders(encoders).decoders(decoders).build();
    endpointConfig.getUserProperties().put(EVERREST_PROCESSOR_ATTRIBUTE, getEverrestProcessor(servletContext));
    endpointConfig.getUserProperties().put(EVERREST_CONFIG_ATTRIBUTE, getEverrestConfiguration(servletContext));
    endpointConfig.getUserProperties().put(EXECUTOR_ATTRIBUTE, createExecutor(servletContext));
    return endpointConfig;
}
 
Example #25
Source File: TestWsServerContainer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test(expected = DeploymentException.class)
public void testDuplicatePaths21() throws Exception {
    WsServerContainer sc = new WsServerContainer(new TesterServletContext());

    ServerEndpointConfig configA = ServerEndpointConfig.Builder.create(
            PojoTemplate.class, "/foo/{a}").build();

    sc.addEndpoint(configA, false);
    sc.addEndpoint(PojoTemplate.class, true);
}
 
Example #26
Source File: ServerWebSocketContainer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void addEndpoint(final ServerEndpointConfig endpoint) throws DeploymentException {
    if (deploymentComplete) {
        throw JsrWebSocketMessages.MESSAGES.cannotAddEndpointAfterDeployment();
    }
    JsrWebSocketLogger.ROOT_LOGGER.addingProgramaticEndpoint(endpoint.getEndpointClass(), endpoint.getPath());
    final PathTemplate template = PathTemplate.create(endpoint.getPath());
    if (seenPaths.contains(template)) {
        PathTemplate existing = null;
        for (PathTemplate p : seenPaths) {
            if (p.compareTo(template) == 0) {
                existing = p;
                break;
            }
        }
        throw JsrWebSocketMessages.MESSAGES.multipleEndpointsWithOverlappingPaths(template, existing);
    }
    seenPaths.add(template);
    EncodingFactory encodingFactory = EncodingFactory.createFactory(classIntrospecter, endpoint.getDecoders(), endpoint.getEncoders());

    AnnotatedEndpointFactory annotatedEndpointFactory = null;
    if (!Endpoint.class.isAssignableFrom(endpoint.getEndpointClass())) {
        // We may want to check that the path in @ServerEndpoint matches the specified path, and throw if they are not equivalent
        annotatedEndpointFactory = AnnotatedEndpointFactory.create(endpoint.getEndpointClass(), encodingFactory, template.getParameterNames());
    }
    ConfiguredServerEndpoint confguredServerEndpoint = new ConfiguredServerEndpoint(endpoint, null, template, encodingFactory, annotatedEndpointFactory, endpoint.getExtensions());
    configuredServerEndpoints.add(confguredServerEndpoint);
    handleAddingFilterMapping();
}
 
Example #27
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testText() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final CompletableFuture<?> latch = new CompletableFuture<>();

    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) {
                    session.getAsyncRemote().sendText(message);
                }
            });
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getEventLoopSupplier(), Collections.EMPTY_LIST, false, false);
    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
    deployServlet(builder);

    WebSocketTestClient client = new WebSocketTestClient(new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new TextWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(TextWebSocketFrame.class, payload, latch));
    latch.get();
    Assert.assertNull(cause.get());
    client.destroy();
}
 
Example #28
Source File: TestWsServerContainer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testDuplicatePaths12() throws Exception {
    WsServerContainer sc = new WsServerContainer(new TesterServletContext());

    ServerEndpointConfig configA = ServerEndpointConfig.Builder.create(
            Pojo.class, "/foo").build();

    sc.addEndpoint(Pojo.class, true);
    sc.addEndpoint(configA);

    Assert.assertNotEquals(configA, sc.findMapping("/foo").getConfig());
}
 
Example #29
Source File: TestWsServerContainer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test(expected = javax.websocket.DeploymentException.class)
public void testDuplicatePaths_01() throws Exception {
    WsServerContainer sc =
            new WsServerContainer(new TesterServletContext());

    ServerEndpointConfig configA = ServerEndpointConfig.Builder.create(
            Object.class, "/a/b/c").build();
    ServerEndpointConfig configB = ServerEndpointConfig.Builder.create(
            Object.class, "/a/b/c").build();

    sc.addEndpoint(configA);
    sc.addEndpoint(configB);
}
 
Example #30
Source File: PojoEndpointServer.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {

    ServerEndpointConfig sec = (ServerEndpointConfig) endpointConfig;

    Object pojo;
    try {
        pojo = sec.getConfigurator().getEndpointInstance(
                sec.getEndpointClass());
    } catch (InstantiationException e) {
        throw new IllegalArgumentException(sm.getString(
                "pojoEndpointServer.getPojoInstanceFail",
                sec.getEndpointClass().getName()), e);
    }
    setPojo(pojo);

    @SuppressWarnings("unchecked")
    Map<String,String> pathParameters =
            (Map<String, String>) sec.getUserProperties().get(
                    POJO_PATH_PARAM_KEY);
    setPathParameters(pathParameters);

    PojoMethodMapping methodMapping =
            (PojoMethodMapping) sec.getUserProperties().get(
                    POJO_METHOD_MAPPING_KEY);
    setMethodMapping(methodMapping);

    doOnOpen(session, endpointConfig);
}