org.springframework.http.HttpRequest Java Examples
The following examples show how to use
org.springframework.http.HttpRequest.
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: WingtipsClientHttpRequestInterceptor.java From wingtips with Apache License 2.0 | 6 votes |
/** * Returns the name that should be used for the subspan surrounding the call. Defaults to whatever {@link * HttpTagAndSpanNamingStrategy#getInitialSpanName(Object, HttpTagAndSpanNamingAdapter)} returns, with a fallback * of {@link HttpRequestTracingUtils#getFallbackSpanNameForHttpRequest(String, String)} if the naming strategy * returned null or blank string. You can override this method to return something else if you want different * behavior and you don't want to adjust the naming strategy or adapter. * * @param request The request that is about to be executed. * @param namingStrategy The {@link HttpTagAndSpanNamingStrategy} being used. * @param adapter The {@link HttpTagAndSpanNamingAdapter} being used. * @return The name that should be used for the subspan surrounding the call. */ protected @NotNull String getSubspanSpanName( @NotNull HttpRequest request, @NotNull HttpTagAndSpanNamingStrategy<HttpRequest, ?> namingStrategy, @NotNull HttpTagAndSpanNamingAdapter<HttpRequest, ?> adapter ) { // Try the naming strategy first. String subspanNameFromStrategy = namingStrategy.getInitialSpanName(request, adapter); if (StringUtils.isNotBlank(subspanNameFromStrategy)) { return subspanNameFromStrategy; } // The naming strategy didn't have anything for us. Fall back to something reasonable. return HttpRequestTracingUtils.getFallbackSpanNameForHttpRequest( "resttemplate_downstream_call", getRequestMethodAsString(request.getMethod()) ); }
Example #2
Source File: SpringContractWiremockIssueDemoApplication.java From spring-cloud-contract with Apache License 2.0 | 6 votes |
@Bean @Order public RestTemplateCustomizer someLowestPrecedenceOrderedInterceptorCustomizer() { return new RestTemplateCustomizer() { @Override public void customize(RestTemplate restTemplate) { ClientHttpRequestInterceptor emptyInterceptor = new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { return execution.execute(request, body); } }; restTemplate.getInterceptors().add(emptyInterceptor); } }; }
Example #3
Source File: SpringHttpRequestSignerTest.java From oauth1-signer-java with MIT License | 6 votes |
@Before public void initialize() throws Exception { signingKey = TestUtils.getTestSigningKey(); uri = new URI("https://api.mastercard.com/service"); headers = new HttpHeaders(); request = new HttpRequest() { @Override public HttpMethod getMethod(){ return POST_METHOD; } @Override public String getMethodValue(){ return getMethod().toString(); } @Override public URI getURI(){ return uri; } @Override public HttpHeaders getHeaders(){ return headers; } }; }
Example #4
Source File: UriComponentsBuilderTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void fromHttpRequestMultipleForwardedHeader() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Forwarded", "host=84.198.58.199;proto=https"); request.addHeader("Forwarded", "proto=ftp; host=1.2.3.4"); request.setScheme("http"); request.setServerName("example.com"); request.setRequestURI("/rest/mobile/users/1"); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); assertEquals("https", result.getScheme()); assertEquals("84.198.58.199", result.getHost()); assertEquals("/rest/mobile/users/1", result.getPath()); }
Example #5
Source File: DefaultWebClient.java From spring-analysis-note with MIT License | 6 votes |
private <T extends Publisher<?>> T handleBody(ClientResponse response, T bodyPublisher, Function<Mono<? extends Throwable>, T> errorFunction) { if (HttpStatus.resolve(response.rawStatusCode()) != null) { for (StatusHandler handler : this.statusHandlers) { if (handler.test(response.statusCode())) { HttpRequest request = this.requestSupplier.get(); Mono<? extends Throwable> exMono = handler.apply(response, request); exMono = exMono.flatMap(ex -> drainBody(response, ex)); exMono = exMono.onErrorResume(ex -> drainBody(response, ex)); T result = errorFunction.apply(exMono); return insertCheckpoint(result, response.statusCode(), request); } } return bodyPublisher; } else { return errorFunction.apply(createResponseException(response, this.requestSupplier.get())); } }
Example #6
Source File: RetryLoadBalancerInterceptorTest.java From spring-cloud-commons with Apache License 2.0 | 6 votes |
@Test public void interceptSuccess() throws Throwable { HttpRequest request = mock(HttpRequest.class); when(request.getURI()).thenReturn(new URI("http://foo")); ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[] {}, HttpStatus.OK); LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); ServiceInstance serviceInstance = mock(ServiceInstance.class); when(this.client.choose(eq("foo"))).thenReturn(serviceInstance); when(this.client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse); when(this.lbRequestFactory.createRequest(any(), any(), any())) .thenReturn(mock(LoadBalancerRequest.class)); this.lbProperties.setEnabled(true); RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( this.client, this.lbProperties, this.lbRequestFactory, new MyLoadBalancedRetryFactory(policy)); byte[] body = new byte[] {}; ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); ClientHttpResponse rsp = interceptor.intercept(request, body, execution); then(rsp).isEqualTo(clientHttpResponse); verify(this.lbRequestFactory).createRequest(request, body, execution); }
Example #7
Source File: HttpRequestWrapperWithModifiableHeadersTest.java From wingtips with Apache License 2.0 | 6 votes |
@Test public void verify_non_header_wrapper_methods_pass_through_to_original_request() { // given doReturn(new HttpHeaders()).when(requestMock).getHeaders(); HttpRequestWrapperWithModifiableHeaders wrapper = new HttpRequestWrapperWithModifiableHeaders(requestMock); // when HttpRequest wrappedRequest = wrapper.getRequest(); URI wrapperUri = wrapper.getURI(); HttpMethod wrapperMethod = wrapper.getMethod(); // then assertThat(wrappedRequest).isSameAs(requestMock); assertThat(wrapperUri).isSameAs(uri); assertThat(wrapperMethod).isSameAs(wrapperMethod); verify(requestMock).getURI(); verify(requestMock).getMethod(); }
Example #8
Source File: WebUtils.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Check the given request origin against a list of allowed origins. * A list containing "*" means that all origins are allowed. * An empty list means only same origin is allowed. * @return {@code true} if the request origin is valid, {@code false} otherwise * @since 4.1.5 * @see <a href="https://tools.ietf.org/html/rfc6454">RFC 6454: The Web Origin Concept</a> */ public static boolean isValidOrigin(HttpRequest request, Collection<String> allowedOrigins) { Assert.notNull(request, "Request must not be null"); Assert.notNull(allowedOrigins, "Allowed origins must not be null"); String origin = request.getHeaders().getOrigin(); if (origin == null || allowedOrigins.contains("*")) { return true; } else if (CollectionUtils.isEmpty(allowedOrigins)) { return isSameOrigin(request); } else { return allowedOrigins.contains(origin); } }
Example #9
Source File: UriComponentsBuilderTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void fromHttpRequestForwardedHeaderWithHostPortAndServerPort() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Forwarded", "proto=https; host=84.198.58.199:9090"); request.setScheme("http"); request.setServerPort(8080); request.setServerName("example.com"); request.setRequestURI("/rest/mobile/users/1"); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); assertEquals("https", result.getScheme()); assertEquals("84.198.58.199", result.getHost()); assertEquals("/rest/mobile/users/1", result.getPath()); assertEquals(9090, result.getPort()); assertEquals("https://84.198.58.199:9090/rest/mobile/users/1", result.toUriString()); }
Example #10
Source File: DataConversionHelper.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
private static DdiArtifact createArtifact(final Target target, final ArtifactUrlHandler artifactUrlHandler, final Artifact artifact, final SystemManagement systemManagement, final HttpRequest request) { final DdiArtifact file = new DdiArtifact(); file.setHashes(new DdiArtifactHash(artifact.getSha1Hash(), artifact.getMd5Hash(), artifact.getSha256Hash())); file.setFilename(artifact.getFilename()); file.setSize(artifact.getSize()); artifactUrlHandler .getUrls(new URLPlaceholder(systemManagement.getTenantMetadata().getTenant(), systemManagement.getTenantMetadata().getId(), target.getControllerId(), target.getId(), new SoftwareData(artifact.getSoftwareModule().getId(), artifact.getFilename(), artifact.getId(), artifact.getSha1Hash())), ApiType.DDI, request.getURI()) .forEach(entry -> file.add(new Link(entry.getRef()).withRel(entry.getRel()))); return file; }
Example #11
Source File: ClientHttpRequestCorrelationInterceptorTest.java From request-correlation-spring-cloud-starter with Apache License 2.0 | 6 votes |
@Test public void shouldSetHeader() throws IOException { // given final String requestId = UUID.randomUUID().toString(); CorrelationTestUtils.setRequestId(requestId); final HttpRequest request = mock(HttpRequest.class); final ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); final byte[] body = new byte[0]; when(request.getHeaders()).thenReturn(new HttpHeaders()); // when instance.intercept(request, body, execution); // then assertTrue(request.getHeaders().containsKey(RequestCorrelationConsts.HEADER_NAME)); assertEquals(requestId, request.getHeaders().getFirst(RequestCorrelationConsts.HEADER_NAME)); verify(execution).execute(request, body); }
Example #12
Source File: UriComponentsBuilderTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void fromHttpRequestForwardedHeaderWithHostPortAndWithoutServerPort() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Forwarded", "proto=https; host=84.198.58.199:9090"); request.setScheme("http"); request.setServerName("example.com"); request.setRequestURI("/rest/mobile/users/1"); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); assertEquals("https", result.getScheme()); assertEquals("84.198.58.199", result.getHost()); assertEquals("/rest/mobile/users/1", result.getPath()); assertEquals(9090, result.getPort()); assertEquals("https://84.198.58.199:9090/rest/mobile/users/1", result.toUriString()); }
Example #13
Source File: ForwardedHeaderFilter.java From java-technology-stack with MIT License | 6 votes |
ForwardedHeaderExtractingRequest(HttpServletRequest request, UrlPathHelper pathHelper) { super(request); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); int port = uriComponents.getPort(); this.scheme = uriComponents.getScheme(); this.secure = "https".equals(this.scheme); this.host = uriComponents.getHost(); this.port = (port == -1 ? (this.secure ? 443 : 80) : port); String baseUrl = this.scheme + "://" + this.host + (port == -1 ? "" : ":" + port); Supplier<HttpServletRequest> delegateRequest = () -> (HttpServletRequest) getRequest(); this.forwardedPrefixExtractor = new ForwardedPrefixExtractor(delegateRequest, pathHelper, baseUrl); }
Example #14
Source File: UriComponentsBuilderTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void fromHttpRequestForwardedHeaderWithHostPortAndWithoutServerPort() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Forwarded", "proto=https; host=84.198.58.199:9090"); request.setScheme("http"); request.setServerName("example.com"); request.setRequestURI("/rest/mobile/users/1"); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); assertEquals("https", result.getScheme()); assertEquals("84.198.58.199", result.getHost()); assertEquals("/rest/mobile/users/1", result.getPath()); assertEquals(9090, result.getPort()); assertEquals("https://84.198.58.199:9090/rest/mobile/users/1", result.toUriString()); }
Example #15
Source File: UriComponentsBuilderTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void fromHttpRequestWithForwardedProtoMultiValueHeader() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setScheme("http"); request.setServerName("localhost"); request.setServerPort(8080); request.setRequestURI("/mvc-showcase"); request.addHeader("X-Forwarded-Host", "a.example.org"); request.addHeader("X-Forwarded-Port", "443"); request.addHeader("X-Forwarded-Proto", "https,https"); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); assertEquals("https://a.example.org/mvc-showcase", result.toString()); }
Example #16
Source File: DataConversionHelper.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
static List<DdiChunk> createChunks(final Target target, final Action uAction, final ArtifactUrlHandler artifactUrlHandler, final SystemManagement systemManagement, final HttpRequest request, final ControllerManagement controllerManagement) { final Map<Long, List<SoftwareModuleMetadata>> metadata = controllerManagement .findTargetVisibleMetaDataBySoftwareModuleId(uAction.getDistributionSet().getModules().stream() .map(SoftwareModule::getId).collect(Collectors.toList())); return new ResponseList<>(uAction.getDistributionSet().getModules().stream() .map(module -> new DdiChunk(mapChunkLegacyKeys(module.getType().getKey()), module.getVersion(), module.getName(), createArtifacts(target, module, artifactUrlHandler, systemManagement, request), mapMetadata(metadata.get(module.getId())))) .collect(Collectors.toList())); }
Example #17
Source File: AbstractMessageConverterMethodArgumentResolver.java From spring4-understanding with Apache License 2.0 | 6 votes |
public EmptyBodyCheckingHttpInputMessage(HttpInputMessage inputMessage) throws IOException { this.headers = inputMessage.getHeaders(); InputStream inputStream = inputMessage.getBody(); if (inputStream == null) { this.body = null; } else if (inputStream.markSupported()) { inputStream.mark(1); this.body = (inputStream.read() != -1 ? inputStream : null); inputStream.reset(); } else { PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream); int b = pushbackInputStream.read(); if (b == -1) { this.body = null; } else { this.body = pushbackInputStream; pushbackInputStream.unread(b); } } this.method = ((HttpRequest) inputMessage).getMethod(); }
Example #18
Source File: GrayHttpRequestInterceptor.java From lion with Apache License 2.0 | 6 votes |
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest servletRequest = attributes.getRequest(); // 设置请求头header信息 Enumeration<String> headerNames = servletRequest.getHeaderNames(); if (null != headerNames) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String value = servletRequest.getHeader(name); // 若version版本号为空,则赋值默认版本号 if (name.equals(GrayConstant.VERSION) && StringUtils.isEmpty(value)) { value = GrayConstant.DEFAULT_VERSION; } request.getHeaders().add(name, value); } } // 设置灰度版本 String version = servletRequest.getHeader(GrayConstant.VERSION); RibbonFilterContextHolder.getCurrentContext().add(GrayConstant.VERSION, version); return execution.execute(request, body); }
Example #19
Source File: UriComponentsBuilderTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void fromHttpRequestResetsPortBeforeSettingIt() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("X-Forwarded-Proto", "https"); request.addHeader("X-Forwarded-Host", "84.198.58.199"); request.addHeader("X-Forwarded-Port", 443); request.setScheme("http"); request.setServerName("example.com"); request.setServerPort(80); request.setRequestURI("/rest/mobile/users/1"); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); assertEquals("https", result.getScheme()); assertEquals("84.198.58.199", result.getHost()); assertEquals(-1, result.getPort()); assertEquals("/rest/mobile/users/1", result.getPath()); }
Example #20
Source File: WebUtils.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Check if the request is a same-origin one, based on {@code Origin}, {@code Host}, * {@code Forwarded} and {@code X-Forwarded-Host} headers. * @return {@code true} if the request is a same-origin one, {@code false} in case * of cross-origin request * @since 4.2 */ public static boolean isSameOrigin(HttpRequest request) { String origin = request.getHeaders().getOrigin(); if (origin == null) { return true; } UriComponentsBuilder urlBuilder; if (request instanceof ServletServerHttpRequest) { // Build more efficiently if we can: we only need scheme, host, port for origin comparison HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); urlBuilder = new UriComponentsBuilder(). scheme(servletRequest.getScheme()). host(servletRequest.getServerName()). port(servletRequest.getServerPort()). adaptFromForwardedHeaders(request.getHeaders()); } else { urlBuilder = UriComponentsBuilder.fromHttpRequest(request); } UriComponents actualUrl = urlBuilder.build(); UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build(); return (ObjectUtils.nullSafeEquals(actualUrl.getHost(), originUrl.getHost()) && getPort(actualUrl) == getPort(originUrl)); }
Example #21
Source File: WebUtils.java From spring-analysis-note with MIT License | 6 votes |
/** * Check the given request origin against a list of allowed origins. * A list containing "*" means that all origins are allowed. * An empty list means only same origin is allowed. * * <p><strong>Note:</strong> as of 5.1 this method ignores * {@code "Forwarded"} and {@code "X-Forwarded-*"} headers that specify the * client-originated address. Consider using the {@code ForwardedHeaderFilter} * to extract and use, or to discard such headers. * * @return {@code true} if the request origin is valid, {@code false} otherwise * @since 4.1.5 * @see <a href="https://tools.ietf.org/html/rfc6454">RFC 6454: The Web Origin Concept</a> */ public static boolean isValidOrigin(HttpRequest request, Collection<String> allowedOrigins) { Assert.notNull(request, "Request must not be null"); Assert.notNull(allowedOrigins, "Allowed origins must not be null"); String origin = request.getHeaders().getOrigin(); if (origin == null || allowedOrigins.contains("*")) { return true; } else if (CollectionUtils.isEmpty(allowedOrigins)) { return isSameOrigin(request); } else { return allowedOrigins.contains(origin); } }
Example #22
Source File: UriComponentsBuilderTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void fromHttpRequestForwardedHeaderWithoutHostPortAndWithServerPort() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Forwarded", "proto=https; host=84.198.58.199"); request.setScheme("http"); request.setServerPort(8080); request.setServerName("example.com"); request.setRequestURI("/rest/mobile/users/1"); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); assertEquals("https", result.getScheme()); assertEquals("84.198.58.199", result.getHost()); assertEquals("/rest/mobile/users/1", result.getPath()); assertEquals(-1, result.getPort()); assertEquals("https://84.198.58.199/rest/mobile/users/1", result.toUriString()); }
Example #23
Source File: ForwardedHeaderFilter.java From spring-analysis-note with MIT License | 6 votes |
ForwardedHeaderExtractingRequest(HttpServletRequest request, UrlPathHelper pathHelper) { super(request); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); int port = uriComponents.getPort(); this.scheme = uriComponents.getScheme(); this.secure = "https".equals(this.scheme); this.host = uriComponents.getHost(); this.port = (port == -1 ? (this.secure ? 443 : 80) : port); String baseUrl = this.scheme + "://" + this.host + (port == -1 ? "" : ":" + port); Supplier<HttpServletRequest> delegateRequest = () -> (HttpServletRequest) getRequest(); this.forwardedPrefixExtractor = new ForwardedPrefixExtractor(delegateRequest, pathHelper, baseUrl); }
Example #24
Source File: HeaderExpressionTest.java From spring-cloud-alibaba with Apache License 2.0 | 6 votes |
@Test public void testMatch() { HeaderExpression expression = createExpression("a=1"); HttpRequest request = builder().build(); Assert.assertFalse(expression.match(request)); request = builder().header("a", "").build(); Assert.assertFalse(expression.match(request)); request = builder().header("a", "2").build(); Assert.assertFalse(expression.match(request)); request = builder().header("", "1").build(); Assert.assertFalse(expression.match(request)); request = builder().header("a", "1").build(); Assert.assertTrue(expression.match(request)); }
Example #25
Source File: BasicAuthenticationInterceptor.java From spring-analysis-note with MIT License | 6 votes |
@Override public ClientHttpResponse intercept( HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpHeaders headers = request.getHeaders(); if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { headers.setBasicAuth(this.username, this.password, this.charset); } return execution.execute(request, body); }
Example #26
Source File: SpringHttpClientTagAdapterTest.java From wingtips with Apache License 2.0 | 6 votes |
@DataProvider(value = { "true | spring.asyncresttemplate", "false | spring.resttemplate" }, splitBy = "\\|") @Test public void getSpanHandlerTagValue_works_as_expected_when_request_is_an_HttpRequestWrapper( boolean wrappedRequestIsAsyncClientHttpRequest, String expectedResult ) { // given HttpRequestWrapper request = mock(HttpRequestWrapper.class); HttpRequest wrappedRequest = (wrappedRequestIsAsyncClientHttpRequest) ? mock(AsyncClientHttpRequest.class) : mock(HttpRequest.class); doReturn(wrappedRequest).when(request).getRequest(); // when String result = implSpy.getSpanHandlerTagValue(request, responseMock); // then assertThat(result).isEqualTo(expectedResult); }
Example #27
Source File: UriComponentsBuilderTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void fromHttpRequestForwardedHeader() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Forwarded", "proto=https; host=84.198.58.199"); request.setScheme("http"); request.setServerName("example.com"); request.setRequestURI("/rest/mobile/users/1"); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); assertEquals("https", result.getScheme()); assertEquals("84.198.58.199", result.getHost()); assertEquals("/rest/mobile/users/1", result.getPath()); }
Example #28
Source File: CsrfRouteMatcher.java From syncope with Apache License 2.0 | 5 votes |
@Override public Mono<MatchResult> matches(final ServerWebExchange exchange) { return Mono.just(exchange.getRequest()). map(HttpRequest::getMethod). filter(ALLOWED_METHODS::contains). flatMap(m -> MatchResult.notMatch()). switchIfEmpty(super.matches(exchange)); }
Example #29
Source File: AllureRestTemplate.java From allure-java with Apache License 2.0 | 5 votes |
@SuppressWarnings("NullableProblems") @Override public ClientHttpResponse intercept(@NonNull final HttpRequest request, final byte[] body, @NonNull final ClientHttpRequestExecution execution) throws IOException { final AttachmentProcessor<AttachmentData> processor = new DefaultAttachmentProcessor(); final HttpRequestAttachment.Builder requestAttachmentBuilder = HttpRequestAttachment.Builder .create("Request", request.getURI().toString()) .setMethod(request.getMethodValue()) .setHeaders(toMapConverter(request.getHeaders())); if (body.length != 0) { requestAttachmentBuilder.setBody(new String(body, StandardCharsets.UTF_8)); } final HttpRequestAttachment requestAttachment = requestAttachmentBuilder.build(); processor.addAttachment(requestAttachment, new FreemarkerAttachmentRenderer(requestTemplatePath)); final ClientHttpResponse clientHttpResponse = execution.execute(request, body); final HttpResponseAttachment responseAttachment = HttpResponseAttachment.Builder .create("Response") .setResponseCode(clientHttpResponse.getRawStatusCode()) .setHeaders(toMapConverter(clientHttpResponse.getHeaders())) .setBody(StreamUtils.copyToString(clientHttpResponse.getBody(), StandardCharsets.UTF_8)) .build(); processor.addAttachment(responseAttachment, new FreemarkerAttachmentRenderer(responseTemplatePath)); return clientHttpResponse; }
Example #30
Source File: AsyncRestTemplateCircuitInterceptor.java From spring-cloud-formula with Apache License 2.0 | 5 votes |
@Override public ListenableFuture<ClientHttpResponse> intercept(HttpRequest httpRequest, byte[] body, AsyncClientHttpRequestExecution execution) throws IOException { logger.debug("AsyncRestTemplateCircuitInterceptor start"); URI asUri = httpRequest.getURI(); String httpMethod = httpRequest.getMethod().toString(); String serviceName = asUri.getHost(); String url = asUri.getPath(); logger.info("http with serviceName:{}, menthod:{}, url:{}", serviceName, httpMethod, url); if (circuitBreakerCore.checkRulesExist(httpMethod, serviceName, url)) { try { Method wrappedMethod = AsyncRestTemplateCircuitInterceptor.class.getMethod( "doExecuteAsync", AsyncClientHttpRequestExecution.class, HttpRequest.class, byte[].class); Object[] args = {httpRequest, body}; ListenableFuture<ClientHttpResponse> response = (ListenableFuture<ClientHttpResponse>) circuitBreakerCore.process(httpMethod, serviceName, url, wrappedMethod, this, args); // todo 熔断返回null return response; } catch (Exception e) { logger.error(e.getMessage(), e); if (e instanceof CircuitBreakerOpenException) { throw new RuntimeException(e.getMessage()); } else if (e instanceof IOException) { throw new IOException(e.getMessage()); } else { throw new RuntimeException(e.getMessage()); } } } else { return execution.executeAsync(httpRequest, body); } }