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.ddmlib; 17 18 19 import java.io.UnsupportedEncodingException; 20 21 /** 22 * A {@link IShellOutputReceiver} which collects the whole shell output into one 23 * {@link String}. 24 */ 25 public class CollectingOutputReceiver implements IShellOutputReceiver { 26 27 private StringBuffer mOutputBuffer = new StringBuffer(); 28 private boolean mIsCanceled = false; 29 getOutput()30 public String getOutput() { 31 return mOutputBuffer.toString(); 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 } 48 49 /** 50 * {@inheritDoc} 51 */ 52 @Override addOutput(byte[] data, int offset, int length)53 public void addOutput(byte[] data, int offset, int length) { 54 if (!isCancelled()) { 55 String s = null; 56 try { 57 s = new String(data, offset, length, "UTF-8"); //$NON-NLS-1$ 58 } catch (UnsupportedEncodingException e) { 59 // normal encoding didn't work, try the default one 60 s = new String(data, offset,length); 61 } 62 mOutputBuffer.append(s); 63 } 64 } 65 66 /** 67 * {@inheritDoc} 68 */ 69 @Override flush()70 public void flush() { 71 // ignore 72 } 73 } 74