1 /*
2  * Copyright (C) 2011 The Android Open Source Project
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.android.tradefed.device;
17 
18 import com.android.ddmlib.IShellOutputReceiver;
19 import com.android.tradefed.util.ByteArrayList;
20 
21 /**
22  * A {@link IShellOutputReceiver} which collects the whole shell output into a {@code byte[]}.
23  * This is useful for shell commands that will produce a significant amount of output, where the
24  * 2x {@link String} memory overhead will be significant.
25  */
26 public class CollectingByteOutputReceiver implements IShellOutputReceiver {
27     private ByteArrayList mData = new ByteArrayList();
28     private boolean mIsCanceled = false;
29 
getOutput()30     public byte[] getOutput() {
31         return mData.getContents();
32     }
33 
34     /**
35      * {@inheritDoc}
36      */
37     @Override
isCancelled()38     public boolean isCancelled() {
39         return mIsCanceled;
40     }
41 
42     /**
43      * Cancel the output collection
44      */
cancel()45     public void cancel() {
46         mIsCanceled = true;
47         clear();
48     }
49 
50     /**
51      * {@inheritDoc}
52      */
53     @Override
addOutput(byte[] data, int offset, int length)54     public void addOutput(byte[] data, int offset, int length) {
55         if (!isCancelled()) {
56             mData.addAll(data, offset, length);
57         }
58     }
59 
60     /**
61      * {@inheritDoc}
62      */
63     @Override
flush()64     public void flush() {
65         // ignore
66     }
67 
68     /**
69      * Try to unref everything that we can
70      */
clear()71     public void clear() {
72         mData.clear();
73     }
74 }
75