Java 类org.springframework.http.client.ClientHttpRequestExecution 实例源码

项目:spring-rest-template-logger    文件:LoggingInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
    throws IOException
{
    if (log.isDebugEnabled())
    {
        log.debug(String.format("Request: %s %s %s", request.getMethod(), request.getURI(),
            new String(body, getCharset(request))));
    }

    ClientHttpResponse response = execution.execute(request, body);

    if (log.isDebugEnabled())
    {
        log.debug(String.format("Response: %s %s", response.getStatusCode().value(),
            copyToString(response.getBody(), getCharset(response))));
    }

    return response;
}
项目:incubator-servicecomb-saga    文件:TransactionClientHttpRequestInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
    ClientHttpRequestExecution execution) throws IOException {

  if (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());
  }
  return execution.execute(request, body);
}
项目:desafio-pagarme    文件:Client.java   
/**
 * Sets the api key.
 *
 * @throws JsonParseException the json parse exception
 * @throws JsonMappingException the json mapping exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void setApiKey() throws JsonParseException, JsonMappingException, IOException{
    ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
    interceptors.add((HttpRequest request, byte[] body, ClientHttpRequestExecution execution) -> {
        if(body.length > 0) {
            body = addTokenInObject(body, new JsonNodeFormatter());
        }else{
            try {
                request = addTokenInURI(request);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
        return execution.execute(request, body);
    });
    this.restTemplate.setInterceptors(interceptors);
}
项目:mojito    文件:FormLoginAuthenticationCsrfTokenInterceptor.java   
/**
 * Init
 */
@PostConstruct
protected void init() {

    restTemplateForAuthenticationFlow = new CookieStoreRestTemplate();
    cookieStore = restTemplateForAuthenticationFlow.getCookieStore();

    logger.debug("Inject cookie store used in the rest template for authentication flow into the authRestTemplate so that they will match");
    authRestTemplate.restTemplate.setCookieStoreAndUpdateRequestFactory(cookieStore);

    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor>singletonList(new ClientHttpRequestInterceptor() {
                @Override
                public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
                    if (latestCsrfToken != null) {
                        // At the beginning of auth flow, there's no token yet
                        injectCsrfTokenIntoHeader(request, latestCsrfToken);
                    }
                    return execution.execute(request, body);
                }
            });

    restTemplateForAuthenticationFlow.setRequestFactory(new InterceptingClientHttpRequestFactory(restTemplateForAuthenticationFlow.getRequestFactory(), interceptors));
}
项目:YaasRestClientProject    文件:YaasRequestInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {

    HttpHeaders headers = request.getHeaders();
    String hybrisRequestId = headers.getFirst(YaasAwareTrait.Headers.REQUEST_ID);
    LOGGER.debug(CHECKING_IF_IS_PRESENT, YaasAwareTrait.Headers.REQUEST_ID, hybrisRequestId);
    if (StringUtils.isEmpty(hybrisRequestId)) {
        headers.set(YaasAwareTrait.Headers.REQUEST_ID, StringUtils.EMPTY);
        LOGGER.debug(ADDING_UPDATING_WITH, YaasAwareTrait.Headers.REQUEST_ID, StringUtils.EMPTY);
    }

    String hybrisHop = headers.getFirst(YaasAwareTrait.Headers.HOP);
    LOGGER.debug(CHECKING_IF_IS_PRESENT, YaasAwareTrait.Headers.HOP, hybrisHop);
    String newHybrisHop = "0";
    if (NumberUtils.isDigits(hybrisHop)) {
        int hop = NumberUtils.toInt(hybrisHop);
        hop++;
        newHybrisHop = Integer.toString(hop);
    }
    headers.set(YaasAwareTrait.Headers.HOP, newHybrisHop);
    LOGGER.debug(ADDING_UPDATING_WITH, YaasAwareTrait.Headers.HOP, newHybrisHop);

    return clientHttpRequestExecution.execute(request, body);
}
项目:wingtips    文件:WingtipsClientHttpRequestInterceptor.java   
@Override
public ClientHttpResponse intercept(
    HttpRequest request, byte[] body, ClientHttpRequestExecution execution
) throws IOException {
    Tracer tracer = Tracer.getInstance();
    Span spanAroundCall = null;
    try {
        if (surroundCallsWithSubspan) {
            // Will start a new trace if necessary, or a subspan if a trace is already in progress.
            spanAroundCall = tracer.startSpanInCurrentContext(getSubspanSpanName(request), SpanPurpose.CLIENT);
        }

        HttpRequest wrapperRequest = new HttpRequestWrapperWithModifiableHeaders(request);
        propagateTracingHeaders(wrapperRequest, tracer.getCurrentSpan());

        return execution.execute(wrapperRequest, body);
    }
    finally {
        if (spanAroundCall != null) {
            // Span.close() contains the logic we want - if the spanAroundCall was an overall span (new trace)
            //      then tracer.completeRequestSpan() will be called, otherwise it's a subspan and
            //      tracer.completeSubSpan() will be called.
            spanAroundCall.close();
        }
    }
}
项目:haven-platform    文件:RegistryAuthInterceptor.java   
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
                                    final ClientHttpRequestExecution execution) throws IOException {
    final HttpHeaders headers = request.getHeaders();
    ClientHttpResponse execute = execution.execute(request, body);

    if (execute.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        List<String> list = execute.getHeaders().get("Www-Authenticate");
        if (!CollectionUtils.isEmpty(list)) {
            String tokenString = list.get(0);
            RegistryAuthAdapter.AuthContext ctx = new RegistryAuthAdapter.AuthContext(headers,
              HttpHeaders.readOnlyHttpHeaders(headers),
              tokenString);
            adapter.handle(ctx);
            return execution.execute(request, body);
        }
    }
    return execute;
}
项目:bowman    文件:JsonClientHttpRequestInterceptorTest.java   
@Test
public void interceptSetsContentTypeAndAcceptHeaders() throws IOException {
    HttpRequest request = mock(HttpRequest.class);
    when(request.getHeaders()).thenReturn(new HttpHeaders());

    ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);

    interceptor.intercept(request, new byte[] {1}, execution);

    ArgumentCaptor<HttpRequest> finalRequest = ArgumentCaptor.forClass(HttpRequest.class);
    verify(execution).execute(finalRequest.capture(), aryEq(new byte[] {1}));

    HttpHeaders finalHeaders = finalRequest.getValue().getHeaders();
    assertThat(finalHeaders.getAccept(), contains(MediaType.valueOf("application/hal+json")));
    assertThat(finalHeaders.getContentType(), is(MediaType.valueOf("application/hal+json")));
}
项目:bowman    文件:AbstractIT.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {

    if (LOG.isTraceEnabled()) {
        LOG.trace(request.getMethod().name() + " " + request.getURI() + " : "
                + new String(body, "UTF-8"));
    }

    ClientHttpResponse response = execution.execute(request, body);

    if (LOG.isTraceEnabled()) {
        LOG.trace("response " + response.getStatusCode().value() + " : "
                + IOUtils.toString(response.getBody()));
    }

    return response;
}
项目:Robusto    文件:ResponseTimeInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException
{
   long startTime = System.currentTimeMillis();

   ClientHttpResponse response = execution.execute(request, body);

   long endTime = System.currentTimeMillis();

   if(useDebug)
   {
      LOG.debug("Request for {} took {} ms", request.getURI().toString(), endTime - startTime);
   }
   else
   {
      LOG.info("Request for {} took {} ms", request.getURI().toString(), endTime - startTime);
   }

   return response;
}
项目:uaa-service    文件:HttpHeaderInterceptor.java   
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
        final ClientHttpRequestExecution execution) throws IOException {

    final HttpHeaders requestHeaders = request.getHeaders();

    for (final Entry<String, String> entry : headers.entrySet()) {
        requestHeaders.add(entry.getKey(), entry.getValue());
    }

    return execution.execute(request, body);
}
项目:riptide    文件:PluginInterceptors.java   
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
        final ClientHttpRequestExecution execution) throws IOException {

    final RequestArguments arguments = toArguments(request, body);
    final RequestExecution requestExecution = () -> {
        final CompletableFuture<ClientHttpResponse> future = new CompletableFuture<>();

        try {
            future.complete(execution.execute(request, body));
        } catch (final Exception e) {
            future.completeExceptionally(e);
        }

        return future;
    };

    // since there is no routing to be done, we just call the plugin twice in succession
    final RequestExecution before = plugin.interceptBeforeRouting(arguments, requestExecution);
    final RequestExecution after = plugin.interceptAfterRouting(arguments, before);

    return Completion.join(after.execute());
}
项目:github-job-keywords    文件:XUserAgentInterceptor.java   
/**
 * This isn't needed now - but was needed when trying to figure out why term extractor wasn't
 * returning data.
 */
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {

    // HttpHeaders headers = request.getHeaders();
    // headers.add("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    /*
     * headers.add("X-User-Agent",
     * "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 Query String Parametersview sourceview URL encoded"
     * );
     * headers.add("Accept-Encoding", "gzip, deflate, sdch");
     * headers.add("Accept-Language", "en-US,en;q=0.8");
     * headers.add("Cache-Control", "max-age=0");
     * headers.add("Connection", "keep-alive");
     * headers.add("Cookie",
     * "CTK=19asr9k230nph1f0; RF=\"TFTzyBUJoNr4wP5QpciSOn6ifEMTEVq4ARC0hGY5P-gkhvCY-D1UltWIqfxDhxhHqiN1UggLuPE=\"; IRF=\"1qRi-3v0F_uf-yOkOwHemehIPriDHeZ-AD_rnIAayJ8=\"; CSRF=RCTCj8Abxq9j3u0bL2cYybndr26rFwzL; LC=\"co=FR&hl=fr_FR\"; SHOE=\"uQsQNsQkFYUJ008ISZ8DRWVFtv6W_JMN4mdL-LLfXiJuOW0VoJAjjiVpkv4kQoV23Sg-_-1ytM1OqAz8ROZROJDcOAoDohJHdMU_EBqxbwMOyVIOjrryq7DH189GzMI=\"; PUB=1; BIGipServerjob_iad=!YlkJJm1KgDuhYWHnj+SL47ecq6aoxVInDdjtEnHOjpnVpzOxZBWTrFttjRp0eryuGzkmkx1TYdWHS2k=; INDEED_CSRF_TOKEN=ClPCTHOQ2zlw3egLg2bQl8WakmtEeWpf; _mkto_trk=id:699-SXJ-715&token:_mch-indeed.com-1420554563497-42566; TS01c598d3=0160a2beff09f16a3c10d0f0f0a6a553318c160463ca6c315ab349cad0aefb8dfaa95db17be5052c844f60ecad51ec7c72d952d440688e76cfdabdb3074ee99a7773918ac93d8b06d43de5f602f27582982fb39fbe34263631f197d1f19e0fb70752db8b562fd68ecd5716b3e3d26da06ac246cd6f060c5f347cb466bd53402f81a2506ff7ee638943466c4de4e47bb62d5ee23bd42ae6ba9a59c0ca38e446b40736cbc688; DCT=4; JSESSIONID=97208F039EED60B31A14EF12640B8D84.jasxB_iad-job18; TS016080f8=0160a2beff8af91efc651c51dff589379d71c19e188469c827f0265638b0194c2885f98c9fe455fc17b6ea59258cb631c44485df3e271eae4c2090e2cedce12f163b39094c07e6f01fc7144638866b7333691120a4c4648f7b3b8f00c08419b665958f61ce"
     * );
     * headers.add("DNT", "1");
     * headers.add("Host", "api.indeed.com");
     */
    return execution.execute(request, body);
}
项目:request-correlation-spring-cloud-starter    文件:ClientHttpRequestCorrelationInterceptorTest.java   
@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);
}
项目:request-correlation-spring-cloud-starter    文件:ClientHttpRequestCorrelationInterceptorTest.java   
@Test
public void shouldNotSetHeader() throws IOException {

    // given
    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
    assertFalse(request.getHeaders().containsKey(RequestCorrelationConsts.HEADER_NAME));
    verify(execution).execute(request, body);
}
项目:spring-cloud-netflix-contrib    文件:SpectatorClientHttpRequestInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    String urlTemplate = RestTemplateUrlTemplateHolder.getRestTemplateUrlTemplate();
    if (urlTemplate == null)
        urlTemplate = "none";

    long startTime = registry.clock().wallTime();
    String status = "CLIENT_ERROR";
    try {
        ClientHttpResponse response = execution.execute(request, body);
        status = ((Integer) response.getRawStatusCode()).toString();
        return response;
    } finally {
        String host = request.getURI().getHost();

        registry.timer(metricName, "method", request.getMethod().name(), "uri",
                urlTemplate.replaceAll("^https?://[^/]+/", "").replaceAll("/", "_").replaceAll("[{}]", "-"),
                "status", status, "clientName", host != null ? host : "none").record(
                registry.clock().wallTime() - startTime, TimeUnit.MILLISECONDS);
    }
}
项目:Robusto    文件:ResponseTimeInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException
{
   long startTime = System.currentTimeMillis();

   ClientHttpResponse response = execution.execute(request, body);

   long endTime = System.currentTimeMillis();

   if(useDebug)
   {
      LOG.debug("Request for {} took {} ms", request.getURI().toString(), endTime - startTime);
   }
   else
   {
      LOG.info("Request for {} took {} ms", request.getURI().toString(), endTime - startTime);
   }

   return response;
}
项目:computoser    文件:PurchaseService.java   
@PostConstruct
public void init() {
    jsonMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
    template.getInterceptors().add(new ClientHttpRequestInterceptor() {

        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
                throws IOException {
            request.getHeaders().add("Accept", "application/json");
            request.getHeaders().add("Content-Type", "application/json");
            request.getHeaders().add("User-Agent", "");
            return execution.execute(request, body);
        }
    });
    //paymentContext = new PaymillContext(secret);
}
项目:spring-cloud-commons    文件:LoadBalancerRequestFactory.java   
public LoadBalancerRequest<ClientHttpResponse> createRequest(final HttpRequest request,
        final byte[] body, final ClientHttpRequestExecution execution) {
    return new LoadBalancerRequest<ClientHttpResponse>() {

        @Override
        public ClientHttpResponse apply(final ServiceInstance instance)
                throws Exception {
            HttpRequest serviceRequest = new ServiceRequestWrapper(request, instance, loadBalancer);
            if (transformers != null) {
                for (LoadBalancerRequestTransformer transformer : transformers) {
                    serviceRequest = transformer.transformRequest(serviceRequest, instance);
                }
            }
            return execution.execute(serviceRequest, body);
        }

    };
}
项目:spring-cloud-commons    文件:RetryLoadBalancerInterceptorTest.java   
@Test(expected = IOException.class)
public void interceptDisableRetry() throws Throwable {
    HttpRequest request = mock(HttpRequest.class);
    when(request.getURI()).thenReturn(new URI("http://foo"));
    LoadBalancedRetryPolicyFactory lbRetryPolicyFactory = mock(LoadBalancedRetryPolicyFactory.class);
    when(lbRetryPolicyFactory.create(eq("foo"), any(ServiceInstanceChooser.class))).thenReturn(null);
    ServiceInstance serviceInstance = mock(ServiceInstance.class);
    when(client.choose(eq("foo"))).thenReturn(serviceInstance);
    when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenThrow(new IOException());
    lbProperties.setEnabled(false);
    RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory,
            lbRequestFactory, backOffPolicyFactory, retryListenerFactory);
    byte[] body = new byte[]{};
    ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);

    when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class));

    interceptor.intercept(request, body, execution);
    verify(lbRequestFactory).createRequest(request, body, execution);
}
项目:spring-cloud-commons    文件:RetryLoadBalancerInterceptorTest.java   
@Test
public void interceptNeverRetry() throws Throwable {
    HttpRequest request = mock(HttpRequest.class);
    when(request.getURI()).thenReturn(new URI("http://foo"));
    ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[]{}, HttpStatus.OK);
    LoadBalancedRetryPolicyFactory lbRetryPolicyFactory = mock(LoadBalancedRetryPolicyFactory.class);
    when(lbRetryPolicyFactory.create(eq("foo"), any(ServiceInstanceChooser.class))).thenReturn(null);
    ServiceInstance serviceInstance = mock(ServiceInstance.class);
    when(client.choose(eq("foo"))).thenReturn(serviceInstance);
    when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse);
    when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class));
    lbProperties.setEnabled(true);
    RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory,
            lbRequestFactory, backOffPolicyFactory, retryListenerFactory);
    byte[] body = new byte[]{};
    ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
    interceptor.intercept(request, body, execution);
    verify(lbRequestFactory).createRequest(request, body, execution);
}
项目:spring-cloud-commons    文件:RetryLoadBalancerInterceptorTest.java   
@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);
      LoadBalancedRetryPolicyFactory lbRetryPolicyFactory = mock(LoadBalancedRetryPolicyFactory.class);
      when(lbRetryPolicyFactory.create(eq("foo"), any(ServiceInstanceChooser.class))).thenReturn(policy);
      ServiceInstance serviceInstance = mock(ServiceInstance.class);
      when(client.choose(eq("foo"))).thenReturn(serviceInstance);
      when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse);
when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class));
      lbProperties.setEnabled(true);
      RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory,
              lbRequestFactory, backOffPolicyFactory, retryListenerFactory);
      byte[] body = new byte[]{};
      ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
      ClientHttpResponse rsp = interceptor.intercept(request, body, execution);
      assertThat(rsp, is(clientHttpResponse));
      verify(lbRequestFactory).createRequest(request, body, execution);
  }
项目:spring-cloud-commons    文件:RetryLoadBalancerInterceptorTest.java   
@Test(expected = IOException.class)
  public void interceptFailedRetry() throws Exception {
      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);
      when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))).thenReturn(false);
      LoadBalancedRetryPolicyFactory lbRetryPolicyFactory = mock(LoadBalancedRetryPolicyFactory.class);
      when(lbRetryPolicyFactory.create(eq("foo"), any(ServiceInstanceChooser.class))).thenReturn(policy);
      ServiceInstance serviceInstance = mock(ServiceInstance.class);
      when(client.choose(eq("foo"))).thenReturn(serviceInstance);
      when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenThrow(new IOException()).thenReturn(clientHttpResponse);
when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class));
      lbProperties.setEnabled(true);
      RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory,
              lbRequestFactory, backOffPolicyFactory, retryListenerFactory);
      byte[] body = new byte[]{};
      ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
      interceptor.intercept(request, body, execution);
      verify(lbRequestFactory).createRequest(request, body, execution);
  }
项目:spring-cloud-commons    文件:RetryLoadBalancerInterceptorTest.java   
@Test(expected = TerminatedRetryException.class)
public void retryListenerTestNoRetry() throws Throwable {
    HttpRequest request = mock(HttpRequest.class);
    when(request.getURI()).thenReturn(new URI("http://noRetry"));
    ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[]{}, HttpStatus.OK);
    LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class);
    LoadBalancedRetryPolicyFactory lbRetryPolicyFactory = mock(LoadBalancedRetryPolicyFactory.class);
    when(lbRetryPolicyFactory.create(eq("noRetry"), any(ServiceInstanceChooser.class))).thenReturn(policy);
    LoadBalancedBackOffPolicyFactory backOffPolicyFactory = mock(LoadBalancedBackOffPolicyFactory.class);
    MyBackOffPolicy backOffPolicy = new MyBackOffPolicy();
    when(backOffPolicyFactory.createBackOffPolicy(eq("noRetry"))).thenReturn(backOffPolicy);
    ServiceInstance serviceInstance = mock(ServiceInstance.class);
    lbProperties.setEnabled(true);
    MyRetryListenersNotRetry retryListeners = new MyRetryListenersNotRetry();
    RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory, lbRequestFactory,
        backOffPolicyFactory, retryListeners);
    byte[] body = new byte[]{};
    ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
    interceptor.intercept(request, body, execution);
}
项目:chassis    文件:HttpTransportTest.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    logger.info("Sending headers: " + request.getHeaders());

    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);
}
项目:spring-social-slideshare    文件:SlideShareTemplate.java   
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
                                    ClientHttpRequestExecution execution) throws
                                                                          IOException {
    HttpRequest protectedResourceRequest = new HttpRequestDecorator(request) {
        @Override
        public URI getURI() {

            String ts = Long.toString(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
            String hash = DigestUtils.sha1Hex(sharedSecret + ts).toLowerCase();

            UriComponentsBuilder builder = UriComponentsBuilder.fromUri(super.getURI());
            builder.queryParam("api_key", apiKey);
            builder.queryParam("ts", ts);
            builder.queryParam("hash", hash);

            // all params are already encoded at this point
            UriComponents uriComponents = builder.build(true);
            logger.debug("requesting SlideShare API: " + uriComponents.toUriString());

            return uriComponents.toUri();
        }
    };

    return execution.execute(protectedResourceRequest, body);
}
项目:oauth-client-master    文件:ImplicitProviderTests.java   
@Test
@OAuth2ContextConfiguration(resource = AutoApproveImplicit.class, initialize = false)
public void testPostForAutomaticApprovalToken() throws Exception {
    final ImplicitAccessTokenProvider implicitProvider = new ImplicitAccessTokenProvider();
    implicitProvider.setInterceptors(Arrays
            .<ClientHttpRequestInterceptor> asList(new ClientHttpRequestInterceptor() {
                public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                        ClientHttpRequestExecution execution) throws IOException {
                    ClientHttpResponse result = execution.execute(request, body);
                    latestHeaders = result.getHeaders();
                    return result;
                }
            }));
    context.setAccessTokenProvider(implicitProvider);
    context.getAccessTokenRequest().setCookie(cookie);
    assertNotNull(context.getAccessToken());
    assertTrue("Wrong location header: " + latestHeaders.getLocation().getFragment(), latestHeaders.getLocation().getFragment()
            .contains("scope=read write trust"));
}
项目:github-cla-integration    文件:RateLimitingClientHttpRequestInterceptorTest.java   
@Test
public void block() throws InterruptedException, IOException {
    CountDownLatch latch = new CountDownLatch(1);

    MockClientHttpRequest request = new MockClientHttpRequest();
    MockClientHttpResponse response = new MockClientHttpResponse(new byte[0], HttpStatus.OK);
    ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);

    request.setMethod(HttpMethod.GET);
    request.setURI(URI.create("http://localhost"));

    when(execution.execute(request, new byte[0])).thenReturn(response);

    new Thread(new Trigger(this.interceptor, latch)).start();
    latch.await();

    this.interceptor.intercept(request, new byte[0], execution);
}
项目:github-cla-integration    文件:RateLimitingClientHttpRequestInterceptorTest.java   
@Override
public void run() {
    MockClientHttpRequest request = new MockClientHttpRequest();
    MockClientHttpResponse response = new MockClientHttpResponse(new byte[0], HttpStatus.OK);
    ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);

    response.getHeaders().add("X-RateLimit-Remaining", "50");
    response.getHeaders().add("X-RateLimit-Reset", String.valueOf((System.currentTimeMillis() / 1000) + 1));

    try {
        when(execution.execute(request, new byte[0])).thenReturn(response);

        this.interceptor.intercept(request, new byte[0], execution);
    } catch (IOException e) {
    } finally {
        this.latch.countDown();
    }
}
项目:Settings    文件:ApiClient.java   
@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;
}
项目:tx-lcn    文件:TransactionHttpRequestInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    TxTransactionLocal txTransactionLocal = TxTransactionLocal.current();
    String groupId = txTransactionLocal==null?null:txTransactionLocal.getGroupId();
    request.getHeaders().add("tx-group",groupId);
    if (txTransactionLocal != null) {
        if (txTransactionLocal.isHasCompensate()) {
            request.getHeaders().add("tx-group", CompensateService.COMPENSATE_KEY);
        } else {
            request.getHeaders().add("tx-group",groupId);
        }
    }
    return execution.execute(request,body);
}
项目:che-starter    文件:GitHubInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add(AUTHORIZATION_HEADER, gitHubToken);
    headers.add(USER_AGENT_HEADER, USER_AGENT_VALUE);
    headers.setContentType(MediaType.APPLICATION_JSON);
    return execution.execute(request, body);
}
项目:che-starter    文件:KeycloakInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add(AUTHORIZATION_HEADER, keycloakToken);
    headers.add(REQUEST_ID_HEADER, getRequestId());
    return execution.execute(request, body);
}
项目:micrometer    文件:MetricsClientHttpRequestInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                    ClientHttpRequestExecution execution) throws IOException {
    long startTime = System.nanoTime();
    ClientHttpResponse response = null;
    try {
        response = execution.execute(request, body);
        return response;
    } finally {
        getTimeBuilder(request, response).register(this.meterRegistry)
            .record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
        urlTemplate.remove();
    }
}
项目:OAuth-2.0-Cookbook    文件:HttpRequestWithPoPSignatureInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
    ClientHttpRequestExecution execution) throws IOException {
    OAuth2ClientContext clientContext = applicationContext.getBean(OAuth2ClientContext.class);
    OAuth2AccessToken accessToken = clientContext.getAccessToken();

    request.getHeaders().set("Authorization", "Bearer " + accessToken.getValue());
    request.getHeaders().set("nonce", keyPairManager.getSignedContent(UUID.randomUUID().toString()));

    return execution.execute(request, body);
}
项目:twitch4j    文件:HeaderRequestInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpRequestWrapper wrapper = new HttpRequestWrapper(request);

    if(name != null && value != null) {
        wrapper.getHeaders().set(name, value);
    }

    return execution.execute(wrapper, body);
}
项目:twitch4j    文件:QueryRequestInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpRequestDecorator httpRequest = new HttpRequestDecorator(request);

    if(name != null && value != null) {
        httpRequest.addParameter(name, value);
    }

    return execution.execute(httpRequest, body);
}
项目:logistimo-web-service    文件:LocaleRequestInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                    ClientHttpRequestExecution execution) throws
    IOException {
  SecureUserDetails
      userDetails =
      ThreadLocalUtil.get().getSecureUserDetails();
  if (userDetails != null) {
    request.getHeaders().set("Accept-Language", userDetails.getLocale().getLanguage());
  }
  return execution.execute(request, body);
}
项目:sample.microservices.security.jwt    文件:JWTAuthenticationInterceptor.java   
@Override
public ClientHttpResponse intercept(
        HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {

    HttpHeaders headers = request.getHeaders();
    headers.add("jwt", getJwt());
    return execution.execute(request, body);
}
项目:eventapis    文件:RequestInterceptor.java   
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    traceRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    traceResponse(response);
    return response;
}