Here are the examples of the java api org.springframework.http.server.ServerHttpRequest taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
327 Examples
19
View Source File : HttpStatusHandlerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Tests for {@link HttpStatusHandler}.
*
* @author Phillip Webb
*/
public clreplaced HttpStatusHandlerTests {
private MockHttpServletRequest servletRequest;
private MockHttpServletResponse servletResponse;
private ServerHttpResponse response;
private ServerHttpRequest request;
@Before
public void setup() {
this.servletRequest = new MockHttpServletRequest();
this.servletResponse = new MockHttpServletResponse();
this.request = new ServletServerHttpRequest(this.servletRequest);
this.response = new ServletServerHttpResponse(this.servletResponse);
}
@Test
public void statusMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusHandler(null)).withMessageContaining("Status must not be null");
}
@Test
public void respondsOk() throws Exception {
HttpStatusHandler handler = new HttpStatusHandler();
handler.handle(this.request, this.response);
replacedertThat(this.servletResponse.getStatus()).isEqualTo(200);
}
@Test
public void respondsWithStatus() throws Exception {
HttpStatusHandler handler = new HttpStatusHandler(HttpStatus.I_AM_A_TEAPOT);
handler.handle(this.request, this.response);
replacedertThat(this.servletResponse.getStatus()).isEqualTo(418);
}
}
19
View Source File : HttpHeaderAccessManagerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Tests for {@link HttpHeaderAccessManager}.
*
* @author Rob Winch
* @author Phillip Webb
*/
public clreplaced HttpHeaderAccessManagerTests {
private static final String HEADER = "X-AUTH_TOKEN";
private static final String SECRET = "preplacedword";
private MockHttpServletRequest request;
private ServerHttpRequest serverRequest;
private HttpHeaderAccessManager manager;
@Before
public void setup() {
this.request = new MockHttpServletRequest("GET", "/");
this.serverRequest = new ServletServerHttpRequest(this.request);
this.manager = new HttpHeaderAccessManager(HEADER, SECRET);
}
@Test
public void headerNameMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(null, SECRET)).withMessageContaining("HeaderName must not be empty");
}
@Test
public void headerNameMustNotBeEmpty() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager("", SECRET)).withMessageContaining("HeaderName must not be empty");
}
@Test
public void expectedSecretMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, null)).withMessageContaining("ExpectedSecret must not be empty");
}
@Test
public void expectedSecretMustNotBeEmpty() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, "")).withMessageContaining("ExpectedSecret must not be empty");
}
@Test
public void allowsMatching() {
this.request.addHeader(HEADER, SECRET);
replacedertThat(this.manager.isAllowed(this.serverRequest)).isTrue();
}
@Test
public void disallowsWrongSecret() {
this.request.addHeader(HEADER, "wrong");
replacedertThat(this.manager.isAllowed(this.serverRequest)).isFalse();
}
@Test
public void disallowsNoSecret() {
replacedertThat(this.manager.isAllowed(this.serverRequest)).isFalse();
}
@Test
public void disallowsWrongHeader() {
this.request.addHeader("X-WRONG", SECRET);
replacedertThat(this.manager.isAllowed(this.serverRequest)).isFalse();
}
}
19
View Source File : HttpTunnelServerHandler.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Override
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
this.server.handle(request, response);
}
19
View Source File : HttpTunnelServer.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Handle an incoming HTTP connection.
* @param request the HTTP request
* @param response the HTTP response
* @throws IOException in case of I/O errors
*/
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
handle(new HttpConnection(request, response));
}
19
View Source File : Dispatcher.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Dispatch the specified request to an appropriate {@link Handler}.
* @param request the request
* @param response the response
* @return {@code true} if the request was dispatched
* @throws IOException in case of I/O errors
*/
public boolean handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
for (HandlerMapper mapper : this.mappers) {
Handler handler = mapper.getHandler(request);
if (handler != null) {
handle(handler, request, response);
return true;
}
}
return false;
}
19
View Source File : TestHttpSockJsSession.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
protected byte[] getPrelude(ServerHttpRequest request) {
return new byte[0];
}
19
View Source File : HtmlFileTransportHandler.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
protected SockJsFrameFormat getFrameFormat(ServerHttpRequest request) {
return new DefaultSockJsFrameFormat("<script>\np(\"%s\");\n</script>\r\n") {
@Override
protected String preProcessContent(String content) {
return JavaScriptUtils.javaScriptEscape(content);
}
};
}
19
View Source File : HttpSessionHandshakeInterceptor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Nullable
private HttpSession getSession(ServerHttpRequest request) {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
return serverRequest.getServletRequest().getSession(isCreateSession());
}
return null;
}
19
View Source File : AbstractHandshakeHandler.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Return whether the request {@code Origin} header value is valid or not.
* By default, all origins as considered as valid. Consider using an
* {@link OriginHandshakeInterceptor} for filtering origins if needed.
*/
protected boolean isValidOrigin(ServerHttpRequest request) {
return true;
}
19
View Source File : AbstractStandardUpgradeStrategy.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public List<WebSocketExtension> getSupportedExtensions(ServerHttpRequest request) {
List<WebSocketExtension> extensions = this.extensions;
if (extensions == null) {
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
extensions = getInstalledExtensions(getContainer(servletRequest));
this.extensions = extensions;
}
return extensions;
}
19
View Source File : AbstractStandardUpgradeStrategy.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
protected final HttpServletRequest getHttpServletRequest(ServerHttpRequest request) {
replacedert.isInstanceOf(ServletServerHttpRequest.clreplaced, request, "ServletServerHttpRequest required");
return ((ServletServerHttpRequest) request).getServletRequest();
}
19
View Source File : JettyRequestUpgradeStrategy.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public List<WebSocketExtension> getSupportedExtensions(ServerHttpRequest request) {
if (this.supportedExtensions == null) {
this.supportedExtensions = buildWebSocketExtensions();
}
return this.supportedExtensions;
}
19
View Source File : RequestPartServletServerHttpRequestTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
// SPR-13317
@Test
public void getBodyWithWrappedRequest() throws Exception {
byte[] bytes = "content".getBytes("UTF-8");
MultipartFile part = new MockMultipartFile("part", "", "application/json", bytes);
this.mockRequest.addFile(part);
HttpServletRequest wrapped = new HttpServletRequestWrapper(this.mockRequest);
ServerHttpRequest request = new RequestPartServletServerHttpRequest(wrapped, "part");
byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
replacedertArrayEquals(bytes, result);
}
19
View Source File : RequestPartServletServerHttpRequestTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
// SPR-13096
@Test
public void getBodyViaRequestParameter() throws Exception {
MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest() {
@Override
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("application", "octet-stream", StandardCharsets.ISO_8859_1));
return headers;
}
};
byte[] bytes = { (byte) 0xC4 };
mockRequest.setParameter("part", new String(bytes, StandardCharsets.ISO_8859_1));
ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part");
byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
replacedertArrayEquals(bytes, result);
}
19
View Source File : DefaultCorsProcessor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Nullable
private HttpMethod getMethodToUse(ServerHttpRequest request, boolean isPreFlight) {
return (isPreFlight ? request.getHeaders().getAccessControlRequestMethod() : request.getMethod());
}
19
View Source File : RequestPartServletServerHttpRequestTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
// SPR-13317
@Test
public void getBodyWithWrappedRequest() throws Exception {
byte[] bytes = "content".getBytes("UTF-8");
MultipartFile part = new MockMultipartFile("part", "", "application/json", bytes);
this.mockRequest.addFile(part);
HttpServletRequest wrapped = new HttpServletRequestWrapper(this.mockRequest);
ServerHttpRequest request = new RequestPartServletServerHttpRequest(wrapped, "part");
byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
replacedertThat(result).isEqualTo(bytes);
}
19
View Source File : RequestPartServletServerHttpRequestTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void getBody() throws Exception {
byte[] bytes = "content".getBytes("UTF-8");
MultipartFile part = new MockMultipartFile("part", "", "application/json", bytes);
this.mockRequest.addFile(part);
ServerHttpRequest request = new RequestPartServletServerHttpRequest(this.mockRequest, "part");
byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
replacedertThat(result).isEqualTo(bytes);
}
19
View Source File : AbstractHttpSockJsSession.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* @deprecated as of 4.2 this method is deprecated since the prelude is written
* in {@link #handleRequestInternal} of the StreamingSockJsSession subclreplaced.
*/
@Deprecated
protected void writePrelude(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
}
19
View Source File : AbstractHttpSockJsSession.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* Handle the first request for receiving messages on a SockJS HTTP transport
* based session.
* <p>Long polling-based transports (e.g. "xhr", "jsonp") complete the request
* after writing the open frame. 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 handleInitialRequest(ServerHttpRequest request, ServerHttpResponse response, SockJsFrameFormat frameFormat) throws SockJsException {
this.uri = request.getURI();
this.handshakeHeaders = request.getHeaders();
this.principal = request.getPrincipal();
this.localAddress = request.getLocalAddress();
this.remoteAddress = request.getRemoteAddress();
synchronized (this.responseLock) {
try {
this.response = response;
this.frameFormat = frameFormat;
this.asyncRequestControl = request.getAsyncRequestControl(response);
this.asyncRequestControl.start(-1);
disableShallowEtagHeaderFilter(request);
// Let "our" handler know before sending the open frame to the remote handler
delegateConnectionEstablished();
handleRequestInternal(request, response, true);
// Request might have been reset (e.g. polling sessions do after writing)
this.readyToSend = isActive();
} catch (Throwable ex) {
tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
throw new SockJsTransportFailureException("Failed to open session", getId(), ex);
}
}
}
19
View Source File : HttpSessionHandshakeInterceptor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
private HttpSession getSession(ServerHttpRequest request) {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
return serverRequest.getServletRequest().getSession(isCreateSession());
}
return null;
}
19
View Source File : AbstractStandardUpgradeStrategy.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
protected final HttpServletRequest getHttpServletRequest(ServerHttpRequest request) {
replacedert.isTrue(request instanceof ServletServerHttpRequest);
return ((ServletServerHttpRequest) request).getServletRequest();
}
19
View Source File : AbstractStandardUpgradeStrategy.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Override
public List<WebSocketExtension> getSupportedExtensions(ServerHttpRequest request) {
if (this.extensions == null) {
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
this.extensions = getInstalledExtensions(getContainer(servletRequest));
}
return this.extensions;
}
19
View Source File : JettyRequestUpgradeStrategy.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Override
public List<WebSocketExtension> getSupportedExtensions(ServerHttpRequest request) {
if (this.supportedExtensions == null) {
this.supportedExtensions = getWebSocketExtensions();
}
return this.supportedExtensions;
}
19
View Source File : DefaultCorsProcessor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
private HttpMethod getMethodToUse(ServerHttpRequest request, boolean isPreFlight) {
return (isPreFlight ? request.getHeaders().getAccessControlRequestMethod() : request.getMethod());
}
19
View Source File : HttpTunnelServer.java
License : Apache License 2.0
Project Creator : hello-shf
License : Apache License 2.0
Project Creator : hello-shf
/**
* Handle an incoming HTTP connection.
*
* @param request the HTTP request
* @param response the HTTP response
* @throws IOException in case of I/O errors
*/
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
handle(new HttpConnection(request, response));
}
19
View Source File : Dispatcher.java
License : Apache License 2.0
Project Creator : hello-shf
License : Apache License 2.0
Project Creator : hello-shf
/**
* Dispatch the specified request to an appropriate {@link Handler}.
*
* @param request the request
* @param response the response
* @return {@code true} if the request was dispatched
* @throws IOException in case of I/O errors
*/
public boolean handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
for (HandlerMapper mapper : this.mappers) {
Handler handler = mapper.getHandler(request);
if (handler != null) {
handle(handler, request, response);
return true;
}
}
return false;
}
19
View Source File : GlobalSpringRestResponseBodyAdvice.java
License : Apache License 2.0
Project Creator : fangjinuo
License : Apache License 2.0
Project Creator : fangjinuo
private HttpServletRequest extractHttpServletRequest(ServerHttpRequest request) {
if (request instanceof ServletServerHttpRequest) {
return ((ServletServerHttpRequest) request).getServletRequest();
}
return null;
}
19
View Source File : InetSocketAddressHelper.java
License : Apache License 2.0
Project Creator : ctripcorp
License : Apache License 2.0
Project Creator : ctripcorp
public static String getRemoteIP(ServerHttpRequest request) {
return getRemoteIP(request.getRemoteAddress());
}
18
View Source File : HandshakeInterceptor.java
License : Apache License 2.0
Project Creator : Zephery
License : Apache License 2.0
Project Creator : Zephery
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
super.afterHandshake(request, response, wsHandler, ex);
}
18
View Source File : HttpTunnelServerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Tests for {@link HttpTunnelServer}.
*
* @author Phillip Webb
*/
public clreplaced HttpTunnelServerTests {
private static final int DEFAULT_LONG_POLL_TIMEOUT = 10000;
private static final byte[] NO_DATA = {};
private static final String SEQ_HEADER = "x-seq";
private HttpTunnelServer server;
@Mock
private TargetServerConnection serverConnection;
private MockHttpServletRequest servletRequest;
private MockHttpServletResponse servletResponse;
private ServerHttpRequest request;
private ServerHttpResponse response;
private MockServerChannel serverChannel;
@Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
this.server = new HttpTunnelServer(this.serverConnection);
given(this.serverConnection.open(anyInt())).willAnswer((invocation) -> {
MockServerChannel channel = HttpTunnelServerTests.this.serverChannel;
channel.setTimeout(invocation.getArgument(0));
return channel;
});
this.servletRequest = new MockHttpServletRequest();
this.servletRequest.setAsyncSupported(true);
this.servletResponse = new MockHttpServletResponse();
this.request = new ServletServerHttpRequest(this.servletRequest);
this.response = new ServletServerHttpResponse(this.servletResponse);
this.serverChannel = new MockServerChannel();
}
@Test
public void serverConnectionIsRequired() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServer(null)).withMessageContaining("ServerConnection must not be null");
}
@Test
public void serverConnectedOnFirstRequest() throws Exception {
verify(this.serverConnection, never()).open(anyInt());
this.server.handle(this.request, this.response);
verify(this.serverConnection, times(1)).open(DEFAULT_LONG_POLL_TIMEOUT);
}
@Test
public void longPollTimeout() throws Exception {
this.server.setLongPollTimeout(800);
this.server.handle(this.request, this.response);
verify(this.serverConnection, times(1)).open(800);
}
@Test
public void longPollTimeoutMustBePositiveValue() {
replacedertThatIllegalArgumentException().isThrownBy(() -> this.server.setLongPollTimeout(0)).withMessageContaining("LongPollTimeout must be a positive value");
}
@Test
public void initialRequestIsSentToServer() throws Exception {
this.servletRequest.addHeader(SEQ_HEADER, "1");
this.servletRequest.setContent("hello".getBytes());
this.server.handle(this.request, this.response);
this.serverChannel.disconnect();
this.server.getServerThread().join();
this.serverChannel.verifyReceived("hello");
}
@Test
public void initialRequestIsUsedForFirstServerResponse() throws Exception {
this.servletRequest.addHeader(SEQ_HEADER, "1");
this.servletRequest.setContent("hello".getBytes());
this.server.handle(this.request, this.response);
System.out.println("sending");
this.serverChannel.send("hello");
this.serverChannel.disconnect();
this.server.getServerThread().join();
replacedertThat(this.servletResponse.getContentreplacedtring()).isEqualTo("hello");
this.serverChannel.verifyReceived("hello");
}
@Test
public void initialRequestHasNoPayload() throws Exception {
this.server.handle(this.request, this.response);
this.serverChannel.disconnect();
this.server.getServerThread().join();
this.serverChannel.verifyReceived(NO_DATA);
}
@Test
public void typicalRequestResponseTraffic() throws Exception {
MockHttpConnection h1 = new MockHttpConnection();
this.server.handle(h1);
MockHttpConnection h2 = new MockHttpConnection("hello server", 1);
this.server.handle(h2);
this.serverChannel.verifyReceived("hello server");
this.serverChannel.send("hello client");
h1.verifyReceived("hello client", 1);
MockHttpConnection h3 = new MockHttpConnection("1+1", 2);
this.server.handle(h3);
this.serverChannel.send("=2");
h2.verifyReceived("=2", 2);
MockHttpConnection h4 = new MockHttpConnection("1+2", 3);
this.server.handle(h4);
this.serverChannel.send("=3");
h3.verifyReceived("=3", 3);
this.serverChannel.disconnect();
this.server.getServerThread().join();
}
@Test
public void clientIsAwareOfServerClose() throws Exception {
MockHttpConnection h1 = new MockHttpConnection("1", 1);
this.server.handle(h1);
this.serverChannel.disconnect();
this.server.getServerThread().join();
replacedertThat(h1.getServletResponse().getStatus()).isEqualTo(410);
}
@Test
public void clientCanCloseServer() throws Exception {
MockHttpConnection h1 = new MockHttpConnection();
this.server.handle(h1);
MockHttpConnection h2 = new MockHttpConnection("DISCONNECT", 1);
h2.getServletRequest().addHeader("Content-Type", "application/x-disconnect");
this.server.handle(h2);
this.server.getServerThread().join();
replacedertThat(h1.getServletResponse().getStatus()).isEqualTo(410);
replacedertThat(this.serverChannel.isOpen()).isFalse();
}
@Test
public void neverMoreThanTwoHttpConnections() throws Exception {
MockHttpConnection h1 = new MockHttpConnection();
this.server.handle(h1);
MockHttpConnection h2 = new MockHttpConnection("1", 2);
this.server.handle(h2);
MockHttpConnection h3 = new MockHttpConnection("2", 3);
this.server.handle(h3);
h1.waitForResponse();
replacedertThat(h1.getServletResponse().getStatus()).isEqualTo(429);
this.serverChannel.disconnect();
this.server.getServerThread().join();
}
@Test
public void requestReceivedOutOfOrder() throws Exception {
MockHttpConnection h1 = new MockHttpConnection();
MockHttpConnection h2 = new MockHttpConnection("1+2", 1);
MockHttpConnection h3 = new MockHttpConnection("+3", 2);
this.server.handle(h1);
this.server.handle(h3);
this.server.handle(h2);
this.serverChannel.verifyReceived("1+2+3");
this.serverChannel.disconnect();
this.server.getServerThread().join();
}
@Test
public void httpConnectionsAreClosedAfterLongPollTimeout() throws Exception {
this.server.setDisconnectTimeout(1000);
this.server.setLongPollTimeout(100);
MockHttpConnection h1 = new MockHttpConnection();
this.server.handle(h1);
MockHttpConnection h2 = new MockHttpConnection();
this.server.handle(h2);
Thread.sleep(400);
this.serverChannel.disconnect();
this.server.getServerThread().join();
replacedertThat(h1.getServletResponse().getStatus()).isEqualTo(204);
replacedertThat(h2.getServletResponse().getStatus()).isEqualTo(204);
}
@Test
public void disconnectTimeout() throws Exception {
this.server.setDisconnectTimeout(100);
this.server.setLongPollTimeout(100);
MockHttpConnection h1 = new MockHttpConnection();
this.server.handle(h1);
this.serverChannel.send("hello");
this.server.getServerThread().join();
replacedertThat(this.serverChannel.isOpen()).isFalse();
}
@Test
public void disconnectTimeoutMustBePositive() {
replacedertThatIllegalArgumentException().isThrownBy(() -> this.server.setDisconnectTimeout(0)).withMessageContaining("DisconnectTimeout must be a positive value");
}
@Test
public void httpConnectionRespondWithPayload() throws Exception {
HttpConnection connection = new HttpConnection(this.request, this.response);
connection.waitForResponse();
connection.respond(new HttpTunnelPayload(1, ByteBuffer.wrap("hello".getBytes())));
replacedertThat(this.servletResponse.getStatus()).isEqualTo(200);
replacedertThat(this.servletResponse.getContentreplacedtring()).isEqualTo("hello");
replacedertThat(this.servletResponse.getHeader(SEQ_HEADER)).isEqualTo("1");
}
@Test
public void httpConnectionRespondWithStatus() throws Exception {
HttpConnection connection = new HttpConnection(this.request, this.response);
connection.waitForResponse();
connection.respond(HttpStatus.I_AM_A_TEAPOT);
replacedertThat(this.servletResponse.getStatus()).isEqualTo(418);
replacedertThat(this.servletResponse.getContentLength()).isEqualTo(0);
}
@Test
public void httpConnectionAsync() throws Exception {
ServerHttpAsyncRequestControl async = mock(ServerHttpAsyncRequestControl.clreplaced);
ServerHttpRequest request = mock(ServerHttpRequest.clreplaced);
given(request.getAsyncRequestControl(this.response)).willReturn(async);
HttpConnection connection = new HttpConnection(request, this.response);
connection.waitForResponse();
verify(async).start();
connection.respond(HttpStatus.NO_CONTENT);
verify(async).complete();
}
@Test
public void httpConnectionNonAsync() throws Exception {
testHttpConnectionNonAsync(0);
testHttpConnectionNonAsync(100);
}
private void testHttpConnectionNonAsync(long sleepBeforeResponse) throws IOException, InterruptedException {
ServerHttpRequest request = mock(ServerHttpRequest.clreplaced);
given(request.getAsyncRequestControl(this.response)).willThrow(new IllegalArgumentException());
final HttpConnection connection = new HttpConnection(request, this.response);
final AtomicBoolean responded = new AtomicBoolean();
Thread connectionThread = new Thread(() -> {
connection.waitForResponse();
responded.set(true);
});
connectionThread.start();
replacedertThat(responded.get()).isFalse();
Thread.sleep(sleepBeforeResponse);
connection.respond(HttpStatus.NO_CONTENT);
connectionThread.join();
replacedertThat(responded.get()).isTrue();
}
@Test
public void httpConnectionRunning() throws Exception {
HttpConnection connection = new HttpConnection(this.request, this.response);
replacedertThat(connection.isOlderThan(100)).isFalse();
Thread.sleep(200);
replacedertThat(connection.isOlderThan(100)).isTrue();
}
/**
* Mock {@link ByteChannel} used to simulate the server connection.
*/
private static clreplaced MockServerChannel implements ByteChannel {
private static final ByteBuffer DISCONNECT = ByteBuffer.wrap(NO_DATA);
private int timeout;
private BlockingDeque<ByteBuffer> outgoing = new LinkedBlockingDeque<>();
private ByteArrayOutputStream written = new ByteArrayOutputStream();
private AtomicBoolean open = new AtomicBoolean(true);
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void send(String content) {
send(content.getBytes());
}
public void send(byte[] bytes) {
this.outgoing.addLast(ByteBuffer.wrap(bytes));
}
public void disconnect() {
this.outgoing.addLast(DISCONNECT);
}
public void verifyReceived(String expected) {
verifyReceived(expected.getBytes());
}
public void verifyReceived(byte[] expected) {
synchronized (this.written) {
replacedertThat(this.written.toByteArray()).isEqualTo(expected);
this.written.reset();
}
}
@Override
public int read(ByteBuffer dst) throws IOException {
try {
ByteBuffer bytes = this.outgoing.pollFirst(this.timeout, TimeUnit.MILLISECONDS);
if (bytes == null) {
throw new SocketTimeoutException();
}
if (bytes == DISCONNECT) {
this.open.set(false);
return -1;
}
int initialRemaining = dst.remaining();
bytes.limit(Math.min(bytes.limit(), initialRemaining));
dst.put(bytes);
bytes.limit(bytes.capacity());
return initialRemaining - dst.remaining();
} catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public int write(ByteBuffer src) throws IOException {
int remaining = src.remaining();
synchronized (this.written) {
Channels.newChannel(this.written).write(src);
}
return remaining;
}
@Override
public boolean isOpen() {
return this.open.get();
}
@Override
public void close() {
this.open.set(false);
}
}
/**
* Mock {@link HttpConnection}.
*/
private static clreplaced MockHttpConnection extends HttpConnection {
MockHttpConnection() {
super(new ServletServerHttpRequest(new MockHttpServletRequest()), new ServletServerHttpResponse(new MockHttpServletResponse()));
}
MockHttpConnection(String content, int seq) {
this();
MockHttpServletRequest request = getServletRequest();
request.setContent(content.getBytes());
request.addHeader(SEQ_HEADER, String.valueOf(seq));
}
@Override
protected ServerHttpAsyncRequestControl startAsync() {
getServletRequest().setAsyncSupported(true);
return super.startAsync();
}
@Override
protected void complete() {
super.complete();
getServletResponse().setCommitted(true);
}
public MockHttpServletRequest getServletRequest() {
return (MockHttpServletRequest) ((ServletServerHttpRequest) getRequest()).getServletRequest();
}
public MockHttpServletResponse getServletResponse() {
return (MockHttpServletResponse) ((ServletServerHttpResponse) getResponse()).getServletResponse();
}
public void verifyReceived(String expectedContent, int expectedSeq) throws Exception {
waitForServletResponse();
MockHttpServletResponse resp = getServletResponse();
replacedertThat(resp.getContentreplacedtring()).isEqualTo(expectedContent);
replacedertThat(resp.getHeader(SEQ_HEADER)).isEqualTo(String.valueOf(expectedSeq));
}
public void waitForServletResponse() throws InterruptedException {
while (!getServletResponse().isCommitted()) {
Thread.sleep(10);
}
}
}
}
18
View Source File : HttpTunnelServerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
private void testHttpConnectionNonAsync(long sleepBeforeResponse) throws IOException, InterruptedException {
ServerHttpRequest request = mock(ServerHttpRequest.clreplaced);
given(request.getAsyncRequestControl(this.response)).willThrow(new IllegalArgumentException());
final HttpConnection connection = new HttpConnection(request, this.response);
final AtomicBoolean responded = new AtomicBoolean();
Thread connectionThread = new Thread(() -> {
connection.waitForResponse();
responded.set(true);
});
connectionThread.start();
replacedertThat(responded.get()).isFalse();
Thread.sleep(sleepBeforeResponse);
connection.respond(HttpStatus.NO_CONTENT);
connectionThread.join();
replacedertThat(responded.get()).isTrue();
}
18
View Source File : HttpTunnelServerHandlerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void handleDelegatesToServer() throws Exception {
HttpTunnelServer server = mock(HttpTunnelServer.clreplaced);
HttpTunnelServerHandler handler = new HttpTunnelServerHandler(server);
ServerHttpRequest request = mock(ServerHttpRequest.clreplaced);
ServerHttpResponse response = mock(ServerHttpResponse.clreplaced);
handler.handle(request, response);
verify(server).handle(request, response);
}
18
View Source File : HttpRestartServerHandlerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void handleDelegatesToServer() throws Exception {
HttpRestartServer server = mock(HttpRestartServer.clreplaced);
HttpRestartServerHandler handler = new HttpRestartServerHandler(server);
ServerHttpRequest request = mock(ServerHttpRequest.clreplaced);
ServerHttpResponse response = mock(ServerHttpResponse.clreplaced);
handler.handle(request, response);
verify(server).handle(request, response);
}
18
View Source File : DispatcherTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Tests for {@link Dispatcher}.
*
* @author Phillip Webb
*/
public clreplaced DispatcherTests {
@Mock
private AccessManager accessManager;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private ServerHttpRequest serverRequest;
private ServerHttpResponse serverResponse;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.serverRequest = new ServletServerHttpRequest(this.request);
this.serverResponse = new ServletServerHttpResponse(this.response);
}
@Test
public void accessManagerMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(null, Collections.emptyList())).withMessageContaining("AccessManager must not be null");
}
@Test
public void mappersMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(this.accessManager, null)).withMessageContaining("Mappers must not be null");
}
@Test
public void accessManagerVetoRequest() throws Exception {
given(this.accessManager.isAllowed(any(ServerHttpRequest.clreplaced))).willReturn(false);
HandlerMapper mapper = mock(HandlerMapper.clreplaced);
Handler handler = mock(Handler.clreplaced);
given(mapper.getHandler(any(ServerHttpRequest.clreplaced))).willReturn(handler);
Dispatcher dispatcher = new Dispatcher(this.accessManager, Collections.singleton(mapper));
dispatcher.handle(this.serverRequest, this.serverResponse);
verifyZeroInteractions(handler);
replacedertThat(this.response.getStatus()).isEqualTo(403);
}
@Test
public void accessManagerAllowRequest() throws Exception {
given(this.accessManager.isAllowed(any(ServerHttpRequest.clreplaced))).willReturn(true);
HandlerMapper mapper = mock(HandlerMapper.clreplaced);
Handler handler = mock(Handler.clreplaced);
given(mapper.getHandler(any(ServerHttpRequest.clreplaced))).willReturn(handler);
Dispatcher dispatcher = new Dispatcher(this.accessManager, Collections.singleton(mapper));
dispatcher.handle(this.serverRequest, this.serverResponse);
verify(handler).handle(this.serverRequest, this.serverResponse);
}
@Test
public void ordersMappers() throws Exception {
HandlerMapper mapper1 = mock(HandlerMapper.clreplaced, withSettings().extraInterfaces(Ordered.clreplaced));
HandlerMapper mapper2 = mock(HandlerMapper.clreplaced, withSettings().extraInterfaces(Ordered.clreplaced));
given(((Ordered) mapper1).getOrder()).willReturn(1);
given(((Ordered) mapper2).getOrder()).willReturn(2);
List<HandlerMapper> mappers = Arrays.asList(mapper2, mapper1);
Dispatcher dispatcher = new Dispatcher(AccessManager.PERMIT_ALL, mappers);
dispatcher.handle(this.serverRequest, this.serverResponse);
InOrder inOrder = inOrder(mapper1, mapper2);
inOrder.verify(mapper1).getHandler(this.serverRequest);
inOrder.verify(mapper2).getHandler(this.serverRequest);
}
}
18
View Source File : HttpRestartServer.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Handle a server request.
* @param request the request
* @param response the response
* @throws IOException in case of I/O errors
*/
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
try {
replacedert.state(request.getHeaders().getContentLength() > 0, "No content");
ObjectInputStream objectInputStream = new ObjectInputStream(request.getBody());
ClreplacedLoaderFiles files = (ClreplacedLoaderFiles) objectInputStream.readObject();
objectInputStream.close();
this.server.updateAndRestart(files);
response.setStatusCode(HttpStatus.OK);
} catch (Exception ex) {
logger.warn("Unable to handler restart server HTTP request", ex);
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
18
View Source File : UrlHandlerMapper.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Override
public Handler getHandler(ServerHttpRequest request) {
if (this.requestUri.equals(request.getURI().getPath())) {
return this.handler;
}
return null;
}
18
View Source File : HttpStatusHandler.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Override
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
response.setStatusCode(this.status);
}
18
View Source File : HttpHeaderAccessManager.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Override
public boolean isAllowed(ServerHttpRequest request) {
String providedSecret = request.getHeaders().getFirst(this.headerName);
return this.expectedSecret.equals(providedSecret);
}
18
View Source File : Dispatcher.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
private void handle(Handler handler, ServerHttpRequest request, ServerHttpResponse response) throws IOException {
if (!this.accessManager.isAllowed(request)) {
response.setStatusCode(HttpStatus.FORBIDDEN);
return;
}
handler.handle(request, response);
}
18
View Source File : TerminalHandShaker.java
License : Apache License 2.0
Project Creator : yile0906
License : Apache License 2.0
Project Creator : yile0906
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
super.afterHandshake(request, response, wsHandler, exception);
}
18
View Source File : WebSocketInterceptor.java
License : MIT License
Project Creator : yidao620c
License : MIT License
Project Creator : yidao620c
@Override
public void afterHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1, WebSocketHandler arg2, Exception arg3) {
logger.info("afterHandshake完成");
}
18
View Source File : HandshakeInterceptor.java
License : MIT License
Project Creator : xlui
License : MIT License
Project Creator : xlui
/**
* After websocket handshake
*/
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
log.info("HandshakeInterceptor: afterHandshake");
super.afterHandshake(request, response, wsHandler, ex);
}
18
View Source File : HandshakeInterceptor.java
License : MIT License
Project Creator : xlui
License : MIT License
Project Creator : xlui
/**
* Before websocket handshake
* You can put some data into {@code attributes} here, and get it in WebSocketHandler's session
* <p>
* WebSocket 握手前 —— 可以设置数据到 attributes 中,并在 WebSocketHandler 的 session 中获取
*/
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
log.info("HandshakeInterceptor: beforeHandshake");
log.info("Attributes: " + attributes.toString());
return super.beforeHandshake(request, response, wsHandler, attributes);
}
18
View Source File : WebSocketHandshakeInterceptor.java
License : Apache License 2.0
Project Creator : XiaoMi
License : Apache License 2.0
Project Creator : XiaoMi
@Nullable
private HttpSession getSession(ServerHttpRequest request) {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
return serverRequest.getServletRequest().getSession(false);
} else {
return null;
}
}
18
View Source File : WebSocketHandshakeInterceptor.java
License : Apache License 2.0
Project Creator : XiaoMi
License : Apache License 2.0
Project Creator : XiaoMi
@Override
public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
}
18
View Source File : WebSocketHandShakeInterceptor.java
License : Apache License 2.0
Project Creator : WeBankFinTech
License : Apache License 2.0
Project Creator : WeBankFinTech
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
// useless
}
18
View Source File : WebSocketHandShakeInterceptor.java
License : Apache License 2.0
Project Creator : WeBankFinTech
License : Apache License 2.0
Project Creator : WeBankFinTech
/**
* get request ip,and check it
*
* @param request request
* @return ip address
*/
private String getIpAddress(ServerHttpRequest request) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
String ip = servletRequest.getServletRequest().getHeader("X-Forwarded-For");
log.debug("ServerHttpRequest host: {}", ip);
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
log.debug("unknown ServerHttpRequest host");
return servletRequest.getRemoteAddress().getHostString();
}
String[] ips = ip.split(",");
for (String strIp : ips) {
if (!UNKNOWN.equalsIgnoreCase(strIp)) {
return strIp;
}
}
return "";
}
18
View Source File : MyPrincipalHandshakeHandler.java
License : MIT License
Project Creator : wayn111
License : MIT License
Project Creator : wayn111
/* @Lazy
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;*/
/**
* 重写determineUser用于填写用户认证信息
*
* @param request
* @param wsHandler
* @param attributes
* @return
*/
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
Object object = attributes.get(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (Objects.isNull(object)) {
log.error("未登录系统,禁止登录websocket!");
// simpMessagingTemplate.convertAndSend("/topic/judgeUserAuth", "您的登陆信息以过期,请重新登录!");
return null;
}
SimplePrincipalCollection simplePrincipalCollection = (SimplePrincipalCollection) object;
User user = (User) simplePrincipalCollection.getPrimaryPrincipal();
return user::getId;
}
18
View Source File : HttpSockJsSessionTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Unit tests for {@link AbstractHttpSockJsSession}.
*
* @author Rossen Stoyanchev
*/
public clreplaced HttpSockJsSessionTests extends AbstractSockJsSessionTests<TestAbstractHttpSockJsSession> {
protected ServerHttpRequest request;
protected ServerHttpResponse response;
protected MockHttpServletRequest servletRequest;
protected MockHttpServletResponse servletResponse;
private SockJsFrameFormat frameFormat;
@Override
protected TestAbstractHttpSockJsSession initSockJsSession() {
return new TestAbstractHttpSockJsSession(this.sockJsConfig, this.webSocketHandler, null);
}
@Before
public void setup() {
super.setUp();
this.frameFormat = new DefaultSockJsFrameFormat("%s");
this.servletResponse = new MockHttpServletResponse();
this.response = new ServletServerHttpResponse(this.servletResponse);
this.servletRequest = new MockHttpServletRequest();
this.servletRequest.setAsyncSupported(true);
this.request = new ServletServerHttpRequest(this.servletRequest);
}
@Test
public void handleInitialRequest() throws Exception {
this.session.handleInitialRequest(this.request, this.response, this.frameFormat);
replacedertEquals("hhh\no", this.servletResponse.getContentreplacedtring());
replacedertTrue(this.servletRequest.isAsyncStarted());
verify(this.webSocketHandler).afterConnectionEstablished(this.session);
}
@Test
public void handleSuccessiveRequest() throws Exception {
this.session.getMessageCache().add("x");
this.session.handleSuccessiveRequest(this.request, this.response, this.frameFormat);
replacedertTrue(this.servletRequest.isAsyncStarted());
replacedertTrue(this.session.wasHeartbeatScheduled());
replacedertTrue(this.session.wasCacheFlushed());
replacedertEquals("hhh\n", this.servletResponse.getContentreplacedtring());
verifyNoMoreInteractions(this.webSocketHandler);
}
static clreplaced TestAbstractHttpSockJsSession extends StreamingSockJsSession {
private IOException exceptionOnWriteFrame;
private boolean cacheFlushed;
private boolean heartbeatScheduled;
public TestAbstractHttpSockJsSession(SockJsServiceConfig config, WebSocketHandler handler, Map<String, Object> attributes) {
super("1", config, handler, attributes);
}
@Override
protected byte[] getPrelude(ServerHttpRequest request) {
return "hhh\n".getBytes();
}
public boolean wasCacheFlushed() {
return this.cacheFlushed;
}
public boolean wasHeartbeatScheduled() {
return this.heartbeatScheduled;
}
public void setExceptionOnWriteFrame(IOException exceptionOnWriteFrame) {
this.exceptionOnWriteFrame = exceptionOnWriteFrame;
}
@Override
protected void flushCache() {
this.cacheFlushed = true;
scheduleHeartbeat();
}
@Override
protected void scheduleHeartbeat() {
this.heartbeatScheduled = true;
}
@Override
protected synchronized void writeFrameInternal(SockJsFrame frame) throws IOException {
if (this.exceptionOnWriteFrame != null) {
throw this.exceptionOnWriteFrame;
} else {
super.writeFrameInternal(frame);
}
}
}
}
18
View Source File : HandlersBeanDefinitionParserTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
See More Examples