views:

75

answers:

2

In the following program am giving name as "don" so the command will search activedirectory with all the names starting with don (like donald etc). But the line2 variable becomes null after the assignment from reader object and it never goes into the loop. What am i doing wrong? FYI: the command works when i give it on the command line.

try {
    Process p = Runtime.getRuntime().exec(
        "dsquery user -name " + name + "* -limit 200|dsget user -samid -display");
    p.waitFor();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line2 = reader.readLine();
    HashMap<String,String> hmap = new HashMap<String,String>();
    while (line2 != null) {
        line2 = line2.trim();
        if (line2.startsWith("dsget")||line2.startsWith("samid")) {
            continue;
        }
        String[] arr = line2.split(" ",1);
        hmap.put(arr[0].toLowerCase(),arr[1].toLowerCase());
        line2 = reader.readLine();
    }
    reader.close();
    line2 = reader.readLine();
}
+4  A: 

If I am not mistaken, the pipe (or redirection) requires to launch the programs with cmd.exe. Something like:

Process p = Runtime.getRuntime().exec("cmd /c dsquery user -name " + name + "* -limit 200|dsget user -samid -display");
PhiLho
you can consume the errorstream to confirm it's not finding the command
helios
You're right. Piping is a functionality of cmd/shell and only available in that context.
Andreas_D
I'll try this approach now.. Thanks :-)
BoCode
Thank you very much. This approach works for me
BoCode
A: 

I can see at least some possible problems:

1) as PhiLho wrote: pipe and redirection is done by the shell (sh, bash,... or cmd.exe on Windows). You must handle it in the Java code or run your commands in a shell.

2) after calling waitFor() the Thread is blocked until the process terminates, the process only terminates if you "consume" it's InputStream. This is not happening since waitFor() is still waiting... Better to read and process the InputStream in an additional Thread (or call waitFor after reading the InputStream).

3) reading after closing (2 last lines) should throw an Exception.

Reading the ErrorStream could help find some errors, and checking the return of waitFor is also indicated.

EDIT:
actually there should be some Exceptions being throw by that code.
Are the Exceptions being reported (printStackTrace) or just ignored?

Carlos Heuberger
actually no exceptions are being thrown at all (which is surprising!). It just comes to the line string line2 = reader.getline() and line2 becomes null...jumps over the loop giving me nothing in return. I'll have to try the cmd.exe approach though.
BoCode
small correction...i was debugging (line by line) the program upto reader2.close()... didnt really run it thru the end. If i do run it i get exception because i closed the stream and reading again :-).
BoCode