Search in sources :

Example 26 with BufferedSource

use of okio.BufferedSource in project okhttp by square.

the class DiskLruCacheTest method readJournalLines.

private List<String> readJournalLines() throws Exception {
    List<String> result = new ArrayList<>();
    BufferedSource source = Okio.buffer(fileSystem.source(journalFile));
    for (String line; (line = source.readUtf8Line()) != null; ) {
        result.add(line);
    }
    source.close();
    return result;
}
Also used : ArrayList(java.util.ArrayList) BufferedSource(okio.BufferedSource)

Example 27 with BufferedSource

use of okio.BufferedSource in project wire by square.

the class ParsingTester method main.

public static void main(String... args) {
    int total = 0;
    int failed = 0;
    Deque<File> fileQueue = new ArrayDeque<>();
    fileQueue.add(ROOT);
    while (!fileQueue.isEmpty()) {
        File file = fileQueue.removeFirst();
        if (file.isDirectory()) {
            Collections.addAll(fileQueue, file.listFiles());
        } else if (file.getName().endsWith(".proto")) {
            System.out.println("Parsing " + file.getPath());
            total += 1;
            try (BufferedSource in = Okio.buffer(Okio.source(file))) {
                String data = in.readUtf8();
                ProtoParser.parse(Location.get(file.getPath()), data);
            } catch (Exception e) {
                e.printStackTrace();
                failed += 1;
            }
        }
    }
    System.out.println("\nTotal: " + total + "  Failed: " + failed);
}
Also used : File(java.io.File) ArrayDeque(java.util.ArrayDeque) BufferedSource(okio.BufferedSource)

Example 28 with BufferedSource

use of okio.BufferedSource in project okhttp by square.

the class CallTest method reusedSourcesGetIndependentTimeoutInstances.

@Test
public void reusedSourcesGetIndependentTimeoutInstances() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.enqueue(new MockResponse().setBody("def"));
    // Call 1: set a deadline on the response body.
    Request request1 = new Request.Builder().url(server.url("/")).build();
    Response response1 = client.newCall(request1).execute();
    BufferedSource body1 = response1.body().source();
    assertEquals("abc", body1.readUtf8());
    body1.timeout().deadline(5, TimeUnit.SECONDS);
    // Call 2: check for the absence of a deadline on the request body.
    Request request2 = new Request.Builder().url(server.url("/")).build();
    Response response2 = client.newCall(request2).execute();
    BufferedSource body2 = response2.body().source();
    assertEquals("def", body2.readUtf8());
    assertFalse(body2.timeout().hasDeadline());
    // Use sequence numbers to confirm the connection was pooled.
    assertEquals(0, server.takeRequest().getSequenceNumber());
    assertEquals(1, server.takeRequest().getSequenceNumber());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) BufferedSource(okio.BufferedSource) Test(org.junit.Test)

Example 29 with BufferedSource

use of okio.BufferedSource in project okhttp by square.

the class CacheTest method secureResponseCaching.

@Test
public void secureResponseCaching() throws IOException {
    server.useHttps(sslClient.socketFactory, false);
    server.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setBody("ABC"));
    client = client.newBuilder().sslSocketFactory(sslClient.socketFactory, sslClient.trustManager).hostnameVerifier(NULL_HOSTNAME_VERIFIER).build();
    Request request = new Request.Builder().url(server.url("/")).build();
    Response response1 = client.newCall(request).execute();
    BufferedSource in = response1.body().source();
    assertEquals("ABC", in.readUtf8());
    // OpenJDK 6 fails on this line, complaining that the connection isn't open yet
    CipherSuite cipherSuite = response1.handshake().cipherSuite();
    List<Certificate> localCerts = response1.handshake().localCertificates();
    List<Certificate> serverCerts = response1.handshake().peerCertificates();
    Principal peerPrincipal = response1.handshake().peerPrincipal();
    Principal localPrincipal = response1.handshake().localPrincipal();
    // Cached!
    Response response2 = client.newCall(request).execute();
    assertEquals("ABC", response2.body().string());
    assertEquals(2, cache.requestCount());
    assertEquals(1, cache.networkCount());
    assertEquals(1, cache.hitCount());
    assertEquals(cipherSuite, response2.handshake().cipherSuite());
    assertEquals(localCerts, response2.handshake().localCertificates());
    assertEquals(serverCerts, response2.handshake().peerCertificates());
    assertEquals(peerPrincipal, response2.handshake().peerPrincipal());
    assertEquals(localPrincipal, response2.handshake().localPrincipal());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Principal(java.security.Principal) BufferedSource(okio.BufferedSource) Certificate(java.security.cert.Certificate) Test(org.junit.Test)

Example 30 with BufferedSource

use of okio.BufferedSource in project okhttp by square.

the class Cache method urls.

/**
   * Returns an iterator over the URLs in this cache. This iterator doesn't throw {@code
   * ConcurrentModificationException}, but if new responses are added while iterating, their URLs
   * will not be returned. If existing responses are evicted during iteration, they will be absent
   * (unless they were already returned).
   *
   * <p>The iterator supports {@linkplain Iterator#remove}. Removing a URL from the iterator evicts
   * the corresponding response from the cache. Use this to evict selected responses.
   */
public Iterator<String> urls() throws IOException {
    return new Iterator<String>() {

        final Iterator<DiskLruCache.Snapshot> delegate = cache.snapshots();

        String nextUrl;

        boolean canRemove;

        @Override
        public boolean hasNext() {
            if (nextUrl != null)
                return true;
            // Prevent delegate.remove() on the wrong item!
            canRemove = false;
            while (delegate.hasNext()) {
                DiskLruCache.Snapshot snapshot = delegate.next();
                try {
                    BufferedSource metadata = Okio.buffer(snapshot.getSource(ENTRY_METADATA));
                    nextUrl = metadata.readUtf8LineStrict();
                    return true;
                } catch (IOException ignored) {
                // We couldn't read the metadata for this snapshot; possibly because the host filesystem
                // has disappeared! Skip it.
                } finally {
                    snapshot.close();
                }
            }
            return false;
        }

        @Override
        public String next() {
            if (!hasNext())
                throw new NoSuchElementException();
            String result = nextUrl;
            nextUrl = null;
            canRemove = true;
            return result;
        }

        @Override
        public void remove() {
            if (!canRemove)
                throw new IllegalStateException("remove() before next()");
            delegate.remove();
        }
    };
}
Also used : Iterator(java.util.Iterator) DiskLruCache(okhttp3.internal.cache.DiskLruCache) ByteString(okio.ByteString) IOException(java.io.IOException) NoSuchElementException(java.util.NoSuchElementException) BufferedSource(okio.BufferedSource)

Aggregations

BufferedSource (okio.BufferedSource)72 Test (org.junit.Test)33 Buffer (okio.Buffer)21 IOException (java.io.IOException)19 Request (okhttp3.Request)8 Response (okhttp3.Response)8 BarCode (com.nytimes.android.external.store.base.impl.BarCode)7 MockResponse (okhttp3.mockwebserver.MockResponse)7 EOFException (java.io.EOFException)6 InputStream (java.io.InputStream)6 ResponseBody (okhttp3.ResponseBody)6 Gson (com.google.gson.Gson)4 File (java.io.File)4 Charset (java.nio.charset.Charset)4 Headers (okhttp3.Headers)4 MediaType (okhttp3.MediaType)4 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)4 BufferedSink (okio.BufferedSink)4 Sink (okio.Sink)4 RequestBody (okhttp3.RequestBody)3