1 /* 2 * Copyright (C) 2010 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 20 import java.io.UnsupportedEncodingException; 21 22 /** 23 * A {@link IShellOutputReceiver} which collects the whole shell output into one 24 * {@link String}. 25 */ 26 public class CollectingOutputReceiver implements IShellOutputReceiver { 27 28 private StringBuffer mOutputBuffer = new StringBuffer(); 29 private boolean mIsCanceled = false; 30 getOutput()31 public String getOutput() { 32 return mOutputBuffer.toString(); 33 } 34 35 /** 36 * {@inheritDoc} 37 */ 38 @Override isCancelled()39 public boolean isCancelled() { 40 return mIsCanceled; 41 } 42 43 /** 44 * Cancel the output collection 45 */ cancel()46 public void cancel() { 47 mIsCanceled = true; 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 String s = null; 57 try { 58 s = new String(data, offset, length, "ISO-8859-1"); //$NON-NLS-1$ 59 } catch (UnsupportedEncodingException e) { 60 // normal encoding didn't work, try the default one 61 s = new String(data, offset,length); 62 } 63 mOutputBuffer.append(s); 64 } 65 } 66 67 /** 68 * {@inheritDoc} 69 */ 70 @Override flush()71 public void flush() { 72 // ignore 73 } 74 75 /** Clear the content of the buffer. */ clearBuffer()76 public void clearBuffer() { 77 mOutputBuffer.setLength(0); 78 } 79 } 80