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 25 /** 26 * An opener that writes a byte[] of data for a Uri. 27 * 28 * <p>Usage: <code> 29 * storage.open(uri, WriteByteArrayOpener.create(bytes)); 30 * </code> 31 */ 32 public final class WriteByteArrayOpener implements Opener<Void> { 33 34 private final byte[] bytesToWrite; 35 private Behavior[] behaviors; 36 WriteByteArrayOpener(byte[] bytesToWrite)37 private WriteByteArrayOpener(byte[] bytesToWrite) { 38 this.bytesToWrite = bytesToWrite; 39 } 40 41 @CanIgnoreReturnValue withBehaviors(Behavior... behaviors)42 public WriteByteArrayOpener withBehaviors(Behavior... behaviors) { 43 this.behaviors = behaviors; 44 return this; 45 } 46 47 /** Creates a new opener instance to write a byte array. */ create(byte[] bytesToWrite)48 public static WriteByteArrayOpener create(byte[] bytesToWrite) { 49 return new WriteByteArrayOpener(bytesToWrite); 50 } 51 52 @Override open(OpenContext openContext)53 public Void open(OpenContext openContext) throws IOException { 54 try (OutputStream out = WriteStreamOpener.create().withBehaviors(behaviors).open(openContext)) { 55 out.write(bytesToWrite); 56 if (behaviors != null) { 57 for (Behavior behavior : behaviors) { 58 behavior.commit(); 59 } 60 } 61 } 62 return null; // Required by Void return type. 63 } 64 } 65