org.springframework.web.socket.sockjs.frame.SockJsFrame Java Examples

The following examples show how to use org.springframework.web.socket.sockjs.frame.SockJsFrame. 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: AbstractClientSockJsSession.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public void handleFrame(String payload) {
	SockJsFrame frame = new SockJsFrame(payload);
	switch (frame.getType()) {
		case OPEN:
			handleOpenFrame();
			break;
		case HEARTBEAT:
			if (logger.isTraceEnabled()) {
				logger.trace("Received heartbeat in " + this);
			}
			break;
		case MESSAGE:
			handleMessageFrame(frame);
			break;
		case CLOSE:
			handleCloseFrame(frame);
	}
}
 
Example #2
Source File: SockJsSessionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void close() throws Exception {

	this.session.delegateConnectionEstablished();
	assertOpen();

	this.session.setActive(true);
	this.session.close();

	assertEquals(1, this.session.getSockJsFramesWritten().size());
	assertEquals(SockJsFrame.closeFrameGoAway(), this.session.getSockJsFramesWritten().get(0));

	assertEquals(1, this.session.getNumberOfLastActiveTimeUpdates());
	assertTrue(this.session.didCancelHeartbeat());

	assertEquals(new CloseStatus(3000, "Go away!"), this.session.getCloseStatus());
	assertClosed();
	verify(this.webSocketHandler).afterConnectionClosed(this.session, new CloseStatus(3000, "Go away!"));
}
 
Example #3
Source File: WebSocketServerSockJsSession.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public void initializeDelegateSession(WebSocketSession session) {
	synchronized (this.initSessionLock) {
		this.webSocketSession = session;
		try {
			// Let "our" handler know before sending the open frame to the remote handler
			delegateConnectionEstablished();
			this.webSocketSession.sendMessage(new TextMessage(SockJsFrame.openFrame().getContent()));

			// Flush any messages cached in the mean time
			while (!this.initSessionCache.isEmpty()) {
				writeFrame(SockJsFrame.messageFrame(getMessageCodec(), this.initSessionCache.poll()));
			}
			scheduleHeartbeat();
			this.openFrameSent = true;
		}
		catch (Exception ex) {
			tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
		}
	}
}
 
Example #4
Source File: WebSocketServerSockJsSession.java    From java-technology-stack with MIT License 6 votes vote down vote up
public void initializeDelegateSession(WebSocketSession session) {
	synchronized (this.initSessionLock) {
		this.webSocketSession = session;
		try {
			// Let "our" handler know before sending the open frame to the remote handler
			delegateConnectionEstablished();
			this.webSocketSession.sendMessage(new TextMessage(SockJsFrame.openFrame().getContent()));

			// Flush any messages cached in the mean time
			while (!this.initSessionCache.isEmpty()) {
				writeFrame(SockJsFrame.messageFrame(getMessageCodec(), this.initSessionCache.poll()));
			}
			scheduleHeartbeat();
			this.openFrameSent = true;
		}
		catch (Throwable ex) {
			tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
		}
	}
}
 
Example #5
Source File: AbstractHttpSockJsSession.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Handle all requests, except the first one, to receive messages on a SockJS
 * HTTP transport based session.
 * <p>Long polling-based transports (e.g. "xhr", "jsonp") complete the request
 * after writing any buffered message frames (or the next one). Streaming-based
 * transports ("xhr_streaming", "eventsource", and "htmlfile") leave the
 * response open longer for further streaming of message frames but will also
 * close it eventually after some amount of data has been sent.
 * @param request the current request
 * @param response the current response
 * @param frameFormat the transport-specific SocksJS frame format to use
 */
public void handleSuccessiveRequest(ServerHttpRequest request, ServerHttpResponse response,
		SockJsFrameFormat frameFormat) throws SockJsException {

	synchronized (this.responseLock) {
		try {
			if (isClosed()) {
				response.getBody().write(SockJsFrame.closeFrameGoAway().getContentBytes());
				return;
			}
			this.response = response;
			this.frameFormat = frameFormat;
			ServerHttpAsyncRequestControl control = request.getAsyncRequestControl(response);
			this.asyncRequestControl = control;
			control.start(-1);
			disableShallowEtagHeaderFilter(request);
			handleRequestInternal(request, response, false);
			this.readyToSend = isActive();
		}
		catch (Throwable ex) {
			tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
			throw new SockJsTransportFailureException("Failed to handle SockJS receive request", getId(), ex);
		}
	}
}
 
Example #6
Source File: RestTemplateXhrTransportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void connectReceiveAndCloseWithStompFrame() throws Exception {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
	accessor.setDestination("/destination");
	MessageHeaders headers = accessor.getMessageHeaders();
	Message<byte[]> message = MessageBuilder.createMessage("body".getBytes(StandardCharsets.UTF_8), headers);
	byte[] bytes = new StompEncoder().encode(message);
	TextMessage textMessage = new TextMessage(bytes);
	SockJsFrame frame = SockJsFrame.messageFrame(new Jackson2SockJsMessageCodec(), textMessage.getPayload());

	String body = "o\n" + frame.getContent() + "\n" + "c[3000,\"Go away!\"]";
	ClientHttpResponse response = response(HttpStatus.OK, body);
	connect(response);

	verify(this.webSocketHandler).afterConnectionEstablished(any());
	verify(this.webSocketHandler).handleMessage(any(), eq(textMessage));
	verify(this.webSocketHandler).afterConnectionClosed(any(), eq(new CloseStatus(3000, "Go away!")));
	verifyNoMoreInteractions(this.webSocketHandler);
}
 
Example #7
Source File: WebSocketServerSockJsSession.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void sendMessageInternal(String message) throws SockJsTransportFailureException {
	// Open frame not sent yet?
	// If in the session initialization thread, then cache, otherwise wait.
	if (!this.openFrameSent) {
		synchronized (this.initSessionLock) {
			if (!this.openFrameSent) {
				this.initSessionCache.add(message);
				return;
			}
		}
	}

	cancelHeartbeat();
	writeFrame(SockJsFrame.messageFrame(getMessageCodec(), message));
	scheduleHeartbeat();
}
 
Example #8
Source File: SockJsSessionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void close() throws Exception {
	this.session.delegateConnectionEstablished();
	assertOpen();

	this.session.setActive(true);
	this.session.close();

	assertEquals(1, this.session.getSockJsFramesWritten().size());
	assertEquals(SockJsFrame.closeFrameGoAway(), this.session.getSockJsFramesWritten().get(0));

	assertEquals(1, this.session.getNumberOfLastActiveTimeUpdates());
	assertTrue(this.session.didCancelHeartbeat());

	assertEquals(new CloseStatus(3000, "Go away!"), this.session.getCloseStatus());
	assertClosed();
	verify(this.webSocketHandler).afterConnectionClosed(this.session, new CloseStatus(3000, "Go away!"));
}
 
Example #9
Source File: HttpSendingTransportHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void frameFormats() throws Exception {
	this.servletRequest.setQueryString("c=callback");
	this.servletRequest.addParameter("c", "callback");

	SockJsFrame frame = SockJsFrame.openFrame();

	SockJsFrameFormat format = new XhrPollingTransportHandler().getFrameFormat(this.request);
	String formatted = format.format(frame);
	assertEquals(frame.getContent() + "\n", formatted);

	format = new XhrStreamingTransportHandler().getFrameFormat(this.request);
	formatted = format.format(frame);
	assertEquals(frame.getContent() + "\n", formatted);

	format = new HtmlFileTransportHandler().getFrameFormat(this.request);
	formatted = format.format(frame);
	assertEquals("<script>\np(\"" + frame.getContent() + "\");\n</script>\r\n", formatted);

	format = new EventSourceTransportHandler().getFrameFormat(this.request);
	formatted = format.format(frame);
	assertEquals("data: " + frame.getContent() + "\r\n\r\n", formatted);
}
 
Example #10
Source File: AbstractSockJsSession.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * For internal use within a TransportHandler and the (TransportHandler-specific)
 * session class.
 */
protected void writeFrame(SockJsFrame frame) throws SockJsTransportFailureException {
	if (logger.isTraceEnabled()) {
		logger.trace("Preparing to write " + frame);
	}
	try {
		writeFrameInternal(frame);
	}
	catch (Throwable ex) {
		logWriteFrameFailure(ex);
		try {
			// Force disconnect (so we won't try to send close frame)
			disconnect(CloseStatus.SERVER_ERROR);
		}
		catch (Throwable disconnectFailure) {
			// Ignore
		}
		try {
			close(CloseStatus.SERVER_ERROR);
		}
		catch (Throwable closeFailure) {
			// Nothing of consequence, already forced disconnect
		}
		throw new SockJsTransportFailureException("Failed to write " + frame, getId(), ex);
	}
}
 
Example #11
Source File: AbstractSockJsSession.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * For internal use within a TransportHandler and the (TransportHandler-specific)
 * session class.
 */
protected void writeFrame(SockJsFrame frame) throws SockJsTransportFailureException {
	if (logger.isTraceEnabled()) {
		logger.trace("Preparing to write " + frame);
	}
	try {
		writeFrameInternal(frame);
	}
	catch (Throwable ex) {
		logWriteFrameFailure(ex);
		try {
			// Force disconnect (so we won't try to send close frame)
			disconnect(CloseStatus.SERVER_ERROR);
		}
		catch (Throwable disconnectFailure) {
			// Ignore
		}
		try {
			close(CloseStatus.SERVER_ERROR);
		}
		catch (Throwable closeFailure) {
			// Nothing of consequence, already forced disconnect
		}
		throw new SockJsTransportFailureException("Failed to write " + frame, getId(), ex);
	}
}
 
Example #12
Source File: SockJsSessionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void close() throws Exception {
	this.session.delegateConnectionEstablished();
	assertOpen();

	this.session.setActive(true);
	this.session.close();

	assertEquals(1, this.session.getSockJsFramesWritten().size());
	assertEquals(SockJsFrame.closeFrameGoAway(), this.session.getSockJsFramesWritten().get(0));

	assertEquals(1, this.session.getNumberOfLastActiveTimeUpdates());
	assertTrue(this.session.didCancelHeartbeat());

	assertEquals(new CloseStatus(3000, "Go away!"), this.session.getCloseStatus());
	assertClosed();
	verify(this.webSocketHandler).afterConnectionClosed(this.session, new CloseStatus(3000, "Go away!"));
}
 
Example #13
Source File: AbstractClientSockJsSession.java    From java-technology-stack with MIT License 6 votes vote down vote up
public void handleFrame(String payload) {
	SockJsFrame frame = new SockJsFrame(payload);
	switch (frame.getType()) {
		case OPEN:
			handleOpenFrame();
			break;
		case HEARTBEAT:
			if (logger.isTraceEnabled()) {
				logger.trace("Received heartbeat in " + this);
			}
			break;
		case MESSAGE:
			handleMessageFrame(frame);
			break;
		case CLOSE:
			handleCloseFrame(frame);
	}
}
 
Example #14
Source File: SockJsSessionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void writeFrame() throws Exception {
	this.session.writeFrame(SockJsFrame.openFrame());

	assertEquals(1, this.session.getSockJsFramesWritten().size());
	assertEquals(SockJsFrame.openFrame(), this.session.getSockJsFramesWritten().get(0));
}
 
Example #15
Source File: UndertowXhrTransport.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void handleFrame() {
	byte[] bytes = this.outputStream.toByteArray();
	this.outputStream.reset();
	String content = new String(bytes, SockJsFrame.CHARSET);
	if (logger.isTraceEnabled()) {
		logger.trace("XHR content received: " + content);
	}
	if (!PRELUDE.equals(content)) {
		this.session.handleFrame(new String(bytes, SockJsFrame.CHARSET));
	}
}
 
Example #16
Source File: ClientSockJsSessionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void afterTransportClosed() throws Exception {
	this.session.handleFrame(SockJsFrame.openFrame().getContent());
	this.session.afterTransportClosed(CloseStatus.SERVER_ERROR);
	assertThat(this.session.isOpen(), equalTo(false));
	verify(this.handler).afterConnectionEstablished(this.session);
	verify(this.handler).afterConnectionClosed(this.session, CloseStatus.SERVER_ERROR);
	verifyNoMoreInteractions(this.handler);
}
 
Example #17
Source File: ClientSockJsSessionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void closeWithStatusOutOfRange() throws Exception {
	this.session.handleFrame(SockJsFrame.openFrame().getContent());
	this.thrown.expect(IllegalArgumentException.class);
	this.thrown.expectMessage("Invalid close status");
	this.session.close(new CloseStatus(2999, "reason"));
}
 
Example #18
Source File: ClientSockJsSessionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void closeWithNullStatus() throws Exception {
	this.session.handleFrame(SockJsFrame.openFrame().getContent());
	this.thrown.expect(IllegalArgumentException.class);
	this.thrown.expectMessage("Invalid close status");
	this.session.close(null);
}
 
Example #19
Source File: ClientSockJsSessionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void close() throws Exception {
	this.session.handleFrame(SockJsFrame.openFrame().getContent());
	this.session.close();
	assertThat(this.session.isOpen(), equalTo(false));
	assertThat(this.session.disconnectStatus, equalTo(CloseStatus.NORMAL));
	verify(this.handler).afterConnectionEstablished(this.session);
	verifyNoMoreInteractions(this.handler);
}
 
Example #20
Source File: ClientSockJsSessionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleFrameMessageWhenNotOpen() throws Exception {
	this.session.handleFrame(SockJsFrame.openFrame().getContent());
	this.session.close();
	reset(this.handler);
	this.session.handleFrame(SockJsFrame.messageFrame(CODEC, "foo", "bar").getContent());
	verifyNoMoreInteractions(this.handler);
}
 
Example #21
Source File: WebSocketServerSockJsSession.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void writeFrameInternal(SockJsFrame frame) throws IOException {
	Assert.state(this.webSocketSession != null, "WebSocketSession not yet initialized");
	if (logger.isTraceEnabled()) {
		logger.trace("Writing " + frame);
	}
	TextMessage message = new TextMessage(frame.getContent());
	this.webSocketSession.sendMessage(message);
}
 
Example #22
Source File: RestTemplateXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<String> extractData(ClientHttpResponse response) throws IOException {
	if (response.getBody() == null) {
		return new ResponseEntity<String>(response.getHeaders(), response.getStatusCode());
	}
	else {
		String body = StreamUtils.copyToString(response.getBody(), SockJsFrame.CHARSET);
		return new ResponseEntity<String>(body, response.getHeaders(), response.getStatusCode());
	}
}
 
Example #23
Source File: PollingSockJsSession.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void flushCache() throws SockJsTransportFailureException {
	String[] messages = new String[getMessageCache().size()];
	for (int i = 0; i < messages.length; i++) {
		messages[i] = getMessageCache().poll();
	}
	SockJsMessageCodec messageCodec = getSockJsServiceConfig().getMessageCodec();
	SockJsFrame frame = SockJsFrame.messageFrame(messageCodec, messages);
	writeFrame(frame);
	resetRequest();
}
 
Example #24
Source File: RestTemplateXhrTransport.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
	request.getHeaders().putAll(this.headers);
	if (this.body != null) {
		StreamUtils.copy(this.body, SockJsFrame.CHARSET, request.getBody());
	}
}
 
Example #25
Source File: ClientSockJsSessionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleFrameClose() throws Exception {
	this.session.handleFrame(SockJsFrame.openFrame().getContent());
	this.session.handleFrame(SockJsFrame.closeFrame(1007, "").getContent());
	assertThat(this.session.isOpen(), equalTo(false));
	assertThat(this.session.disconnectStatus, equalTo(new CloseStatus(1007, "")));
	verify(this.handler).afterConnectionEstablished(this.session);
	verifyNoMoreInteractions(this.handler);
}
 
Example #26
Source File: PollingSockJsSession.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response,
		boolean initialRequest) throws IOException {

	if (initialRequest) {
		writeFrame(SockJsFrame.openFrame());
	}
	else if (!getMessageCache().isEmpty()) {
		flushCache();
	}
	else {
		scheduleHeartbeat();
	}
}
 
Example #27
Source File: ClientSockJsSessionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleFrameOpenWhenStatusNotNew() throws Exception {
	this.session.handleFrame(SockJsFrame.openFrame().getContent());
	assertThat(this.session.isOpen(), is(true));
	this.session.handleFrame(SockJsFrame.openFrame().getContent());
	assertThat(this.session.disconnectStatus, equalTo(new CloseStatus(1006, "Server lost session")));
}
 
Example #28
Source File: HttpSendingTransportHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void frameFormats() throws Exception {
	this.servletRequest.setQueryString("c=callback");
	this.servletRequest.addParameter("c", "callback");

	SockJsFrame frame = SockJsFrame.openFrame();

	SockJsFrameFormat format = new XhrPollingTransportHandler().getFrameFormat(this.request);
	String formatted = format.format(frame);
	assertEquals(frame.getContent() + "\n", formatted);

	format = new XhrStreamingTransportHandler().getFrameFormat(this.request);
	formatted = format.format(frame);
	assertEquals(frame.getContent() + "\n", formatted);

	format = new HtmlFileTransportHandler().getFrameFormat(this.request);
	formatted = format.format(frame);
	assertEquals("<script>\np(\"" + frame.getContent() + "\");\n</script>\r\n", formatted);

	format = new EventSourceTransportHandler().getFrameFormat(this.request);
	formatted = format.format(frame);
	assertEquals("data: " + frame.getContent() + "\r\n\r\n", formatted);

	format = new JsonpPollingTransportHandler().getFrameFormat(this.request);
	formatted = format.format(frame);
	assertEquals("/**/callback(\"" + frame.getContent() + "\");\r\n", formatted);
}
 
Example #29
Source File: RestTemplateXhrTransport.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void handleFrame(ByteArrayOutputStream os) {
	byte[] bytes = os.toByteArray();
	os.reset();
	String content = new String(bytes, SockJsFrame.CHARSET);
	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive content: " + content);
	}
	if (!PRELUDE.equals(content)) {
		this.sockJsSession.handleFrame(new String(bytes, SockJsFrame.CHARSET));
	}
}
 
Example #30
Source File: UndertowXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void handleFrame() {
	byte[] bytes = this.outputStream.toByteArray();
	this.outputStream.reset();
	String content = new String(bytes, SockJsFrame.CHARSET);
	if (logger.isTraceEnabled()) {
		logger.trace("XHR content received: " + content);
	}
	if (!PRELUDE.equals(content)) {
		this.session.handleFrame(new String(bytes, SockJsFrame.CHARSET));
	}
}