Java Code Examples for org.springframework.http.server.reactive.ServerHttpResponse#setStatusCode()
The following examples show how to use
org.springframework.http.server.reactive.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: CorsConfig.java From microservice-recruit with Apache License 2.0 | 6 votes |
@Bean public WebFilter corsFilter() { return (ServerWebExchange ctx, WebFilterChain chain) -> { ServerHttpRequest request = ctx.getRequest(); if (CorsUtils.isCorsRequest(request)) { HttpHeaders requestHeaders = request.getHeaders(); ServerHttpResponse response = ctx.getResponse(); HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod(); HttpHeaders headers = response.getHeaders(); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin()); headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders .getAccessControlRequestHeaders()); if(requestMethod != null){ headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name()); } headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*"); headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE); if (request.getMethod() == HttpMethod.OPTIONS) { response.setStatusCode(HttpStatus.OK); return Mono.empty(); } } return chain.filter(ctx); }; }
Example 2
Source File: CorsConfig.java From spring-cloud-sofastack-samples with Apache License 2.0 | 6 votes |
@Bean public WebFilter corsFilter() { return (ServerWebExchange ctx, WebFilterChain chain) -> { ServerHttpRequest request = ctx.getRequest(); if (CorsUtils.isCorsRequest(request)) { ServerHttpResponse response = ctx.getResponse(); HttpHeaders headers = response.getHeaders(); headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN); headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS); headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS); headers.add("Access-Control-Expose-Headers", ALLOWED_EXPOSE); headers.add("Access-Control-Allow-Credentials", "true"); if (request.getMethod() == HttpMethod.OPTIONS) { response.setStatusCode(HttpStatus.OK); return Mono.empty(); } } return chain.filter(ctx); }; }
Example 3
Source File: GatewayConfiguration.java From microservice-integration with MIT License | 6 votes |
@Bean public WebFilter corsFilter() { return (ServerWebExchange ctx, WebFilterChain chain) -> { ServerHttpRequest request = ctx.getRequest(); if (CorsUtils.isCorsRequest(request)) { ServerHttpResponse response = ctx.getResponse(); HttpHeaders headers = response.getHeaders(); headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN); headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS); headers.add("Access-Control-Max-Age", MAX_AGE); headers.add("Access-Control-Allow-Headers",ALLOWED_HEADERS); if (request.getMethod() == HttpMethod.OPTIONS) { response.setStatusCode(HttpStatus.OK); return Mono.empty(); } } return chain.filter(ctx); }; }
Example 4
Source File: CorsFilter.java From sophia_scaffolding with Apache License 2.0 | 6 votes |
@Override public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain chain) { ServerHttpRequest request = serverWebExchange.getRequest(); ServerHttpResponse response = serverWebExchange.getResponse(); HttpHeaders headers = response.getHeaders(); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE, PATCH"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*"); headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL); headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE); if (request.getMethod() == HttpMethod.OPTIONS) { response.setStatusCode(HttpStatus.OK); return Mono.empty(); } return chain.filter(serverWebExchange); }
Example 5
Source File: HttpWebHandlerAdapter.java From spring-analysis-note with MIT License | 6 votes |
private Mono<Void> handleUnresolvedError(ServerWebExchange exchange, Throwable ex) { ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); String logPrefix = exchange.getLogPrefix(); if (isDisconnectedClientError(ex)) { if (lostClientLogger.isTraceEnabled()) { lostClientLogger.trace(logPrefix + "Client went away", ex); } else if (lostClientLogger.isDebugEnabled()) { lostClientLogger.debug(logPrefix + "Client went away: " + ex + " (stacktrace at TRACE level for '" + DISCONNECTED_CLIENT_LOG_CATEGORY + "')"); } return Mono.empty(); } else if (response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR)) { logger.error(logPrefix + "500 Server Error for " + formatRequest(request), ex); return Mono.empty(); } else { // After the response is committed, propagate errors to the server... logger.error(logPrefix + "Error [" + ex + "] for " + formatRequest(request) + ", but ServerHttpResponse already committed (" + response.getStatusCode() + ")"); return Mono.error(ex); } }
Example 6
Source File: GraphQLController.java From graphql-java-examples with MIT License | 5 votes |
private Mono<Void> handleNormalResponse(ServerHttpResponse serverHttpResponse, ExecutionResult executionResult) throws IOException { Map<String, Object> result = executionResult.toSpecification(); serverHttpResponse.setStatusCode(HttpStatus.OK); HttpHeaders headers = serverHttpResponse.getHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); String body = objectMapper.writeValueAsString(result); return serverHttpResponse.writeWith(strToDataBuffer(body)); }
Example 7
Source File: DefaultServerResponseBuilder.java From spring-analysis-note with MIT License | 5 votes |
private void writeStatusAndHeaders(ServerHttpResponse response) { if (response instanceof AbstractServerHttpResponse) { ((AbstractServerHttpResponse) response).setStatusCodeValue(this.statusCode); } else { HttpStatus status = HttpStatus.resolve(this.statusCode); if (status == null) { throw new IllegalStateException( "Unresolvable HttpStatus for general ServerHttpResponse: " + this.statusCode); } response.setStatusCode(status); } copy(this.headers, response.getHeaders()); copy(this.cookies, response.getCookies()); }
Example 8
Source File: JWTFilter.java From spring-jwt-gateway with Apache License 2.0 | 5 votes |
private Mono<Void> onError(ServerWebExchange exchange, String err) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); response.getHeaders().add(WWW_AUTH_HEADER, this.formatErrorMsg(err)); return response.setComplete(); }
Example 9
Source File: CorsConfiguration.java From zuihou-admin-cloud with Apache License 2.0 | 5 votes |
/** * attention:简单跨域就是GET,HEAD和POST请求,但是POST请求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain * 反之,就是非简单跨域,此跨域有一个预检机制,说直白点,就是会发两次请求,一次OPTIONS请求,一次真正的请求 */ @Bean public WebFilter corsFilter() { return (ctx, chain) -> { ServerHttpRequest request = ctx.getRequest(); if (!CorsUtils.isCorsRequest(request)) { return chain.filter(ctx); } HttpHeaders requestHeaders = request.getHeaders(); ServerHttpResponse response = ctx.getResponse(); HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod(); HttpHeaders headers = response.getHeaders(); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin()); headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders()); if (requestMethod != null) { headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name()); } headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL); headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE); if (request.getMethod() == HttpMethod.OPTIONS) { response.setStatusCode(HttpStatus.OK); return Mono.empty(); } return chain.filter(ctx); }; }
Example 10
Source File: HttpBasicAuthenticationEntryPoint.java From spring-security-reactive with Apache License 2.0 | 5 votes |
@Override public <T> Mono<T> commence(ServerWebExchange exchange, AuthenticationException e) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); response.getHeaders().set("WWW-Authenticate", "Basic realm=\"Reactive\""); return Mono.empty(); }
Example 11
Source File: HttpWebHandlerAdapter.java From java-technology-stack with MIT License | 5 votes |
private Mono<Void> handleUnresolvedError(ServerWebExchange exchange, Throwable ex) { ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); String logPrefix = exchange.getLogPrefix(); if (isDisconnectedClientError(ex)) { if (lostClientLogger.isTraceEnabled()) { lostClientLogger.trace(logPrefix + "Client went away", ex); } else if (lostClientLogger.isDebugEnabled()) { lostClientLogger.debug(logPrefix + "Client went away: " + ex + " (stacktrace at TRACE level for '" + DISCONNECTED_CLIENT_LOG_CATEGORY + "')"); } return Mono.empty(); } else if (response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR)) { logger.error(logPrefix + "500 Server Error for " + formatRequest(request), ex); return Mono.empty(); } else { // After the response is committed, propagate errors to the server.. logger.error(logPrefix + "Error [" + ex + "] for " + formatRequest(request) + ", but ServerHttpResponse already committed (" + response.getStatusCode() + ")"); return Mono.error(ex); } }
Example 12
Source File: AuthFilter.java From SpringBlade with Apache License 2.0 | 5 votes |
private Mono<Void> unAuth(ServerHttpResponse resp, String msg) { resp.setStatusCode(HttpStatus.UNAUTHORIZED); resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8"); String result = ""; try { result = objectMapper.writeValueAsString(ResponseProvider.unAuth(msg)); } catch (JsonProcessingException e) { log.error(e.getMessage(), e); } DataBuffer buffer = resp.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8)); return resp.writeWith(Flux.just(buffer)); }
Example 13
Source File: ArmeriaReactiveWebServerFactoryTest.java From armeria with Apache License 2.0 | 5 votes |
@Override public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { response.setStatusCode(HttpStatus.OK); return request.getBody().map(data -> { // skip data, then throw an exception. throw HttpStatusException.of(com.linecorp.armeria.common.HttpStatus.BAD_REQUEST); }).doOnComplete(() -> { // An HTTP GET request doesn't have a body, so onComplete will be immediately called. throw HttpStatusException.of(com.linecorp.armeria.common.HttpStatus.BAD_REQUEST); }).then(); }
Example 14
Source File: SwaggerWelcome.java From springdoc-openapi with Apache License 2.0 | 5 votes |
/** * Redirect to ui mono. * * @param request the request * @param response the response * @return the mono */ @Operation(hidden = true) @GetMapping(SWAGGER_UI_PATH) public Mono<Void> redirectToUi(ServerHttpRequest request, ServerHttpResponse response) { String contextPath = this.fromCurrentContextPath(request); String sbUrl = this.buildUrl(contextPath, swaggerUiConfigParameters.getUiRootPath() + springDocConfigProperties.getWebjars().getPrefix() + SWAGGER_UI_URL); UriComponentsBuilder uriBuilder = getUriComponentsBuilder(sbUrl); response.setStatusCode(HttpStatus.TEMPORARY_REDIRECT); response.getHeaders().setLocation(URI.create(uriBuilder.build().encode().toString())); return response.setComplete(); }
Example 15
Source File: AdviceUtils.java From problem-spring-web with MIT License | 5 votes |
public static Mono<Void> setHttpResponse(final ResponseEntity<Problem> entity, final ServerWebExchange exchange, final ObjectMapper mapper) { final ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(entity.getStatusCode()); response.getHeaders().addAll(entity.getHeaders()); try { final DataBuffer buffer = response.bufferFactory() .wrap(mapper.writeValueAsBytes(entity.getBody())); return response.writeWith(Mono.just(buffer)) .doOnError(error -> DataBufferUtils.release(buffer)); } catch (final JsonProcessingException ex) { return Mono.error(ex); } }
Example 16
Source File: ResourceHttpMessageWriter.java From spring-analysis-note with MIT License | 4 votes |
@Override public Mono<Void> write(Publisher<? extends Resource> inputStream, @Nullable ResolvableType actualType, ResolvableType elementType, @Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response, Map<String, Object> hints) { HttpHeaders headers = response.getHeaders(); headers.set(HttpHeaders.ACCEPT_RANGES, "bytes"); List<HttpRange> ranges; try { ranges = request.getHeaders().getRange(); } catch (IllegalArgumentException ex) { response.setStatusCode(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); return response.setComplete(); } return Mono.from(inputStream).flatMap(resource -> { if (ranges.isEmpty()) { return writeResource(resource, elementType, mediaType, response, hints); } response.setStatusCode(HttpStatus.PARTIAL_CONTENT); List<ResourceRegion> regions = HttpRange.toResourceRegions(ranges, resource); MediaType resourceMediaType = getResourceMediaType(mediaType, resource, hints); if (regions.size() == 1){ ResourceRegion region = regions.get(0); headers.setContentType(resourceMediaType); long contentLength = lengthOf(resource); if (contentLength != -1) { long start = region.getPosition(); long end = start + region.getCount() - 1; end = Math.min(end, contentLength - 1); headers.add("Content-Range", "bytes " + start + '-' + end + '/' + contentLength); headers.setContentLength(end - start + 1); } return writeSingleRegion(region, response, hints); } else { String boundary = MimeTypeUtils.generateMultipartBoundaryString(); MediaType multipartType = MediaType.parseMediaType("multipart/byteranges;boundary=" + boundary); headers.setContentType(multipartType); Map<String, Object> allHints = Hints.merge(hints, ResourceRegionEncoder.BOUNDARY_STRING_HINT, boundary); return encodeAndWriteRegions(Flux.fromIterable(regions), resourceMediaType, response, allHints); } }); }
Example 17
Source File: ResourceHttpMessageWriter.java From java-technology-stack with MIT License | 4 votes |
@Override @SuppressWarnings("unchecked") public Mono<Void> write(Publisher<? extends Resource> inputStream, @Nullable ResolvableType actualType, ResolvableType elementType, @Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response, Map<String, Object> hints) { HttpHeaders headers = response.getHeaders(); headers.set(HttpHeaders.ACCEPT_RANGES, "bytes"); List<HttpRange> ranges; try { ranges = request.getHeaders().getRange(); } catch (IllegalArgumentException ex) { response.setStatusCode(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); return response.setComplete(); } return Mono.from(inputStream).flatMap(resource -> { if (ranges.isEmpty()) { return writeResource(resource, elementType, mediaType, response, hints); } response.setStatusCode(HttpStatus.PARTIAL_CONTENT); List<ResourceRegion> regions = HttpRange.toResourceRegions(ranges, resource); MediaType resourceMediaType = getResourceMediaType(mediaType, resource, hints); if (regions.size() == 1){ ResourceRegion region = regions.get(0); headers.setContentType(resourceMediaType); long contentLength = lengthOf(resource); if (contentLength != -1) { long start = region.getPosition(); long end = start + region.getCount() - 1; end = Math.min(end, contentLength - 1); headers.add("Content-Range", "bytes " + start + '-' + end + '/' + contentLength); headers.setContentLength(end - start + 1); } return writeSingleRegion(region, response, hints); } else { String boundary = MimeTypeUtils.generateMultipartBoundaryString(); MediaType multipartType = MediaType.parseMediaType("multipart/byteranges;boundary=" + boundary); headers.setContentType(multipartType); Map<String, Object> allHints = Hints.merge(hints, ResourceRegionEncoder.BOUNDARY_STRING_HINT, boundary); return encodeAndWriteRegions(Flux.fromIterable(regions), resourceMediaType, response, allHints); } }); }
Example 18
Source File: ValidateCodeGatewayFilter.java From smaker with GNU Lesser General Public License v3.0 | 4 votes |
@Override public GatewayFilter apply(Object config) { return (exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); // 不是登录请求,直接向下执行 if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath() , SecurityConstants.OAUTH_TOKEN_URL)) { return chain.filter(exchange); } // 刷新token,直接向下执行 String grantType = request.getQueryParams().getFirst("grant_type"); if (StrUtil.equals(SecurityConstants.REFRESH_TOKEN, grantType)) { return chain.filter(exchange); } // 终端设置不校验, 直接向下执行 try { String[] clientInfos = WebUtils.getClientId(request); if (filterIgnorePropertiesConfig.getClients().contains(clientInfos[0])) { return chain.filter(exchange); } //校验验证码 checkCode(request); } catch (Exception e) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED); try { return response.writeWith(Mono.just(response.bufferFactory() .wrap(objectMapper.writeValueAsBytes( SmakerResult.builder().msg(e.getMessage()) .code(CommonConstants.FAIL).build())))); } catch (JsonProcessingException e1) { log.error("对象输出异常", e1); } } return chain.filter(exchange); }; }
Example 19
Source File: HttpResponseMapper.java From charon-spring-boot-starter with Apache License 2.0 | 4 votes |
private void setStatus(ClientResponse clientResponse, ServerHttpResponse response) { response.setStatusCode(clientResponse.statusCode()); }
Example 20
Source File: WebFluxJettyMinimalIntegrationTest.java From java-spring-web with Apache License 2.0 | 4 votes |
private static Mono<Void> handler(final ServerWebExchange serverWebExchange) { final ServerHttpResponse response = serverWebExchange.getResponse(); response.setStatusCode(HttpStatus.OK); return response.writeWith(Mono.just(new DefaultDataBufferFactory().wrap("Hello World!\n".getBytes()))); }