Java Code Examples for org.springframework.http.HttpRequest

The following examples show how to use org.springframework.http.HttpRequest. These examples are extracted from open source projects. 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 Project: java-technology-stack   Source File: ForwardedHeaderFilter.java    License: MIT License 6 votes vote down vote up
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 2
@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 3
Source Project: java-technology-stack   Source File: UriComponentsBuilderTests.java    License: MIT License 6 votes vote down vote up
@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 4
Source Project: spring-analysis-note   Source File: DefaultWebClient.java    License: MIT License 6 votes vote down vote up
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 5
Source Project: hawkbit   Source File: DataConversionHelper.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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 6
@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 7
Source Project: hawkbit   Source File: DataConversionHelper.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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 8
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 9
Source Project: lion   Source File: GrayHttpRequestInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
@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 11
Source Project: spring-analysis-note   Source File: WebUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 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 12
Source Project: spring-analysis-note   Source File: ForwardedHeaderFilter.java    License: MIT License 6 votes vote down vote up
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 13
Source Project: wingtips   Source File: SpringHttpClientTagAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 14
Source Project: spring-cloud-alibaba   Source File: HeaderExpressionTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 15
Source Project: java-technology-stack   Source File: UriComponentsBuilderTests.java    License: MIT License 6 votes vote down vote up
@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 16
Source Project: lams   Source File: WebUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 17
Source Project: java-technology-stack   Source File: UriComponentsBuilderTests.java    License: MIT License 6 votes vote down vote up
@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 18
/**
 * 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 19
@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 20
Source Project: spring4-understanding   Source File: WebUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 21
@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 22
Source Project: spring-analysis-note   Source File: UriComponentsBuilderTests.java    License: MIT License 6 votes vote down vote up
@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 23
Source Project: oauth1-signer-java   Source File: SpringHttpRequestSignerTest.java    License: MIT License 6 votes vote down vote up
@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 24
Source Project: spring-analysis-note   Source File: UriComponentsBuilderTests.java    License: MIT License 6 votes vote down vote up
@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 25
@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 26
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes,
    ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
  DTMContext dtmContext = DTMContext.getDTMContext();
  long gid = dtmContext.getGlobalTxId();
  HttpHeaders headers = httpRequest.getHeaders();
  if (gid != -1) {
    DtmContextDTO dtmContextDTO = DtmContextDTO.fromDtmContext(dtmContext);
    headers.add(DtmConstants.DTM_CONTEXT, Json.encode(dtmContextDTO));
  }
  return clientHttpRequestExecution.execute(httpRequest, bytes);
}
 
Example 27
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
		final ClientHttpRequestExecution execution) throws IOException {
	final URI originalUri = request.getURI();
	String serviceName = originalUri.getHost();
	Assert.state(serviceName != null,
			"Request URI does not contain a valid hostname: " + originalUri);
	return this.loadBalancer.execute(serviceName,
			this.requestFactory.createRequest(request, body, execution));
}
 
Example 28
Source Project: brave   Source File: TracingClientHttpRequestInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override public ClientHttpResponse intercept(HttpRequest req, byte[] body,
  ClientHttpRequestExecution execution) throws IOException {
  HttpRequestWrapper request = new HttpRequestWrapper(req);
  Span span = handler.handleSend(request);
  ClientHttpResponse response = null;
  Throwable error = null;
  try (Scope ws = currentTraceContext.newScope(span.context())) {
    return response = execution.execute(req, body);
  } catch (Throwable e) {
    error = e;
    throw e;
  } finally {
    handler.handleReceive(new ClientHttpResponseWrapper(request, response, error), span);
  }
}
 
Example 29
Source Project: chassis   Source File: HybridServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
	if (body.length > 0) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		HexDump.dump(body, 0, baos, 0);
		
		logger.info("Sending to [{}]: \n{}", request.getURI(), baos.toString(Charsets.UTF_8.name()).trim());
	} else {
		logger.info("Sending empty body to [{}]!", request.getURI());
	}
	
	return execution.execute(request, body);
}
 
Example 30
Source Project: java-technology-stack   Source File: UriComponentsBuilderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void fromHttpRequestForwardedHeaderQuoted()  {
	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());
}