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.IOException; 23 import java.io.OutputStream; 24 import java.util.List; 25 26 /** An opener that returns a simple OutputStream that appends to the file. */ 27 public final class AppendStreamOpener implements Opener<OutputStream> { 28 29 private Behavior[] behaviors; 30 AppendStreamOpener()31 private AppendStreamOpener() {} 32 create()33 public static AppendStreamOpener create() { 34 return new AppendStreamOpener(); 35 } 36 37 /** 38 * Supports adding options to writes. For example, SyncBehavior will force data to be flushed and 39 * durably persisted. 40 */ 41 @CanIgnoreReturnValue withBehaviors(Behavior... behaviors)42 public AppendStreamOpener withBehaviors(Behavior... behaviors) { 43 this.behaviors = behaviors; 44 return this; 45 } 46 47 @Override open(OpenContext openContext)48 public OutputStream open(OpenContext openContext) throws IOException { 49 OutputStream backendOutput = openContext.backend().openForAppend(openContext.encodedUri()); 50 List<OutputStream> chain = openContext.chainTransformsForAppend(backendOutput); 51 if (behaviors != null) { 52 for (Behavior behavior : behaviors) { 53 behavior.forOutputChain(chain); 54 } 55 } 56 return chain.get(0); 57 } 58 } 59