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.behaviors; 17 18 import com.google.android.libraries.mobiledatadownload.file.Behavior; 19 import com.google.android.libraries.mobiledatadownload.file.common.Syncable; 20 import com.google.android.libraries.mobiledatadownload.file.common.UnsupportedFileStorageOperation; 21 import com.google.common.collect.Iterables; 22 import java.io.IOException; 23 import java.io.OutputStream; 24 import java.util.List; 25 26 /** 27 * This Behavior can be used to ensure that all application buffers and OS buffers are flushed to 28 * persistent storage. 29 * 30 * <p>NOTE: not final for testing purposes only. 31 */ 32 public class SyncingBehavior implements Behavior { 33 34 private OutputStream headStream; 35 private Syncable syncable; 36 37 @Override forOutputChain(List<OutputStream> chain)38 public void forOutputChain(List<OutputStream> chain) throws IOException { 39 OutputStream backendStream = Iterables.getLast(chain); 40 if (backendStream instanceof Syncable) { 41 syncable = ((Syncable) backendStream); 42 headStream = chain.get(0); 43 } 44 } 45 sync()46 public void sync() throws IOException { 47 if (syncable == null) { 48 throw new UnsupportedFileStorageOperation("Cannot sync underlying stream"); 49 } 50 headStream.flush(); 51 syncable.sync(); 52 } 53 54 @Override commit()55 public void commit() throws IOException { 56 sync(); 57 } 58 } 59