package com.eactive.eai.common.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

public class RunCommandUtil {
	public String execCommand(String command) {
		String result = "";
		Runtime rt = Runtime.getRuntime();
		Process ps = null;
		InputStream is = null;
		byte[] buff = null;

		int len;
		ByteArrayOutputStream baos = null;

		try {
//            System.out.println("Command Exec : " + command);
			ps = rt.exec(command);
			ps.waitFor(20, TimeUnit.SECONDS);
			if (!isError(ps)) {
				is = ps.getInputStream();
				len = 0;
				buff = new byte[4096];
				baos = new ByteArrayOutputStream();

				while ((len = is.read(buff)) > 0) {
					baos.write(buff, 0, len);
				}

				result = new String(baos.toByteArray());
			}
		} catch (Exception e) {
//            System.out.println(e.toString());
			result = null;
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					baos = null;
				}
			}

			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					is = null;
				}
			}

			if (ps != null) {
				ps.destroy();
			}
		}
		return result;
	}

	private boolean isError(Process ps) {

		boolean result = true;
		InputStream es = ps.getErrorStream();
		byte[] buff = new byte[1024];

		try {

			// check
			if (es.available() <= 0) {
//                 System.out.println("isError = false");
				return false;
			}

			if (es.read(buff) != -1) {
//                String s = new String(buff);
//                System.out.println(s);
				result = true;
			} else {
				result = false;
			}
		} catch (IOException e) {
			result = true;
		} finally {
			if (es != null) {
				try {
					es.close();
				} catch (IOException e) {
					es = null;
				}
			}
		}
		return result;
	}

//	public static void main(String[] args) {
//		RunCommandUtil r = new RunCommandUtil();
//		String cmd = "/fswas/wasadm/script/eai/was_sna_status.sh";
////		String cmd = "c:\\ls.bat";
//		String result = r.execCommand(cmd);
//		System.out.println("Cmd : " +cmd);
//		System.out.println(result);
//	}
}
