/**
 * File:    ExecuteProcessThread.java
 * Created: 24.11.2006
 *
/*******************************************************************************
 * Copyright (c) 2005-2011
 * University of Augsburg, Germany <www.ds-lab.org>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Wolf Fischer, Programming distributed Systems Lab, University of Augsburg 
 *    	- initial API and implementation
 *******************************************************************************/


package org.eclipse.jwt.we.editors.actions.managed.process;

import java.io.File;

import org.eclipse.jwt.we.misc.logging.Logger;


/**
 * Starts an instance of an external application
 * 
 * @version $Id: ExecuteProcessThread.java,v 1.9 2009-11-26 12:41:39 chsaad Exp $
 * @author Wolf Fischer, Programming distributed Systems Lab, University of Augsburg,
 *         Germany, www.ds-lab.org
 */
public class ExecuteProcessThread
		extends Thread
{

	Logger logger = Logger.getLogger(ExecuteProcessThread.class);

	String executable;

	String argument;


	/**
	 * Standardconstructor. Initialises the thread where the application is running in
	 * 
	 * @param executable
	 *            Path to the executable
	 * @param argument
	 *            An argument being passed to the executable
	 */
	public ExecuteProcessThread(String executable, String argument)
	{
		this.executable = executable;
		this.argument = argument;
		this.start();
	}


	/**
	 * Executes a program
	 */
	@Override
	public void run()
	{
		try
		{
			String path = getPath();
			ProcessBuilder builder = new ProcessBuilder(executable, argument);
			builder.directory(new File(path));
			Process p = builder.start();
			try
			{
				new ThreadedReader(p.getErrorStream(), false);
				new ThreadedReader(p.getInputStream(), false);
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
		/**
		 * @return The directory that contains the simulator
		 */
		private String getPath() {
			String res = executable.substring(0, executable.lastIndexOf(File.separator));
			res = new File(res).getAbsolutePath();
			return res;
		}

}
