org.springframework.web.reactive.socket.WebSocketHandler Java Examples
The following examples show how to use
org.springframework.web.reactive.socket.WebSocketHandler.
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: WebSocketMessagingHandlerConfiguration.java From jetlinks-community with Apache License 2.0 | 6 votes |
@Bean public HandlerMapping webSocketMessagingHandlerMapping(MessagingManager messagingManager, UserTokenManager userTokenManager, ReactiveAuthenticationManager authenticationManager) { WebSocketMessagingHandler messagingHandler=new WebSocketMessagingHandler( messagingManager, userTokenManager, authenticationManager ); final Map<String, WebSocketHandler> map = new HashMap<>(1); map.put("/messaging/**", messagingHandler); final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE); mapping.setUrlMap(map); return mapping; }
Example #2
Source File: WebSocketConfig.java From Learning-Spring-Boot-2.0-Second-Edition with MIT License | 6 votes |
@Bean HandlerMapping webSocketMapping(CommentService commentService) { Map<String, WebSocketHandler> urlMap = new HashMap<>(); urlMap.put("/topic/comments.new", commentService); Map<String, CorsConfiguration> corsConfigurationMap = new HashMap<>(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("http://localhost:8080"); corsConfigurationMap.put( "/topic/comments.new", corsConfiguration); SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(10); mapping.setUrlMap(urlMap); mapping.setCorsConfigurations(corsConfigurationMap); return mapping; }
Example #3
Source File: StandardWebSocketClient.java From spring-analysis-note with MIT License | 6 votes |
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 #4
Source File: WebSocketPlugin.java From soul with Apache License 2.0 | 6 votes |
@NonNull @Override public Mono<Void> handle(@NonNull final WebSocketSession session) { // pass headers along so custom headers can be sent through return client.execute(url, this.headers, new WebSocketHandler() { @NonNull @Override public Mono<Void> handle(@NonNull final WebSocketSession webSocketSession) { // Use retain() for Reactor Netty Mono<Void> sessionSend = webSocketSession .send(session.receive().doOnNext(WebSocketMessage::retain)); Mono<Void> serverSessionSend = session.send( webSocketSession.receive().doOnNext(WebSocketMessage::retain)); return Mono.zip(sessionSend, serverSessionSend).then(); } @NonNull @Override public List<String> getSubProtocols() { return SoulWebSocketHandler.this.subProtocols; } }); }
Example #5
Source File: WebSocketIT.java From vertx-spring-boot with Apache License 2.0 | 6 votes |
@Bean public HandlerMapping handlerMapping() { Map<String, WebSocketHandler> map = new HashMap<>(); map.put("/echo", this::echoHandler); map.put("/sink", this::sinkHandler); map.put("/double-producer", this::doubleProducerHandler); map.put("/close", this::closeHandler); SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setUrlMap(map); mapping.setOrder(-1); CorsConfiguration cors = new CorsConfiguration(); cors.addAllowedOrigin("http://snowdrop.dev"); mapping.setCorsConfigurations(Collections.singletonMap("/sink", cors)); return mapping; }
Example #6
Source File: ReactorNettyRequestUpgradeStrategy.java From spring-analysis-note with MIT License | 6 votes |
@Override public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) { ServerHttpResponse response = exchange.getResponse(); HttpServerResponse reactorResponse = ((AbstractServerHttpResponse) response).getNativeResponse(); HandshakeInfo handshakeInfo = handshakeInfoFactory.get(); NettyDataBufferFactory bufferFactory = (NettyDataBufferFactory) response.bufferFactory(); return reactorResponse.sendWebsocket(subProtocol, this.maxFramePayloadLength, (in, out) -> { ReactorNettyWebSocketSession session = new ReactorNettyWebSocketSession( in, out, handshakeInfo, bufferFactory, this.maxFramePayloadLength); URI uri = exchange.getRequest().getURI(); return handler.handle(session).checkpoint(uri + " [ReactorNettyRequestUpgradeStrategy]"); }); }
Example #7
Source File: UndertowRequestUpgradeStrategy.java From java-technology-stack with MIT License | 6 votes |
@Override public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) { ServerHttpRequest request = exchange.getRequest(); Assert.isInstanceOf(AbstractServerHttpRequest.class, request); HttpServerExchange httpExchange = ((AbstractServerHttpRequest) request).getNativeRequest(); Set<String> protocols = (subProtocol != null ? Collections.singleton(subProtocol) : Collections.emptySet()); Hybi13Handshake handshake = new Hybi13Handshake(protocols, false); List<Handshake> handshakes = Collections.singletonList(handshake); HandshakeInfo handshakeInfo = handshakeInfoFactory.get(); DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory(); try { DefaultCallback callback = new DefaultCallback(handshakeInfo, handler, bufferFactory); new WebSocketProtocolHandshakeHandler(handshakes, callback).handleRequest(httpExchange); } catch (Exception ex) { return Mono.error(ex); } return Mono.empty(); }
Example #8
Source File: ReactorNettyRequestUpgradeStrategy.java From java-technology-stack with MIT License | 6 votes |
@Override public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) { ServerHttpResponse response = exchange.getResponse(); HttpServerResponse reactorResponse = ((AbstractServerHttpResponse) response).getNativeResponse(); HandshakeInfo handshakeInfo = handshakeInfoFactory.get(); NettyDataBufferFactory bufferFactory = (NettyDataBufferFactory) response.bufferFactory(); return reactorResponse.sendWebsocket(subProtocol, this.maxFramePayloadLength, (in, out) -> { ReactorNettyWebSocketSession session = new ReactorNettyWebSocketSession( in, out, handshakeInfo, bufferFactory, this.maxFramePayloadLength); return handler.handle(session); }); }
Example #9
Source File: ReactorNettyWebSocketClient.java From java-technology-stack with MIT License | 6 votes |
@Override public Mono<Void> execute(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) { return getHttpClient() .headers(nettyHeaders -> setNettyHeaders(requestHeaders, nettyHeaders)) .websocket(StringUtils.collectionToCommaDelimitedString(handler.getSubProtocols())) .uri(url.toString()) .handle((inbound, outbound) -> { HttpHeaders responseHeaders = toHttpHeaders(inbound); String protocol = responseHeaders.getFirst("Sec-WebSocket-Protocol"); HandshakeInfo info = new HandshakeInfo(url, responseHeaders, Mono.empty(), protocol); NettyDataBufferFactory factory = new NettyDataBufferFactory(outbound.alloc()); WebSocketSession session = new ReactorNettyWebSocketSession(inbound, outbound, info, factory); if (logger.isDebugEnabled()) { logger.debug("Started session '" + session.getId() + "' for " + url); } return handler.handle(session); }) .doOnRequest(n -> { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + url); } }) .next(); }
Example #10
Source File: UndertowRequestUpgradeStrategy.java From spring-analysis-note with MIT License | 6 votes |
@Override public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) { ServerHttpRequest request = exchange.getRequest(); Assert.isInstanceOf(AbstractServerHttpRequest.class, request); HttpServerExchange httpExchange = ((AbstractServerHttpRequest) request).getNativeRequest(); Set<String> protocols = (subProtocol != null ? Collections.singleton(subProtocol) : Collections.emptySet()); Hybi13Handshake handshake = new Hybi13Handshake(protocols, false); List<Handshake> handshakes = Collections.singletonList(handshake); HandshakeInfo handshakeInfo = handshakeInfoFactory.get(); DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory(); try { DefaultCallback callback = new DefaultCallback(handshakeInfo, handler, bufferFactory); new WebSocketProtocolHandshakeHandler(handshakes, callback).handleRequest(httpExchange); } catch (Exception ex) { return Mono.error(ex); } return Mono.empty(); }
Example #11
Source File: StandardWebSocketClient.java From java-technology-stack with MIT License | 6 votes |
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 #12
Source File: WebsocketRoutingFilter.java From spring-cloud-gateway with Apache License 2.0 | 6 votes |
@Override public Mono<Void> handle(WebSocketSession session) { // pass headers along so custom headers can be sent through return client.execute(url, this.headers, new WebSocketHandler() { @Override public Mono<Void> handle(WebSocketSession proxySession) { // Use retain() for Reactor Netty Mono<Void> proxySessionSend = proxySession .send(session.receive().doOnNext(WebSocketMessage::retain)); // .log("proxySessionSend", Level.FINE); Mono<Void> serverSessionSend = session.send( proxySession.receive().doOnNext(WebSocketMessage::retain)); // .log("sessionSend", Level.FINE); return Mono.zip(proxySessionSend, serverSessionSend).then(); } /** * Copy subProtocols so they are available downstream. * @return */ @Override public List<String> getSubProtocols() { return ProxyWebSocketHandler.this.subProtocols; } }); }
Example #13
Source File: HandshakeWebSocketServiceTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void sessionAttributePredicate() { MockWebSession session = new MockWebSession(); session.getAttributes().put("a1", "v1"); session.getAttributes().put("a2", "v2"); session.getAttributes().put("a3", "v3"); session.getAttributes().put("a4", "v4"); session.getAttributes().put("a5", "v5"); MockServerHttpRequest request = initHandshakeRequest(); MockServerWebExchange exchange = MockServerWebExchange.builder(request).session(session).build(); TestRequestUpgradeStrategy upgradeStrategy = new TestRequestUpgradeStrategy(); HandshakeWebSocketService service = new HandshakeWebSocketService(upgradeStrategy); service.setSessionAttributePredicate(name -> Arrays.asList("a1", "a3", "a5").contains(name)); service.handleRequest(exchange, mock(WebSocketHandler.class)).block(); HandshakeInfo info = upgradeStrategy.handshakeInfo; assertNotNull(info); Map<String, Object> attributes = info.getAttributes(); assertEquals(3, attributes.size()); assertThat(attributes, Matchers.hasEntry("a1", "v1")); assertThat(attributes, Matchers.hasEntry("a3", "v3")); assertThat(attributes, Matchers.hasEntry("a5", "v5")); }
Example #14
Source File: ServiceInstanceLogStreamAutoConfiguration.java From spring-cloud-app-broker with Apache License 2.0 | 5 votes |
@Bean public HandlerMapping logsHandlerMapping(StreamingLogWebSocketHandler webSocketHandler) { Map<String, WebSocketHandler> map = new HashMap<>(); map.put("/logs/**/stream", webSocketHandler); SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping(); handlerMapping.setOrder(1); handlerMapping.setUrlMap(map); return handlerMapping; }
Example #15
Source File: WebSocketConfiguration.java From reactor-workshop with GNU General Public License v3.0 | 5 votes |
@Bean public HandlerMapping handlerMapping() { Map<String, WebSocketHandler> map = Map.of( "/echo", new EchoHandler(), "/time", new TimeHandler() ); SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setUrlMap(map); mapping.setOrder(-1); return mapping; }
Example #16
Source File: VertxRequestUpgradeStrategy.java From vertx-spring-boot with Apache License 2.0 | 5 votes |
@Override public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) { LOGGER.debug("Upgrading request to web socket"); ServerHttpRequest request = exchange.getRequest(); HttpServerRequest vertxRequest = ((AbstractServerHttpRequest) request).getNativeRequest(); ServerWebSocket webSocket = vertxRequest.upgrade(); VertxWebSocketSession session = new VertxWebSocketSession(webSocket, handshakeInfoFactory.get(), bufferConverter); return handler.handle(session); }
Example #17
Source File: SpringWebFluxDemoApplication.java From Spring-5.0-Projects with MIT License | 5 votes |
@Bean public HandlerMapping webSockertHandlerMapping() { Map<String, WebSocketHandler> map = new HashMap<>(); map.put("/student", studentWebSocketHandler); SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setUrlMap(map); return mapping; }
Example #18
Source File: WebSocketConfiguration.java From soul with Apache License 2.0 | 5 votes |
/** * Web socket mapping handler mapping. * * @param echoHandler the echo handler * @return the handler mapping */ @Bean public HandlerMapping webSocketMapping(final EchoHandler echoHandler) { final Map<String, WebSocketHandler> map = new HashMap<>(1); map.put("/echo", echoHandler); final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE); mapping.setUrlMap(map); return mapping; }
Example #19
Source File: ReactiveWebSocketConfig.java From spring-redis-websocket with Apache License 2.0 | 5 votes |
@Bean public HandlerMapping webSocketHandlerMapping(ChatWebSocketHandler webSocketHandler) { Map<String, WebSocketHandler> map = new HashMap<>(); map.put(WEBSOCKET_MESSAGE_MAPPING, webSocketHandler); SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping(); handlerMapping.setCorsConfigurations(Collections.singletonMap("*", new CorsConfiguration().applyPermitDefaultValues())); handlerMapping.setOrder(1); handlerMapping.setUrlMap(map); return handlerMapping; }
Example #20
Source File: VertxWebSocketClient.java From vertx-spring-boot with Apache License 2.0 | 5 votes |
private void connect(URI uri, VertxHttpHeaders headers, WebSocketHandler handler, MonoSink<Void> callback) { HttpClient client = vertx.createHttpClient(clientOptions); client.websocket(uri.getPort(), uri.getHost(), uri.getPath(), headers, socket -> handler.handle(initSession(uri, socket)) .doOnSuccess(callback::success) .doOnError(callback::error) .doFinally(ignore -> client.close()) .subscribe(), callback::error ); }
Example #21
Source File: HandshakeWebSocketService.java From java-technology-stack with MIT License | 5 votes |
@Override public Mono<Void> handleRequest(ServerWebExchange exchange, WebSocketHandler handler) { ServerHttpRequest request = exchange.getRequest(); HttpMethod method = request.getMethod(); HttpHeaders headers = request.getHeaders(); if (HttpMethod.GET != method) { return Mono.error(new MethodNotAllowedException( request.getMethodValue(), Collections.singleton(HttpMethod.GET))); } if (!"WebSocket".equalsIgnoreCase(headers.getUpgrade())) { return handleBadRequest(exchange, "Invalid 'Upgrade' header: " + headers); } List<String> connectionValue = headers.getConnection(); if (!connectionValue.contains("Upgrade") && !connectionValue.contains("upgrade")) { return handleBadRequest(exchange, "Invalid 'Connection' header: " + headers); } String key = headers.getFirst(SEC_WEBSOCKET_KEY); if (key == null) { return handleBadRequest(exchange, "Missing \"Sec-WebSocket-Key\" header"); } String protocol = selectProtocol(headers, handler); return initAttributes(exchange).flatMap(attributes -> this.upgradeStrategy.upgrade(exchange, handler, protocol, () -> createHandshakeInfo(exchange, request, protocol, attributes)) ); }
Example #22
Source File: ServiceInstanceLogStreamingTest.java From spring-cloud-app-broker with Apache License 2.0 | 5 votes |
private WebSocketHandler getWebSocketHandler() { return session -> session .receive() .doOnNext(message -> { DataBuffer buffer = message.getPayload(); try { actualEnvelope.set(Envelope.ADAPTER.decode( buffer.asInputStream())); } catch (IOException e) { throw new RuntimeException(e); } }) .then(); }
Example #23
Source File: JettyRequestUpgradeStrategy.java From java-technology-stack with MIT License | 5 votes |
@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 factory = response.bufferFactory(); JettyWebSocketHandlerAdapter adapter = new JettyWebSocketHandlerAdapter( handler, session -> new JettyWebSocketSession(session, handshakeInfo, factory)); startLazily(servletRequest); Assert.state(this.factory != null, "No WebSocketServerFactory available"); boolean isUpgrade = this.factory.isUpgradeRequest(servletRequest, servletResponse); Assert.isTrue(isUpgrade, "Not a WebSocket handshake"); try { adapterHolder.set(new WebSocketHandlerContainer(adapter, subProtocol)); this.factory.acceptWebSocket(servletRequest, servletResponse); } catch (IOException ex) { return Mono.error(ex); } finally { adapterHolder.remove(); } return Mono.empty(); }
Example #24
Source File: ReactiveWebSocketConfiguration.java From tutorials with MIT License | 5 votes |
@Bean public HandlerMapping webSocketHandlerMapping() { Map<String, WebSocketHandler> map = new HashMap<>(); map.put("/event-emitter", webSocketHandler); SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping(); handlerMapping.setOrder(1); handlerMapping.setUrlMap(map); return handlerMapping; }
Example #25
Source File: WebSocketIntegrationTests.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
@Bean public HandlerMapping handlerMapping() { Map<String, WebSocketHandler> map = new HashMap<>(); map.put("/echo", new EchoWebSocketHandler()); map.put("/echoForHttp", new EchoWebSocketHandler()); map.put("/sub-protocol", new SubProtocolWebSocketHandler()); map.put("/custom-header", new CustomHeaderHandler()); map.put("/close", new SessionClosingHandler()); SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setUrlMap(map); return mapping; }
Example #26
Source File: WebSocketConfig.java From Learning-Spring-Boot-2.0-Second-Edition with MIT License | 5 votes |
@Bean HandlerMapping webSocketMapping(CommentService commentService, InboundChatService inboundChatService, OutboundChatService outboundChatService) { Map<String, WebSocketHandler> urlMap = new HashMap<>(); urlMap.put("/topic/comments.new", commentService); urlMap.put("/app/chatMessage.new", inboundChatService); urlMap.put("/topic/chatMessage.new", outboundChatService); Map<String, CorsConfiguration> corsConfigurationMap = new HashMap<>(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("http://localhost:8080"); corsConfigurationMap.put( "/topic/comments.new", corsConfiguration); corsConfigurationMap.put( "/app/chatMessage.new", corsConfiguration); corsConfigurationMap.put( "/topic/chatMessage.new", corsConfiguration); SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(10); mapping.setUrlMap(urlMap); mapping.setCorsConfigurations(corsConfigurationMap); return mapping; }
Example #27
Source File: WebSocketConfig.java From Learning-Spring-Boot-2.0-Second-Edition with MIT License | 5 votes |
private static SimpleUrlHandlerMapping configureUrlMappings(CommentService commentService, InboundChatService inboundChatService, OutboundChatService outboundChatService) { Map<String, WebSocketHandler> urlMap = new HashMap<>(); urlMap.put("/topic/comments.new", commentService); urlMap.put("/app/chatMessage.new", inboundChatService); urlMap.put("/topic/chatMessage.new", outboundChatService); SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(10); mapping.setUrlMap(urlMap); return mapping; }
Example #28
Source File: StandardWebSocketHandlerAdapter.java From java-technology-stack with MIT License | 5 votes |
public StandardWebSocketHandlerAdapter(WebSocketHandler handler, Function<Session, StandardWebSocketSession> sessionFactory) { Assert.notNull(handler, "WebSocketHandler is required"); Assert.notNull(sessionFactory, "'sessionFactory' is required"); this.delegateHandler = handler; this.sessionFactory = sessionFactory; }
Example #29
Source File: StandardWebSocketHandlerAdapter.java From spring-analysis-note with MIT License | 5 votes |
public StandardWebSocketHandlerAdapter(WebSocketHandler handler, Function<Session, StandardWebSocketSession> sessionFactory) { Assert.notNull(handler, "WebSocketHandler is required"); Assert.notNull(sessionFactory, "'sessionFactory' is required"); this.delegateHandler = handler; this.sessionFactory = sessionFactory; }
Example #30
Source File: HandshakeWebSocketService.java From java-technology-stack with MIT License | 5 votes |
@Nullable private String selectProtocol(HttpHeaders headers, WebSocketHandler handler) { String protocolHeader = headers.getFirst(SEC_WEBSOCKET_PROTOCOL); if (protocolHeader != null) { List<String> supportedProtocols = handler.getSubProtocols(); for (String protocol : StringUtils.commaDelimitedListToStringArray(protocolHeader)) { if (supportedProtocols.contains(protocol)) { return protocol; } } } return null; }