Search in sources :

Example 31 with BufferedSource

use of okio.BufferedSource in project Store by NYTimes.

the class StoreRefreshWhenStaleTest method diskWasNotRefreshedWhenFreshRecord.

@Test
public void diskWasNotRefreshedWhenFreshRecord() {
    when(fetcher.fetch(barCode)).thenReturn(Observable.just(network1));
    when(persister.read(barCode)).thenReturn(//get should return from disk
    Observable.just(disk1)).thenReturn(//backfill should read from disk again
    Observable.just(disk2));
    when(persister.getRecordState(barCode)).thenReturn(RecordState.FRESH);
    when(persister.write(barCode, network1)).thenReturn(Observable.just(true));
    BufferedSource result = store.get(barCode).test().awaitTerminalEvent().getOnNextEvents().get(0);
    assertThat(result).isEqualTo(disk1);
    verify(fetcher, times(0)).fetch(barCode);
    verify(persister, times(1)).getRecordState(barCode);
    store.clear(barCode);
    result = store.get(barCode).test().awaitTerminalEvent().getOnNextEvents().get(0);
    assertThat(result).isEqualTo(disk2);
    verify(fetcher, times(0)).fetch(barCode);
    verify(persister, times(2)).getRecordState(barCode);
}
Also used : BufferedSource(okio.BufferedSource) Test(org.junit.Test)

Example 32 with BufferedSource

use of okio.BufferedSource in project Store by NYTimes.

the class MoshiSourceParserTest method setUp.

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    BufferedSource bufferedSource = source(sourceString);
    assertNotNull(bufferedSource);
    when(fetcher.fetch(barCode)).thenReturn(Observable.just(bufferedSource));
    when(persister.read(barCode)).thenReturn(Observable.<BufferedSource>empty()).thenReturn(Observable.just(bufferedSource));
    when(persister.write(barCode, bufferedSource)).thenReturn(Observable.just(true));
}
Also used : BufferedSource(okio.BufferedSource) Before(org.junit.Before)

Example 33 with BufferedSource

use of okio.BufferedSource in project MVPArms by JessYanCoding.

the class RequestIntercept method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (//在请求服务器之前可以拿到request,做一些操作比如给request添加header,如果不做操作则返回参数中的request
    mHandler != null)
        request = mHandler.onHttpRequestBefore(chain, request);
    Buffer requestbuffer = new Buffer();
    if (request.body() != null) {
        request.body().writeTo(requestbuffer);
    } else {
        Timber.tag("Request").w("request.body() == null");
    }
    //打印url信息
    Timber.tag("Request").w("Sending Request %s on %n Params --->  %s%n Connection ---> %s%n Headers ---> %s", request.url(), request.body() != null ? parseParams(request.body(), requestbuffer) : "null", chain.connection(), request.headers());
    long t1 = System.nanoTime();
    Response originalResponse = chain.proceed(request);
    long t2 = System.nanoTime();
    //打印响应时间
    Timber.tag("Response").w("Received response  in %.1fms%n%s", (t2 - t1) / 1e6d, originalResponse.headers());
    //读取服务器返回的结果
    ResponseBody responseBody = originalResponse.body();
    BufferedSource source = responseBody.source();
    // Buffer the entire body.
    source.request(Long.MAX_VALUE);
    Buffer buffer = source.buffer();
    //获取content的压缩类型
    String encoding = originalResponse.headers().get("Content-Encoding");
    Buffer clone = buffer.clone();
    String bodyString;
    //解析response content
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        //content使用gzip压缩
        //解压
        bodyString = ZipHelper.decompressForGzip(clone.readByteArray());
    } else if (encoding != null && encoding.equalsIgnoreCase("zlib")) {
        //content使用zlib压缩
        //解压
        bodyString = ZipHelper.decompressToStringForZlib(clone.readByteArray());
    } else {
        //content没有被压缩
        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(charset);
        }
        bodyString = clone.readString(charset);
    }
    Timber.tag("Result").w(jsonFormat(bodyString));
    if (//这里可以比客户端提前一步拿到服务器返回的结果,可以做一些操作,比如token超时,重新获取
    mHandler != null)
        return mHandler.onHttpResultResponse(bodyString, chain, originalResponse);
    return originalResponse;
}
Also used : Buffer(okio.Buffer) Response(okhttp3.Response) Request(okhttp3.Request) Charset(java.nio.charset.Charset) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

Example 34 with BufferedSource

use of okio.BufferedSource in project BookReader by JustWayward.

the class LoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol(protocol);
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }
        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            logger.log("");
            logger.log(buffer.readString(charset));
            logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        }
    }
    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }
        if (!logBody || !HttpEngine.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }
            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }
    return response;
}
Also used : Buffer(okio.Buffer) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 35 with BufferedSource

use of okio.BufferedSource in project Store by NYTimes.

the class FilePersisterTest method readExists.

@Test
public void readExists() throws FileNotFoundException {
    when(fileSystem.exists(resolvedPath)).thenReturn(true);
    when(fileSystem.read(resolvedPath)).thenReturn(bufferedSource);
    BufferedSource returnedValue = fileSystemPersister.read(simple).blockingGet();
    assertThat(returnedValue).isEqualTo(bufferedSource);
}
Also used : BufferedSource(okio.BufferedSource) Test(org.junit.Test)

Aggregations

BufferedSource (okio.BufferedSource)97 Test (org.junit.Test)51 IOException (java.io.IOException)23 Buffer (okio.Buffer)23 Request (okhttp3.Request)10 Response (okhttp3.Response)10 Gson (com.google.gson.Gson)8 EOFException (java.io.EOFException)8 ResponseBody (okhttp3.ResponseBody)8 BarCode (com.nytimes.android.external.store.base.impl.BarCode)7 BarCode (com.nytimes.android.external.store3.base.impl.BarCode)7 Charset (java.nio.charset.Charset)7 MediaType (okhttp3.MediaType)7 MockResponse (okhttp3.mockwebserver.MockResponse)7 File (java.io.File)6 InputStream (java.io.InputStream)6 Headers (okhttp3.Headers)6 RequestBody (okhttp3.RequestBody)6 BufferedSink (okio.BufferedSink)6 List (java.util.List)4