Search in sources :

Example 1 with CacheRequest

use of okhttp3.internal.cache.CacheRequest in project okhttp by square.

the class CacheInterceptor method cacheWritingResponse.

/**
   * Returns a new source that writes bytes to {@code cacheRequest} as they are read by the source
   * consumer. This is careful to discard bytes left over when the stream is closed; otherwise we
   * may never exhaust the source stream and therefore not complete the cached response.
   */
private Response cacheWritingResponse(final CacheRequest cacheRequest, Response response) throws IOException {
    // Some apps return a null body; for compatibility we treat that like a null cache request.
    if (cacheRequest == null)
        return response;
    Sink cacheBodyUnbuffered = cacheRequest.body();
    if (cacheBodyUnbuffered == null)
        return response;
    final BufferedSource source = response.body().source();
    final BufferedSink cacheBody = Okio.buffer(cacheBodyUnbuffered);
    Source cacheWritingSource = new Source() {

        boolean cacheRequestClosed;

        @Override
        public long read(Buffer sink, long byteCount) throws IOException {
            long bytesRead;
            try {
                bytesRead = source.read(sink, byteCount);
            } catch (IOException e) {
                if (!cacheRequestClosed) {
                    cacheRequestClosed = true;
                    // Failed to write a complete cache response.
                    cacheRequest.abort();
                }
                throw e;
            }
            if (bytesRead == -1) {
                if (!cacheRequestClosed) {
                    cacheRequestClosed = true;
                    // The cache response is complete!
                    cacheBody.close();
                }
                return -1;
            }
            sink.copyTo(cacheBody.buffer(), sink.size() - bytesRead, bytesRead);
            cacheBody.emitCompleteSegments();
            return bytesRead;
        }

        @Override
        public Timeout timeout() {
            return source.timeout();
        }

        @Override
        public void close() throws IOException {
            if (!cacheRequestClosed && !discard(this, HttpCodec.DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)) {
                cacheRequestClosed = true;
                cacheRequest.abort();
            }
            source.close();
        }
    };
    return response.newBuilder().body(new RealResponseBody(response.headers(), Okio.buffer(cacheWritingSource))).build();
}
Also used : Buffer(okio.Buffer) Sink(okio.Sink) BufferedSink(okio.BufferedSink) RealResponseBody(okhttp3.internal.http.RealResponseBody) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) Source(okio.Source) BufferedSource(okio.BufferedSource) BufferedSource(okio.BufferedSource)

Example 2 with CacheRequest

use of okhttp3.internal.cache.CacheRequest in project okhttp by square.

the class CacheAdapterTest method put_httpsGet.

@Test
public void put_httpsGet() throws Exception {
    final URL serverUrl = configureHttpsServer(new MockResponse());
    assertEquals("https", serverUrl.getProtocol());
    ResponseCache responseCache = new AbstractResponseCache() {

        @Override
        public CacheRequest put(URI uri, URLConnection connection) throws IOException {
            try {
                assertTrue(connection instanceof HttpsURLConnection);
                assertEquals(toUri(serverUrl), uri);
                assertEquals(serverUrl, connection.getURL());
                HttpsURLConnection cacheHttpsUrlConnection = (HttpsURLConnection) connection;
                HttpsURLConnection realHttpsUrlConnection = (HttpsURLConnection) CacheAdapterTest.this.connection;
                assertEquals(realHttpsUrlConnection.getCipherSuite(), cacheHttpsUrlConnection.getCipherSuite());
                assertEquals(realHttpsUrlConnection.getPeerPrincipal(), cacheHttpsUrlConnection.getPeerPrincipal());
                assertArrayEquals(realHttpsUrlConnection.getLocalCertificates(), cacheHttpsUrlConnection.getLocalCertificates());
                assertArrayEquals(realHttpsUrlConnection.getServerCertificates(), cacheHttpsUrlConnection.getServerCertificates());
                assertEquals(realHttpsUrlConnection.getLocalPrincipal(), cacheHttpsUrlConnection.getLocalPrincipal());
                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);
    executeGet(connection);
}
Also used : AbstractResponseCache(okhttp3.AbstractResponseCache) OkUrlFactory(okhttp3.OkUrlFactory) MockResponse(okhttp3.mockwebserver.MockResponse) IOException(java.io.IOException) ResponseCache(java.net.ResponseCache) AbstractResponseCache(okhttp3.AbstractResponseCache) URI(java.net.URI) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Test(org.junit.Test)

Example 3 with CacheRequest

use of okhttp3.internal.cache.CacheRequest in project okhttp by square.

the class JavaApiConverterTest method createOkResponseForCacheGet_secure.

@Test
public void createOkResponseForCacheGet_secure() throws Exception {
    final String statusLine = "HTTP/1.1 200 Fantastic";
    final Principal localPrincipal = LOCAL_CERT.getSubjectX500Principal();
    final List<Certificate> localCertificates = Arrays.<Certificate>asList(LOCAL_CERT);
    final Principal serverPrincipal = SERVER_CERT.getSubjectX500Principal();
    final List<Certificate> serverCertificates = Arrays.<Certificate>asList(SERVER_CERT);
    URI uri = new URI("https://foo/bar");
    Request request = new Request.Builder().url(uri.toURL()).build();
    SecureCacheResponse cacheResponse = new SecureCacheResponse() {

        @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));
        }

        @Override
        public String getCipherSuite() {
            return "SSL_RSA_WITH_NULL_MD5";
        }

        @Override
        public List<Certificate> getLocalCertificateChain() {
            return localCertificates;
        }

        @Override
        public List<Certificate> getServerCertificateChain() throws SSLPeerUnverifiedException {
            return serverCertificates;
        }

        @Override
        public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
            return serverPrincipal;
        }

        @Override
        public Principal getLocalPrincipal() {
            return localPrincipal;
        }
    };
    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());
    Handshake handshake = response.handshake();
    assertNotNull(handshake);
    assertNotNullAndEquals(CipherSuite.TLS_RSA_WITH_NULL_MD5, handshake.cipherSuite());
    assertEquals(localPrincipal, handshake.localPrincipal());
    assertEquals(serverPrincipal, handshake.peerPrincipal());
    assertEquals(serverCertificates, handshake.peerCertificates());
    assertEquals(localCertificates, handshake.localCertificates());
}
Also used : SecureCacheResponse(java.net.SecureCacheResponse) Headers(okhttp3.Headers) Request(okhttp3.Request) URI(java.net.URI) LinkedHashMap(java.util.LinkedHashMap) CacheResponse(java.net.CacheResponse) Response(okhttp3.Response) SecureCacheResponse(java.net.SecureCacheResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) Principal(java.security.Principal) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) Handshake(okhttp3.Handshake) Test(org.junit.Test)

Example 4 with CacheRequest

use of okhttp3.internal.cache.CacheRequest in project okhttp by square.

the class JavaApiConverterTest method createOkResponseForCacheGet.

@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());
}
Also used : CacheResponse(java.net.CacheResponse) Response(okhttp3.Response) SecureCacheResponse(java.net.SecureCacheResponse) CacheResponse(java.net.CacheResponse) SecureCacheResponse(java.net.SecureCacheResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) Headers(okhttp3.Headers) Request(okhttp3.Request) List(java.util.List) URI(java.net.URI) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 5 with CacheRequest

use of okhttp3.internal.cache.CacheRequest in project okhttp by square.

the class ResponseCacheTest method responseCacheReturnsNullOutputStream.

/** Don't explode if the cache returns a null body. http://b/3373699 */
@Test
public void responseCacheReturnsNullOutputStream() throws Exception {
    final AtomicBoolean aborted = new AtomicBoolean();
    setInternalCache(new CacheAdapter(new AbstractResponseCache() {

        @Override
        public CacheRequest put(URI uri, URLConnection connection) {
            return new CacheRequest() {

                @Override
                public void abort() {
                    aborted.set(true);
                }

                @Override
                public OutputStream getBody() throws IOException {
                    return null;
                }
            };
        }
    }));
    server.enqueue(new MockResponse().setBody("abcdef"));
    HttpURLConnection connection = openConnection(server.url("/").url());
    assertEquals("abc", readAscii(connection, 3));
    connection.getInputStream().close();
    // The best behavior is ambiguous, but RI 6 doesn't abort here
    assertFalse(aborted.get());
}
Also used : AbstractResponseCache(okhttp3.AbstractResponseCache) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) CacheRequest(java.net.CacheRequest) URI(java.net.URI) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Test(org.junit.Test)

Aggregations

URI (java.net.URI)9 IOException (java.io.IOException)7 HttpURLConnection (java.net.HttpURLConnection)7 Request (okhttp3.Request)7 Test (org.junit.Test)7 URLConnection (java.net.URLConnection)5 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)5 AbstractResponseCache (okhttp3.AbstractResponseCache)5 Response (okhttp3.Response)5 MockResponse (okhttp3.mockwebserver.MockResponse)5 URL (java.net.URL)4 OkUrlFactory (okhttp3.OkUrlFactory)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 CacheResponse (java.net.CacheResponse)3 ResponseCache (java.net.ResponseCache)3 SecureCacheResponse (java.net.SecureCacheResponse)3 Headers (okhttp3.Headers)3 CacheRequest (okhttp3.internal.cache.CacheRequest)3 ArtifactMetadata (com.facebook.buck.artifact_cache.thrift.ArtifactMetadata)2 BuckCacheFetchRequest (com.facebook.buck.artifact_cache.thrift.BuckCacheFetchRequest)2