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.samples; 17 18 import android.net.Uri; 19 import androidx.annotation.VisibleForTesting; 20 import com.google.android.libraries.mobiledatadownload.file.spi.Monitor; 21 import java.util.concurrent.atomic.AtomicLong; 22 23 /** A monitor that counts bytes read and written. */ 24 public class ByteCountingMonitor implements Monitor { 25 private final AtomicLong bytesRead = new AtomicLong(); 26 private final AtomicLong bytesWritten = new AtomicLong(); 27 28 // NOTE: A real implementation of this would transmit these stats to a logging 29 // system such as <internal>. The counters are atomic so that such a monitoring 30 // task can happen in another thread safely. 31 @VisibleForTesting stats()32 public long[] stats() { 33 return new long[] {bytesRead.longValue(), bytesWritten.longValue()}; 34 } 35 36 @Override monitorRead(Uri uri)37 public Monitor.InputMonitor monitorRead(Uri uri) { 38 return new InputCounter(); 39 } 40 41 @Override monitorWrite(Uri uri)42 public Monitor.OutputMonitor monitorWrite(Uri uri) { 43 return new OutputCounter(); 44 } 45 46 @Override monitorAppend(Uri uri)47 public Monitor.OutputMonitor monitorAppend(Uri uri) { 48 return new OutputCounter(); 49 } 50 51 class InputCounter implements Monitor.InputMonitor { 52 @Override bytesRead(byte[] b, int off, int len)53 public void bytesRead(byte[] b, int off, int len) { 54 bytesRead.getAndAdd(len); 55 } 56 } 57 58 class OutputCounter implements Monitor.OutputMonitor { 59 @Override bytesWritten(byte[] b, int off, int len)60 public void bytesWritten(byte[] b, int off, int len) { 61 bytesWritten.getAndAdd(len); 62 } 63 } 64 } 65