Friday, February 15, 2013

Example java daemon code for Powershell interaction


Copy-pasted from: https://forums.oracle.com/forums/thread.jspa?messageID=10078419
public class Gobbler implements Runnable {
 
    private PrintStream out;
    private String message;
 
    private BufferedReader reader;
 
    public Gobbler(InputStream inputStream, PrintStream out) {
        this.reader = new BufferedReader(new InputStreamReader(inputStream));
               this.out = out;
        this.message = ( null != message ) ? message : "";
    }
 
    public void run() {
        String line;
 
        try {
            while (null != (line = this.reader.readLine())) {
                out.println(message + line);
            }
            this.reader.close();
        } catch (IOException e) {
            System.err.println("ERROR: " + e.getMessage());
        }
    }
}
 
 
public class PowerConsole {
 
    private ProcessBuilder pb;
    Process p;
    boolean closed = false;
    PrintWriter writer;
 
    PowerConsole(String[] commandList) {
        pb = new ProcessBuilder(commandList);
        try {
            p = pb.start();
        } catch (IOException ex) {
            throw new RuntimeException("Cannot execute PowerShell.exe", ex);
        }
        writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
        Gobbler outGobbler = new Gobbler(p.getInputStream(), System.out);
        Gobbler errGobbler = new Gobbler(p.getErrorStream(), System.out);
        Thread outThread = new Thread(outGobbler);
        Thread errThread = new Thread(errGobbler);
        outThread.start();
        errThread.start();
    }
 
    public void execute(String command) {
        if (!closed) {
            writer.println(command);
            writer.flush();
        } else {
            throw new IllegalStateException("Power console has ben closed.");
        }
    }
 
    public void close() {
        try {
            execute("exit");
            p.waitFor();
        } catch (InterruptedException ex) {
        }
    }
 
    public static void main(String[] args) throws IOException, InterruptedException {
        /*   PowerConsole pc = new PowerConsole(new String[]{"/bin/bash"});
        
        PowerConsole pc = new PowerConsole(new String[]{"/bin/bash"});
        pc.execute("pwd");
        pc.execute("ls");
        pc.execute("cd /");
        pc.execute("ls -l");
        pc.execute("cd ~");
        pc.execute("find . -name 'test.*' -print");
        pc.close();
         */
        //      PowerConsole pc = new PowerConsole(new String[]{"cmd.exe"});
        PowerConsole pc = new PowerConsole(new String[]{"powershell.exe", "-NoExit", "-Command", "-"});
        System.out.println("========== Executing dir");
        pc.execute("dir"); 
        System.out.println("========== Executing cd\\");
        pc.execute("cd \\"); Thread.sleep(2000);
        System.out.println("========== Executing dir");
        pc.execute("dir"); Thread.sleep(2000);
        System.out.println("========== Executing cd \\temp");
        pc.execute("cd \\temp"); Thread.sleep(2000);
        System.out.println("========== Executing dir");
        pc.execute("dir"); Thread.sleep(2000);
        System.out.println("========== Executing cd \\bubba");
        pc.execute("cd \\bubba"); Thread.sleep(2000);
        System.out.println("========== Exiting .... bye.");
        pc.close();
    }
}


I tested this and there is still a little problem -look at the test below.
It seems that when thecommand
executed in the powershell prints only a one ot two lines,
powershell doesn't flush the output stream
.... but this rather problem of powershell, not the java code
I have not a clue how to force powershell to flush
it's output stream after each command.
C:\temp>java -jar PowerShell.jar
========== Executing dir
 
 
    Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp
 
 
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2012-01-09     01:16       5290 PowerShell.jar
 
 
========== Executing cd\
========== Executing dir
 
 
    Directory: Microsoft.PowerShell.Core\FileSystem::C:\
 
 
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        2012-01-08     02:56            61587b977687a6e22fbe
d----        2011-12-14     03:19            Documents and Settings
d----        2011-12-15     00:05            oraclexe
d-r--        2012-01-08     03:44            Program Files
d----        2012-01-05     19:59            sqldeveloper
d----        2012-01-09     01:15            temp
d----        2012-01-09     01:13            WINDOWS
-a---        2011-12-14     03:12          0 AUTOEXEC.BAT
-a---        2011-12-14     03:12          0 CONFIG.SYS
 
 
========== Executing cd \temp
========== Executing dir
 
 
    Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp
 
 
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2012-01-09     01:16       5290 PowerShell.jar
 
 
========== Executing cd \bubba
Set-Location : Cannot find path 'C:\bubba' because it does not exist.
At line:1 char:3
+ cd  <<<< \bubba
========== Exiting .... bye.
 
C:\temp>

No comments: