Java Code Examples for org.springframework.http.server.reactive.ServerHttpResponse#setComplete()

The following examples show how to use org.springframework.http.server.reactive.ServerHttpResponse#setComplete() . 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: JwtSsoTokenGatewayFilterFactory.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
protected Mono<Void> handleAuthenticationFailure(ServerWebExchange exchange, String errorMsg) {
    CommonResponseDto responseDto = CommonResponseDto.error(errorMsg);
    ServerHttpResponse response = exchange.getResponse();
    try {
        byte[] bits = objectMapper.writeValueAsBytes(responseDto);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE, headerValue);

        return response.writeWith(Mono.just(buffer));
    } catch (JsonProcessingException e) {
        log.debug("failed to process json", e);
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }
}
 
Example 2
Source File: SwaggerWelcome.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * 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 3
Source File: JWTFilter.java    From spring-jwt-gateway with Apache License 2.0 5 votes vote down vote up
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 4
Source File: AuthorizeFilter.java    From spring-cloud-microservice with MIT License 5 votes vote down vote up
/**
 * 全局过滤教研token,生产环境可以用数据库
 *
 * @param exchange
 * @param chain
 * @return
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    HttpHeaders headers = request.getHeaders();
    String token = headers.getFirst(AUTHORIZE_TOKEN);
    String uid = headers.getFirst(AUTHORIZE_UID);
    if (token == null) {
        token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
    }
    if (uid == null) {
        uid = request.getQueryParams().getFirst(AUTHORIZE_UID);
    }

    ServerHttpResponse response = exchange.getResponse();
    if (StringUtils.isEmpty(token) || StringUtils.isEmpty(uid)) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
    String authToken = stringRedisTemplate.opsForValue().get(uid);
    if (authToken == null || !authToken.equals(token)) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    return chain.filter(exchange);
}
 
Example 5
Source File: RedirectToGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public GatewayFilter apply(HttpStatusHolder httpStatus, URI uri) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			if (!exchange.getResponse().isCommitted()) {
				setResponseStatus(exchange, httpStatus);

				final ServerHttpResponse response = exchange.getResponse();
				response.getHeaders().set(HttpHeaders.LOCATION, uri.toString());
				return response.setComplete();
			}
			return Mono.empty();
		}

		@Override
		public String toString() {
			String status;
			if (httpStatus.getHttpStatus() != null) {
				status = String.valueOf(httpStatus.getHttpStatus().value());
			}
			else {
				status = httpStatus.getStatus().toString();
			}
			return filterToStringCreator(RedirectToGatewayFilterFactory.this)
					.append(status, uri).toString();
		}
	};
}
 
Example 6
Source File: ResourceHttpMessageWriter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@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 7
Source File: ResourceHttpMessageWriter.java    From java-technology-stack with MIT License 4 votes vote down vote up
@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);
		}
	});
}