Java Code Examples for org.springframework.http.server.ServerHttpResponse#setStatusCode()
The following examples show how to use
org.springframework.http.server.ServerHttpResponse#setStatusCode() .
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: JsonpPollingTransportHandler.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response, AbstractHttpSockJsSession sockJsSession) throws SockJsException { try { String callback = getCallbackParam(request); if (!StringUtils.hasText(callback)) { response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); response.getBody().write("\"callback\" parameter required".getBytes(UTF8_CHARSET)); return; } } catch (Throwable ex) { sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR); throw new SockJsTransportFailureException("Failed to send error", sockJsSession.getId(), ex); } super.handleRequestInternal(request, response, sockJsSession); }
Example 2
Source File: AbstractSockJsService.java From java-technology-stack 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 3
Source File: AbstractHandshakeHandler.java From spring-analysis-note with MIT License | 6 votes |
protected void handleWebSocketVersionNotSupported(ServerHttpRequest request, ServerHttpResponse response) { if (logger.isErrorEnabled()) { String version = request.getHeaders().getFirst("Sec-WebSocket-Version"); logger.error("Handshake failed due to unsupported WebSocket version: " + version + ". Supported versions: " + Arrays.toString(getSupportedVersions())); } response.setStatusCode(HttpStatus.UPGRADE_REQUIRED); response.getHeaders().set(WebSocketHttpHeaders.SEC_WEBSOCKET_VERSION, StringUtils.arrayToCommaDelimitedString(getSupportedVersions())); }
Example 4
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 5
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 6
Source File: HtmlFileTransportHandler.java From spring-analysis-note with MIT License | 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(StandardCharsets.UTF_8)); } 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 7
Source File: AbstractSockJsService.java From spring-analysis-note with MIT License | 5 votes |
@Override public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException { if (request.getMethod() != HttpMethod.GET) { sendMethodNotAllowed(response, HttpMethod.GET); return; } String content = String.format(IFRAME_CONTENT, getSockJsClientLibraryUrl()); byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8); StringBuilder builder = new StringBuilder("\"0"); DigestUtils.appendMd5DigestAsHex(contentBytes, builder); builder.append('"'); String etagValue = builder.toString(); List<String> ifNoneMatch = request.getHeaders().getIfNoneMatch(); if (!CollectionUtils.isEmpty(ifNoneMatch) && ifNoneMatch.get(0).equals(etagValue)) { response.setStatusCode(HttpStatus.NOT_MODIFIED); return; } response.getHeaders().setContentType(new MediaType("text", "html", StandardCharsets.UTF_8)); response.getHeaders().setContentLength(contentBytes.length); // No cache in order to check every time if IFrame are authorized addNoCacheHeaders(response); response.getHeaders().setETag(etagValue); response.getBody().write(contentBytes); }
Example 8
Source File: AbstractHandshakeHandler.java From java-technology-stack with MIT License | 5 votes |
protected void handleInvalidUpgradeHeader(ServerHttpRequest request, ServerHttpResponse response) throws IOException { if (logger.isErrorEnabled()) { logger.error("Handshake failed due to invalid Upgrade header: " + request.getHeaders().getUpgrade()); } response.setStatusCode(HttpStatus.BAD_REQUEST); response.getBody().write("Can \"Upgrade\" only to \"WebSocket\".".getBytes(StandardCharsets.UTF_8)); }
Example 9
Source File: AbstractHttpReceivingTransportHandler.java From java-technology-stack with MIT License | 5 votes |
private void handleReadError(ServerHttpResponse response, String error, String sessionId) { try { response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); response.getBody().write(error.getBytes(StandardCharsets.UTF_8)); } catch (IOException ex) { throw new SockJsException("Failed to send error: " + error, sessionId, ex); } }
Example 10
Source File: OriginHandshakeInterceptor.java From java-technology-stack with MIT License | 5 votes |
@Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { if (!WebUtils.isSameOrigin(request) && !WebUtils.isValidOrigin(request, this.allowedOrigins)) { response.setStatusCode(HttpStatus.FORBIDDEN); if (logger.isDebugEnabled()) { logger.debug("Handshake request rejected, Origin header value " + request.getHeaders().getOrigin() + " not allowed"); } return false; } return true; }
Example 11
Source File: OriginHandshakeInterceptor.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { if (!WebUtils.isSameOrigin(request) && !WebUtils.isValidOrigin(request, this.allowedOrigins)) { response.setStatusCode(HttpStatus.FORBIDDEN); if (logger.isDebugEnabled()) { logger.debug("Handshake request rejected, Origin header value " + request.getHeaders().getOrigin() + " not allowed"); } return false; } return true; }
Example 12
Source File: CustomAuthenticationEntryPoint.java From spring-glee-o-meter with GNU General Public License v3.0 | 5 votes |
@Override public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException { ApiError apiError = new ApiError(UNAUTHORIZED); apiError.setMessage(e.getMessage()); apiError.setDebugMessage(e.getMessage()); ServerHttpResponse outputMessage = new ServletServerHttpResponse(httpServletResponse); outputMessage.setStatusCode(HttpStatus.UNAUTHORIZED); messageConverter.write(mapper.writeValueAsString(apiError), MediaType.APPLICATION_JSON, outputMessage); }
Example 13
Source File: AbstractHandshakeHandler.java From spring4-understanding with Apache License 2.0 | 5 votes |
protected void handleWebSocketVersionNotSupported(ServerHttpRequest request, ServerHttpResponse response) { if (logger.isErrorEnabled()) { String version = request.getHeaders().getFirst("Sec-WebSocket-Version"); logger.error("Handshake failed due to unsupported WebSocket version: " + version + ". Supported versions: " + Arrays.toString(getSupportedVersions())); } response.setStatusCode(HttpStatus.UPGRADE_REQUIRED); response.getHeaders().set(WebSocketHttpHeaders.SEC_WEBSOCKET_VERSION, StringUtils.arrayToCommaDelimitedString(getSupportedVersions())); }
Example 14
Source File: AbstractHandshakeHandler.java From spring-analysis-note with MIT License | 5 votes |
protected void handleInvalidConnectHeader(ServerHttpRequest request, ServerHttpResponse response) throws IOException { if (logger.isErrorEnabled()) { logger.error("Handshake failed due to invalid Connection header " + request.getHeaders().getConnection()); } response.setStatusCode(HttpStatus.BAD_REQUEST); response.getBody().write("\"Connection\" must be \"upgrade\".".getBytes(StandardCharsets.UTF_8)); }
Example 15
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(); }
Example 16
Source File: OriginHandshakeInterceptor.java From spring-analysis-note with MIT License | 5 votes |
@Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { if (!WebUtils.isSameOrigin(request) && !WebUtils.isValidOrigin(request, this.allowedOrigins)) { response.setStatusCode(HttpStatus.FORBIDDEN); if (logger.isDebugEnabled()) { logger.debug("Handshake request rejected, Origin header value " + request.getHeaders().getOrigin() + " not allowed"); } return false; } return true; }
Example 17
Source File: AbstractHandshakeHandler.java From java-technology-stack with MIT License | 5 votes |
protected void handleInvalidConnectHeader(ServerHttpRequest request, ServerHttpResponse response) throws IOException { if (logger.isErrorEnabled()) { logger.error("Handshake failed due to invalid Connection header " + request.getHeaders().getConnection()); } response.setStatusCode(HttpStatus.BAD_REQUEST); response.getBody().write("\"Connection\" must be \"upgrade\".".getBytes(StandardCharsets.UTF_8)); }
Example 18
Source File: AbstractSockJsService.java From java-technology-stack with MIT License | 4 votes |
protected void sendMethodNotAllowed(ServerHttpResponse response, HttpMethod... httpMethods) { logger.warn("Sending Method Not Allowed (405)"); response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED); response.getHeaders().setAllow(new LinkedHashSet<>(Arrays.asList(httpMethods))); }
Example 19
Source File: AbstractSockJsService.java From spring4-understanding with Apache License 2.0 | 4 votes |
protected void sendMethodNotAllowed(ServerHttpResponse response, HttpMethod... httpMethods) { logger.warn("Sending Method Not Allowed (405)"); response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED); response.getHeaders().setAllow(new HashSet<HttpMethod>(Arrays.asList(httpMethods))); }
Example 20
Source File: DefaultCorsProcessor.java From lams with GNU General Public License v2.0 | 2 votes |
/** * Invoked when one of the CORS checks failed. * The default implementation sets the response status to 403 and writes * "Invalid CORS request" to the response. */ protected void rejectRequest(ServerHttpResponse response) throws IOException { response.setStatusCode(HttpStatus.FORBIDDEN); response.getBody().write("Invalid CORS request".getBytes(UTF8_CHARSET)); }