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.common.testing; 17 18 import android.net.Uri; 19 import com.google.android.libraries.mobiledatadownload.file.spi.Monitor; 20 import java.io.ByteArrayOutputStream; 21 22 /** A testing monitor buffers bytes read and written. */ 23 public class BufferingMonitor implements Monitor { 24 private final ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(); 25 private final ByteArrayOutputStream writeBuffer = new ByteArrayOutputStream(); 26 private final ByteArrayOutputStream appendBuffer = new ByteArrayOutputStream(); 27 bytesRead()28 public byte[] bytesRead() { 29 return readBuffer.toByteArray(); 30 } 31 bytesWritten()32 public byte[] bytesWritten() { 33 return writeBuffer.toByteArray(); 34 } 35 bytesAppended()36 public byte[] bytesAppended() { 37 return appendBuffer.toByteArray(); 38 } 39 40 @Override monitorRead(Uri uri)41 public Monitor.InputMonitor monitorRead(Uri uri) { 42 return new ReadMonitor(); 43 } 44 45 @Override monitorWrite(Uri uri)46 public Monitor.OutputMonitor monitorWrite(Uri uri) { 47 return new WriteMonitor(); 48 } 49 50 @Override monitorAppend(Uri uri)51 public Monitor.OutputMonitor monitorAppend(Uri uri) { 52 return new AppendMonitor(); 53 } 54 55 class ReadMonitor implements Monitor.InputMonitor { 56 @Override bytesRead(byte[] b, int off, int len)57 public void bytesRead(byte[] b, int off, int len) { 58 readBuffer.write(b, off, len); 59 } 60 } 61 62 class WriteMonitor implements Monitor.OutputMonitor { 63 @Override bytesWritten(byte[] b, int off, int len)64 public void bytesWritten(byte[] b, int off, int len) { 65 writeBuffer.write(b, off, len); 66 } 67 } 68 69 class AppendMonitor implements Monitor.OutputMonitor { 70 @Override bytesWritten(byte[] b, int off, int len)71 public void bytesWritten(byte[] b, int off, int len) { 72 appendBuffer.write(b, off, len); 73 } 74 } 75 } 76