Execute a .jar in a Groovy script - java

I'm creating a test case with Katalon Studio using the script mode which is a groovy script. I need that groovy script to execute a .jar that will be inside the Katalon project folder.
For testing purposes I created a .jar that creates a file named "the-file-name" and prints a message in the console.
I found a way to execute a command in Groovy:
def command = "git --version"
def proc = command.execute()
proc.waitFor()
println proc.in.text
This prints git's version in the Katalon console. So I guessed that putting "java -jar test.jar" would be enough but even though the execution seems to end correctly it also seems that the .jar didn't do anything. Just to be sure, I executed the same .jar using de Windows command line and it works perfectly. The file is created and the message written in the console.
When executing, Katalon console acts as if it was correctly executed. There are no error messages and execution is marked as successful yet the test file "the-file-name" is nowhere to be found and I'm not getting the .jar's console output shown in the Katalon console as in the git command.

Found a way to do it.
public class CustomKeywords {
#Keyword
def runBatch(String path) {
def cmd = "cmd /c \"java -jar \"" + path + "\"\"";
runCmd(cmd)
}
def runCmd(String cmd) {
KeywordUtil.logInfo("cmd: ${cmd}")
def proc = cmd.execute();
def outputStream = new StringBuffer();
def errStream = new StringBuffer()
proc.waitForProcessOutput(outputStream, errStream);
println(outputStream.toString());
println(errStream.toString())
if(proc.exitValue() != 0){
KeywordUtil.markFailed("Out:" + outputStream.toString() + ", Err: " + errStream.toString())
}
}
}

Related

Executing command in ProcessBuilder does not seem to work for "java" commands in Windows (Kotlin)

Currently trying to execute a .jar file programmatically. But to test out java, I tried running the the following:
val p = ProcessBuilder("cmd.exe", "/c", "java", "-version").start()
val results: List<String> = p.inputStream.bufferedReader().readLines()
assertThat("Results should contain java version: ", results, hasItem(containsString("java version")))
However, nothing seems to output.
I am successfully able to run:
val pb = ProcessBuilder("cmd.exe", "/c", "echo", "hello world")
I have tried adding a working directory where the java executable is located, but nothing happens.
I am running out of ideas on how to make this work. If I run cmd and type out java -version I get the version information.
What else could I do to get this to work?
ProcessBuilder writes the result of command java -version to error output Process.errorStream, not Process.inputStream.
Try this code:
val results: List<String> = p.errorStream.bufferedReader().readLines()
Also you may try Koproc lib
It's a small Kotlin lib to run process and execute commands based on Java ProcessBuilder
You may run java process with timeout = 120 sec :
val koproc = "java -jar some.jar".startProcess { timeoutSec = 120 }
koproc.use {
println("Out: ${it.readAvailableOut}")
println("Err: ${it.readAvailableErrOut}")
}
println("Full result after closing: ${koproc.result}")
Run cmd command:
// 'cmd.exe' process will be closed after timeout
val commandResult = "cmd.exe dirs".startCommand { timeoutSec = 1 }
// But you will get the output
println("Out: ${commandResult.out}")
See examples in unit tests: https://github.com/kochetkov-ma/koproc/blob/main/src/test/kotlin/ru/iopump/koproc/ExtensionKtIT.kt

Java command through CMD not working in C#.NET

I'm trying to run a java command in cmd using C# to get some inputs for my program, the path for Java is set correctly, and I am able to run Java commands in the cmd without any trouble but when I tried it in C#, it's showing " 'java' is not recognized as an internal or external command, operable program or batch file. " as if the path is not set.
But I am able to run the same command outside, don't know what seems to be the issue, kindly help, thanks in advance!
string cmd = #"/c java -jar """ + $"{treeEditDistanceDataFolder}libs" + $#"\RTED_v1.1.jar"" -f ""{f1}"" ""{f2}"" -c 1 1 1 -s heavy --switch -m";
Console.WriteLine(cmd);
var proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = cmd;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
Console.WriteLine("Process started");
string output = proc.StandardOutput.ReadToEnd();
Console.WriteLine("Output was read");
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();
This line is your problem:
proc.StartInfo.UseShellExecute = false;
When UseShellExecute is true, the system and user PATH variables will be used if the application to launch is just the executable name. Because you're setting it to false, and java doesn't exist in your application's folder, it isn't possible for .NET to find it.
You have two options:
Set UseShellExecute to true so that it can use the PATH variable to find java.
Use a fully qualified path, e.g. "C:\Program Files\Java\jdk1.8.0_101\bin\java"
See this answer for more info.

Execute a shell script in runtime of Java code from Eclipse

I have a shell script that I want to execute in Eclipse from a Java code.
I am able to use external tools in order to run the script, but I want the script to run during the execution of the Java code i.e. the Java code should make a call to the script.
Earlier I was using the "Process Builder" to do so but it seems Eclipse does not support that method as it says "File not found" when I have given it all the permissions.
Any idea how to run the script from a Java code in Eclipse?
Here is the code:
String line1 = null;
String target = new String("/home/aditya_s/workspace/rs-test/src/iperf_parse.sh " + host + " " + "9000");
while(line1 == null)
{
Process p1 = Runtime.getRuntime().exec(target);
BufferedReader input1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
System.out.println("Ran");
line1 = input1.readLine();
p1.destroy();
}
BW = Double.parseDouble(line1);
TIP: Right click on the shell script and go to Properties. There give the 'Read/Write/Execute' permissions to 'Owner'. By default, the 'Execute' permission is not there. So you might get an error like 'Could not execute script.sh'.
Eclipse runs your java program just as it normally would, so ProcessBuilder will work as well. It is possible that you passed in the wrong path. If the path is relative, it will be relative to System.getProperty("user.dir").
You should be able to use the below, replace shellscript with the script you want to run.
String s = "shellscript";
Process proc = Runtime.getRuntime().exec(s);
You should look at ProcessBuilder

execute command from Grails app

I want to perform an svn delete from my Grails app. I tested out both of the following in the Grails console:
"svn delete /usr/share/mydir".execute()
Runtime.getRuntime().exec("svn delete /usr/share/mydir")
In both cases, a instance of java.lang.Process is returned, but the command does not get executed (/usr/share/mydir is not deleted).
This behaviour only happens when the app is running on Linux (Ubuntu). If I run it on Windows, the command does get executed.
Update
Following Tim's advice in the comments, I changed the command so that it captures the process output:
def process = "svn delete /usr/share/mydir".execute()
def out = new StringBuilder()
process.waitForProcessOutput(out, new StringBuilder())
println "$out"
I now see that the reason it's failing is because:
error svn: Can't open file '/usr/share/mydir/.svn/lock': Permission
denied
The below code works fine for me on CentOS.
def scriptCom="/folderlocation/shellscript.sh"
println "[[Running $scriptCom]]"
def proc = scriptCom.execute()
def oneMinute = 60000
proc.waitForOrKill(oneMinute)
if(proc.exitValue()!=0){
println "[[return code: ${proc.exitValue()}]]"
println "[[stderr: ${proc.err.text}]]"
return null
}else{
println "[[stdout:$revisionid]]"
return proc.in.text.readLines()
}

Shell script not running R (Rhipe) program from Java code

I have a simple shell script which looks like this:
R --vanilla<myMRjob.R
hadoop fs -get /output_03/ /home/user/Desktop/hdfs_output/
This shell script runs myMRjob.R, and gets the output from hdfs to local file system. It executes fine from terminal.
When i am trying to run shell script from java code, i am unable to launch the MapReduce job i.e. the first line isn't getting executed. While "hadoop fs -get .." line is running fine through Java code.
Java code which i used is:
import java.io.*;
public class Dtry {
public static void main(String[] args) {
File wd = new File("/home/dipesh/");
System.out.println("Working Directory: " +wd);
Process proc = null;
try {
proc = Runtime.getRuntime().exec("./Recomm.sh", null, wd);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The reason behind this whole exercise is that i want to trigger and display the result of the myMRjob.R in JSP.
Please help!
The reason your shell script isn't running from the exec call is because shell scripts are really just text files and they aren't native executables. It is the shell (Bash) that knows how to interpret them. The exec call is expecting to find a native executable binary.
Adjust your Java like this in order to call the shell and have it run your script:
proc = Runtime.getRuntime().exec("/bin/bash Recomm.sh", null, wd);
When you called hadoop directly from Java, it is a native executable and that's why it worked.

Categories