0

I am unable to execute maven command via script using java. The maven command is suppose a create an archetype folder which is not being created.

This is what the java code looks like :

ProcessBuilder pb = new ProcessBuilder("/log/script.sh");
pb.directory(new File("/log"));
Process p = pb.start();
p.waitFor();        
IOUtils.copy(p.getInputStream(), System.out);

This is what script.sh looks like

mvn archetype:generate -B -DarchetypeGroupId=my.archetype -DarchetypeArtifactId=archetype -DarchetypeVersion=1.0.0-SNAPSHOT  -DgroupId=my.groupid -DartifactId=artifact -Dpackage=my.groupid.artifact -Dversion=1.0.0-SNAPSHOT -DarchetypeRepository=<link-to-repo>
ls

I can see in the output of the ls command that the folder that was supposed to be created by the maven command is not getting created, whereas, when I try running the script from the terminal, it gets created. I have giving the folder 777 permission. Can someone let me know what I might be doing wrong ?

4
  • Are you seeing any error ? Commented Jun 11, 2017 at 5:03
  • Nope. No error on the console atleast Commented Jun 11, 2017 at 5:12
  • Is that the complete code ? Where are you calling the start method on the pb object ? Commented Jun 11, 2017 at 5:21
  • Thanks for pointing that out. I had missed it while copy pasting Commented Jun 11, 2017 at 5:47

1 Answer 1

1

Here are a couple of observations:

  1. The stream returned by getInputStream() is the standard output stream for the child process. Error messages are typically written to standard error. Try reading getErrorStream() instead / as well.

  2. I'm not sure if it is even possible to read a Process object's standard output / error after the call to waitFor() has returned. It could give you nothing at all, or a truncated stream. In the worst case, it could deadlock. (The external process gets stuck because its output / error pipe is blocked ... 'cos nothing is reading it. Therefore it canbot exit. Therefore the Java waitFor() call cannot return. But the Java side only reads from the pipe after waitFor() returns.)

Fixes:

  1. Do the IOUtils.copy in a separate thread, and start that thread before you call p.waitFor.
  2. Read both streams ... or use redirection to combine them into one stream.
  3. Alternatively, redirect the output to a file and look at it external to Java.

There is a lot of material in the ProcessBuilder on how to implement redirection. Alternatively, do it in the shell script.

Sign up to request clarification or add additional context in comments.

1 Comment

Using getErrorStream() I was able to find out the problem in the script. I had to set the mvn path explicitly when I was executing the script via Java.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.