package de.hsadmin.core.qserv;


/**
 * A ShellProcessor encapsulates a shell command as a Processor.
 * 
 * As such, a client can prepare shell commands to be processed on a server.
 * 
 * @author mi
 */
public class ShellProcessor extends AbstractProcessor {

	private static final long serialVersionUID = -649045174380048818L;

	private String aSystemCall;
	private String[] aEnv;
	private String aInput;
	private String aOutput;
	private String aErrors;

	/**
	 * Constructor for a queue entry which executes a system call.
	 * 
	 * @param aSystemCall
	 *            the system call to be executed
	 */
	public ShellProcessor(String aSystemCall) {
		this(aSystemCall, null, null);
	}

	/**
	 * Constructor for a queue entry which executes a system call with stdin
	 * data.
	 * 
	 * @param aSystemCall
	 *            the system call to be executed
	 * @param aInput
	 *            data for stdin of the system call
	 */
	public ShellProcessor(String aSystemCall, String aInput) {
		this.aSystemCall = aSystemCall;
		this.aInput = aInput;
	}

	public ShellProcessor(String aSystemCall, String[] aEnv, String aInput) {
		this.aSystemCall = aSystemCall;
		this.aEnv = aEnv;
		this.aInput = aInput;
	}

	public Object process() throws ProcessorException {
		try {
			CommandShell.setEnvironment(aEnv);
			aOutput = CommandShell.execute(aSystemCall, aInput);
			return aOutput;
		} catch (ShellException aExc) {
			aExc.printStackTrace(System.err); // Logging
			throw new ProcessorException(aExc);
		}
	}

	/**
	 * @return Returns stderr as a String.
	 */
	public String getErrors() {
		return aErrors;
	}

	/**
	 * @return Returns stdout as a String.
	 */
	public String getOutput() {
		return aOutput;
	}

}
