org.springframework.http.server.ServerHttpRequest Java Examples
The following examples show how to use
org.springframework.http.server.ServerHttpRequest.
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: HtmlFileTransportHandler.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response, AbstractHttpSockJsSession sockJsSession) throws SockJsException { String callback = getCallbackParam(request); if (!StringUtils.hasText(callback)) { response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); try { response.getBody().write("\"callback\" parameter required".getBytes(UTF8_CHARSET)); } catch (IOException ex) { sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR); throw new SockJsTransportFailureException("Failed to write to response", sockJsSession.getId(), ex); } return; } super.handleRequestInternal(request, response, sockJsSession); }
Example #2
Source File: PageResponseBodyAdvisor.java From spring-boot-jpa with Apache License 2.0 | 6 votes |
@Override protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { Page<?> page = ((Page<?>) bodyContainer.getValue()); response.getHeaders().add(CUSTOM_HEADER_META_PAGINATION, String.format(PAGE_METADATA_FMT, page.getNumber(), page.getSize(), page.getTotalElements(), page.getTotalPages(), page.isFirst(), page.isLast())); getHttpHeaderLinksString(request, page) .filter(StringUtils::isNotEmpty) .ifPresent(s -> response.getHeaders().add(HttpHeaders.LINK, s)); // finally, strip out the actual content and replace it as the body value bodyContainer.setValue(page.getContent()); }
Example #3
Source File: InstancesProxyController.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@ResponseBody @RequestMapping(path = APPLICATION_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS }) public Flux<InstanceWebProxy.InstanceResponse> endpointProxy( @PathVariable("applicationName") String applicationName, HttpServletRequest servletRequest) { ServerHttpRequest request = new ServletServerHttpRequest(servletRequest); String endpointLocalPath = this.getEndpointLocalPath(this.adminContextPath + APPLICATION_MAPPED_PATH, servletRequest); URI uri = UriComponentsBuilder.fromPath(endpointLocalPath).query(request.getURI().getRawQuery()).build(true) .toUri(); Flux<DataBuffer> cachedBody = DataBufferUtils.readInputStream(request::getBody, this.bufferFactory, 4096) .cache(); return this.instanceWebProxy.forward(this.registry.getInstances(applicationName), uri, request.getMethod(), this.httpHeadersFilter.filterHeaders(request.getHeaders()), BodyInserters.fromDataBuffers(cachedBody)); }
Example #4
Source File: WebSphereRequestUpgradeStrategy.java From spring-analysis-note with MIT License | 6 votes |
@Override public void upgradeInternal(ServerHttpRequest httpRequest, ServerHttpResponse httpResponse, @Nullable String selectedProtocol, List<Extension> selectedExtensions, Endpoint endpoint) throws HandshakeFailureException { HttpServletRequest request = getHttpServletRequest(httpRequest); HttpServletResponse response = getHttpServletResponse(httpResponse); StringBuffer requestUrl = request.getRequestURL(); String path = request.getRequestURI(); // shouldn't matter Map<String, String> pathParams = Collections.<String, String> emptyMap(); ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(path, endpoint); endpointConfig.setSubprotocols(Collections.singletonList(selectedProtocol)); endpointConfig.setExtensions(selectedExtensions); try { ServerContainer container = getContainer(request); upgradeMethod.invoke(container, request, response, endpointConfig, pathParams); } catch (Exception ex) { throw new HandshakeFailureException( "Servlet request failed to upgrade to WebSocket for " + requestUrl, ex); } }
Example #5
Source File: AbstractSockJsService.java From spring-analysis-note with MIT License | 6 votes |
@Override public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { if (request.getMethod() == HttpMethod.GET) { addNoCacheHeaders(response); if (checkOrigin(request, response)) { response.getHeaders().setContentType(new MediaType("application", "json", StandardCharsets.UTF_8)); String content = String.format( INFO_CONTENT, random.nextInt(), isSessionCookieNeeded(), isWebSocketEnabled()); response.getBody().write(content.getBytes()); } } else if (request.getMethod() == HttpMethod.OPTIONS) { if (checkOrigin(request, response)) { addCacheHeaders(response); response.setStatusCode(HttpStatus.NO_CONTENT); } } else { sendMethodNotAllowed(response, HttpMethod.GET, HttpMethod.OPTIONS); } }
Example #6
Source File: HttpSessionHandshakeInterceptor.java From spring-analysis-note with MIT License | 6 votes |
@Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { HttpSession session = getSession(request); if (session != null) { if (isCopyHttpSessionId()) { attributes.put(HTTP_SESSION_ID_ATTR_NAME, session.getId()); } Enumeration<String> names = session.getAttributeNames(); while (names.hasMoreElements()) { String name = names.nextElement(); if (isCopyAllAttributes() || getAttributeNames().contains(name)) { attributes.put(name, session.getAttribute(name)); } } } return true; }
Example #7
Source File: WebUtilsTests.java From java-technology-stack with MIT License | 6 votes |
private void testWithXForwardedHeaders(String serverName, int port, String forwardedProto, String forwardedHost, int forwardedPort, String originHeader) throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName(serverName); if (port != -1) { request.setServerPort(port); } if (forwardedProto != null) { request.addHeader("X-Forwarded-Proto", forwardedProto); } if (forwardedHost != null) { request.addHeader("X-Forwarded-Host", forwardedHost); } if (forwardedPort != -1) { request.addHeader("X-Forwarded-Port", String.valueOf(forwardedPort)); } request.addHeader(HttpHeaders.ORIGIN, originHeader); HttpServletRequest requestToUse = adaptFromForwardedHeaders(request); ServerHttpRequest httpRequest = new ServletServerHttpRequest(requestToUse); assertTrue(WebUtils.isSameOrigin(httpRequest)); }
Example #8
Source File: WebSocketHandShakeInterceptor.java From WeEvent with Apache License 2.0 | 6 votes |
/** * 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 ""; }
Example #9
Source File: AbstractSockJsService.java From spring-analysis-note with MIT License | 6 votes |
protected boolean checkOrigin(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods) throws IOException { if (WebUtils.isSameOrigin(request)) { return true; } if (!WebUtils.isValidOrigin(request, this.allowedOrigins)) { if (logger.isWarnEnabled()) { logger.warn("Origin header value '" + request.getHeaders().getOrigin() + "' not allowed."); } response.setStatusCode(HttpStatus.FORBIDDEN); return false; } return true; }
Example #10
Source File: JSONPResponseBodyAdvice.java From uavstack with Apache License 2.0 | 6 votes |
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { ResponseJSONP responseJsonp = returnType.getMethodAnnotation(ResponseJSONP.class); if(responseJsonp == null){ responseJsonp = returnType.getContainingClass().getAnnotation(ResponseJSONP.class); } HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); String callbackMethodName = servletRequest.getParameter(responseJsonp.callback()); if (!IOUtils.isValidJsonpQueryParam(callbackMethodName)) { if (logger.isDebugEnabled()) { logger.debug("Invalid jsonp parameter value:" + callbackMethodName); } callbackMethodName = null; } JSONPObject jsonpObject = new JSONPObject(callbackMethodName); jsonpObject.addParameter(body); beforeBodyWriteInternal(jsonpObject, selectedContentType, returnType, request, response); return jsonpObject; }
Example #11
Source File: ResponseMessageAdviser.java From flow-platform-x with Apache License 2.0 | 6 votes |
@Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { if (body instanceof Resource) { return body; } if (MediaType.TEXT_PLAIN.equals(selectedContentType)) { return body; } return new ResponseMessage<>(StatusCode.OK, SUCCESS_MESSAGE, body); }
Example #12
Source File: HandshakeInterceptorChain.java From spring4-understanding with Apache License 2.0 | 6 votes |
public boolean applyBeforeHandshake(ServerHttpRequest request, ServerHttpResponse response, Map<String, Object> attributes) throws Exception { for (int i = 0; i < this.interceptors.size(); i++) { HandshakeInterceptor interceptor = this.interceptors.get(i); if (!interceptor.beforeHandshake(request, response, this.wsHandler, attributes)) { if (logger.isDebugEnabled()) { logger.debug(interceptor + " returns false from beforeHandshake - precluding handshake"); } applyAfterHandshake(request, response, null); return false; } this.interceptorIndex = i; } return true; }
Example #13
Source File: HandshakeInterceptorChain.java From spring-analysis-note with MIT License | 6 votes |
public boolean applyBeforeHandshake(ServerHttpRequest request, ServerHttpResponse response, Map<String, Object> attributes) throws Exception { for (int i = 0; i < this.interceptors.size(); i++) { HandshakeInterceptor interceptor = this.interceptors.get(i); if (!interceptor.beforeHandshake(request, response, this.wsHandler, attributes)) { if (logger.isDebugEnabled()) { logger.debug(interceptor + " returns false from beforeHandshake - precluding handshake"); } applyAfterHandshake(request, response, null); return false; } this.interceptorIndex = i; } return true; }
Example #14
Source File: AbstractHttpSockJsSession.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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); } } }
Example #15
Source File: AbstractMappingJacksonResponseBodyAdvice.java From spring-analysis-note with MIT License | 5 votes |
@Override @Nullable public final Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response) { if (body == null) { return null; } MappingJacksonValue container = getOrCreateContainer(body); beforeBodyWriteInternal(container, contentType, returnType, request, response); return container; }
Example #16
Source File: HttpSessionHandshakeInterceptor.java From spring-analysis-note with MIT License | 5 votes |
@Nullable private HttpSession getSession(ServerHttpRequest request) { if (request instanceof ServletServerHttpRequest) { ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request; return serverRequest.getServletRequest().getSession(isCreateSession()); } return null; }
Example #17
Source File: HtmlFileTransportHandler.java From spring-analysis-note with MIT License | 5 votes |
@Override protected byte[] getPrelude(ServerHttpRequest request) { // We already validated the parameter above... String callback = getCallbackParam(request); String html = String.format(PARTIAL_HTML_CONTENT, callback); return html.getBytes(StandardCharsets.UTF_8); }
Example #18
Source File: WebSocketTransportHandler.java From spring-analysis-note with MIT License | 5 votes |
@Override public void handleRequest(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, SockJsSession wsSession) throws SockJsException { WebSocketServerSockJsSession sockJsSession = (WebSocketServerSockJsSession) wsSession; try { wsHandler = new SockJsWebSocketHandler(getServiceConfig(), wsHandler, sockJsSession); this.handshakeHandler.doHandshake(request, response, wsHandler, sockJsSession.getAttributes()); } catch (Throwable ex) { sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR); throw new SockJsTransportFailureException("WebSocket handshake failure", wsSession.getId(), ex); } }
Example #19
Source File: RequestResponseBodyAdviceChainTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public String beforeBodyWrite(String body, MethodParameter returnType, MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response) { return body + "-TargetedControllerAdvice"; }
Example #20
Source File: StreamingSockJsSession.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response, boolean initialRequest) throws IOException { byte[] prelude = getPrelude(request); Assert.notNull(prelude); response.getBody().write(prelude); response.flush(); if (initialRequest) { writeFrame(SockJsFrame.openFrame()); } flushCache(); }
Example #21
Source File: WebSocketTransportHandler.java From java-technology-stack with MIT License | 5 votes |
@Override public void handleRequest(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, SockJsSession wsSession) throws SockJsException { WebSocketServerSockJsSession sockJsSession = (WebSocketServerSockJsSession) wsSession; try { wsHandler = new SockJsWebSocketHandler(getServiceConfig(), wsHandler, sockJsSession); this.handshakeHandler.doHandshake(request, response, wsHandler, sockJsSession.getAttributes()); } catch (Throwable ex) { sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR); throw new SockJsTransportFailureException("WebSocket handshake failure", wsSession.getId(), ex); } }
Example #22
Source File: WxMessageResponseBodyAdvice.java From FastBootWeixin with Apache License 2.0 | 5 votes |
@Override public WxMessage beforeBodyWrite(WxMessage body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { if (!(request instanceof ServletServerHttpRequest) || body == null) { return body; } HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); WxRequest wxRequest = WxWebUtils.getWxRequestFromRequest(servletRequest); return wxMessageProcessor.process(new WxRequestMessageParameter(wxRequest), body); }
Example #23
Source File: HandshakeInterceptorChain.java From spring4-understanding with Apache License 2.0 | 5 votes |
public void applyAfterHandshake(ServerHttpRequest request, ServerHttpResponse response, Exception failure) { for (int i = this.interceptorIndex; i >= 0; i--) { HandshakeInterceptor interceptor = this.interceptors.get(i); try { interceptor.afterHandshake(request, response, this.wsHandler, failure); } catch (Throwable ex) { if (logger.isWarnEnabled()) { logger.warn(interceptor + " threw exception in afterHandshake: " + ex); } } } }
Example #24
Source File: ParamEncryptResponseBodyAdvice.java From open-capacity-platform with Apache License 2.0 | 5 votes |
@Override public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { if (null != body) { boolean encode = false; if (methodParameter.getMethod() .isAnnotationPresent((Class<? extends Annotation>) SecurityParameter.class)) { final SecurityParameter serializedField = (SecurityParameter) methodParameter .getMethodAnnotation((Class) SecurityParameter.class); encode = serializedField.outEncode(); } if (encode) { log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密"); final ObjectMapper objectMapper = new ObjectMapper(); try { final String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body); return DESHelper.encrypt(result); } catch (Exception e) { log.info( "对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密出现异常:" + e.getMessage()); } } } return body; }
Example #25
Source File: RequestResponseBodyAdviceChainTests.java From java-technology-stack with MIT License | 5 votes |
@Override public String beforeBodyWrite(String body, MethodParameter returnType, MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response) { return body + "-MyControllerAdvice"; }
Example #26
Source File: RequestResponseBodyAdviceChain.java From java-technology-stack with MIT License | 5 votes |
@SuppressWarnings("unchecked") @Nullable private <T> Object processBody(@Nullable Object body, MethodParameter returnType, MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response) { for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) { if (advice.supports(returnType, converterType)) { body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType, contentType, converterType, request, response); } } return body; }
Example #27
Source File: AbstractStandardUpgradeStrategy.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public List<WebSocketExtension> getSupportedExtensions(ServerHttpRequest request) { if (this.extensions == null) { HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); this.extensions = getInstalledExtensions(getContainer(servletRequest)); } return this.extensions; }
Example #28
Source File: ApiResultAdvice.java From summerframework with Apache License 2.0 | 5 votes |
@Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { Object result = apiResultTransformer.changeBody(body, returnType, selectedContentType, selectedConverterType, request, response); if (result != null && result instanceof ApiResultWrapper) { ApiResultWrapper apiResultWrapper = (ApiResultWrapper) result; result= apiResponseFilter.filter(apiResultWrapper,(k,v)->response.getHeaders().set(k.toString(),v.toString())); } return result; }
Example #29
Source File: SockJsHttpRequestHandler.java From spring-analysis-note with MIT License | 5 votes |
@Override public void handleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { ServerHttpRequest request = new ServletServerHttpRequest(servletRequest); ServerHttpResponse response = new ServletServerHttpResponse(servletResponse); try { this.sockJsService.handleRequest(request, response, getSockJsPath(servletRequest), this.webSocketHandler); } catch (Throwable ex) { throw new SockJsException("Uncaught failure in SockJS request, uri=" + request.getURI(), ex); } }
Example #30
Source File: InstancesProxyController.java From spring-boot-admin with Apache License 2.0 | 5 votes |
@ResponseBody @RequestMapping(path = INSTANCE_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS }) public Mono<Void> endpointProxy(@PathVariable("instanceId") String instanceId, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException { ServerHttpRequest request = new ServletServerHttpRequest(servletRequest); String endpointLocalPath = this.getEndpointLocalPath(this.adminContextPath + INSTANCE_MAPPED_PATH, servletRequest); URI uri = UriComponentsBuilder.fromPath(endpointLocalPath).query(request.getURI().getRawQuery()).build(true) .toUri(); // We need to explicitly block until the headers are recieved and write them // before the async dispatch. // otherwise the FrameworkServlet will add wrong Allow header for OPTIONS request Flux<DataBuffer> requestBody = DataBufferUtils.readInputStream(request::getBody, this.bufferFactory, 4096); ClientResponse clientResponse = this.instanceWebProxy .forward(this.registry.getInstance(InstanceId.of(instanceId)), uri, request.getMethod(), this.httpHeadersFilter.filterHeaders(request.getHeaders()), BodyInserters.fromDataBuffers(requestBody)) .block(); ServerHttpResponse response = new ServletServerHttpResponse(servletResponse); response.setStatusCode(clientResponse.statusCode()); response.getHeaders().addAll(this.httpHeadersFilter.filterHeaders(clientResponse.headers().asHttpHeaders())); OutputStream responseBody = response.getBody(); response.flush(); return clientResponse.body(BodyExtractors.toDataBuffers()).window(1) .concatMap((body) -> writeAndFlush(body, responseBody)).then(); }