1 /* 2 * Copyright 2022 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.google.android.libraries.mobiledatadownload.file.openers; 17 18 import com.google.android.libraries.mobiledatadownload.file.Behavior; 19 import com.google.android.libraries.mobiledatadownload.file.OpenContext; 20 import com.google.android.libraries.mobiledatadownload.file.Opener; 21 import com.google.errorprone.annotations.CanIgnoreReturnValue; 22 import java.io.BufferedInputStream; 23 import java.io.IOException; 24 import java.io.InputStream; 25 import java.util.List; 26 27 /** An opener that returns a simple InputStream opened for read. */ 28 public final class ReadStreamOpener implements Opener<InputStream> { 29 30 private boolean bufferIo = false; 31 private Behavior[] behaviors; 32 ReadStreamOpener()33 private ReadStreamOpener() {} 34 create()35 public static ReadStreamOpener create() { 36 return new ReadStreamOpener(); 37 } 38 39 @CanIgnoreReturnValue withBehaviors(Behavior... behaviors)40 public ReadStreamOpener withBehaviors(Behavior... behaviors) { 41 this.behaviors = behaviors; 42 return this; 43 } 44 45 /** 46 * If enabled, uses {@link BufferedInputStream} to buffer IO from the backend. Depending on the 47 * situation this can help or hurt performance, so please contact <internal> before using it. 48 * 49 * <p>Encouraged: zip files. 50 * 51 * <p>Discouraged: protos (already buffered internally). 52 */ 53 @CanIgnoreReturnValue withBufferedIo()54 public ReadStreamOpener withBufferedIo() { 55 this.bufferIo = true; 56 return this; 57 } 58 59 @Override open(OpenContext openContext)60 public InputStream open(OpenContext openContext) throws IOException { 61 InputStream backendInput = openContext.backend().openForRead(openContext.encodedUri()); 62 if (bufferIo) { 63 backendInput = new BufferedInputStream(backendInput); 64 } 65 List<InputStream> chain = openContext.chainTransformsForRead(backendInput); 66 if (behaviors != null) { 67 for (Behavior behavior : behaviors) { 68 behavior.forInputChain(chain); 69 } 70 } 71 return chain.get(0); 72 } 73 } 74