/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/06/02, 18:41
!  AUTHOR(S): KOGA, Junichiro
!  File : Execute.java
!  
!  Contact address :  Phase System Consortium
!                     E-mail: phase_system@nims.go.jp URL https://azuma.nims.go.jp
!
!
!   Since 2002, this program set had been intensively developed as a part of the following 
!  national projects supported by the Ministry of Education, Culture, Sports, Science and
!  Technology (MEXT) of Japan; "Frontier Simulation Software for Industrial Science
!  (FSIS)" from 2002 to 2005, "Revolutionary Simulation Software (RSS21)" from 2006 to
!  2008. "Research and Development of Innovative Simulation Software (RISS)" from 2008
!  to 2013. These projects is lead by the Center for Research on Innovative Simulation 
!  Software (CISS), the Institute of Industrial Science (IIS), the University of Tokyo.
!   Since 2013, this program set has been further developed centering on PHASE System
!  Consortium. 
!   The activity of development of this program set has been supervised by Takahisa Ohno.
!
!=======================================================================
 */
package ciss.phase_viewer.ssh;

import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * 
 * @author KOGA, Junichiro
 */
public class Execute implements Runnable {
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger
            .getLogger(Execute.class.getName());
    private Session session;
    private String command;
    private boolean verbose = true;

    /** Creates a new instance of Execute */
    public Execute(Session session) {
        this.session = session;
    }

    public void isVerbose(boolean verbose) {
        this.verbose = verbose;
    }

    /**
     * 別スレッドで投げたいときはこっちのコンストラクターを使用する. 標準出力などは無視される.
     * 
     * @param session
     *            リモートホストへのSession
     * @param command
     *            実行したいコマンド.
     */
    public Execute(Session session, String command) {
        this.session = session;
        this.command = command;
        verbose = false;
    }

    public void disconnect() {
        if (session != null)
            session.disconnect();
    }

    public String command(String command) {
        if (!session.isConnected()) {
            logger.error("not connected.");
            // return null;
            try {
                session.connect();
            } catch (JSchException e) {
                e.printStackTrace();
            }
        }
        logger.debug("executing command: " + command);

        String ret = "";
        Channel channel = null;
        try {
            channel = session.openChannel("exec");
        } catch (Exception exc) {
            logger.error("failed to open channel.");
            return null;
        }

        ((ChannelExec) channel).setCommand(command);
        // channel.setInputStream(System.in);
        // ((ChannelExec) channel).setErrStream(System.err);

        InputStream in = null;
        try {
            in = channel.getInputStream();
        } catch (IOException ioe) {
            logger.error("failed to get inputstream.");
            return null;
        }

        try {
            channel.connect();
        } catch (JSchException jse) {
            logger.error("failed connection.");
        }

        if (verbose) {
            byte[] tmp = new byte[1024];
            while (true) {
                try {
                    if (channel.isEOF() && in.available() <= 0)
                        break;
                    while (in.available() > 0) {
                        int i = in.read(tmp, 0, 1024);
                        if (i < 0)
                            break;
                        ret += new String(tmp, 0, i);
                    }
                } catch (Exception ex) {
                    logger.error("failed to obtain result... return val is incomplete.");
                }
            }
        }
        channel.disconnect();
        return ret;
    }

    public void run() {
        command(command);
    }

}
