Package com.atolsystems.atolutilities

Source Code of com.atolsystems.atolutilities.AConsolMonitor$StdInMonitor

/*
*/

/*
* AConsolMonitor.java
*
* Created on May 24, 2009, 8:05:12 PM
*/
package com.atolsystems.atolutilities;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

/**
*
* @author seb
*/
public class AConsolMonitor extends javax.swing.JDialog {

    ProcessBuilder processBuilder;
    StdInMonitor monitor;
    Thread monitorThread;
    Process process;
    boolean mustClose;
    private byte[] exitCmd;
    private long exitCmdTimeout;
    private boolean mustTerminateProcess;

    /** Creates new form AConsolMonitor */
    void init(java.awt.Frame parent, boolean modal, ProcessBuilder pBuilder, String title, byte[] exitCmd, long exitCmdTimeout) {
        initComponents();
        processBuilder = pBuilder;
        mustClose = false;
        this.setTitle(title);
        this.exitCmd = exitCmd;
        this.exitCmdTimeout = exitCmdTimeout;
    }

    public AConsolMonitor(java.awt.Frame parent, boolean modal, ProcessBuilder pBuilder, String title) {
        super(parent, modal);
        init(parent, modal, pBuilder, title, null, 0);
    }

    public AConsolMonitor(java.awt.Frame parent, boolean modal, ProcessBuilder pBuilder, String title, byte[] exitCmd, long exitCmdTimeout) {
        super(parent, modal);
        init(parent, modal, pBuilder, title, exitCmd, exitCmdTimeout);
    }

    public int execProcess() throws IOException {//, InterruptedException {
        this.setVisible(true);
        processBuilder.redirectErrorStream(true);
        process = processBuilder.start();
        monitor = new StdInMonitor(this, process);
        monitor.setExitCmd(exitCmd, exitCmdTimeout);
        monitorThread = new Thread(monitor);
        monitorThread.start();
        return 0;//p.waitFor();
    }

    public void terminateProcessAndCloseMonitoringWindow() {
        this.setVisible(false);
        mustTerminateProcess=true;
        close();
    }

    public void closeMonitoringWindow() {
        this.setVisible(false);
        mustTerminateProcess=false;
        close();
    }

    private void close(){
        mustClose = true;
        /*while ((monitorThread != null) && monitorThread.isAlive()) {
            Thread.yield();
        }*/
        monitorThread = null;
        monitor = null;
        process = null;
    }

    protected class StdInMonitor implements Runnable {

        javax.swing.JTextPane textPane;
        Document doc;
        Process process;
        AConsolMonitor consolMonitor;
        private byte[] exitCmd;
        private long exitCmdTimeout;

        public StdInMonitor(AConsolMonitor cm, Process p) {
            textPane = cm.consolTextPane;
            doc = textPane.getDocument();
            process = p;
            consolMonitor = cm;
        }

        public void setExitCmd(byte[] exitCmd, long exitCmdTimeout) {
            this.exitCmd = exitCmd;
            this.exitCmdTimeout = exitCmdTimeout;
        }

        public void run() {
            System.out.println("start of StdInMonitor.run");
            OutputStream processInput = process.getOutputStream();
            InputStream in = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);
            char cbuf[] = new char[256];
            int emptyCnt=0;
            if (in != null) {
                try {
                    while (consolMonitor.mustClose == false) {
                        try {
                            int status = process.exitValue();
                            break;//We get here if the process is terminated
                        } catch (Exception e) {
                            //We get here if the process is not terminated yet, nothing to do
                        }
                        String s = "";
                        if (isr.ready()) {
                            emptyCnt=0;
                            int n = isr.read(cbuf);
                            for (int i = 0; i < n; i++) {
                                s += cbuf[i];
                            }
                            doc.insertString(doc.getLength(), s, null);
                            consolMonitor.consolTextPane.setCaretPosition(doc.getLength());
                        }
                        else
                        {
                            emptyCnt++;
                            if(emptyCnt<100){
                                Thread.yield();
                            }
                            else{
                                Thread.sleep(20);
                            }
                        }
                    }
                } catch (Exception ex) {
                    Logger.getLogger(AConsolMonitor.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                System.out.println("process.getInputStream() returned null");
            }
            if(mustTerminateProcess){
                if (exitCmd != null) {
                    try {
                        System.out.println("AConsolMonitor.run: send exitCmd");
                        processInput.write(exitCmd);
                        processInput.flush();
                        long start = System.currentTimeMillis();
                        try {
                            while (start+exitCmdTimeout>System.currentTimeMillis()) {
                                try {
                                    int status = process.exitValue();
                                    break;//We get here if the process is terminated
                                } catch (Exception e) {
                                    //We get here if the process is not terminated yet, nothing to do
                                }
                                String s = "";
                                if (isr.ready()) {
                                    int n = isr.read(cbuf);
                                    for (int i = 0; i < n; i++) {
                                        s += cbuf[i];
                                    }
                                    doc.insertString(doc.getLength(), s, null);
                                    consolMonitor.consolTextPane.setCaretPosition(doc.getLength());
                                }
                            }
                        } catch (Exception ex) {
                            Logger.getLogger(AConsolMonitor.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } catch (Exception ex) {
                        //do nothing
                    }
                }
                System.out.println("AConsolMonitor.run: destroy process");
                process.destroy();
            }
            consolMonitor = null;
            doc = null;
            textPane = null;
            System.out.println("end of StdInMonitor.run");
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        consolTextPane = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeAction(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        consolTextPane.setEditable(false);
        consolTextPane.setName("consolTextPane"); // NOI18N
        jScrollPane1.setViewportView(consolTextPane);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void closeAction(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeAction
        mustTerminateProcess=true;
        mustClose = true;
    }//GEN-LAST:event_closeAction

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextPane consolTextPane;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
TOP

Related Classes of com.atolsystems.atolutilities.AConsolMonitor$StdInMonitor

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.