/*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/



package com.nokia.s60tools.imaker.internal.wrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;

/**
 * Helper class to read and parse command line output data
 * 
 * @version 0.3
 */
public class StreamGobbler extends Thread {
	/** Default thread sleed time in milliseconds. */
	public static final int DEFAULT_THREAD_SLEEP_TIME = 200;
	public static final String NEWLINE            = System.getProperty("line.separator");

	/** Buffer where output is stored. */
    private ArrayList<String> cmdOutput;
    private OutputStream output;
	private InputStream input;


     /**
      * Default constructor
      */
     public StreamGobbler(InputStream in, OutputStream out) {
    	 cmdOutput = new ArrayList<String>();
    	 this.output = out;
    	 this.input = in;
     }
     
     /**
      * Returns output generated by the input stream.
      * 
      * @return output of input stream
      */
     public ArrayList<String> getOutput() {
    	 return cmdOutput;
     }

     /*
      * (non-Javadoc)
      * 
      * @see java.lang.Thread#run()
     */
     @Override
     public void run() {
    	 try {
    		 // Get BufferedReader from InputStream
             BufferedReader br = new BufferedReader(new InputStreamReader(input));
             String line = null;
             
             // Go through lines in BufferedReader
             while ((line = br.readLine()) != null) {
            	 if (output != null) {
            		 output.write((line+NEWLINE).getBytes());
            		 output.flush();
            	 }
            	 cmdOutput.add(line);
             }
             br.close();
             if (output != null) {
            	 output.flush();
            	 output.close();
            	 output = null;
             }
         } catch (IOException ioe) {
    		 ioe.printStackTrace();
         }
    }
}
