org.springframework.web.socket.WebSocketMessage Java Examples
The following examples show how to use
org.springframework.web.socket.WebSocketMessage.
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: ConcurrentWebSocketSessionDecorator.java From spring-analysis-note with MIT License | 6 votes |
@Override public void sendMessage(WebSocketMessage<?> message) throws IOException { if (shouldNotSend()) { return; } this.buffer.add(message); this.bufferSize.addAndGet(message.getPayloadLength()); do { if (!tryFlushMessageBuffer()) { if (logger.isTraceEnabled()) { logger.trace(String.format("Another send already in progress: " + "session id '%s':, \"in-progress\" send time %d (ms), buffer size %d bytes", getId(), getTimeSinceSendStarted(), getBufferSize())); } checkSessionLimits(); break; } } while (!this.buffer.isEmpty() && !shouldNotSend()); }
Example #2
Source File: ConcurrentWebSocketSessionDecorator.java From java-technology-stack with MIT License | 6 votes |
@Override public void sendMessage(WebSocketMessage<?> message) throws IOException { if (shouldNotSend()) { return; } this.buffer.add(message); this.bufferSize.addAndGet(message.getPayloadLength()); do { if (!tryFlushMessageBuffer()) { if (logger.isTraceEnabled()) { logger.trace(String.format("Another send already in progress: " + "session id '%s':, \"in-progress\" send time %d (ms), buffer size %d bytes", getId(), getTimeSinceSendStarted(), getBufferSize())); } checkSessionLimits(); break; } } while (!this.buffer.isEmpty() && !shouldNotSend()); }
Example #3
Source File: ConcurrentWebSocketSessionDecorator.java From java-technology-stack with MIT License | 6 votes |
private boolean tryFlushMessageBuffer() throws IOException { if (this.flushLock.tryLock()) { try { while (true) { WebSocketMessage<?> message = this.buffer.poll(); if (message == null || shouldNotSend()) { break; } this.bufferSize.addAndGet(-message.getPayloadLength()); this.sendStartTime = System.currentTimeMillis(); getDelegate().sendMessage(message); this.sendStartTime = 0; } } finally { this.sendStartTime = 0; this.flushLock.unlock(); } return true; } return false; }
Example #4
Source File: StompSubProtocolHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void handleMessageToClientWithUserDestination() { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE); headers.setMessageId("mess0"); headers.setSubscriptionId("sub0"); headers.setDestination("/queue/foo-user123"); headers.setNativeHeader(StompHeaderAccessor.ORIGINAL_DESTINATION, "/user/queue/foo"); Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(1, this.session.getSentMessages().size()); WebSocketMessage<?> textMessage = this.session.getSentMessages().get(0); assertTrue(((String) textMessage.getPayload()).contains("destination:/user/queue/foo\n")); assertFalse(((String) textMessage.getPayload()).contains(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION)); }
Example #5
Source File: AbstractWebSocketSession.java From java-technology-stack with MIT License | 6 votes |
@Override public final void sendMessage(WebSocketMessage<?> message) throws IOException { checkNativeSessionInitialized(); if (logger.isTraceEnabled()) { logger.trace("Sending " + message + ", " + this); } if (message instanceof TextMessage) { sendTextMessage((TextMessage) message); } else if (message instanceof BinaryMessage) { sendBinaryMessage((BinaryMessage) message); } else if (message instanceof PingMessage) { sendPingMessage((PingMessage) message); } else if (message instanceof PongMessage) { sendPongMessage((PongMessage) message); } else { throw new IllegalStateException("Unexpected WebSocketMessage type: " + message); } }
Example #6
Source File: AbstractClientSockJsSession.java From java-technology-stack with MIT License | 6 votes |
@Override public final void sendMessage(WebSocketMessage<?> message) throws IOException { if (!(message instanceof TextMessage)) { throw new IllegalArgumentException(this + " supports text messages only."); } if (this.state != State.OPEN) { throw new IllegalStateException(this + " is not open: current state " + this.state); } String payload = ((TextMessage) message).getPayload(); payload = getMessageCodec().encode(payload); payload = payload.substring(1); // the client-side doesn't need message framing (letter "a") TextMessage messageToSend = new TextMessage(payload); if (logger.isTraceEnabled()) { logger.trace("Sending message " + messageToSend + " in " + this); } sendInternal(messageToSend); }
Example #7
Source File: NodeMgmtWebSocketHandler.java From java-trader with Apache License 2.0 | 6 votes |
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { NodeSession nodeSession = (NodeSession)session.getAttributes().get(NodeSession.ATTR_SESSION); if ( nodeSession==null ){ nodeSession = nodeMgmtService.onSessionConnected(session); } String text = null; Object payload = message.getPayload(); if ( payload instanceof byte[] ){ text = new String((byte[])payload, 0, message.getPayloadLength(), utf8); }else{ text = payload.toString(); } nodeSession.onMessage(text); }
Example #8
Source File: AbstractWebSocketHandler.java From spring-analysis-note with MIT License | 5 votes |
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { if (message instanceof TextMessage) { handleTextMessage(session, (TextMessage) message); } else if (message instanceof BinaryMessage) { handleBinaryMessage(session, (BinaryMessage) message); } else if (message instanceof PongMessage) { handlePongMessage(session, (PongMessage) message); } else { throw new IllegalStateException("Unexpected WebSocket message type: " + message); } }
Example #9
Source File: ServiceDiscovery.java From artemis with Apache License 2.0 | 5 votes |
public ServiceDiscovery(final ServiceRepository serviceRepository, final ArtemisClientConfig config) { Preconditions.checkArgument(serviceRepository != null, "ServiceRepository should not be null"); this.serviceRepository = serviceRepository; this.discoveryHttpClient = new ArtemisDiscoveryHttpClient(config); ttl = config.properties().getLongProperty(config.key("service-discovery.ttl"), 15 * 60 * 1000L, 60 * 1000, 24 * 60 * 60 * 1000); sessionContext = new WebSocketSessionContext(config) { @Override protected void afterConnectionEstablished(final WebSocketSession session) { subscribe(session); } @Override protected void handleMessage(final WebSocketSession session, final WebSocketMessage<?> message) { try { InstanceChange instanceChange = JacksonJsonSerializer.INSTANCE.deserialize((String) message.getPayload(), InstanceChange.class); onInstanceChange(instanceChange); } catch (final Throwable e) { logger.warn("convert message failed", e); } } }; sessionContext.start(); final DynamicScheduledThreadConfig dynamicScheduledThreadConfig = new DynamicScheduledThreadConfig(config.properties(), new RangePropertyConfig<Integer>(0, 0, 200), new RangePropertyConfig<Integer>(60 * 1000, 60 * 1000, 24 * 60 * 60 * 1000)); poller = new DynamicScheduledThread(config.key("service-discovery"), new Runnable() { @Override public void run() { try { reload(getReloadDiscoveryConfigs()); } catch (Throwable t) { logger.warn("reload services failed", t); } } }, dynamicScheduledThreadConfig); poller.setDaemon(true); poller.start(); }
Example #10
Source File: LoggingWebSocketHandlerDecorator.java From spring-analysis-note with MIT License | 5 votes |
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { if (logger.isTraceEnabled()) { logger.trace("Handling " + message + " in " + session); } super.handleMessage(session, message); }
Example #11
Source File: WebSocketStompClient.java From spring-analysis-note with MIT License | 5 votes |
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> webSocketMessage) { this.lastReadTime = (this.lastReadTime != -1 ? System.currentTimeMillis() : -1); List<Message<byte[]>> messages; try { messages = this.codec.decode(webSocketMessage); } catch (Throwable ex) { this.connectionHandler.handleFailure(ex); return; } for (Message<byte[]> message : messages) { this.connectionHandler.handleMessage(message); } }
Example #12
Source File: LoggingWebSocketHandlerDecorator.java From java-technology-stack with MIT License | 5 votes |
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { if (logger.isTraceEnabled()) { logger.trace("Handling " + message + " in " + session); } super.handleMessage(session, message); }
Example #13
Source File: WebSocketProxyServerHandlerTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void givenValidSession_whenTheMessageIsReceived_thenTheMessageIsPassedToTheSession() throws Exception { WebSocketSession establishedSession = mock(WebSocketSession.class); String validSessionId = "123"; when(establishedSession.getId()).thenReturn(validSessionId); WebSocketRoutedSession internallyStoredSession = mock(WebSocketRoutedSession.class); routedSessions.put(validSessionId, internallyStoredSession); WebSocketMessage<String> passedMessage = mock(WebSocketMessage.class); underTest.handleMessage(establishedSession, passedMessage); verify(internallyStoredSession).sendMessageToServer(passedMessage); }
Example #14
Source File: ExceptionWebSocketHandlerDecorator.java From java-technology-stack with MIT License | 5 votes |
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) { try { getDelegate().handleMessage(session, message); } catch (Throwable ex) { tryCloseWithError(session, ex, logger); } }
Example #15
Source File: WebSocketProxyServerHandler.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Override public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception { log.debug("handleMessage(session={},message={})", webSocketSession, webSocketMessage); WebSocketRoutedSession session = getRoutedSession(webSocketSession); if (session != null) { session.sendMessageToServer(webSocketMessage); } }
Example #16
Source File: SubProtocolWebSocketHandler.java From java-technology-stack with MIT License | 5 votes |
/** * Handle an inbound message from a WebSocket client. */ @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { WebSocketSessionHolder holder = this.sessions.get(session.getId()); if (holder != null) { session = holder.getSession(); } SubProtocolHandler protocolHandler = findProtocolHandler(session); protocolHandler.handleMessageFromClient(session, message, this.clientInboundChannel); if (holder != null) { holder.setHasHandledMessages(); } checkSessions(); }
Example #17
Source File: WebSocketStompClient.java From java-technology-stack with MIT License | 5 votes |
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> webSocketMessage) { this.lastReadTime = (this.lastReadTime != -1 ? System.currentTimeMillis() : -1); List<Message<byte[]>> messages; try { messages = this.codec.decode(webSocketMessage); } catch (Throwable ex) { this.connectionHandler.handleFailure(ex); return; } for (Message<byte[]> message : messages) { this.connectionHandler.handleMessage(message); } }
Example #18
Source File: InstanceRegistry.java From artemis with Apache License 2.0 | 5 votes |
protected void acceptHeartbeat(final WebSocketMessage<?> message) { try { final HeartbeatResponse response = JacksonJsonSerializer.INSTANCE.deserialize((String) message.getPayload(), HeartbeatResponse.class); final ResponseStatus status = response.getResponseStatus(); if (status == null) { _heartbeatStatus.addEvent("null"); } else { _heartbeatStatus.addEvent(status.getStatus()); } long heartbeatTime = System.currentTimeMillis() - _heartbeatAcceptStartTime; _heartbeatAcceptLatency.addValue(heartbeatTime); if (ResponseStatusUtil.isServiceDown(status)) { _sessionContext.markdown(); } if (ResponseStatusUtil.isFail(status)) { _logger.warn("heartbeat failed: " + status.getMessage()); } else if (ResponseStatusUtil.isPartialFail(status)) { _logger.info("heartbeat partial failed: " + status.getMessage()); } registerToServicesRegistry(response.getFailedInstances()); } catch (final Throwable e) { _logger.error("handle heartbeat message failed", e); } }
Example #19
Source File: WebSocketStompClient.java From java-technology-stack with MIT License | 5 votes |
public WebSocketMessage<?> encode(Message<byte[]> message, Class<? extends WebSocketSession> sessionType) { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); Assert.notNull(accessor, "No StompHeaderAccessor available"); byte[] payload = message.getPayload(); byte[] bytes = ENCODER.encode(accessor.getMessageHeaders(), payload); boolean useBinary = (payload.length > 0 && !(SockJsSession.class.isAssignableFrom(sessionType)) && MimeTypeUtils.APPLICATION_OCTET_STREAM.isCompatibleWith(accessor.getContentType())); return (useBinary ? new BinaryMessage(bytes) : new TextMessage(bytes)); }
Example #20
Source File: ConcurrentWebSocketSessionDecoratorTests.java From java-technology-stack with MIT License | 5 votes |
@Override public void sendMessage(WebSocketMessage<?> message) throws IOException { super.sendMessage(message); if (this.nextMessageLatch != null) { this.nextMessageLatch.get().countDown(); } block(); }
Example #21
Source File: StompSubProtocolHandlerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void handleMessageToClientWithConnectedFrame() { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECTED); Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(1, this.session.getSentMessages().size()); WebSocketMessage<?> textMessage = this.session.getSentMessages().get(0); assertEquals("CONNECTED\n" + "user-name:joe\n" + "\n" + "\u0000", textMessage.getPayload()); }
Example #22
Source File: StompSubProtocolHandlerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void handleMessageToClientWithDestinationUserNameProvider() { this.session.setPrincipal(new UniqueUser("joe")); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECTED); Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(1, this.session.getSentMessages().size()); WebSocketMessage<?> textMessage = this.session.getSentMessages().get(0); assertEquals("CONNECTED\n" + "user-name:joe\n" + "\n" + "\u0000", textMessage.getPayload()); }
Example #23
Source File: StompSubProtocolHandlerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void handleMessageToClientWithHeartbeatSuppressingSockJsHeartbeat() throws IOException { SockJsSession sockJsSession = Mockito.mock(SockJsSession.class); when(sockJsSession.getId()).thenReturn("s1"); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED); accessor.setHeartbeat(0, 10); Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders()); this.protocolHandler.handleMessageToClient(sockJsSession, message); verify(sockJsSession).getId(); verify(sockJsSession).getPrincipal(); verify(sockJsSession).disableHeartbeat(); verify(sockJsSession).sendMessage(any(WebSocketMessage.class)); verifyNoMoreInteractions(sockJsSession); sockJsSession = Mockito.mock(SockJsSession.class); when(sockJsSession.getId()).thenReturn("s1"); accessor = StompHeaderAccessor.create(StompCommand.CONNECTED); accessor.setHeartbeat(0, 0); message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders()); this.protocolHandler.handleMessageToClient(sockJsSession, message); verify(sockJsSession).getId(); verify(sockJsSession).getPrincipal(); verify(sockJsSession).sendMessage(any(WebSocketMessage.class)); verifyNoMoreInteractions(sockJsSession); }
Example #24
Source File: StompSubProtocolHandlerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void handleMessageToClientWithBinaryWebSocketMessage() { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE); headers.setMessageId("mess0"); headers.setSubscriptionId("sub0"); headers.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM); headers.setDestination("/queue/foo"); // Non-empty payload byte[] payload = new byte[1]; Message<byte[]> message = MessageBuilder.createMessage(payload, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(1, this.session.getSentMessages().size()); WebSocketMessage<?> webSocketMessage = this.session.getSentMessages().get(0); assertTrue(webSocketMessage instanceof BinaryMessage); // Empty payload payload = EMPTY_PAYLOAD; message = MessageBuilder.createMessage(payload, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(2, this.session.getSentMessages().size()); webSocketMessage = this.session.getSentMessages().get(1); assertTrue(webSocketMessage instanceof TextMessage); }
Example #25
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 #26
Source File: RsvpsKafkaProducer.java From -Data-Stream-Development-with-Apache-Spark-Kafka-and-Spring-Boot with MIT License | 5 votes |
public void sendRsvpMessage(WebSocketMessage<?> message) { source.output() .send(MessageBuilder.withPayload(message.getPayload()) .build(), SENDING_MESSAGE_TIMEOUT_MS); }
Example #27
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 #28
Source File: RsvpsKafkaProducer.java From -Data-Stream-Development-with-Apache-Spark-Kafka-and-Spring-Boot with MIT License | 5 votes |
public void sendRsvpMessage(WebSocketMessage<?> message) { source.output() .send(MessageBuilder.withPayload(message.getPayload()) .build(), SENDING_MESSAGE_TIMEOUT_MS); }
Example #29
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()); hmlHandler.handleNewRsvp((String) message.getPayload()); }
Example #30
Source File: WebSocketPlugin.java From TrackRay with GNU General Public License v3.0 | 5 votes |
public void sendColorMsg(WebSocketMessage msg){ if (session!=null && session.isOpen()) { synchronized (session){ try { session.sendMessage(msg); } catch (IOException e) { e.printStackTrace(); } } }else{ System.out.println(msg.getPayload()); } }