Java Code Examples for java.net.CacheResponse

The following are top voted examples for showing how to use java.net.CacheResponse. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: JavaApiConverter.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an OkHttp Response.Body containing the supplied information.
 */
private static ResponseBody createOkBody(final Headers okHeaders,
    final CacheResponse cacheResponse) throws IOException {
  final BufferedSource body = Okio.buffer(Okio.source(cacheResponse.getBody()));
  return new ResponseBody() {
    @Override
    public MediaType contentType() {
      String contentTypeHeader = okHeaders.get("Content-Type");
      return contentTypeHeader == null ? null : MediaType.parse(contentTypeHeader);
    }

    @Override
    public long contentLength() {
      return HttpHeaders.contentLength(okHeaders);
    }

    @Override public BufferedSource source() {
      return body;
    }
  };
}
 
Example 2
Project: GitHub   File: CacheAdapterTest.java   Source Code and License 6 votes vote down vote up
@Test public void get_httpGet() throws Exception {
  final URL serverUrl = configureServer(new MockResponse());
  assertEquals("http", serverUrl.getProtocol());

  ResponseCache responseCache = new AbstractResponseCache() {
    @Override public CacheResponse get(
        URI uri, String method, Map<String, List<String>> headers) throws IOException {
      try {
        assertEquals(toUri(serverUrl), uri);
        assertEquals("GET", method);
        assertTrue("Arbitrary standard header not present", headers.containsKey("User-Agent"));
        assertEquals(Collections.singletonList("value1"), headers.get("key1"));
        return null;
      } catch (Throwable t) {
        throw new IOException("unexpected cache failure", t);
      }
    }
  };
  setInternalCache(new CacheAdapter(responseCache));

  connection = new OkUrlFactory(client).open(serverUrl);
  connection.setRequestProperty("key1", "value1");

  executeGet(connection);
}
 
Example 3
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) throws IOException {
  final CacheResponse response = delegate.get(uri, requestMethod, requestHeaders);
  if (response instanceof SecureCacheResponse) {
    return new CacheResponse() {
      @Override public InputStream getBody() throws IOException {
        return response.getBody();
      }

      @Override public Map<String, List<String>> getHeaders() throws IOException {
        return response.getHeaders();
      }
    };
  }
  return response;
}
 
Example 4
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
@Test public void responseCacheRequestHeaders() throws IOException, URISyntaxException {
  server.enqueue(new MockResponse()
      .setBody("ABC"));

  final AtomicReference<Map<String, List<String>>> requestHeadersRef = new AtomicReference<>();
  setInternalCache(new CacheAdapter(new AbstractResponseCache() {
    @Override public CacheResponse get(URI uri, String requestMethod,
        Map<String, List<String>> requestHeaders) throws IOException {
      requestHeadersRef.set(requestHeaders);
      return null;
    }
  }));

  URL url = server.url("/").url();
  URLConnection urlConnection = openConnection(url);
  urlConnection.addRequestProperty("A", "android");
  readAscii(urlConnection);
  assertEquals(Arrays.asList("android"), requestHeadersRef.get().get("A"));
}
 
Example 5
Project: GitHub   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
/** Test for https://code.google.com/p/android/issues/detail?id=160522 */
@Test public void createOkResponseForCacheGet_withMissingStatusLine() throws Exception {
  URI uri = new URI("http://foo/bar");
  Request request = new Request.Builder().url(uri.toURL()).build();
  CacheResponse cacheResponse = new CacheResponse() {
    @Override public Map<String, List<String>> getHeaders() throws IOException {
      Map<String, List<String>> headers = new LinkedHashMap<>();
      // Headers is deliberately missing an entry with a null key.
      headers.put("xyzzy", Arrays.asList("bar", "baz"));
      return headers;
    }

    @Override public InputStream getBody() throws IOException {
      return null; // Should never be called
    }
  };

  try {
    JavaApiConverter.createOkResponseForCacheGet(request, cacheResponse);
    fail();
  } catch (IOException expected) {
  }
}
 
Example 6
Project: GitHub   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
@Test public void createJavaCacheResponse_httpGet() throws Exception {
  Request okRequest =
      createArbitraryOkRequest().newBuilder()
          .url("http://insecure/request")
          .get()
          .build();
  Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
      .protocol(Protocol.HTTP_1_1)
      .code(200)
      .message("Fantastic")
      .addHeader("key1", "value1_1")
      .addHeader("key2", "value2")
      .addHeader("key1", "value1_2")
      .body(null)
      .build();
  CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse);
  assertFalse(javaCacheResponse instanceof SecureCacheResponse);
  Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders();
  assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1"));
  assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null));
  assertNull(javaCacheResponse.getBody());
}
 
Example 7
Project: GitHub   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
@Test public void createJavaCacheResponse_httpPost() throws Exception {
  Request okRequest =
      createArbitraryOkRequest().newBuilder()
          .url("http://insecure/request")
          .post(createRequestBody("RequestBody"))
          .build();
  ResponseBody responseBody = createResponseBody("ResponseBody");
  Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
      .protocol(Protocol.HTTP_1_1)
      .code(200)
      .message("Fantastic")
      .addHeader("key1", "value1_1")
      .addHeader("key2", "value2")
      .addHeader("key1", "value1_2")
      .body(responseBody)
      .build();
  CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse);
  assertFalse(javaCacheResponse instanceof SecureCacheResponse);
  Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders();
  assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1"));
  assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null));
  assertEquals("ResponseBody", readAll(javaCacheResponse.getBody()));
}
 
Example 8
Project: GitHub   File: JavaApiConverter.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an OkHttp Response.Body containing the supplied information.
 */
private static ResponseBody createOkBody(final Headers okHeaders,
    final CacheResponse cacheResponse) throws IOException {
  final BufferedSource body = Okio.buffer(Okio.source(cacheResponse.getBody()));
  return new ResponseBody() {
    @Override
    public MediaType contentType() {
      String contentTypeHeader = okHeaders.get("Content-Type");
      return contentTypeHeader == null ? null : MediaType.parse(contentTypeHeader);
    }

    @Override
    public long contentLength() {
      return HttpHeaders.contentLength(okHeaders);
    }

    @Override public BufferedSource source() {
      return body;
    }
  };
}
 
Example 9
Project: GitHub   File: CacheAdapterTest.java   Source Code and License 6 votes vote down vote up
@Test public void get_httpGet() throws Exception {
  final URL serverUrl = configureServer(new MockResponse());
  assertEquals("http", serverUrl.getProtocol());

  ResponseCache responseCache = new AbstractResponseCache() {
    @Override public CacheResponse get(
        URI uri, String method, Map<String, List<String>> headers) throws IOException {
      try {
        assertEquals(toUri(serverUrl), uri);
        assertEquals("GET", method);
        assertTrue("Arbitrary standard header not present", headers.containsKey("User-Agent"));
        assertEquals(Collections.singletonList("value1"), headers.get("key1"));
        return null;
      } catch (Throwable t) {
        throw new IOException("unexpected cache failure", t);
      }
    }
  };
  setInternalCache(new CacheAdapter(responseCache));

  connection = new OkUrlFactory(client).open(serverUrl);
  connection.setRequestProperty("key1", "value1");

  executeGet(connection);
}
 
Example 10
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) throws IOException {
  final CacheResponse response = delegate.get(uri, requestMethod, requestHeaders);
  if (response instanceof SecureCacheResponse) {
    return new CacheResponse() {
      @Override public InputStream getBody() throws IOException {
        return response.getBody();
      }

      @Override public Map<String, List<String>> getHeaders() throws IOException {
        return response.getHeaders();
      }
    };
  }
  return response;
}
 
Example 11
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
@Test public void responseCacheRequestHeaders() throws IOException, URISyntaxException {
  server.enqueue(new MockResponse()
      .setBody("ABC"));

  final AtomicReference<Map<String, List<String>>> requestHeadersRef = new AtomicReference<>();
  setInternalCache(new CacheAdapter(new AbstractResponseCache() {
    @Override public CacheResponse get(URI uri, String requestMethod,
        Map<String, List<String>> requestHeaders) throws IOException {
      requestHeadersRef.set(requestHeaders);
      return null;
    }
  }));

  URL url = server.url("/").url();
  URLConnection urlConnection = openConnection(url);
  urlConnection.addRequestProperty("A", "android");
  readAscii(urlConnection);
  assertEquals(Arrays.asList("android"), requestHeadersRef.get().get("A"));
}
 
Example 12
Project: GitHub   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
/** Test for https://code.google.com/p/android/issues/detail?id=160522 */
@Test public void createOkResponseForCacheGet_withMissingStatusLine() throws Exception {
  URI uri = new URI("http://foo/bar");
  Request request = new Request.Builder().url(uri.toURL()).build();
  CacheResponse cacheResponse = new CacheResponse() {
    @Override public Map<String, List<String>> getHeaders() throws IOException {
      Map<String, List<String>> headers = new LinkedHashMap<>();
      // Headers is deliberately missing an entry with a null key.
      headers.put("xyzzy", Arrays.asList("bar", "baz"));
      return headers;
    }

    @Override public InputStream getBody() throws IOException {
      return null; // Should never be called
    }
  };

  try {
    JavaApiConverter.createOkResponseForCacheGet(request, cacheResponse);
    fail();
  } catch (IOException expected) {
  }
}
 
Example 13
Project: GitHub   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
@Test public void createJavaCacheResponse_httpGet() throws Exception {
  Request okRequest =
      createArbitraryOkRequest().newBuilder()
          .url("http://insecure/request")
          .get()
          .build();
  Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
      .protocol(Protocol.HTTP_1_1)
      .code(200)
      .message("Fantastic")
      .addHeader("key1", "value1_1")
      .addHeader("key2", "value2")
      .addHeader("key1", "value1_2")
      .body(null)
      .build();
  CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse);
  assertFalse(javaCacheResponse instanceof SecureCacheResponse);
  Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders();
  assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1"));
  assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null));
  assertNull(javaCacheResponse.getBody());
}
 
Example 14
Project: GitHub   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
@Test public void createJavaCacheResponse_httpPost() throws Exception {
  Request okRequest =
      createArbitraryOkRequest().newBuilder()
          .url("http://insecure/request")
          .post(createRequestBody("RequestBody"))
          .build();
  ResponseBody responseBody = createResponseBody("ResponseBody");
  Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
      .protocol(Protocol.HTTP_1_1)
      .code(200)
      .message("Fantastic")
      .addHeader("key1", "value1_1")
      .addHeader("key2", "value2")
      .addHeader("key1", "value1_2")
      .body(responseBody)
      .build();
  CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse);
  assertFalse(javaCacheResponse instanceof SecureCacheResponse);
  Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders();
  assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1"));
  assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null));
  assertEquals("ResponseBody", readAll(javaCacheResponse.getBody()));
}
 
Example 15
Project: LoRaWAN-Smart-Parking   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 16
Project: LoRaWAN-Smart-Parking   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
    throws IOException {
  HttpEngine httpEngine = getHttpEngine(httpConnection);
  URI uri = httpEngine.getUri();
  ResponseHeaders response = httpEngine.getResponseHeaders();
  RawHeaders varyHeaders =
      httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
  Entry entry = new Entry(uri, varyHeaders, httpConnection);
  DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
      ? ((EntryCacheResponse) conditionalCacheHit).snapshot
      : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
  DiskLruCache.Editor editor = null;
  try {
    editor = snapshot.edit(); // returns null if snapshot is not current
    if (editor != null) {
      entry.writeTo(editor);
      editor.commit();
    }
  } catch (IOException e) {
    abortQuietly(editor);
  }
}
 
Example 17
Project: LoRaWAN-Smart-Parking   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 18
Project: LoRaWAN-Smart-Parking   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
    throws IOException {
  HttpEngine httpEngine = getHttpEngine(httpConnection);
  URI uri = httpEngine.getUri();
  ResponseHeaders response = httpEngine.getResponseHeaders();
  RawHeaders varyHeaders =
      httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
  Entry entry = new Entry(uri, varyHeaders, httpConnection);
  DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
      ? ((EntryCacheResponse) conditionalCacheHit).snapshot
      : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
  DiskLruCache.Editor editor = null;
  try {
    editor = snapshot.edit(); // returns null if snapshot is not current
    if (editor != null) {
      entry.writeTo(editor);
      editor.commit();
    }
  } catch (IOException e) {
    abortQuietly(editor);
  }
}
 
Example 19
Project: PriorityOkHttp   File: JavaApiConverter.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an OkHttp Response.Body containing the supplied information.
 */
private static ResponseBody createOkBody(final Headers okHeaders,
    final CacheResponse cacheResponse) throws IOException {
  final BufferedSource body = Okio.buffer(Okio.source(cacheResponse.getBody()));
  return new ResponseBody() {
    @Override
    public MediaType contentType() {
      String contentTypeHeader = okHeaders.get("Content-Type");
      return contentTypeHeader == null ? null : MediaType.parse(contentTypeHeader);
    }

    @Override
    public long contentLength() {
      return OkHeaders.contentLength(okHeaders);
    }

    @Override public BufferedSource source() {
      return body;
    }
  };
}
 
Example 20
Project: PriorityOkHttp   File: CacheAdapterTest.java   Source Code and License 6 votes vote down vote up
@Test public void get_httpGet() throws Exception {
  final URL serverUrl = configureServer(new MockResponse());
  assertEquals("http", serverUrl.getProtocol());

  ResponseCache responseCache = new AbstractResponseCache() {
    @Override public CacheResponse get(
        URI uri, String method, Map<String, List<String>> headers) throws IOException {
      assertEquals(toUri(serverUrl), uri);
      assertEquals("GET", method);
      assertTrue("Arbitrary standard header not present", headers.containsKey("User-Agent"));
      assertEquals(Collections.singletonList("value1"), headers.get("key1"));
      return null;
    }
  };
  setInternalCache(new CacheAdapter(responseCache));

  connection = new OkUrlFactory(client).open(serverUrl);
  connection.setRequestProperty("key1", "value1");

  executeGet(connection);
}
 
Example 21
Project: PriorityOkHttp   File: CacheAdapterTest.java   Source Code and License 6 votes vote down vote up
@Test public void get_httpsGet() throws Exception {
  final URL serverUrl = configureHttpsServer(new MockResponse());
  assertEquals("https", serverUrl.getProtocol());

  ResponseCache responseCache = new AbstractResponseCache() {
    @Override public CacheResponse get(URI uri, String method, Map<String, List<String>> headers)
        throws IOException {
      assertEquals("https", uri.getScheme());
      assertEquals(toUri(serverUrl), uri);
      assertEquals("GET", method);
      assertTrue("Arbitrary standard header not present", headers.containsKey("User-Agent"));
      assertEquals(Collections.singletonList("value1"), headers.get("key1"));
      return null;
    }
  };
  setInternalCache(new CacheAdapter(responseCache));
  client = client.newBuilder()
      .sslSocketFactory(sslContext.getSocketFactory())
      .hostnameVerifier(hostnameVerifier)
      .build();

  connection = new OkUrlFactory(client).open(serverUrl);
  connection.setRequestProperty("key1", "value1");

  executeGet(connection);
}
 
Example 22
Project: PriorityOkHttp   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) throws IOException {
  final CacheResponse response = delegate.get(uri, requestMethod, requestHeaders);
  if (response instanceof SecureCacheResponse) {
    return new CacheResponse() {
      @Override public InputStream getBody() throws IOException {
        return response.getBody();
      }

      @Override public Map<String, List<String>> getHeaders() throws IOException {
        return response.getHeaders();
      }
    };
  }
  return response;
}
 
Example 23
Project: PriorityOkHttp   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
@Test public void responseCacheRequestHeaders() throws IOException, URISyntaxException {
  server.enqueue(new MockResponse()
      .setBody("ABC"));

  final AtomicReference<Map<String, List<String>>> requestHeadersRef = new AtomicReference<>();
  setInternalCache(new CacheAdapter(new AbstractResponseCache() {
    @Override public CacheResponse get(URI uri, String requestMethod,
        Map<String, List<String>> requestHeaders) throws IOException {
      requestHeadersRef.set(requestHeaders);
      return null;
    }
  }));

  URL url = server.url("/").url();
  URLConnection urlConnection = openConnection(url);
  urlConnection.addRequestProperty("A", "android");
  readAscii(urlConnection);
  assertEquals(Arrays.asList("android"), requestHeadersRef.get().get("A"));
}
 
Example 24
Project: PriorityOkHttp   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
/** Test for https://code.google.com/p/android/issues/detail?id=160522 */
@Test public void createOkResponseForCacheGet_withMissingStatusLine() throws Exception {
  URI uri = new URI("http://foo/bar");
  Request request = new Request.Builder().url(uri.toURL()).build();
  CacheResponse cacheResponse = new CacheResponse() {
    @Override public Map<String, List<String>> getHeaders() throws IOException {
      Map<String, List<String>> headers = new HashMap<>();
      // Headers is deliberately missing an entry with a null key.
      headers.put("xyzzy", Arrays.asList("bar", "baz"));
      return headers;
    }

    @Override public InputStream getBody() throws IOException {
      return null; // Should never be called
    }
  };

  try {
    JavaApiConverter.createOkResponseForCacheGet(request, cacheResponse);
    fail();
  } catch (IOException expected) {
  }
}
 
Example 25
Project: PriorityOkHttp   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
@Test public void createJavaCacheResponse_httpGet() throws Exception {
  Request okRequest =
      createArbitraryOkRequest().newBuilder()
          .url("http://insecure/request")
          .get()
          .build();
  Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
      .protocol(Protocol.HTTP_1_1)
      .code(200)
      .message("Fantastic")
      .addHeader("key1", "value1_1")
      .addHeader("key2", "value2")
      .addHeader("key1", "value1_2")
      .body(null)
      .build();
  CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse);
  assertFalse(javaCacheResponse instanceof SecureCacheResponse);
  Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders();
  assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1"));
  assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null));
  assertNull(javaCacheResponse.getBody());
}
 
Example 26
Project: PriorityOkHttp   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
@Test public void createJavaCacheResponse_httpPost() throws Exception {
  Request okRequest =
      createArbitraryOkRequest().newBuilder()
          .url("http://insecure/request")
          .post(createRequestBody("RequestBody"))
          .build();
  ResponseBody responseBody = createResponseBody("ResponseBody");
  Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
      .protocol(Protocol.HTTP_1_1)
      .code(200)
      .message("Fantastic")
      .addHeader("key1", "value1_1")
      .addHeader("key2", "value2")
      .addHeader("key1", "value1_2")
      .body(responseBody)
      .build();
  CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse);
  assertFalse(javaCacheResponse instanceof SecureCacheResponse);
  Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders();
  assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1"));
  assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null));
  assertEquals("ResponseBody", readAll(javaCacheResponse.getBody()));
}
 
Example 27
Project: Okhttp   File: JavaApiConverter.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an OkHttp Response.Body containing the supplied information.
 */
private static ResponseBody createOkBody(final Headers okHeaders,
    final CacheResponse cacheResponse) throws IOException {
  final BufferedSource body = Okio.buffer(Okio.source(cacheResponse.getBody()));
  return new ResponseBody() {
    @Override
    public MediaType contentType() {
      String contentTypeHeader = okHeaders.get("Content-Type");
      return contentTypeHeader == null ? null : MediaType.parse(contentTypeHeader);
    }

    @Override
    public long contentLength() {
      return HttpHeaders.contentLength(okHeaders);
    }

    @Override public BufferedSource source() {
      return body;
    }
  };
}
 
Example 28
Project: Okhttp   File: CacheAdapterTest.java   Source Code and License 6 votes vote down vote up
@Test public void get_httpGet() throws Exception {
  final URL serverUrl = configureServer(new MockResponse());
  assertEquals("http", serverUrl.getProtocol());

  ResponseCache responseCache = new AbstractResponseCache() {
    @Override public CacheResponse get(
        URI uri, String method, Map<String, List<String>> headers) throws IOException {
      try {
        assertEquals(toUri(serverUrl), uri);
        assertEquals("GET", method);
        assertTrue("Arbitrary standard header not present", headers.containsKey("User-Agent"));
        assertEquals(Collections.singletonList("value1"), headers.get("key1"));
        return null;
      } catch (Throwable t) {
        throw new IOException("unexpected cache failure", t);
      }
    }
  };
  setInternalCache(new CacheAdapter(responseCache));

  connection = new OkUrlFactory(client).open(serverUrl);
  connection.setRequestProperty("key1", "value1");

  executeGet(connection);
}
 
Example 29
Project: Okhttp   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) throws IOException {
  final CacheResponse response = delegate.get(uri, requestMethod, requestHeaders);
  if (response instanceof SecureCacheResponse) {
    return new CacheResponse() {
      @Override public InputStream getBody() throws IOException {
        return response.getBody();
      }

      @Override public Map<String, List<String>> getHeaders() throws IOException {
        return response.getHeaders();
      }
    };
  }
  return response;
}
 
Example 30
Project: Okhttp   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
@Test public void responseCacheRequestHeaders() throws IOException, URISyntaxException {
  server.enqueue(new MockResponse()
      .setBody("ABC"));

  final AtomicReference<Map<String, List<String>>> requestHeadersRef = new AtomicReference<>();
  setInternalCache(new CacheAdapter(new AbstractResponseCache() {
    @Override public CacheResponse get(URI uri, String requestMethod,
        Map<String, List<String>> requestHeaders) throws IOException {
      requestHeadersRef.set(requestHeaders);
      return null;
    }
  }));

  URL url = server.url("/").url();
  URLConnection urlConnection = openConnection(url);
  urlConnection.addRequestProperty("A", "android");
  readAscii(urlConnection);
  assertEquals(Arrays.asList("android"), requestHeadersRef.get().get("A"));
}
 
Example 31
Project: Okhttp   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
/** Test for https://code.google.com/p/android/issues/detail?id=160522 */
@Test public void createOkResponseForCacheGet_withMissingStatusLine() throws Exception {
  URI uri = new URI("http://foo/bar");
  Request request = new Request.Builder().url(uri.toURL()).build();
  CacheResponse cacheResponse = new CacheResponse() {
    @Override public Map<String, List<String>> getHeaders() throws IOException {
      Map<String, List<String>> headers = new HashMap<>();
      // Headers is deliberately missing an entry with a null key.
      headers.put("xyzzy", Arrays.asList("bar", "baz"));
      return headers;
    }

    @Override public InputStream getBody() throws IOException {
      return null; // Should never be called
    }
  };

  try {
    JavaApiConverter.createOkResponseForCacheGet(request, cacheResponse);
    fail();
  } catch (IOException expected) {
  }
}
 
Example 32
Project: Okhttp   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
@Test public void createJavaCacheResponse_httpGet() throws Exception {
  Request okRequest =
      createArbitraryOkRequest().newBuilder()
          .url("http://insecure/request")
          .get()
          .build();
  Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
      .protocol(Protocol.HTTP_1_1)
      .code(200)
      .message("Fantastic")
      .addHeader("key1", "value1_1")
      .addHeader("key2", "value2")
      .addHeader("key1", "value1_2")
      .body(null)
      .build();
  CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse);
  assertFalse(javaCacheResponse instanceof SecureCacheResponse);
  Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders();
  assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1"));
  assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null));
  assertNull(javaCacheResponse.getBody());
}
 
Example 33
Project: Okhttp   File: JavaApiConverterTest.java   Source Code and License 6 votes vote down vote up
@Test public void createJavaCacheResponse_httpPost() throws Exception {
  Request okRequest =
      createArbitraryOkRequest().newBuilder()
          .url("http://insecure/request")
          .post(createRequestBody("RequestBody"))
          .build();
  ResponseBody responseBody = createResponseBody("ResponseBody");
  Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
      .protocol(Protocol.HTTP_1_1)
      .code(200)
      .message("Fantastic")
      .addHeader("key1", "value1_1")
      .addHeader("key2", "value2")
      .addHeader("key1", "value1_2")
      .body(responseBody)
      .build();
  CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse);
  assertFalse(javaCacheResponse instanceof SecureCacheResponse);
  Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders();
  assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1"));
  assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null));
  assertEquals("ResponseBody", readAll(javaCacheResponse.getBody()));
}
 
Example 34
Project: smart-mirror-app   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 35
Project: smart-mirror-app   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
    throws IOException {
  HttpEngine httpEngine = getHttpEngine(httpConnection);
  URI uri = httpEngine.getUri();
  ResponseHeaders response = httpEngine.getResponseHeaders();
  RawHeaders varyHeaders =
      httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
  Entry entry = new Entry(uri, varyHeaders, httpConnection);
  DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
      ? ((EntryCacheResponse) conditionalCacheHit).snapshot
      : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
  DiskLruCache.Editor editor = null;
  try {
    editor = snapshot.edit(); // returns null if snapshot is not current
    if (editor != null) {
      entry.writeTo(editor);
      editor.commit();
    }
  } catch (IOException e) {
    abortQuietly(editor);
  }
}
 
Example 36
Project: cordova-plugin-background-mode   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 37
Project: cordova-plugin-background-mode   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
    throws IOException {
  HttpEngine httpEngine = getHttpEngine(httpConnection);
  URI uri = httpEngine.getUri();
  ResponseHeaders response = httpEngine.getResponseHeaders();
  RawHeaders varyHeaders =
      httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
  Entry entry = new Entry(uri, varyHeaders, httpConnection);
  DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
      ? ((EntryCacheResponse) conditionalCacheHit).snapshot
      : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
  DiskLruCache.Editor editor = null;
  try {
    editor = snapshot.edit(); // returns null if snapshot is not current
    if (editor != null) {
      entry.writeTo(editor);
      editor.commit();
    }
  } catch (IOException e) {
    abortQuietly(editor);
  }
}
 
Example 38
Project: krakn   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 39
Project: multirotorstuff-vtx-calc   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
    throws IOException {
  HttpEngine httpEngine = getHttpEngine(httpConnection);
  URI uri = httpEngine.getUri();
  ResponseHeaders response = httpEngine.getResponseHeaders();
  RawHeaders varyHeaders =
      httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
  Entry entry = new Entry(uri, varyHeaders, httpConnection);
  DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
      ? ((EntryCacheResponse) conditionalCacheHit).snapshot
      : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
  DiskLruCache.Editor editor = null;
  try {
    editor = snapshot.edit(); // returns null if snapshot is not current
    if (editor != null) {
      entry.writeTo(editor);
      editor.commit();
    }
  } catch (IOException e) {
    abortQuietly(editor);
  }
}
 
Example 40
Project: volley-it   File: MainActivity.java   Source Code and License 6 votes vote down vote up
/**
 * Fetches an entry value from the HttpResponseCache cache
 * @param connection connection from which we need the cache
 * @param uri uri to use to get the cache entry
 * @return cache entry value as String
 */
private String fetchFromHTTPUrlConnectionCache(HttpURLConnection connection, URI uri) {

    try {
        HttpResponseCache responseCache = HttpResponseCache.getInstalled();
        if(responseCache != null){
            CacheResponse cacheResponse = responseCache.get(uri, "GET", connection.getRequestProperties());
            Scanner scanner = new Scanner(cacheResponse.getBody(), "UTF-8");
            StringBuilder sb = new StringBuilder();
            while (scanner.hasNextLine()){
                sb.append(scanner.nextLine());
            }

            return sb.toString();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;

}
 
Example 41
Project: hackmxdf-2015   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 42
Project: wototoplayer   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 43
Project: L.TileLayer.Cordova   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
    throws IOException {
  HttpEngine httpEngine = getHttpEngine(httpConnection);
  URI uri = httpEngine.getUri();
  ResponseHeaders response = httpEngine.getResponseHeaders();
  RawHeaders varyHeaders =
      httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
  Entry entry = new Entry(uri, varyHeaders, httpConnection);
  DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
      ? ((EntryCacheResponse) conditionalCacheHit).snapshot
      : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
  DiskLruCache.Editor editor = null;
  try {
    editor = snapshot.edit(); // returns null if snapshot is not current
    if (editor != null) {
      entry.writeTo(editor);
      editor.commit();
    }
  } catch (IOException e) {
    abortQuietly(editor);
  }
}
 
Example 44
Project: cordova-muse   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
    throws IOException {
  HttpEngine httpEngine = getHttpEngine(httpConnection);
  URI uri = httpEngine.getUri();
  ResponseHeaders response = httpEngine.getResponseHeaders();
  RawHeaders varyHeaders =
      httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
  Entry entry = new Entry(uri, varyHeaders, httpConnection);
  DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
      ? ((EntryCacheResponse) conditionalCacheHit).snapshot
      : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
  DiskLruCache.Editor editor = null;
  try {
    editor = snapshot.edit(); // returns null if snapshot is not current
    if (editor != null) {
      entry.writeTo(editor);
      editor.commit();
    }
  } catch (IOException e) {
    abortQuietly(editor);
  }
}
 
Example 45
Project: cordova-android-tv   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 46
Project: Cordova-Locale-Plugin   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 47
Project: mytourbook   File: LocalResponseCache.java   Source Code and License 6 votes vote down vote up
@Override
public CacheResponse get(final URI uri, final String rqstMethod, final Map<String, List<String>> rqstHeaders)
		throws IOException {
	final File localFile = getLocalFile(uri);
	if (!localFile.exists()) {
		// the file isn't already in our cache, return null
		return null;
	}

	if (isUpdateAvailable(uri, localFile)) {
		// there is an update available, so don't return cached version
		return null;
	}

	if (!localFile.exists()) {
		// the file isn't already in our cache, return null
		return null;
	}

	return new LocalCacheResponse(localFile, rqstHeaders);
}
 
Example 48
Project: android-discourse   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection) throws IOException {
    HttpEngine httpEngine = getHttpEngine(httpConnection);
    URI uri = httpEngine.getUri();
    ResponseHeaders response = httpEngine.getResponseHeaders();
    RawHeaders varyHeaders = httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
    Entry entry = new Entry(uri, varyHeaders, httpConnection);
    DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse) ? ((EntryCacheResponse) conditionalCacheHit).snapshot : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
    DiskLruCache.Editor editor = null;
    try {
        editor = snapshot.edit(); // returns null if snapshot is not current
        if (editor != null) {
            entry.writeTo(editor);
            editor.commit();
        }
    } catch (IOException e) {
        abortQuietly(editor);
    }
}
 
Example 49
Project: IoTgo_Android_App   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 50
Project: Wetube   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
    throws IOException {
  HttpEngine httpEngine = getHttpEngine(httpConnection);
  URI uri = httpEngine.getUri();
  ResponseHeaders response = httpEngine.getResponseHeaders();
  RawHeaders varyHeaders =
      httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
  Entry entry = new Entry(uri, varyHeaders, httpConnection);
  DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
      ? ((EntryCacheResponse) conditionalCacheHit).snapshot
      : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
  DiskLruCache.Editor editor = null;
  try {
    editor = snapshot.edit(); // returns null if snapshot is not current
    if (editor != null) {
      entry.writeTo(editor);
      editor.commit();
    }
  } catch (IOException e) {
    abortQuietly(editor);
  }
}
 
Example 51
Project: CanDoVS2015   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 52
Project: android-discourse   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override
public CacheResponse get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders) {
    String key = uriToKey(uri);
    DiskLruCache.Snapshot snapshot;
    Entry entry;
    try {
        snapshot = cache.get(key);
        if (snapshot == null) {
            return null;
        }
        entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
    } catch (IOException e) {
        // Give up because the cache cannot be read.
        return null;
    }

    if (!entry.matches(uri, requestMethod, requestHeaders)) {
        snapshot.close();
        return null;
    }

    return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot) : new EntryCacheResponse(entry, snapshot);
}
 
Example 53
Project: krakn   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 54
Project: CrossWalkAndroidStudio   File: HttpResponseCache.java   Source Code and License 6 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) {
  String key = uriToKey(uri);
  DiskLruCache.Snapshot snapshot;
  Entry entry;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
    entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
  } catch (IOException e) {
    // Give up because the cache cannot be read.
    return null;
  }

  if (!entry.matches(uri, requestMethod, requestHeaders)) {
    snapshot.close();
    return null;
  }

  return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
      : new EntryCacheResponse(entry, snapshot);
}
 
Example 55
Project: GitHub   File: CacheAdapter.java   Source Code and License 5 votes vote down vote up
@Override public Response get(Request request) throws IOException {
  CacheResponse javaResponse = getJavaCachedResponse(request);
  if (javaResponse == null) {
    return null;
  }
  return JavaApiConverter.createOkResponseForCacheGet(request, javaResponse);
}
 
Example 56
Project: GitHub   File: AndroidShimResponseCache.java   Source Code and License 5 votes vote down vote up
@Override public CacheResponse get(URI uri, String requestMethod,
    Map<String, List<String>> requestHeaders) throws IOException {
  Request okRequest = JavaApiConverter.createOkRequest(uri, requestMethod, requestHeaders);
  Response okResponse = delegate.internalCache.get(okRequest);
  if (okResponse == null) {
    return null;
  }
  return JavaApiConverter.createJavaCacheResponse(okResponse);
}
 
Example 57
Project: GitHub   File: CacheAdapterTest.java   Source Code and License 5 votes vote down vote up
@Test public void get_httpsGet() throws Exception {
  final URL serverUrl = configureHttpsServer(new MockResponse());
  assertEquals("https", serverUrl.getProtocol());

  ResponseCache responseCache = new AbstractResponseCache() {
    @Override public CacheResponse get(URI uri, String method, Map<String, List<String>> headers)
        throws IOException {
      try {
        assertEquals("https", uri.getScheme());
        assertEquals(toUri(serverUrl), uri);
        assertEquals("GET", method);
        assertTrue("Arbitrary standard header not present", headers.containsKey("User-Agent"));
        assertEquals(Collections.singletonList("value1"), headers.get("key1"));
        return null;
      } catch (Throwable t) {
        throw new IOException("unexpected cache failure", t);
      }
    }
  };
  setInternalCache(new CacheAdapter(responseCache));
  client = client.newBuilder()
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(hostnameVerifier)
      .build();

  connection = new OkUrlFactory(client).open(serverUrl);
  connection.setRequestProperty("key1", "value1");

  executeGet(connection);
}
 
Example 58
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 5 votes vote down vote up
private void assertCached(boolean shouldPut, int responseCode) throws Exception {
  int expectedResponseCode = responseCode;

  server = new MockWebServer();
  MockResponse mockResponse = new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setResponseCode(responseCode)
      .setBody("ABCDE")
      .addHeader("WWW-Authenticate: challenge");
  if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
    mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
  } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
    mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
  } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT
      || responseCode == HttpURLConnection.HTTP_RESET) {
    mockResponse.setBody(""); // We forbid bodies for 204 and 205.
  }
  server.enqueue(mockResponse);

  if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
    // 408's are a bit of an outlier because we may repeat the request if we encounter this
    // response code. In this scenario, there are 2 responses: the initial 408 and then the 200
    // because of the retry. We just want to ensure the initial 408 isn't cached.
    expectedResponseCode = 200;
    server.enqueue(new MockResponse()
        .setHeader("Cache-Control", "no-store")
        .setBody("FGHIJ"));
  }

  server.start();

  URL url = server.url("/").url();
  HttpURLConnection connection = openConnection(url);
  assertEquals(expectedResponseCode, connection.getResponseCode());

  // Exhaust the content stream.
  readAscii(connection);

  CacheResponse cached = cache.get(url.toURI(), "GET", null);
  if (shouldPut) {
    assertNotNull(Integer.toString(responseCode), cached);
  } else {
    assertNull(Integer.toString(responseCode), cached);
  }
  server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers
}
 
Example 59
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 5 votes vote down vote up
/**
 * Fail if a badly-behaved cache returns a null status line header.
 * https://code.google.com/p/android/issues/detail?id=160522
 */
@Test public void responseCacheReturnsNullStatusLine() throws Exception {
  String cachedContentString = "Hello";
  final byte[] cachedContent = cachedContentString.getBytes(StandardCharsets.US_ASCII);

  setInternalCache(new CacheAdapter(new AbstractResponseCache() {
    @Override
    public CacheResponse get(URI uri, String requestMethod,
        Map<String, List<String>> requestHeaders)
        throws IOException {
      return new CacheResponse() {
        @Override public Map<String, List<String>> getHeaders() throws IOException {
          String contentType = "text/plain";
          Map<String, List<String>> headers = new LinkedHashMap<>();
          headers.put("Content-Length", Arrays.asList(Integer.toString(cachedContent.length)));
          headers.put("Content-Type", Arrays.asList(contentType));
          headers.put("Expires", Arrays.asList(formatDate(-1, TimeUnit.HOURS)));
          headers.put("Cache-Control", Arrays.asList("max-age=60"));
          // Crucially, the header with a null key is missing, which renders the cache response
          // unusable because OkHttp only caches responses with cacheable response codes.
          return headers;
        }

        @Override public InputStream getBody() throws IOException {
          return new ByteArrayInputStream(cachedContent);
        }
      };
    }
  }));
  HttpURLConnection connection = openConnection(server.url("/").url());
  // If there was no status line from the cache an exception will be thrown. No network request
  // should be made.
  try {
    connection.getResponseCode();
    fail();
  } catch (ProtocolException expected) {
  }
}
 
Example 60
Project: GitHub   File: JavaApiConverterTest.java   Source Code and License 5 votes vote down vote up
@Test public void createOkResponseForCacheGet() throws Exception {
  final String statusLine = "HTTP/1.1 200 Fantastic";
  URI uri = new URI("http://foo/bar");
  Request request = new Request.Builder().url(uri.toURL()).build();
  CacheResponse cacheResponse = new CacheResponse() {
    @Override public Map<String, List<String>> getHeaders() throws IOException {
      Map<String, List<String>> headers = new LinkedHashMap<>();
      headers.put(null, Collections.singletonList(statusLine));
      headers.put("xyzzy", Arrays.asList("bar", "baz"));
      return headers;
    }

    @Override public InputStream getBody() throws IOException {
      return new ByteArrayInputStream("HelloWorld".getBytes(StandardCharsets.UTF_8));
    }
  };

  Response response = JavaApiConverter.createOkResponseForCacheGet(request, cacheResponse);
  Request cacheRequest = response.request();
  assertEquals(request.url(), cacheRequest.url());
  assertEquals(request.method(), cacheRequest.method());
  assertEquals(0, request.headers().size());

  assertEquals(Protocol.HTTP_1_1, response.protocol());
  assertEquals(200, response.code());
  assertEquals("Fantastic", response.message());
  Headers okResponseHeaders = response.headers();
  assertEquals("baz", okResponseHeaders.get("xyzzy"));
  assertEquals("HelloWorld", response.body().string());
  assertNull(response.handshake());
}