Newer
Older
IoTP / src / main / java / info / istlab / IoTP / ScriptRunner.java
@motoki miura motoki miura on 26 Feb 2023 2 KB d
package info.istlab.IoTP;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JButton;

/**
 * スクリプトファイルの実行
 */
public class ScriptRunner implements Runnable {
    String scriptfile;
    String srcfile;

    Thread thread;
    Process process;
    JButton runB;
    String originalButtonLabel;

    public ScriptRunner(String shfile, JButton rB, String targetfile) {
        scriptfile = shfile;
        srcfile = targetfile;
        runB = rB;
    }

    public void startstop() {
        if (thread == null) {
            thread = new Thread(this);
            thread.start();
            // originalButtonLabel = runB.getText();
            // runB.setText("Stop");
        } else {
            process.destroyForcibly();
            thread = null;
            // runB.setText(originalButtonLabel);
        }
    }

    @Override
    public void run() {
        // Run script
        // System.out.println(scriptfile);
        ArrayList<String> comlist = new ArrayList<String>();
        comlist.add("bash");
        comlist.add("Upload.sh");
        if (srcfile.length()>0) comlist.add(srcfile);

        ProcessBuilder processBuilder = new ProcessBuilder(comlist);
        // ProcessBuilder processBuilder = new ProcessBuilder("pwd");
        processBuilder.directory(new File(App.workingDir));
        // processBuilder.inheritIO();
        JTAConsole con = new JTAConsole("(Exec) " + scriptfile+ " "+srcfile);
        // con.setMainSrcByFileName(scriptfile);
        con.Systemoutprintln("=== 実行開始 ===");
        // con.Systemoutprintln(CommandRunner.prompt+"cd ~" + App.nwpsrc+"    (注:~ はチルダ記号〜 で,ホームディレクトリを表します)");
        for(String s: comlist){
            con.Systemoutprintln(s);
        }

        try {
            process = processBuilder.start();
            con.startBR(process);

            // BufferedReader reader = new BufferedReader(new
            // InputStreamReader(process.getInputStream()));
            // String line;
            // while ((line = reader.readLine()) != null) {
            // jta.append(line);
            // }
            process.waitFor();
        } catch (IOException | InterruptedException e1) {
            e1.printStackTrace();
        }
        con.Systemoutprintln("=== 終了 === (ALT+Wで閉じる)");
        thread = null;
        // runB.setText("Run");
        SerialWindow.invoke();
    }

}