package com.eactive.eai.rms.client.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


public class CommandUtils {

    /** F/W logger. */
    private static com.eactive.eai.common.util.Logger logger = com.eactive.eai.common.util.Logger.getLogger(com.eactive.eai.common.util.Logger.LOGGER_CLIENT);


    public static Object processExec(String[] command, CommandParser parser) {

        if (logger.isDebugEnabled()) {

            StringBuilder sb = new StringBuilder("command를 실행 합니다. command : ");
            for (int i = 0; i < command.length; i++) {
                sb.append(command[i]).append(",");
            }

            logger.debug(sb.toString());
        }

        String lineStr = null;
        BufferedReader br = null;
        Process process = null;
        StringBuilder sb = new StringBuilder();
        InputStreamReader inputStreamReader = null;
        InputStream inputStream = null;

        Object result = null;

        try {
            process = new ProcessBuilder(command).start();

            inputStream = process.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);

            br = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));

            process.waitFor();

            while ((lineStr = br.readLine()) != null) {
                sb.append(lineStr).append("\n");
            }

            result = parser.parse(sb.toString().trim());

        } catch (Exception e) {
            logger.warn("command 실행 도중 에러 발생 : " + e.getMessage());
        } finally {

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
            if (process != null) {
                try {
                    process.destroy();
                } catch (Exception e) {
                }
            }
        }

        return result;
    }
}
