Execute Maven plugin command from Java code - java

As the title suggests I was wondering if there was a way to execute a maven command like this from Java code ...
mvn --dependency:get -Dartifact=groupid.com:artifactId:1.0.0-SNAPSHOT
I can run this from the command line but when I try to run this using the Java ProcessBuilder I get
Unable to parse command line options: Unrecognized option:
--dependency:get
It looks like the ProcessBuilder can't find the maven-dependency-plugin.
Here is my code snippet, note that the mvn --version command works but the command that requires the plugin does not :(
private static void RunCommand() {
//String command = "mvn --version";
String command = "mvn --dependency:get -Dartifact=groupid.com:artifactId:1.0.0-SNAPSHOT";
try {
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
ProcessBuilder builder = new ProcessBuilder();
builder.redirectErrorStream(true);
if (isWindows) {
builder.command("cmd.exe", "/c", command);
} else {
builder.command("sh", "-c", command);
}
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
Is there anyway to tell ProcessBuilder where to find the maven plugin?

It should be
mvn dependency:get
reference

Related

Running docker-compose command in Java application

I'm trying to run
docker-compose up -d
in Java application. Here's my code:
List<String> commands = new ArrayList<>();
commands.add("zsh");
commands.add("-c");
commands.add("docker-compose up --build");
Process dockerComposeCommand;
ProcessBuilder pb = new ProcessBuilder();
pb.command(commands);
pb.directory(new File(server_config.getDOCKERFILE_PATH()));
String path = System.getenv("PATH");
pb.environment().put("PATH","/usr/bin:"+path);
pb.redirectErrorStream(true);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
List<String> result = new ArrayList<>();
try {
dockerComposeCommand = pb.start();
dockerComposeCommand.waitFor();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(dockerComposeCommand.getInputStream()))) {
String line = reader.readLine();
while (line != null) {
result.add(line);
line = reader.readLine();
System.out.println(line);
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
However, the result was
zsh:1: command not found: docker-compose
I've checked my .zshrc file and add
export PATH="$PATH:/usr/local/bin"
to include docker-compose's path.
Did I miss something or docker-compose just can't simply execute by Java?
Any advice would be helpful!

Sending 'exec' commands to Docker container using Java

I'm trying to send docker commands using Java Runtime.
Commands like docker cp works very nice with the below method as well as typing directly from the terminal.
First problem is that the docker exec command works only from the terminal, not with the Java Runtime. Other docker commands like docker cp works as expected. The only problem is that I can't run commands on the container, like echoing on the container's terminal.
Also the 2nd problem is that the System.out.println(...)method in the below method, doesn't actually print anything.
private static void runCommand() throws IOException, InterruptedException {
Process proc = Runtime.getRuntime().exec(
new String[]{"/bin/sh",
"-c",
"docker exec -u 0 -it <CONTAINER_NAME> echo", "'abc'"});
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
}
There is no need to run docker inside a shell. You can start the process directly.
As of Java 1.7 you can also use ProcessBuilder.inheritIO() to redirect the standard I/O of the subprocess
Below a working example that prints the output of the echo command:
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("docker", "exec" , "-it", "<CONTAINER_NAME_OR_ID>", "echo", "abc").inheritIO();
try {
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps.

How to execute cmd line of psexec and log to text file in a single line using JAVA?

I am trying to execute the following line in java(with escaped characters):
"psexec -i -d \\\\computerName -u user -p pass calc 2>
somePath\\psexecOut.txt"
I use the following method to execute cmd lines:
private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
System.out.println("command is = \n"+command);
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
The line is executed and calc is starting , but the log part doesn't work. The log file psexecOut.txt is not created.
When I run the command normally (without excaped characters) in cmd it runs fine and the log file is created, but using java it doesn't create the log file.
I suspect that > needs to be escaped but as I read it's already escaped as it is.
How can I execute the psexec with log to text file in a single cmd line using java like I can do manually in windows console ?
Solved:
As lit suggested in the comments: cmd.exe /c works.
So the corrected method is:
private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
System.out.println("command is = \n"+command);
Process p;
try {
p = Runtime.getRuntime().exec("cmd.exe /c "+command); // <-correction done here
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
Try putting cmd.exe /C at the beginning of the command? It is cmd.exe that interprets the > redirection.
"cmd.exe /C psexec -i -d \\\\computerName -u user -p pass calc 2> somePath\\psexecOut.txt"

Java ProcessBuilder executing command has no output

I am using ProcessBuilder to execute git command inside my java application. The output string is correct when the command is "git status" or "git branch", however the output was empty when the command is "git clone". I wonder how can I get the output string of "git clone". Thanks in advance.
try {
ProcessBuilder pb = new ProcessBuilder("git", "clone", "address");
Process pr = pb.start();
BufferedReader buf = new BufferReader(new InputStreamReader(pr.getInputStream()));
String cmdLine = "";
while ((cmdLine = buf.readLine()) != null) {
System.out.println(cmdLine);
}
} catch (Exception e) {
}

Java passing commands to the terminal difference

I want to talk to the program cordova in Java. In the terminal I can do this to get the version:
cordova -v
and in the terminal will return:
3.4.1-0.1.0
But if I ask Java to run cordova -v It returned Error: java.io.IOException: Cannot run program "cordova": error=2, No such file or directory.
I tried this in the terminal:
/usr/local/bin/cordova -v
and it still returned:
3.4.1-0.1.0
But when I asked Java to run /usr/local/bin/cordova -v it didn't return anything. Got a fix for my problem?
Edit
Pasted from comment
I'm calling my runShell function like
runShell("cordova -v");
private String runShell(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
System.out.println(e); return "Error: " + e;
}
return output.toString();
}
You want
Runtime.getRuntime().exec(new String[]{ "/usr/local/bin/cordova", "-v" });
You have to pass the command and each of its arguments separately, because you're not invoking a shell to parse the command line for you.

Categories

Resources