javax.websocket.Endpoint Java Examples

The following examples show how to use javax.websocket.Endpoint. 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: SuspendResumeTestCase.java    From quarkus-http with Apache License 2.0 7 votes vote down vote up
@Test
public void testRejectWhenSuspended() throws Exception {
    try {
        serverContainer.pause(null);
        ContainerProvider.getWebSocketContainer().connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig config) {

            }
        }, new URI(DefaultServer.getDefaultServerURL() + "/"));
    } catch (IOException e) {
        //expected
    } finally {
        serverContainer.resume();
    }

}
 
Example #2
Source File: WebSphereRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void upgradeInternal(ServerHttpRequest httpRequest, ServerHttpResponse httpResponse,
		@Nullable String selectedProtocol, List<Extension> selectedExtensions, Endpoint endpoint)
		throws HandshakeFailureException {

	HttpServletRequest request = getHttpServletRequest(httpRequest);
	HttpServletResponse response = getHttpServletResponse(httpResponse);

	StringBuffer requestUrl = request.getRequestURL();
	String path = request.getRequestURI();  // shouldn't matter
	Map<String, String> pathParams = Collections.<String, String> emptyMap();

	ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(path, endpoint);
	endpointConfig.setSubprotocols(Collections.singletonList(selectedProtocol));
	endpointConfig.setExtensions(selectedExtensions);

	try {
		ServerContainer container = getContainer(request);
		upgradeMethod.invoke(container, request, response, endpointConfig, pathParams);
	}
	catch (Exception ex) {
		throw new HandshakeFailureException(
				"Servlet request failed to upgrade to WebSocket for " + requestUrl, ex);
	}
}
 
Example #3
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 #4
Source File: WebSphereRequestUpgradeStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void upgradeInternal(ServerHttpRequest httpRequest, ServerHttpResponse httpResponse,
		@Nullable String selectedProtocol, List<Extension> selectedExtensions, Endpoint endpoint)
		throws HandshakeFailureException {

	HttpServletRequest request = getHttpServletRequest(httpRequest);
	HttpServletResponse response = getHttpServletResponse(httpResponse);

	StringBuffer requestUrl = request.getRequestURL();
	String path = request.getRequestURI();  // shouldn't matter
	Map<String, String> pathParams = Collections.<String, String> emptyMap();

	ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(path, endpoint);
	endpointConfig.setSubprotocols(Collections.singletonList(selectedProtocol));
	endpointConfig.setExtensions(selectedExtensions);

	try {
		ServerContainer container = getContainer(request);
		upgradeMethod.invoke(container, request, response, endpointConfig, pathParams);
	}
	catch (Exception ex) {
		throw new HandshakeFailureException(
				"Servlet request failed to upgrade to WebSocket for " + requestUrl, ex);
	}
}
 
Example #5
Source File: WebSocketJSR356Test.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testWebsocketChat() throws Exception {
    LinkedBlockingDeque<String> message = new LinkedBlockingDeque<>();
    Endpoint endpoint = new Endpoint() {
        @Override
        public void onOpen(Session session, EndpointConfig endpointConfig) {
            session.addMessageHandler(new MessageHandler.Whole<String>() {
                @Override
                public void onMessage(String s) {
                    message.add(s);
                }
            });
            session.getAsyncRemote().sendText("Camel Quarkus WebSocket");
        }
    };

    ClientEndpointConfig config = ClientEndpointConfig.Builder.create().build();
    try (Session session = ContainerProvider.getWebSocketContainer().connectToServer(endpoint, config, uri)) {
        Assertions.assertEquals("Hello Camel Quarkus WebSocket", message.poll(5, TimeUnit.SECONDS));
    }
}
 
Example #6
Source File: StandardWebSocketClient.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Mono<Void> executeInternal(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) {
	MonoProcessor<Void> completionMono = MonoProcessor.create();
	return Mono.fromCallable(
			() -> {
				if (logger.isDebugEnabled()) {
					logger.debug("Connecting to " + url);
				}
				List<String> protocols = handler.getSubProtocols();
				DefaultConfigurator configurator = new DefaultConfigurator(requestHeaders);
				Endpoint endpoint = createEndpoint(url, handler, completionMono, configurator);
				ClientEndpointConfig config = createEndpointConfig(configurator, protocols);
				return this.webSocketContainer.connectToServer(endpoint, config, url);
			})
			.subscribeOn(Schedulers.elastic()) // connectToServer is blocking
			.then(completionMono);
}
 
Example #7
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 #8
Source File: StandardWebSocketClient.java    From java-technology-stack with MIT License 6 votes vote down vote up
private Mono<Void> executeInternal(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) {
	MonoProcessor<Void> completionMono = MonoProcessor.create();
	return Mono.fromCallable(
			() -> {
				if (logger.isDebugEnabled()) {
					logger.debug("Connecting to " + url);
				}
				List<String> protocols = handler.getSubProtocols();
				DefaultConfigurator configurator = new DefaultConfigurator(requestHeaders);
				Endpoint endpoint = createEndpoint(url, handler, completionMono, configurator);
				ClientEndpointConfig config = createEndpointConfig(configurator, protocols);
				return this.webSocketContainer.connectToServer(endpoint, config, url);
			})
			.subscribeOn(Schedulers.elastic()) // connectToServer is blocking
			.then(completionMono);
}
 
Example #9
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 #10
Source File: ServerWebSocketContainer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public Session connectToServer(final Class<? extends Endpoint> endpointClass, final ClientEndpointConfig cec, final URI path) throws DeploymentException, IOException {
    if (closed) {
        throw new ClosedChannelException();
    }
    try {
        Endpoint endpoint = classIntrospecter.createInstanceFactory(endpointClass).createInstance().getInstance();
        return connectToServer(endpoint, cec, path);
    } catch (InstantiationException | NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: MockServerContainer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Session connectToServer(Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path)
		throws DeploymentException, IOException {

	throw new UnsupportedOperationException(
			"MockServerContainer does not support connectToServer(Class, ClientEndpointConfig, URI)");
}
 
Example #12
Source File: StandardWebSocketClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler,
		HttpHeaders headers, final URI uri, List<String> protocols,
		List<WebSocketExtension> extensions, Map<String, Object> attributes) {

	int port = getPort(uri);
	InetSocketAddress localAddress = new InetSocketAddress(getLocalHost(), port);
	InetSocketAddress remoteAddress = new InetSocketAddress(uri.getHost(), port);

	final StandardWebSocketSession session = new StandardWebSocketSession(headers,
			attributes, localAddress, remoteAddress);

	final ClientEndpointConfig endpointConfig = ClientEndpointConfig.Builder.create()
			.configurator(new StandardWebSocketClientConfigurator(headers))
			.preferredSubprotocols(protocols)
			.extensions(adaptExtensions(extensions)).build();

	endpointConfig.getUserProperties().putAll(getUserProperties());

	final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session);

	Callable<WebSocketSession> connectTask = () -> {
		this.webSocketContainer.connectToServer(endpoint, endpointConfig, uri);
		return session;
	};

	if (this.taskExecutor != null) {
		return this.taskExecutor.submitListenable(connectTask);
	}
	else {
		ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<>(connectTask);
		task.run();
		return task;
	}
}
 
Example #13
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBinaryWithByteBufferAsync() 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.Partial<ByteBuffer>() {
                @Override
                public void onMessage(ByteBuffer message, boolean last) {
                    Assert.assertTrue(last);
                    ByteBuffer buf = ByteBuffer.allocate(message.remaining());
                    buf.put(message);
                    buf.flip();
                    session.getAsyncRemote().sendBinary(buf);

                }
            });
        }
    }
    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 #14
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testTextAsync() 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.Partial<String>() {

                StringBuilder sb = new StringBuilder();

                @Override
                public void onMessage(String message, boolean last) {
                    sb.append(message);
                    if (!last) {
                        return;
                    }
                    session.getAsyncRemote().sendText(sb.toString());
                }
            });
        }
    }
    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 #15
Source File: DefaultServerEndpointConfig.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Constructor with a path and an {@code javax.websocket.Endpoint}.
 * @param path the endpoint path
 * @param endpoint the endpoint instance
 */
public DefaultServerEndpointConfig(String path, Endpoint endpoint) {
	Assert.hasText(path, "path must not be empty");
	Assert.notNull(endpoint, "endpoint must not be null");
	this.path = path;
	this.endpoint = endpoint;
}
 
Example #16
Source File: TomcatRequestUpgradeStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler,
		@Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory){

	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();

	HttpServletRequest servletRequest = getHttpServletRequest(request);
	HttpServletResponse servletResponse = getHttpServletResponse(response);

	HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
	DataBufferFactory bufferFactory = response.bufferFactory();

	Endpoint endpoint = new StandardWebSocketHandlerAdapter(
			handler, session -> new TomcatWebSocketSession(session, handshakeInfo, bufferFactory));

	String requestURI = servletRequest.getRequestURI();
	DefaultServerEndpointConfig config = new DefaultServerEndpointConfig(requestURI, endpoint);
	config.setSubprotocols(subProtocol != null ?
			Collections.singletonList(subProtocol) : Collections.emptyList());

	try {
		WsServerContainer container = getContainer(servletRequest);
		container.doUpgrade(servletRequest, servletResponse, config, Collections.emptyMap());
	}
	catch (ServletException | IOException ex) {
		return Mono.error(ex);
	}

	return Mono.empty();
}
 
Example #17
Source File: AbstractTyrusRequestUpgradeStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static Constructor<?> getEndpointConstructor() {
	for (Constructor<?> current : TyrusEndpointWrapper.class.getConstructors()) {
		Class<?>[] types = current.getParameterTypes();
		if (Endpoint.class == types[0] && EndpointConfig.class == types[1]) {
			return current;
		}
	}
	throw new IllegalStateException("No compatible Tyrus version found");
}
 
Example #18
Source File: AbstractTyrusRequestUpgradeStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Object createTyrusEndpoint(Endpoint endpoint, String endpointPath, @Nullable String protocol,
		List<Extension> extensions, WebSocketContainer container, TyrusWebSocketEngine engine)
		throws DeploymentException {

	ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(endpointPath, endpoint);
	endpointConfig.setSubprotocols(Collections.singletonList(protocol));
	endpointConfig.setExtensions(extensions);
	return createEndpoint(endpointConfig, this.componentProvider, container, engine);
}
 
Example #19
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testTextByFuture() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Future<Void>> sendResult = 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) {
                    sendResult.set(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();

    sendResult.get();

    client.destroy();
}
 
Example #20
Source File: UndertowSession.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public UndertowSession(Channel channel, URI requestUri, Map<String, String> pathParameters,
                       Map<String, List<String>> requestParameterMap, EndpointSessionHandler handler, Principal user,
                       InstanceHandle<Endpoint> endpoint, EndpointConfig config, final String queryString,
                       final Encoding encoding, final SessionContainer openSessions, final String subProtocol,
                       final List<Extension> extensions, WebsocketConnectionBuilder clientConnectionBuilder,
                       Executor executor) {
    channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            closeInternal(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, null));
        }
    });
    this.clientConnectionBuilder = clientConnectionBuilder;
    assert openSessions != null;
    this.channel = channel;
    this.queryString = queryString;
    this.encoding = encoding;
    this.openSessions = openSessions;
    container = handler.getContainer();
    this.user = user;
    this.requestUri = requestUri;
    this.requestParameterMap = Collections.unmodifiableMap(requestParameterMap);
    this.pathParameters = Collections.unmodifiableMap(pathParameters);
    this.config = config;
    remote = new WebSocketSessionRemoteEndpoint(this, encoding);
    this.endpoint = endpoint;
    this.sessionId = new SecureRandomSessionIdGenerator().createSessionId();
    this.attrs = Collections.synchronizedMap(new HashMap<>(config.getUserProperties()));
    this.extensions = extensions;
    this.subProtocol = subProtocol;
    this.executor = executor;
    setupWebSocketChannel(channel);
}
 
Example #21
Source File: ServerWebSocketContainer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public Session connectToServer(final Endpoint endpointInstance, final ClientEndpointConfig config, final URI path) throws DeploymentException, IOException {
    if (closed) {
        throw new ClosedChannelException();
    }
    ClientEndpointConfig cec = config != null ? config : ClientEndpointConfig.Builder.create().build();

    SSLContext ssl = null;
    if (path.getScheme().equals("wss")) {
        for (WebsocketClientSslProvider provider : clientSslProviders) {
            ssl = provider.getSsl(eventLoopSupplier.get(), endpointInstance, cec, path);
            if (ssl != null) {
                break;
            }
        }
        if (ssl == null) {
            try {
                ssl = SSLContext.getDefault();
            } catch (NoSuchAlgorithmException e) {
                //ignore
            }
        }
    }
    //in theory we should not be able to connect until the deployment is complete, but the definition of when a deployment is complete is a bit nebulous.
    ClientNegotiation clientNegotiation = new ClientNegotiation(cec.getPreferredSubprotocols(), toExtensionList(cec.getExtensions()), cec);


    WebsocketConnectionBuilder connectionBuilder = new WebsocketConnectionBuilder(path, eventLoopSupplier.get())
            .setSsl(ssl)
            .setBindAddress(clientBindAddress)
            .setClientNegotiation(clientNegotiation);

    return connectToServer(endpointInstance, config, connectionBuilder);
}
 
Example #22
Source File: ServerWebSocketContainer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public Session connectToServer(final Object annotatedEndpointInstance, final URI path) throws DeploymentException, IOException {
    if (closed) {
        throw new ClosedChannelException();
    }
    ConfiguredClientEndpoint config = getClientEndpoint(annotatedEndpointInstance.getClass(), false);
    if (config == null) {
        throw JsrWebSocketMessages.MESSAGES.notAValidClientEndpointType(annotatedEndpointInstance.getClass());
    }
    Endpoint instance = config.getFactory().createInstance(new ImmediateInstanceHandle<>(annotatedEndpointInstance));
    SSLContext ssl = null;

    if (path.getScheme().equals("wss")) {
        for (WebsocketClientSslProvider provider : clientSslProviders) {
            ssl = provider.getSsl(eventLoopSupplier.get(), annotatedEndpointInstance, path);
            if (ssl != null) {
                break;
            }
        }
        if (ssl == null) {
            try {
                ssl = SSLContext.getDefault();
            } catch (NoSuchAlgorithmException e) {
                //ignore
            }
        }
    }
    return connectToServerInternal(instance, ssl, config, path);
}
 
Example #23
Source File: ServerWebSocketContainer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public Session connectToServer(final Object annotatedEndpointInstance, WebsocketConnectionBuilder connectionBuilder) throws DeploymentException, IOException {
    if (closed) {
        throw new ClosedChannelException();
    }
    ConfiguredClientEndpoint config = getClientEndpoint(annotatedEndpointInstance.getClass(), false);
    if (config == null) {
        throw JsrWebSocketMessages.MESSAGES.notAValidClientEndpointType(annotatedEndpointInstance.getClass());
    }
    Endpoint instance = config.getFactory().createInstance(new ImmediateInstanceHandle<>(annotatedEndpointInstance));
    return connectToServerInternal(instance, config, connectionBuilder);
}
 
Example #24
Source File: DefaultWebSocketClientSslProvider.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public SSLContext getSsl(EventLoopGroup worker, Endpoint endpoint, ClientEndpointConfig cec, URI uri) {
    SSLContext ssl = getThreadLocalSsl(worker);
    if (ssl != null) {
        return ssl;
    }
    //look for some SSL config
    SSLContext sslContext = (SSLContext) cec.getUserProperties().get(SSL_CONTEXT);

    if (sslContext != null) {
        return sslContext;
    }
    return null;
}
 
Example #25
Source File: MockServerContainer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Session connectToServer(Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path)
		throws DeploymentException, IOException {

	throw new UnsupportedOperationException(
			"MockServerContainer does not support connectToServer(Class, ClientEndpointConfig, URI)");
}
 
Example #26
Source File: MockServerContainer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Session connectToServer(Endpoint endpointInstance, ClientEndpointConfig cec, URI path)
		throws DeploymentException, IOException {

	throw new UnsupportedOperationException(
			"MockServerContainer does not support connectToServer(Endpoint, ClientEndpointConfig, URI)");
}
 
Example #27
Source File: StandardWebSocketClientTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void clientEndpointConfigWithUserProperties() throws Exception {

	Map<String,Object> userProperties = Collections.singletonMap("foo", "bar");

	URI uri = new URI("ws://localhost/abc");
	this.wsClient.setUserProperties(userProperties);
	this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get();

	ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class);
	verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class));
	ClientEndpointConfig endpointConfig = captor.getValue();

	assertEquals(userProperties, endpointConfig.getUserProperties());
}
 
Example #28
Source File: StandardWebSocketClientTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void clientEndpointConfig() throws Exception {

	URI uri = new URI("ws://localhost/abc");
	List<String> protocols = Collections.singletonList("abc");
	this.headers.setSecWebSocketProtocol(protocols);

	this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get();

	ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class);
	verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class));
	ClientEndpointConfig endpointConfig = captor.getValue();

	assertEquals(protocols, endpointConfig.getPreferredSubprotocols());
}
 
Example #29
Source File: ServerEndpointRegistration.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public Endpoint getEndpoint() {
	if (this.endpoint != null) {
		return this.endpoint;
	}
	else {
		Assert.state(this.endpointProvider != null, "No endpoint set");
		return this.endpointProvider.getHandler();
	}
}
 
Example #30
Source File: ServerEndpointRegistration.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new {@link ServerEndpointRegistration} instance from an
 * {@code javax.websocket.Endpoint} class.
 * @param path the endpoint path
 * @param endpointClass the endpoint class
 */
public ServerEndpointRegistration(String path, Class<? extends Endpoint> endpointClass) {
	Assert.hasText(path, "Path must not be empty");
	Assert.notNull(endpointClass, "Endpoint Class must not be null");
	this.path = path;
	this.endpoint = null;
	this.endpointProvider = new BeanCreatingHandlerProvider<>(endpointClass);
}