Java Code Examples for org.springframework.http.client.ClientHttpRequestExecution

The following examples show how to use org.springframework.http.client.ClientHttpRequestExecution. 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
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
    ClientHttpRequestExecution execution) throws IOException {

  if (omegaContext != null && omegaContext.globalTxId() != null) {
    request.getHeaders().add(GLOBAL_TX_ID_KEY, omegaContext.globalTxId());
    request.getHeaders().add(LOCAL_TX_ID_KEY, omegaContext.localTxId());
    request.getHeaders().add(GLOBAL_TX_CATEGORY_KEY, omegaContext.category());

    LOG.debug("Added {} {} and {} {} to request header",
        GLOBAL_TX_ID_KEY,
        omegaContext.globalTxId(),
        LOCAL_TX_ID_KEY,
        omegaContext.localTxId(),
        GLOBAL_TX_CATEGORY_KEY,
        omegaContext.category());
  }
  return execution.execute(request, body);
}
 
Example 2
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
    throws IOException {
    final String urlTemplate = urlTemplateHolder.get();
    urlTemplateHolder.remove();
    final Clock clock = meterRegistry.config().clock();
    final long startTime = clock.monotonicTime();
    IOException ex = null;
    ClientHttpResponse response = null;
    try {
        response = execution.execute(request, body);
        return response;
    } catch (IOException e) {
        ex = e;
        throw e;
    } finally {
        getTimeBuilder(urlTemplate, request, response, ex).register(this.meterRegistry)
            .record(clock.monotonicTime() - startTime, TimeUnit.NANOSECONDS);
    }
}
 
Example 3
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 4
@Override
public ClientHttpResponse intercept(
	HttpRequest request, byte[] bytes,
	ClientHttpRequestExecution execution) throws IOException {
	HttpHeaders headers = BladeHttpHeadersContextHolder.get();
	// 考虑2中情况 1. RestTemplate 不是用 hystrix 2. 使用 hystrix
	if (headers == null) {
		headers = BladeHttpHeadersContextHolder.toHeaders(accountGetter, properties);
	}
	if (headers != null && !headers.isEmpty()) {
		HttpHeaders httpHeaders = request.getHeaders();
		headers.forEach((key, values) -> {
			values.forEach(value -> httpHeaders.add(key, value));
		});
	}
	return execution.execute(request, bytes);
}
 
Example 5
private ClientHttpResponse handleBlockException(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution, BlockException ex) {
	Object[] args = new Object[] { request, body, execution, ex };
	// handle degrade
	if (isDegradeFailure(ex)) {
		Method fallbackMethod = extractFallbackMethod(sentinelRestTemplate.fallback(),
				sentinelRestTemplate.fallbackClass());
		if (fallbackMethod != null) {
			return (ClientHttpResponse) methodInvoke(fallbackMethod, args);
		}
		else {
			return new SentinelClientHttpResponse();
		}
	}
	// handle flow
	Method blockHandler = extractBlockHandlerMethod(
			sentinelRestTemplate.blockHandler(),
			sentinelRestTemplate.blockHandlerClass());
	if (blockHandler != null) {
		return (ClientHttpResponse) methodInvoke(blockHandler, args);
	}
	else {
		return new SentinelClientHttpResponse();
	}
}
 
Example 6
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
    ClientHttpRequestExecution execution) throws IOException {

  if (omegaContext!= null && omegaContext.globalTxId() != null) {
    request.getHeaders().add(GLOBAL_TX_ID_KEY, omegaContext.globalTxId());
    request.getHeaders().add(LOCAL_TX_ID_KEY, omegaContext.localTxId());

    LOG.debug("Added {} {} and {} {} to request header",
        GLOBAL_TX_ID_KEY,
        omegaContext.globalTxId(),
        LOCAL_TX_ID_KEY,
        omegaContext.localTxId());
  } else {
    LOG.debug("Cannot inject transaction ID, as the OmegaContext is null or cannot get the globalTxId.");
  }
  return execution.execute(request, body);
}
 
Example 7
@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 8
Source Project: authmore-framework   Source File: ClientRestTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    Assert.notEmpty(token, "token cannot be empty");
    HttpHeaders headers = request.getHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + token);
    return execution.execute(request, body);
}
 
Example 9
@Override
public ClientHttpResponse intercept(
		HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

	String token = Base64Utils.encodeToString(
			(this.username + ":" + this.password).getBytes(StandardCharsets.UTF_8));
	request.getHeaders().add("Authorization", "Basic " + token);
	return execution.execute(request, body);
}
 
Example 10
@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 11
@Test
public void interceptShouldAddHeader() throws Exception {
	SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
	ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
	ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
	byte[] body = new byte[] {};
	new BasicAuthorizationInterceptor("spring", "boot").intercept(request, body,
			execution);
	verify(execution).execute(request, body);
	assertEquals("Basic c3ByaW5nOmJvb3Q=", request.getHeaders().getFirst("Authorization"));
}
 
Example 12
Source Project: spring-analysis-note   Source File: SampleTests.java    License: MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution) throws IOException {

	ClientHttpResponse response = execution.execute(request, body);
	byte[] expected = FileCopyUtils.copyToByteArray(this.resource.getInputStream());
	byte[] actual = FileCopyUtils.copyToByteArray(response.getBody());
	assertEquals(new String(expected), new String(actual));
	return response;
}
 
Example 13
Source Project: dts   Source File: DtsRemoteInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
    throws IOException {
    HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
    Map<String, String> contexts = SpringCloudDtsContext.getContext().getAttachments();
    for (Map.Entry<String, String> entry : contexts.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        requestWrapper.getHeaders().set(CONTEXT_HEADER_PARENT + key, value);
    }
    return execution.execute(requestWrapper, body);
}
 
Example 14
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    HttpHeaders headers = httpRequest.getHeaders();
    Map<String, String> copyOfContextMap = traceContentFactory.assemblyTraceContent();
    for (Map.Entry<String, String> copyOfContext : copyOfContextMap.entrySet()) {
        headers.add(copyOfContext.getKey(), copyOfContext.getValue());
    }
    return clientHttpRequestExecution.execute(httpRequest, bytes);
}
 
Example 15
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
  // log the http request
  LOG.info("URI: {}", request.getURI());
  LOG.info("HTTP Method: {}", request.getMethodValue());
  LOG.info("HTTP Headers: {}", request.getHeaders());

  return execution.execute(request, bytes);
}
 
Example 16
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    HttpRequestWrapper requestWrapper = new HttpRequestWrapper(httpRequest);
    String xid = RootContext.getXID();
    if (StringUtils.isNotEmpty(xid)) {
        requestWrapper.getHeaders().add(RootContext.KEY_XID, xid);
    }

    return clientHttpRequestExecution.execute(requestWrapper, bytes);
}
 
Example 17
Source Project: wecube-platform   Source File: HttpClientConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    logRequestDetails(request);
    ClientHttpResponse response = execution.execute(request, body);
    logResponseDetails(response);
    return response;
}
 
Example 18
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                    ClientHttpRequestExecution execution) throws IOException {
    request.getHeaders().add("X-BMS-APP-NAME", this.appName);
    request.getHeaders().add("X-BMS-PAAS-TYPE", this.paasType);
    request.getHeaders().add("X-BMS-PLATFORM-NAME", this.platformName);

    // add api version to header
    request.getHeaders().add("X-BMS-API-VERSION", BmsCommonInterceptor.VERSION);

    return execution.execute(request, body);
}
 
Example 19
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes,
                                    ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    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 = RestTemplateCircuitBreakerInterceptor.class.getMethod(
                    "doExecute", ClientHttpRequestExecution.class, HttpRequest.class, byte[].class);
            Object[] args = {clientHttpRequestExecution, httpRequest, bytes};
            ClientHttpResponse response = (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 clientHttpRequestExecution.execute(httpRequest, bytes);
    }
}
 
Example 20
public ClientHttpResponse doExecute(ClientHttpRequestExecution clientHttpRequestExecution,
                                    HttpRequest httpRequest, byte[] bytes) throws IOException {
    try {
        ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
        logger.info("http request response:" + response);
        if (response == null || !HttpStatus.OK.equals(response.getStatusCode())) {
            throw new IOException("response error");
        }
        return response;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 21
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    // add system tags from env
    FormulaConfigUtils.getSystemTags().forEach((k, v) -> {
        request.getHeaders().add(k, v);
    });
    // add service name from input
    request.getHeaders().add(SystemTag.SERVICE_NAME, serviceName);
    logger.debug("RestTemplate: insert {} into httpHeader: {}", SystemTag.SERVICE_NAME, serviceName);
    return execution.execute(request, body);
}
 
Example 22
@Override
public ClientHttpResponse intercept(
		HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

	String token = Base64Utils.encodeToString(
			(this.username + ":" + this.password).getBytes(StandardCharsets.UTF_8));
	request.getHeaders().add("Authorization", "Basic " + token);
	return execution.execute(request, body);
}
 
Example 23
@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 24
@Test
public void interceptShouldAddHeader() throws Exception {
	SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
	ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET);
	ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
	byte[] body = new byte[] {};
	new BasicAuthorizationInterceptor("spring", "boot").intercept(request, body,
			execution);
	verify(execution).execute(request, body);
	assertEquals("Basic c3ByaW5nOmJvb3Q=", request.getHeaders().getFirst("Authorization"));
}
 
Example 25
Source Project: java-technology-stack   Source File: SampleTests.java    License: MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution) throws IOException {

	ClientHttpResponse response = execution.execute(request, body);
	byte[] expected = FileCopyUtils.copyToByteArray(this.resource.getInputStream());
	byte[] actual = FileCopyUtils.copyToByteArray(response.getBody());
	assertEquals(new String(expected), new String(actual));
	return response;
}
 
Example 26
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    if (log.isInfoEnabled()) {
        logRequest(request, body);
    }
    ClientHttpResponse response = execution.execute(request, body);
    if (log.isInfoEnabled()) {
        logResponse(request, response);
    }
    return response;
}
 
Example 27
Source Project: rabbitmq-mock   Source File: LoggingHttpInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request,
                                    byte[] body,
                                    ClientHttpRequestExecution execution) throws IOException {
    ClientHttpResponse response = execution.execute(request, body);
    String responseBody = toString((ByteArrayInputStream) response.getBody());
    logger.info("Config server received request " +
        request.getMethodValue() + " " + request.getURI() +
        " and responded:\n" + responseBody);
    return response;
}
 
Example 28
Source Project: cat_lab   Source File: CatRestInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {

	Transaction t = Cat.newTransaction(CatConstants.TYPE_CALL, request.getURI().toString());

	try {
		HttpHeaders headers = request.getHeaders();

		// 保存和传递CAT调用链上下文
		Context ctx = new CatContext();
		Cat.logRemoteCallClient(ctx);
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID, ctx.getProperty(Cat.Context.ROOT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID, ctx.getProperty(Cat.Context.PARENT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID, ctx.getProperty(Cat.Context.CHILD));

		// 保证请求继续被执行
		ClientHttpResponse response =  execution.execute(request, body);
		t.setStatus(Transaction.SUCCESS);
		return response;
	} catch (Exception e) {
		Cat.getProducer().logError(e);
		t.setStatus(e);
		throw e;
	} finally {
		t.complete();
	}
}
 
Example 29
Source Project: cat_lab   Source File: CatRestInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {

	Transaction t = Cat.newTransaction(CatConstants.TYPE_CALL, request.getURI().toString());

	try {
		HttpHeaders headers = request.getHeaders();

		// 保存和传递CAT调用链上下文
		Context ctx = new CatContext();
		Cat.logRemoteCallClient(ctx);
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID, ctx.getProperty(Cat.Context.ROOT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID, ctx.getProperty(Cat.Context.PARENT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID, ctx.getProperty(Cat.Context.CHILD));

		// 保证请求继续被执行
		ClientHttpResponse response =  execution.execute(request, body);
		t.setStatus(Transaction.SUCCESS);
		return response;
	} catch (Exception e) {
		Cat.getProducer().logError(e);
		t.setStatus(e);
		throw e;
	} finally {
		t.complete();
	}
}
 
Example 30
Source Project: openapi-generator   Source File: ApiClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    logRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    logResponse(response);
    return response;
}