org.springframework.http.server.reactive.ServerHttpResponse Java Examples

The following examples show how to use org.springframework.http.server.reactive.ServerHttpResponse. 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: CorsFilter.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: DefaultClientResponse.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public <T> T body(BodyExtractor<T, ? super ClientHttpResponse> extractor) {
	return extractor.extract(this.response, new BodyExtractor.Context() {
		@Override
		public List<HttpMessageReader<?>> messageReaders() {
			return strategies.messageReaders();
		}
		@Override
		public Optional<ServerHttpResponse> serverResponse() {
			return Optional.empty();
		}
		@Override
		public Map<String, Object> hints() {
			return Hints.from(Hints.LOG_PREFIX_HINT, logPrefix);
		}
	});
}
 
Example #3
Source File: DefaultCorsProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void preflightRequestCredentials() throws Exception {
	ServerWebExchange exchange = MockServerWebExchange.from(preFlightRequest()
			.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
			.header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1"));

	this.conf.addAllowedOrigin("http://domain1.com");
	this.conf.addAllowedOrigin("http://domain2.com");
	this.conf.addAllowedOrigin("http://domain3.com");
	this.conf.addAllowedHeader("Header1");
	this.conf.setAllowCredentials(true);

	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertEquals("http://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertNull(response.getStatusCode());
}
 
Example #4
Source File: WingtipsSpringWebfluxWebFilterTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void Builder_withTagAndNamingStrategy_works_as_expected(boolean valueIsNull) {
    // given
    WingtipsSpringWebfluxWebFilter.Builder origBuilder = new WingtipsSpringWebfluxWebFilter.Builder();
    HttpTagAndSpanNamingStrategy<ServerWebExchange, ServerHttpResponse> expectedValue =
        (valueIsNull) ? null : tagAndNamingStrategy;

    // when
    WingtipsSpringWebfluxWebFilter.Builder result = origBuilder.withTagAndNamingStrategy(expectedValue);

    // then
    assertThat(result).isSameAs(origBuilder);
    assertThat(origBuilder.tagAndNamingStrategy).isEqualTo(expectedValue);
}
 
Example #5
Source File: DefaultCorsProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void actualRequestCredentials() throws Exception {
	ServerWebExchange exchange = actualRequest();
	this.conf.addAllowedOrigin("https://domain1.com");
	this.conf.addAllowedOrigin("https://domain2.com");
	this.conf.addAllowedOrigin("http://domain3.com");
	this.conf.setAllowCredentials(true);
	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertNull(response.getStatusCode());
}
 
Example #6
Source File: DefaultCorsProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void actualRequestCredentialsWithOriginWildcard() throws Exception {
	ServerWebExchange exchange = actualRequest();
	this.conf.addAllowedOrigin("*");
	this.conf.setAllowCredentials(true);
	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertNull(response.getStatusCode());
}
 
Example #7
Source File: CorsConfig.java    From microservice-recruit with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: NettyRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void setResponseStatus(HttpClientResponse clientResponse,
		ServerHttpResponse response) {
	HttpStatus status = HttpStatus.resolve(clientResponse.status().code());
	if (status != null) {
		response.setStatusCode(status);
	}
	else {
		while (response instanceof ServerHttpResponseDecorator) {
			response = ((ServerHttpResponseDecorator) response).getDelegate();
		}
		if (response instanceof AbstractServerHttpResponse) {
			((AbstractServerHttpResponse) response)
					.setStatusCodeValue(clientResponse.status().code());
		}
		else {
			// TODO: log warning here, not throw error?
			throw new IllegalStateException("Unable to set status code "
					+ clientResponse.status().code() + " on response of type "
					+ response.getClass().getName());
		}
	}
}
 
Example #9
Source File: AccessLogFilter.java    From open-cloud with MIT License 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpResponse response = exchange.getResponse();
    DataBufferFactory bufferFactory = response.bufferFactory();
    ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
        @Override
        public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
            if (body instanceof Flux) {
                Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                return super.writeWith(fluxBody.map(dataBuffer -> {
                    // probably should reuse buffers
                    byte[] content = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(content);
                    //释放掉内存
                    DataBufferUtils.release(dataBuffer);
                    return bufferFactory.wrap(content);
                }));
            }
            // if body is not a flux. never got there.
            return super.writeWith(body);
        }
    };
    return chain.filter(exchange.mutate().response(decoratedResponse).build()).then(Mono.fromRunnable(()->{
        accessLogService.sendLog(exchange, null);
    }));
}
 
Example #10
Source File: RateCheckGatewayFilterFactory.java    From momo-cloud-permission with Apache License 2.0 6 votes vote down vote up
private Mono<Void> setRateCheckResponse(ServerWebExchange exchange) {
    //超过了限流
    ServerHttpResponse response = exchange.getResponse();
    //设置headers
    HttpHeaders httpHeaders = response.getHeaders();
    httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
    httpHeaders.add("Access-Control-Allow-Origin", CrossDomainConfiguration.ALLOWED_ORIGIN);
    httpHeaders.add("Access-Control-Allow-Methods", CrossDomainConfiguration.ALLOWED_METHODS);
    httpHeaders.add("Access-Control-Max-Age", CrossDomainConfiguration.MAX_AGE);
    httpHeaders.add("Access-Control-Allow-Headers", CrossDomainConfiguration.ALLOWED_HEADERS);
    httpHeaders.add("Access-Control-Expose-Headers", CrossDomainConfiguration.ALLOWED_Expose);
    httpHeaders.add("Access-Control-Allow-Credentials", "true");
    httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
    //设置body
    JSONResult jsonResult = JSONResult.build(HttpStatus.TOO_MANY_REQUESTS.value(), "当前访问人数过多,请稍后重试", "当前访问人数过多,请稍后重试");
    DataBuffer bodyDataBuffer = response.bufferFactory().wrap(JSONObject.toJSONString(jsonResult).getBytes());
    log.error("限流了================");
    return response.writeWith(Mono.just(bodyDataBuffer));
}
 
Example #11
Source File: DeviceInstanceController.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
@GetMapping("/export.{format}")
@QueryAction
public Mono<Void> export(ServerHttpResponse response,
                         QueryParamEntity parameter,
                         @PathVariable String format) throws IOException {
    response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION,
        "attachment; filename=".concat(URLEncoder.encode("设备实例." + format, StandardCharsets.UTF_8.displayName())));
    return ReactorExcel.<DeviceExcelInfo>writer(format)
        .headers(DeviceExcelInfo.getExportHeaderMapping(Collections.emptyList()))
        .converter(DeviceExcelInfo::toMap)
        .writeBuffer(
            service.query(parameter)
                .map(entity -> FastBeanCopier.copy(entity, new DeviceExcelInfo()))
            , 512 * 1024)//缓冲512k
        .doOnError(err -> log.error(err.getMessage(), err))
        .map(bufferFactory::wrap)
        .as(response::writeWith);
}
 
Example #12
Source File: DefaultCorsProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void actualRequestExposedHeaders() throws Exception {
	ServerWebExchange exchange = actualRequest();
	this.conf.addExposedHeader("header1");
	this.conf.addExposedHeader("header2");
	this.conf.addAllowedOrigin("http://domain2.com");
	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertEquals("http://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS));
	assertTrue(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header1"));
	assertTrue(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header2"));
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertNull(response.getStatusCode());
}
 
Example #13
Source File: ReverseProxyFilter.java    From charon-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    RequestMappingConfiguration configuration = requestMappingResolver.resolveRequestMapping(request);
    if (configuration == null) {
        return chain.filter(exchange);
    }
    WebClient webClient = webClientProvider.getWebClient(configuration);
    return webClient.method(httpRequestMapper.extractMethod(request))
            .uri(httpRequestMapper.extractUri(request))
            .headers(headers -> headers.putAll(httpRequestMapper.extractHeaders(request)))
            .body(httpRequestMapper.extractBody(request))
            .exchange()
            .flatMap(clientResponse -> httpResponseMapper.map(clientResponse, response));
}
 
Example #14
Source File: CorsConfig.java    From spring-cloud-sofastack-samples with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: WingtipsSpringBoot2WebfluxConfigurationTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("extractTagAndNamingAdapterScenarioDataProvider")
@Test
public void extractTagAndNamingAdapter_works_as_expected(
        ExtractTagAndNamingAdapterScenario scenario
) {
    // given
    WingtipsSpringBoot2WebfluxProperties props = generateProps(
            false, null, null, null, scenario.adapterName, false
    );
    WingtipsSpringBoot2WebfluxConfiguration conf = new WingtipsSpringBoot2WebfluxConfiguration(props);

    // when
    HttpTagAndSpanNamingAdapter<ServerWebExchange, ServerHttpResponse> result =
            conf.extractTagAndNamingAdapter(props);

    // then
    if (scenario.expectedResultClass == null) {
        assertThat(result).isNull();
    } else {
        assertThat(result).isNotNull();
        assertThat(result.getClass()).isEqualTo(scenario.expectedResultClass);
    }
}
 
Example #16
Source File: WebFluxSecurityCorsFilter.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("all")
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    if (CorsUtils.isCorsRequest(request)) {
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "*");
        headers.add("Access-Control-Max-Age", "3600");
        headers.add("Access-Control-Allow-Headers", "*");
        if (request.getMethod() == HttpMethod.OPTIONS) {
            response.setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }
    }
    return chain.filter(exchange);
}
 
Example #17
Source File: GraphQLController.java    From graphql-java-examples with MIT License 6 votes vote down vote up
@RequestMapping(value = "/graphql", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@CrossOrigin
public Mono<Void> graphql(@RequestBody Map<String, Object> body, ServerHttpResponse serverHttpResponse) throws IOException {
    String query = (String) body.get("query");
    if (query == null) {
        query = "";
    }
    Map<String, Object> variables = (Map<String, Object>) body.get("variables");
    if (variables == null) {
        variables = new LinkedHashMap<>();
    }
    ExecutionInput executionInput = ExecutionInput.newExecutionInput()
            .query(query)
            .variables(variables)
            .build();

    ExecutionResult executionResult = graphql.execute(executionInput);
    Map<Object, Object> extensions = executionResult.getExtensions();
    if (extensions != null && extensions.containsKey(GraphQL.DEFERRED_RESULTS)) {
        return handleDeferResponse(serverHttpResponse, executionResult, extensions);
    } else {
        return handleNormalResponse(serverHttpResponse, executionResult);
    }
}
 
Example #18
Source File: RenderingResponseIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Mono<Void> render(@Nullable Map<String, ?> model, @Nullable MediaType contentType,
		ServerWebExchange exchange) {
	StringBuilder builder = new StringBuilder();
	builder.append("name=").append(this.name).append('\n');
	for (Map.Entry<String, ?> entry : model.entrySet()) {
		builder.append(entry.getKey()).append('=').append(entry.getValue()).append('\n');
	}
	builder.setLength(builder.length() - 1);
	byte[] bytes = builder.toString().getBytes(StandardCharsets.UTF_8);

	ServerHttpResponse response = exchange.getResponse();
	DataBuffer buffer = response.bufferFactory().wrap(bytes);
	response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
	return response.writeWith(Mono.just(buffer));
}
 
Example #19
Source File: DecoderHttpMessageReader.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<T> readMono(ResolvableType actualType, ResolvableType elementType,
		ServerHttpRequest request, ServerHttpResponse response, Map<String, Object> hints) {

	Map<String, Object> allHints = Hints.merge(hints,
			getReadHints(actualType, elementType, request, response));

	return readMono(elementType, request, allHints);
}
 
Example #20
Source File: WingtipsSpringBoot2WebfluxConfigurationTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@UseDataProvider("extractTagAndNamingStrategyScenarioDataProvider")
@Test
public void extractTagAndNamingStrategy_works_as_expected(
        ExtractTagAndNamingStrategyScenario scenario
) {
    // given
    WingtipsSpringBoot2WebfluxProperties props = generateProps(
            false, null, null, scenario.strategyName, null, false
    );
    WingtipsSpringBoot2WebfluxConfiguration conf = new WingtipsSpringBoot2WebfluxConfiguration(props);

    // when
    HttpTagAndSpanNamingStrategy<ServerWebExchange, ServerHttpResponse> result =
            conf.extractTagAndNamingStrategy(props);

    // then
    if (scenario.expectedResultClass == null) {
        assertThat(result).isNull();
    } else {
        assertThat(result).isNotNull();
        assertThat(result.getClass()).isEqualTo(scenario.expectedResultClass);
    }

    if (scenario.expectedExactMatch != null) {
        assertThat(result).isSameAs(scenario.expectedExactMatch);
    }
}
 
Example #21
Source File: NettyClientResponsePlugin.java    From soul with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final SoulPluginChain chain) {
    return Mono.defer(() -> {
        Connection connection = exchange.getAttribute(Constants.CLIENT_RESPONSE_CONN_ATTR);
        if (connection == null) {
            return Mono.empty();
        }
        if (log.isTraceEnabled()) {
            log.trace("NettyWriteResponseFilter start inbound: "
                    + connection.channel().id().asShortText() + ", outbound: "
                    + exchange.getLogPrefix());
        }
        ServerHttpResponse response = exchange.getResponse();
        NettyDataBufferFactory factory = (NettyDataBufferFactory) response.bufferFactory();
        final Flux<NettyDataBuffer> body = connection
                .inbound()
                .receive()
                .retain()
                .map(factory::wrap);
        MediaType contentType = response.getHeaders().getContentType();
        return isStreamingMediaType(contentType)
                ? response.writeAndFlushWith(body.map(Flux::just))
                : response.writeWith(body);

    })
            .then(chain.execute(exchange)
                    .doOnError(throwable -> cleanup(exchange))).doOnCancel(() -> cleanup(exchange));
}
 
Example #22
Source File: ServerWebExchangeArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolveArgument() {
	testResolveArgument(this.testMethod.arg(ServerWebExchange.class), this.exchange);
	testResolveArgument(this.testMethod.arg(ServerHttpRequest.class), this.exchange.getRequest());
	testResolveArgument(this.testMethod.arg(ServerHttpResponse.class), this.exchange.getResponse());
	testResolveArgument(this.testMethod.arg(HttpMethod.class), HttpMethod.GET);
	testResolveArgument(this.testMethod.arg(TimeZone.class), TimeZone.getDefault());
	testResolveArgument(this.testMethod.arg(ZoneId.class), ZoneId.systemDefault());
}
 
Example #23
Source File: AuthFilter.java    From hello-spring-cloud-alibaba with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    String token = exchange.getRequest().getQueryParams().getFirst("token");

    if (token == null || token.isEmpty()) {
        ServerHttpResponse response = exchange.getResponse();

        // 封装错误信息
        Map<String, Object> responseData = Maps.newHashMap();
        responseData.put("code", 401);
        responseData.put("message", "非法请求");
        responseData.put("cause", "Token is empty");

        try {
            // 将信息转换为 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] data = objectMapper.writeValueAsBytes(responseData);

            // 输出错误信息到页面
            DataBuffer buffer = response.bufferFactory().wrap(data);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            log.error("{}", e);
        }
    }

    return chain.filter(exchange);
}
 
Example #24
Source File: BodyInserters.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static <T> Mono<Void> write(Publisher<? extends T> input, ResolvableType type,
		@Nullable MediaType mediaType, ReactiveHttpOutputMessage message,
		BodyInserter.Context context, HttpMessageWriter<T> writer) {

	return context.serverRequest()
			.map(request -> {
				ServerHttpResponse response = (ServerHttpResponse) message;
				return writer.write(input, type, type, mediaType, request, response, context.hints());
			})
			.orElseGet(() -> writer.write(input, type, mediaType, message, context.hints()));
}
 
Example #25
Source File: DefaultCorsProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void preflightRequestMatchedAllowedMethod() throws Exception {
	ServerWebExchange exchange = MockServerWebExchange.from(
			preFlightRequest().header(ACCESS_CONTROL_REQUEST_METHOD, "GET"));
	this.conf.addAllowedOrigin("*");
	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertNull(response.getStatusCode());
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertEquals("GET,HEAD", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS));
}
 
Example #26
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 #27
Source File: WebFluxIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
    new CreateTraceEntry().traceEntryMarker();
    HttpClient httpClient = HttpClient.create();
    return httpClient.request(HttpMethod.GET, "http://example.org", req -> {
        return req.send();
    }).doOnError(t -> {
        t.printStackTrace();
    }).doOnNext(res -> {
        response.writeWith(Mono.just(response.bufferFactory().wrap("xyzo".getBytes())));
    }).then();
}
 
Example #28
Source File: AuthFilter.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 封装返回值
 *
 * @param response
 * @param result
 * @return
 */
private DataBuffer getBodyBuffer(ServerHttpResponse response, JsonData result) {
	try {
		return response.bufferFactory().wrap(JsonUtil.toJSONBytes(result));
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #29
Source File: GraphQLController.java    From graphql-java-examples with MIT License 5 votes vote down vote up
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 #30
Source File: ViewResolutionResultHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> render(@Nullable Map<String, ?> model, @Nullable MediaType mediaType, ServerWebExchange exchange) {
	ServerHttpResponse response = exchange.getResponse();
	if (mediaType != null) {
		response.getHeaders().setContentType(mediaType);
	}
	model = new TreeMap<>(model);
	String value = this.name + ": " + model.toString();
	ByteBuffer byteBuffer = ByteBuffer.wrap(value.getBytes(UTF_8));
	DataBuffer dataBuffer = new DefaultDataBufferFactory().wrap(byteBuffer);
	return response.writeWith(Flux.just(dataBuffer));
}