当前位置: 首页>>代码示例>>Java>>正文


Java HttpCacheContext.create方法代码示例

本文整理汇总了Java中org.apache.http.client.cache.HttpCacheContext.create方法的典型用法代码示例。如果您正苦于以下问题:Java HttpCacheContext.create方法的具体用法?Java HttpCacheContext.create怎么用?Java HttpCacheContext.create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.http.client.cache.HttpCacheContext的用法示例。


在下文中一共展示了HttpCacheContext.create方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: setUp

import org.apache.http.client.cache.HttpCacheContext; //导入方法依赖的package包/类
@Before
public void setUp() {
    host = new HttpHost("foo.example.com", 80);

    route = new HttpRoute(host);

    body = HttpTestUtils.makeBody(entityLength);

    request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1));

    context = HttpCacheContext.create();
    context.setTargetHost(host);

    originResponse = Proxies.enhanceResponse(HttpTestUtils.make200Response());

    config = CacheConfig.custom()
        .setMaxCacheEntries(MAX_ENTRIES)
        .setMaxObjectSize(MAX_BYTES)
        .build();

    cache = new BasicHttpCache(config);
    mockBackend = EasyMock.createNiceMock(ClientExecChain.class);
    mockCache = EasyMock.createNiceMock(HttpCache.class);
    impl = createCachingExecChain(mockBackend, cache, config);
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:26,代码来源:AbstractProtocolTest.java

示例2: loadFeed

import org.apache.http.client.cache.HttpCacheContext; //导入方法依赖的package包/类
private EventStreamFeed loadFeed(final String url) throws IOException {
   try {
      final HttpGet httpget = new HttpGet(url + "?embed=rich");
      httpget.addHeader(ACCEPT_HEADER, ACCEPT_EVENTSTORE_ATOM_JSON);
      // httpget.addHeader("ES-LongPoll", "5");

      final HttpCacheContext context = HttpCacheContext.create();
      final CloseableHttpResponse response = httpclient.execute(httpget, context);
      try {
         if (context.getCacheResponseStatus() != null) {
            HttpCacheLoggingUtil.logCacheResponseStatus(name, context.getCacheResponseStatus());
         }

         final int statusCode = response.getStatusLine()
               .getStatusCode();
         if (HttpStatus.SC_NOT_FOUND == statusCode || HttpStatus.SC_NO_CONTENT == statusCode) {
            throw new EventStreamNotFoundException();
         }
         if (!(HttpStatus.SC_OK == statusCode)) {
            throw new RuntimeException("Could not load stream feed from url: " + url);
         }
         final EventStreamFeed result = gson.fromJson(new BufferedReader(new InputStreamReader(response.getEntity()
               .getContent())), EventStreamFeed.class);
         EntityUtils.consume(response.getEntity());
         return result;
      } finally {
         response.close();
      }
   } finally {
      httpclient.close();
   }
}
 
开发者ID:Qyotta,项目名称:axon-eventstore,代码行数:33,代码来源:EsReaderDefaultImpl.java

示例3: loadEvent

import org.apache.http.client.cache.HttpCacheContext; //导入方法依赖的package包/类
private EventResponse loadEvent(final String url) throws IOException {
   try {
      final HttpGet httpget = new HttpGet(url);
      httpget.addHeader(ACCEPT_HEADER, ACCEPT_EVENTSTORE_ATOM_JSON);

      LOGGER.info("Executing request " + httpget.getRequestLine());
      final HttpCacheContext context = HttpCacheContext.create();
      final CloseableHttpResponse response = httpclient.execute(httpget, context);
      try {
         if (context.getCacheResponseStatus() != null) {
            HttpCacheLoggingUtil.logCacheResponseStatus(name, context.getCacheResponseStatus());
         }

         final int statusCode = response.getStatusLine()
               .getStatusCode();
         if (HttpStatus.SC_GONE == statusCode) {
            throw new EventDeletedException();
         }
         if (!(HttpStatus.SC_OK == statusCode)) {
            throw new RuntimeException("Could not load stream feed from url: " + url);
         }
         final String read = read(response.getEntity()
               .getContent());
         final EventResponse result = gson.fromJson(read, EventResponse.class);
         EntityUtils.consume(response.getEntity());
         return result;
      } finally {
         response.close();
      }
   } finally {
      httpclient.close();
   }
}
 
开发者ID:Qyotta,项目名称:axon-eventstore,代码行数:34,代码来源:EsReaderDefaultImpl.java

示例4: setUp

import org.apache.http.client.cache.HttpCacheContext; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
@Before
public void setUp() {
    mockRequestPolicy = createNiceMock(CacheableRequestPolicy.class);
    mockValidityPolicy = createNiceMock(CacheValidityPolicy.class);
    mockBackend = createNiceMock(ClientExecChain.class);
    mockCache = createNiceMock(HttpCache.class);
    mockSuitabilityChecker = createNiceMock(CachedResponseSuitabilityChecker.class);
    mockResponsePolicy = createNiceMock(ResponseCachingPolicy.class);
    mockHandler = createNiceMock(ResponseHandler.class);
    mockUriRequest = createNiceMock(HttpUriRequest.class);
    mockCacheEntry = createNiceMock(HttpCacheEntry.class);
    mockResponseGenerator = createNiceMock(CachedHttpResponseGenerator.class);
    mockCachedResponse = createNiceMock(CloseableHttpResponse.class);
    mockConditionalRequestBuilder = createNiceMock(ConditionalRequestBuilder.class);
    mockConditionalRequest = createNiceMock(HttpRequest.class);
    mockStatusLine = createNiceMock(StatusLine.class);
    mockResponseProtocolCompliance = createNiceMock(ResponseProtocolCompliance.class);
    mockRequestProtocolCompliance = createNiceMock(RequestProtocolCompliance.class);
    mockStorage = createNiceMock(HttpCacheStorage.class);
    config = CacheConfig.DEFAULT;
    asyncValidator = new AsynchronousValidator(config);

    host = new HttpHost("foo.example.com", 80);
    route = new HttpRoute(host);
    request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/stuff",
        HttpVersion.HTTP_1_1));
    context = HttpCacheContext.create();
    context.setTargetHost(host);
    entry = HttpTestUtils.makeCacheEntry();
    impl = createCachingExecChain(mockBackend, mockCache, mockValidityPolicy,
        mockResponsePolicy, mockResponseGenerator, mockRequestPolicy, mockSuitabilityChecker,
        mockConditionalRequestBuilder, mockResponseProtocolCompliance,
        mockRequestProtocolCompliance, config, asyncValidator);
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:36,代码来源:TestCachingExecChain.java

示例5: setUp

import org.apache.http.client.cache.HttpCacheContext; //导入方法依赖的package包/类
@Before
public void setUp() {
    host = new HttpHost("foo.example.com", 80);

    route = new HttpRoute(host);

    body = makeBody(entityLength);

    request = new BasicHttpRequest("GET", "/foo", HTTP_1_1);

    context = HttpCacheContext.create();
    context.setTargetHost(host);

    originResponse = Proxies.enhanceResponse(make200Response());

    final CacheConfig config = CacheConfig.custom()
            .setMaxCacheEntries(MAX_ENTRIES)
            .setMaxObjectSize(MAX_BYTES)
            .build();

    final HttpCache cache = new BasicHttpCache(config);
    mockBackend = EasyMock.createNiceMock(ClientExecChain.class);
    mockEntity = EasyMock.createNiceMock(HttpEntity.class);
    mockCache = EasyMock.createNiceMock(HttpCache.class);

    impl = createCachingExecChain(mockBackend, cache, config);
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:28,代码来源:TestProtocolDeviations.java

示例6: execute

import org.apache.http.client.cache.HttpCacheContext; //导入方法依赖的package包/类
private HttpResponse execute(HttpRequestBase method) throws
        IOException {
  HttpCacheContext context = HttpCacheContext.create();
  HttpResponse response = httpClient.execute(method, context);

  try {
    CacheResponseStatus responseStatus = context.getCacheResponseStatus();
    switch (responseStatus) {
      case CACHE_HIT:
        SpotifyApi.LOGGER.log(
                Level.CONFIG,
                "A response was generated from the cache with no requests sent upstream");
        break;
      case CACHE_MODULE_RESPONSE:
        SpotifyApi.LOGGER.log(
                Level.CONFIG,
                "The response was generated directly by the caching module");
        break;
      case CACHE_MISS:
        SpotifyApi.LOGGER.log(
                Level.CONFIG,
                "The response came from an upstream server");
        break;
      case VALIDATED:
        SpotifyApi.LOGGER.log(
                Level.CONFIG,
                "The response was generated from the cache after validating the entry with the origin server");
        break;
    }
  } catch (Exception e) {
    SpotifyApi.LOGGER.log(Level.SEVERE, e.getMessage());
  }

  return response;
}
 
开发者ID:thelinmichael,项目名称:spotify-web-api-java,代码行数:36,代码来源:SpotifyHttpManager.java

示例7: fetchJsonRpc

import org.apache.http.client.cache.HttpCacheContext; //导入方法依赖的package包/类
protected FetchData fetchJsonRpc(String uri, ScrapeTemplate template, Map<String, Object> actualParams) throws IOException, ExecutionException, RetryException {
    final FetchData fetchData = new FetchData();
    fetchData.setUri(uri);
    fetchData.setProtocol(template.getProtocol());
    fetchData.setProtocolVersion(template.getProtocolVersion());
    fetchData.getRequestParams().putAll(actualParams);

    final HttpCacheContext context = HttpCacheContext.create();
    final HttpPost postReq = new HttpPost(uri);
    final JsonRpc2MethodCall methodCall = new JsonRpc2MethodCall();
    methodCall.setMethod(template.getRpcMethod());
    methodCall.getParams().putAll(actualParams);
    postReq.setEntity(
            new StringEntity(JsonUtils.mapper.writeValueAsString(methodCall), ContentType.APPLICATION_JSON)
    );

    final Retryer<JsonRpc2MethodResult> retryer = RetryerBuilder.<JsonRpc2MethodResult>newBuilder()
            .retryIfExceptionOfType(HttpStatusNotOkException.class)
            .retryIfExceptionOfType(SocketException.class)
            .withStopStrategy(StopStrategies.stopAfterAttempt(10))
            .withWaitStrategy(WaitStrategies.fixedWait(30, TimeUnit.SECONDS))
            .build();

    fetchData.setJsonRpcResult(retryer.call(() -> {
        log.info("Trying fetch {} {} {} {} {} ...",
                template.getProtocol(), template.getProtocolVersion(), uri, template.getRpcMethod(), actualParams);
        try (CloseableHttpResponse resp = httpClient.execute(postReq, context)) {
            log.info("Received {} {} {} bytes {}", context.getCacheResponseStatus(),
                    resp.getEntity().getContentType(), resp.getEntity().getContentLength(),
                    resp.getFirstHeader("Content-Encoding"));
            final String entityBody = IOUtils.toString(resp.getEntity().getContent(), StandardCharsets.UTF_8);
            if (resp.getStatusLine().getStatusCode() < 200 || resp.getStatusLine().getStatusCode() >= 300) {
                log.warn("{} {} {} {} {} HTTP Error {} {}: {}",
                        template.getProtocol(), template.getProtocolVersion(), uri, template.getRpcMethod(), actualParams,
                        resp.getStatusLine().getStatusCode(),
                        resp.getStatusLine().getReasonPhrase(), entityBody);
                throw new HttpStatusNotOkException(String.format("%s %s %s %s %s HTTP Error %s %s: %s",
                        template.getProtocol(), template.getProtocolVersion(), uri, template.getRpcMethod(), actualParams,
                        resp.getStatusLine().getStatusCode(),
                        resp.getStatusLine().getReasonPhrase(), entityBody));
            }
            try {
                final JsonRpc2MethodResult methodResult = JsonUtils.mapper.readValue(entityBody, JsonRpc2MethodResult.class);
                log.trace("JSON-RPC Method result: {}", methodResult);
                if (methodResult.getError() != null) {
                    throw new ScrapeException(methodResult.getError(), "Error fetching %s: %s", uri, methodResult.getError());
                }
                return methodResult;
            } catch (Exception e) {
                log.error(String.format("Error converting %s %s %s %s %s to JSON: %s",
                        template.getProtocol(), template.getProtocolVersion(), uri, template.getRpcMethod(), actualParams,
                        entityBody), e);
                throw new ScrapeException(e, "Error converting %s %s %s %s %s to JSON (see previous log)",
                        template.getProtocol(), template.getProtocolVersion(), uri, template.getRpcMethod(), actualParams);
            }
        }
    }));

    return fetchData;
}
 
开发者ID:soluvas,项目名称:soluvas-scrape,代码行数:61,代码来源:Fetcher.java


注:本文中的org.apache.http.client.cache.HttpCacheContext.create方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。