org.springframework.web.socket.WebSocketSession Java Examples
The following examples show how to use
org.springframework.web.socket.WebSocketSession.
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: NetworkHandlers.java From devicehive-java-server with Apache License 2.0 | 6 votes |
@HiveWebsocketAuth @PreAuthorize("isAuthenticated() and hasPermission(#networkId, 'GET_NETWORK')") public void processNetworkGet(Long networkId, JsonObject request, WebSocketSession session) { logger.debug("Network get requested."); if (networkId == null) { logger.error(Messages.NETWORK_ID_REQUIRED); throw new HiveException(Messages.NETWORK_ID_REQUIRED, BAD_REQUEST.getStatusCode()); } NetworkWithUsersAndDevicesVO existing = networkService.getWithDevices(networkId); if (existing == null) { logger.error(String.format(Messages.NETWORK_NOT_FOUND, networkId)); throw new HiveException(String.format(Messages.NETWORK_NOT_FOUND, networkId), NOT_FOUND.getStatusCode()); } WebSocketResponse response = new WebSocketResponse(); response.addValue(NETWORK, existing, NETWORK_PUBLISHED); webSocketClientHandler.sendMessage(request, response, session); }
Example #2
Source File: SocketHandler.java From SpringBootBucket with MIT License | 6 votes |
@Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { logger.info("handleTextMessage start"); // 将消息进行转化,因为是消息是json数据,可能里面包含了发送给某个人的信息,所以需要用json相关的工具类处理之后再封装成TextMessage, // 我这儿并没有做处理,消息的封装格式一般有{from:xxxx,to:xxxxx,msg:xxxxx},来自哪里,发送给谁,什么消息等等 String msg = message.getPayload(); logger.info("msg = " + msg); WsParam<String> wsParam = JacksonUtil.json2Bean(msg, new TypeReference<WsParam<String>>(){}); if ("list".equals(wsParam.getMethod())) { logger.info("call list method..."); WsResponse<String> response = new WsResponse<>(); response.setResult("hello list"); sendMessageToUser(session, new TextMessage(JacksonUtil.bean2Json(response))); } logger.info("handleTextMessage end"); // 给所有用户群发消息 //sendMessagesToUsers(msg); // 给指定用户群发消息 //sendMessageToUser(userId, msg); }
Example #3
Source File: WebSocketProxyServerHandler.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) { log.debug("afterConnectionClosed(session={},status={})", session, status); try { session.close(status); WebSocketRoutedSession webSocketRoutedSession = getRoutedSession(session); if (webSocketRoutedSession != null) { webSocketRoutedSession.close(status); } routedSessions.remove(session.getId()); } catch (NullPointerException | IOException e) { log.debug("Error closing WebSocket connection: {}", e.getMessage(), e); } }
Example #4
Source File: WebSocketStompClient.java From java-technology-stack with MIT License | 6 votes |
@Override public ListenableFuture<Void> send(Message<byte[]> message) { updateLastWriteTime(); SettableListenableFuture<Void> future = new SettableListenableFuture<>(); try { WebSocketSession session = this.session; Assert.state(session != null, "No WebSocketSession available"); session.sendMessage(this.codec.encode(message, session.getClass())); future.set(null); } catch (Throwable ex) { future.setException(ex); } finally { updateLastWriteTime(); } return future; }
Example #5
Source File: RestTemplateXhrTransportTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void connectFailure() throws Exception { final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR); RestOperations restTemplate = mock(RestOperations.class); given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected); final CountDownLatch latch = new CountDownLatch(1); connect(restTemplate).addCallback( new ListenableFutureCallback<WebSocketSession>() { @Override public void onSuccess(WebSocketSession result) { } @Override public void onFailure(Throwable ex) { if (ex == expected) { latch.countDown(); } } } ); verifyNoMoreInteractions(this.webSocketHandler); }
Example #6
Source File: UserHandlers.java From devicehive-java-server with Apache License 2.0 | 6 votes |
@HiveWebsocketAuth @PreAuthorize("isAuthenticated() and hasPermission(null, 'MANAGE_USER')") public void processUserInsert(JsonObject request, WebSocketSession session) { UserUpdate userToCreate = gson.fromJson(request.get(USER), UserUpdate.class); if (userToCreate == null) { logger.error(Messages.USER_REQUIRED); throw new HiveException(Messages.USER_REQUIRED, BAD_REQUEST.getStatusCode()); } hiveValidator.validate(userToCreate); String password = userToCreate.getPassword().orElse(null); UserVO created = userService.createUser(userToCreate.convertTo(), password); WebSocketResponse response = new WebSocketResponse(); response.addValue(USER, created, USER_SUBMITTED); clientHandler.sendMessage(request, response, session); }
Example #7
Source File: WebSocketServerSockJsSession.java From spring-analysis-note with MIT License | 6 votes |
public void handleMessage(TextMessage message, WebSocketSession wsSession) throws Exception { String payload = message.getPayload(); if (!StringUtils.hasLength(payload)) { return; } String[] messages; try { messages = getSockJsServiceConfig().getMessageCodec().decode(payload); } catch (Throwable ex) { logger.error("Broken data received. Terminating WebSocket connection abruptly", ex); tryCloseWithSockJsTransportError(ex, CloseStatus.BAD_DATA); return; } if (messages != null) { delegateMessages(messages); } }
Example #8
Source File: UserHandlers.java From devicehive-java-server with Apache License 2.0 | 6 votes |
@HiveWebsocketAuth @PreAuthorize("isAuthenticated() and hasPermission(null, 'MANAGE_DEVICE_TYPE')") public void processUserAssignDeviceType(JsonObject request, WebSocketSession session) { Long userId = gson.fromJson(request.get(USER_ID), Long.class); if (userId == null) { logger.error(Messages.USER_ID_REQUIRED); throw new HiveException(Messages.USER_ID_REQUIRED, BAD_REQUEST.getStatusCode()); } Long deviceTypeId = gson.fromJson(request.get(DEVICE_TYPE_ID), Long.class); if (deviceTypeId == null) { logger.error(Messages.DEVICE_TYPE_ID_REQUIRED); throw new HiveException(Messages.DEVICE_TYPE_ID_REQUIRED, BAD_REQUEST.getStatusCode()); } userService.assignDeviceType(userId, deviceTypeId); clientHandler.sendMessage(request, new WebSocketResponse(), session); }
Example #9
Source File: MyWebSocketHandler.java From albert with MIT License | 6 votes |
/** * 建立连接后,把登录用户的id写入WebSocketSession */ public void afterConnectionEstablished(WebSocketSession session) throws Exception { Integer uid = (Integer) session.getAttributes().get("uid"); User u=userService.getUserById(uid); if (userSocketSessionMap.get(uid) == null) { userSocketSessionMap.put(uid, session); Message msg = new Message(); msg.setFrom(0);//0表示上线消息 msg.setText(u.getUsername()); msg.setUserId(u.getId()); msg.setAvatar(u.getAvatar()); msg.setEmail(u.getEmail()); this.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg))); } }
Example #10
Source File: ServiceFileTailWatcher.java From Jpom with MIT License | 6 votes |
/** * 添加文件监听 * * @param file 文件 * @param session 会话 * @throws IOException 异常 */ public static void addWatcher(File file, WebSocketSession session) throws IOException { if (!file.exists() || file.isDirectory()) { throw new IOException("文件不存在或者是目录:" + file.getPath()); } ServiceFileTailWatcher<WebSocketSession> agentFileTailWatcher = CONCURRENT_HASH_MAP.computeIfAbsent(file, s -> { try { return new ServiceFileTailWatcher<>(file); } catch (Exception e) { DefaultSystemLog.getLog().error("创建文件监听失败", e); return null; } }); if (agentFileTailWatcher == null) { throw new IOException("加载文件失败:" + file.getPath()); } agentFileTailWatcher.add(session, FileUtil.getName(file)); agentFileTailWatcher.tailWatcherRun.start(); }
Example #11
Source File: GameTest.java From computoser with GNU Affero General Public License v3.0 | 6 votes |
@Test public void gameStartedTest() throws Exception { GameHandler handler = new GameHandler(); handler.setPieceService(pieceServiceMock); initializeGame(handler); Game game = handler.getGames().values().iterator().next(); GameMessage startMsg = new GameMessage(); startMsg.setAction(GameAction.START); startMsg.setGameId(game.getId()); WebSocketSession session = getSession("1"); handler.handleMessage(session, getTextMessage(startMsg)); GameEvent responseNewPiece = mapper.readValue(messages.get("1").removeLast().getPayload().toString(), GameEvent.class); GameEvent responseGameStarted = mapper.readValue(messages.get("1").removeLast().getPayload().toString(), GameEvent.class); Assert.assertEquals(GameEventType.GAME_STARTED, responseGameStarted.getType()); Assert.assertEquals(GameEventType.NEW_PIECE, responseNewPiece.getType()); Assert.assertEquals(piece.getId(), responseNewPiece.getPieceId()); }
Example #12
Source File: WsContent.java From proxyee-down with Apache License 2.0 | 6 votes |
public void sendMsg(WsForm wsForm) { try { if (wsForm == null) { return; } TextMessage message = new TextMessage(JSON.toJSONString(wsForm)); for (Entry<String, WebSocketSession> entry : wcContent.entrySet()) { WebSocketSession session = entry.getValue(); if (session.isOpen()) { synchronized (session) { session.sendMessage(message); } } } } catch (Exception e) { LOGGER.warn("sendMsg", e); } }
Example #13
Source File: RedisTextWebSocketHandler.java From sc-generator with Apache License 2.0 | 6 votes |
public void close(WebSocketSession webSocketSession) { Replicator replicator = replicatorMap.remove(webSocketSession.getId()); if (replicator != null) { try { replicator.close(); webSocketSession.close(); } catch (IOException e) { logger.warn(e.getMessage()); } } RxClient rxClient = rxClientMap.get(webSocketSession.getId()); if (rxClient != null) { rxClient.shutdown(); } observableMap.remove(webSocketSession.getId()); authMap.remove(webSocketSession.getId()); }
Example #14
Source File: TerminalHandler.java From JobX with Apache License 2.0 | 6 votes |
@Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { super.handleTextMessage(session, message); try { getClient(session, null); if (this.terminalClient != null) { if (!terminalClient.isClosed()) { terminalClient.write(message.getPayload()); } else { session.close(); } } } catch (Exception e) { session.sendMessage(new TextMessage("Sorry! jobx Terminal was closed, please try again. ")); terminalClient.disconnect(); session.close(); } }
Example #15
Source File: ExceptionWebSocketHandlerDecorator.java From spring-analysis-note with MIT License | 5 votes |
@Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { try { getDelegate().afterConnectionClosed(session, closeStatus); } catch (Throwable ex) { if (logger.isWarnEnabled()) { logger.warn("Unhandled exception after connection closed for " + this, ex); } } }
Example #16
Source File: WebSocketHandlerTest.java From data-highway with Apache License 2.0 | 5 votes |
@Override public void afterConnectionEstablished(WebSocketSession session) throws java.io.IOException { ObjectMapper mapper = new ObjectMapper(); String event = mapper.writeValueAsString(TestMessage.getTestMessage()); int half = event.length() / 2; String part1 = event.substring(0, half); String part2 = event.substring(half); session.sendMessage(new BinaryMessage(part1.getBytes(UTF_8), false)); session.sendMessage(new BinaryMessage(part2.getBytes(UTF_8), true)); }
Example #17
Source File: ExceptionWebSocketHandlerDecorator.java From spring-analysis-note with MIT License | 5 votes |
@Override public void afterConnectionEstablished(WebSocketSession session) { try { getDelegate().afterConnectionEstablished(session); } catch (Throwable ex) { tryCloseWithError(session, ex, logger); } }
Example #18
Source File: WebSocketRoutedSession.java From api-layer with Eclipse Public License 2.0 | 5 votes |
private WebSocketProxyError webSocketProxyException(String targetUrl, Exception cause, WebSocketSession webSocketServerSession, boolean logError) { String message = String.format("Error opening session to WebSocket service at %s: %s", targetUrl, cause.getMessage()); if (logError) { log.debug(message); } return new WebSocketProxyError(message, cause, webSocketServerSession); }
Example #19
Source File: LoggingWebSocketHandlerDecorator.java From spring-analysis-note with MIT License | 5 votes |
@Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { if (logger.isDebugEnabled()) { logger.debug(session + " closed with " + closeStatus); } super.afterConnectionClosed(session, closeStatus); }
Example #20
Source File: AbstractSockJsIntegrationTests.java From spring-analysis-note with MIT License | 5 votes |
@Test(timeout = 5000) public void fallbackAfterConnectTimeout() throws Exception { TestClientHandler clientHandler = new TestClientHandler(); this.testFilter.sleepDelayMap.put("/xhr_streaming", 10000L); this.testFilter.sendErrorMap.put("/xhr_streaming", 503); initSockJsClient(createXhrTransport()); this.sockJsClient.setConnectTimeoutScheduler(this.wac.getBean(ThreadPoolTaskScheduler.class)); WebSocketSession clientSession = sockJsClient.doHandshake(clientHandler, this.baseUrl + "/echo").get(); assertEquals("Fallback didn't occur", XhrClientSockJsSession.class, clientSession.getClass()); TextMessage message = new TextMessage("message1"); clientSession.sendMessage(message); clientHandler.awaitMessage(message, 5000); clientSession.close(); }
Example #21
Source File: ExceptionWebSocketHandlerDecorator.java From java-technology-stack with MIT License | 5 votes |
@Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { try { getDelegate().afterConnectionClosed(session, closeStatus); } catch (Throwable ex) { if (logger.isWarnEnabled()) { logger.warn("Unhandled exception after connection closed for " + this, ex); } } }
Example #22
Source File: TerminalService.java From opencron with Apache License 2.0 | 5 votes |
public static boolean isOpened(Terminal terminal) { for (Map.Entry<WebSocketSession, TerminalClient> entry : terminalSession.entrySet()) { if (entry.getValue().getTerminal().equals(terminal)) { return true; } } return false; }
Example #23
Source File: AbstractWebSocketClient.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public final ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, WebSocketHttpHeaders headers, URI uri) { Assert.notNull(webSocketHandler, "webSocketHandler must not be null"); assertUri(uri); if (logger.isDebugEnabled()) { logger.debug("Connecting to " + uri); } HttpHeaders headersToUse = new HttpHeaders(); if (headers != null) { for (String header : headers.keySet()) { if (!specialHeaders.contains(header.toLowerCase())) { headersToUse.put(header, headers.get(header)); } } } List<String> subProtocols = ((headers != null) && (headers.getSecWebSocketProtocol() != null)) ? headers.getSecWebSocketProtocol() : Collections.<String>emptyList(); List<WebSocketExtension> extensions = ((headers != null) && (headers.getSecWebSocketExtensions() != null)) ? headers.getSecWebSocketExtensions() : Collections.<WebSocketExtension>emptyList(); return doHandshakeInternal(webSocketHandler, headersToUse, uri, subProtocols, extensions, Collections.<String, Object>emptyMap()); }
Example #24
Source File: WebSocketMessageBrokerConfigurationSupportTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void webSocketHandlerDecorator() throws Exception { ApplicationContext config = createConfig(WebSocketHandlerDecoratorConfig.class); WebSocketHandler handler = config.getBean(SubProtocolWebSocketHandler.class); assertNotNull(handler); SimpleUrlHandlerMapping mapping = (SimpleUrlHandlerMapping) config.getBean("stompWebSocketHandlerMapping"); WebSocketHttpRequestHandler httpHandler = (WebSocketHttpRequestHandler) mapping.getHandlerMap().get("/test"); handler = httpHandler.getWebSocketHandler(); WebSocketSession session = new TestWebSocketSession("id"); handler.afterConnectionEstablished(session); assertEquals(true, session.getAttributes().get("decorated")); }
Example #25
Source File: JettyWebSocketClient.java From java-technology-stack with MIT License | 5 votes |
@Override public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, String uriTemplate, Object... uriVars) { UriComponents uriComponents = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode(); return doHandshake(webSocketHandler, null, uriComponents.toUri()); }
Example #26
Source File: RsvpsWebSocketHandler.java From -Data-Stream-Development-with-Apache-Spark-Kafka-and-Spring-Boot with MIT License | 5 votes |
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) { logger.log(Level.INFO, "New RSVP:\n {0}", message.getPayload()); rsvpsKafkaProducer.sendRsvpMessage(message); }
Example #27
Source File: StompSubProtocolHandler.java From spring-analysis-note with MIT License | 5 votes |
private void handleError(WebSocketSession session, Throwable ex, @Nullable Message<byte[]> clientMessage) { if (getErrorHandler() == null) { sendErrorMessage(session, ex); return; } Message<byte[]> message = getErrorHandler().handleClientMessageProcessingError(clientMessage, ex); if (message == null) { return; } StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); Assert.state(accessor != null, "No StompHeaderAccessor"); sendToClient(session, accessor, message.getPayload()); }
Example #28
Source File: StompSubProtocolHandler.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Invoked when no * {@link #setErrorHandler(StompSubProtocolErrorHandler) errorHandler} * is configured to send an ERROR frame to the client. * @deprecated as of Spring 4.2, in favor of * {@link #setErrorHandler(StompSubProtocolErrorHandler) configuring} * a {@code StompSubProtocolErrorHandler} */ @Deprecated protected void sendErrorMessage(WebSocketSession session, Throwable error) { StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR); headerAccessor.setMessage(error.getMessage()); byte[] bytes = this.stompEncoder.encode(headerAccessor.getMessageHeaders(), EMPTY_PAYLOAD); try { session.sendMessage(new TextMessage(bytes)); } catch (Throwable ex) { // Could be part of normal workflow (e.g. browser tab closed) logger.debug("Failed to send STOMP ERROR to client", ex); } }
Example #29
Source File: WebSocketSessionDecorator.java From java-technology-stack with MIT License | 5 votes |
public static WebSocketSession unwrap(WebSocketSession session) { if (session instanceof WebSocketSessionDecorator) { return ((WebSocketSessionDecorator) session).getLastSession(); } else { return session; } }
Example #30
Source File: ProxyWebSocketHandler.java From spring-cloud-netflix-zuul-websocket with Apache License 2.0 | 5 votes |
private void unsubscribeFromProxiedTarget(WebSocketSession session, WebSocketMessageAccessor accessor) { ProxyWebSocketConnectionManager manager = managers.get(session); if (manager != null) { manager.unsubscribe(accessor.getDestination()); } }