I'm trying to invoke a jar, but I don't see any output when I run the command without args, and when I do run with args, I get the following error:
[ant:java] The args attribute is deprecated. Please use nested arg elements.
[ant:java] Java Result: 1
How do I invoke ant.java in such a way that I see output and can pass arguments?
task compressJs(){
ant.java(jar:"lib/yuicompressor-2.4.6.jar",fork:true,args:['js/file.js', '-o', 'build/js/file.js'])
}
Your args should be specified like this:
ant.java(jar:"lib/yuicompressor-2.4.6.jar",fork:true) {
arg(value: "js/file.js")
arg(value: "-o")
arg(value: "build/js/file.js")
}
Pretty much it is the same as you would do with ant except using the Groovy style markup builder instead of XML.
By default your output will go to the screen. If you want to redirect it, set the 'output' property.
As I said before, it's best to use the JavaExec task. To execute a Jar, you can do:
task exec(type: JavaExec) {
main = "-jar"
args relativePath("lib/yuicompressor-2.4.6.jar")
args ... // add any other args as necessary
}
The comments in http://issues.gradle.org/browse/GRADLE-1274 also explain how to capture output from ant.java, but using JavaExec is the better solution.
To get the output set the --info flag on gradle or set the outputproperty on ant.java:
task compressJs(){
ant.java(outputproperty: 'cmdOut', jar:"lib/yuicompressor-2.4.6.jar",fork:true,args:['js/file.js', '-o', 'build/js/file.js'])
println(ant.project.properties.cmdOut)
}
The Ant task needs to be invoked in the execution phase, not the configuration phase:
task compressJs() << { // note the <<
ant.java(...)
}
You could also use Gradle's JavaExec task. See the documentation.
In Addition to Chris Dail's answer , you can also use something like this
ant.java(jar:"lib/yuicompressor-2.4.6.jar",fork:true) {
arg(line: "js/file.js -o build/js/file.js")
}
This allows one to declare all the arguments in a single line, very similar to the usage in ANT.
Related
I have a Gradle build script that uses the Application plugin, and I want to pass as JVM argument a string that contains the $ character, but I can't because it always is converted to the \$ sequence of characters...
Here is my configuration:
application {
mainClass = 'example.Main'
application.applicationDefaultJvmArgs = ['-javaagent:$APP_HOME/lib/agent.jar']
}
But then in the start script I get:
DEFAULT_JVM_OPTS='"-javaagent:\$APP_HOME/lib/agent.jar"'
And because of that \ it doesn't work, I need the value to be -javaagent:$APP_HOME/lib/agent.jar. All ways I tried get the same result (using interpolation, passing the $ as \u0024, etc.).
I've found a workaround in this answer for a related question. The code in question is the following:
startScripts {
doLast {
unixScript.text = unixScript.text.replace('\\$APP_HOME', '\$APP_HOME')
//do something like this for Windows scripts if needed too
}
}
I'm trying to execute bash script using karate. I'm able to execute the script from karate-config.js and also from .feature file. I'm also able to pass the arguments to the script.
The problem is, that if the script fails (exits with something else than 0) the test execution continues and finishes as succesfull.
I found out that when the script echo-es something then i can access it as a result of the script so I could possibly echo the exit value and do assertion on it (in some re-usable feature), but this seems like a workaround rather than a valid clean solution. Is there some clean way of accessing the exit code without echo-ing it? Am I missing on something?
script
#!/bin/bash
#possible solution
#echo 3
exit 3;
karate-config.js
var result = karate.exec('script.sh arg1')
feture file
def result = karate.exec('script.sh arg1')
Great timing. We very recently did some work for CLI testing which I am sure you can use effectively. Here is a thread on Twitter: https://twitter.com/maxandersen/status/1276431309276151814
And we have just released version 0.9.6.RC4 and new we have a new karate.fork() option that returns an instance of Command on which you can call exitCode
Here's an example:
* def proc = karate.fork('script.sh arg1')
* proc.waitSync()
* match proc.exitCode == 0
You can get more ideas here: https://github.com/intuit/karate/issues/1191#issuecomment-650087023
Note that the argument to karate.fork() can take multiple forms. If you are using karate.exec() (which will block until the process completes) the same arguments work.
string - full command line as seen above
string array - e.g. ['script.sh', 'arg1']
json where the keys can be
line - string (OR)
args - string array
env - optional environment properties (as JSON)
redirectErrorStream - boolean, true by default which means Sys.err appears in Sys.out
workingDir - working directory
useShell - default false, auto-prepend cmd /c or sh -c depending on OS
And since karate.fork() is async, you need to call waitSync() if needed as in the example above.
Do provide feedback and we can tweak further if needed.
EDIT: here's a very advanced example that shows how to listen to the process output / log, collect the log, and conditionally exit: fork-listener.feature
Another answer which can be a useful reference: Conditional match based on OS
And here's how to use cURL for advanced HTTP tests ! https://stackoverflow.com/a/73230200/143475
In case you need to do a lot of local file manipulation, you can use the karate.toJavaFile() utility so you can convert a relative path or a "prefixed" path to an absolute path.
* def file = karate.toJavaFile('classpath:some/file.txt')
* def path = file.getPath()
I have a Java application that runs with a custom gradle task and the application requires some arguments upon being invoked. These are:
programName ( string | -f filename | -d key | -h)
Options:
string Message to be used.
-d key Use default messages, key must be s[hort], m[edium] or l[ong].
-f filename Use specified file as input.
-h Help dialog.
Gradle task looks like:
task run (type: JavaExec){
description = "Secure algorythm testing"
main = 'main.Test'
classpath = sourceSets.main.runtimeClasspath
}
I've tried running gradle run -h and it does not work.
Gradle 4.9+
gradle run --args='arg1 arg2'
This assumes your build.gradle is configured with the Application plugin. Your build.gradle should look similar to this:
plugins {
// Implicitly applies Java plugin
id: 'application'
}
application {
// URI of your main class/application's entry point (required)
mainClassName = 'org.gradle.sample.Main'
}
Pre-Gradle 4.9
Include the following in your build.gradle:
run {
if (project.hasProperty("appArgs")) {
args Eval.me(appArgs)
}
}
Then to run: gradle run -PappArgs="['arg1', 'args2']"
Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar, you can use
gradle run --args='foo --bar'
See Also Gradle Application Plugin
How to upgrade Gradle wrapper
If you want to use the same set of arguments all the time, the following is all you need.
run {
args = ["--myarg1", "--myarg2"]
}
Sorry for answering so late.
I figured an answer alike to #xlm 's:
task run (type: JavaExec, dependsOn: classes){
if(project.hasProperty('myargs')){
args(myargs.split(','))
}
description = "Secure algorythm testing"
main = "main.Test"
classpath = sourceSets.main.runtimeClasspath
}
And invoke like:
gradle run -Pmyargs=-d,s
You can find the solution in Problems passing system properties and parameters when running Java class via Gradle . Both involve the use of the args property
Also you should read the difference between passing with -D or with -P that is explained in the Gradle documentation
Of course the answers above all do the job, but still i would like to use something like
gradle run path1 path2
well this can't be done, but what if we can:
gralde run --- path1 path2
If you think it is more elegant, then you can do it, the trick is to process the command line and modify it before gradle does, this can be done by using init scripts
The init script below:
Process the command line and remove --- and all other arguments following '---'
Add property 'appArgs' to gradle.ext
So in your run task (or JavaExec, Exec) you can:
if (project.gradle.hasProperty("appArgs")) {
List<String> appArgs = project.gradle.appArgs;
args appArgs
}
The init script is:
import org.gradle.api.invocation.Gradle
Gradle aGradle = gradle
StartParameter startParameter = aGradle.startParameter
List tasks = startParameter.getTaskRequests();
List<String> appArgs = new ArrayList<>()
tasks.forEach {
List<String> args = it.getArgs();
Iterator<String> argsI = args.iterator();
while (argsI.hasNext()) {
String arg = argsI.next();
// remove '---' and all that follow
if (arg == "---") {
argsI.remove();
while (argsI.hasNext()) {
arg = argsI.next();
// and add it to appArgs
appArgs.add(arg);
argsI.remove();
}
}
}
}
aGradle.ext.appArgs = appArgs
Limitations:
I was forced to use '---' and not '--'
You have to add some global init script
If you don't like global init script, you can specify it in command line
gradle -I init.gradle run --- f:/temp/x.xml
Or better add an alias to your shell:
gradleapp run --- f:/temp/x.xml
You need to pass them as args to the task using project properties, something like:
args = [project.property('h')]
added to your task definition (see the dsl docs)
Then you can run it as:
gradle -Ph run
I am trying to run a command-line Java app via Gradle as part of a quick integration test. I am porting my build scripts from Maven, where this was easily done via exec-maven-plugin. My two big requirements are:
Being able to pass system properties to the executable Java code
Being able to pass command-line args to the executable Java code
Please note that I am not trying to read these properties in the build script, I'm trying to read them in the Java program that the script builds and executes.
I have found two other SO posts that address Java program execution via Gradle: one with an answer that advocates using apply plugin: "application" in the build file and gradle run at the command line, and another with answers advocating that approach as well as using task execute(type:JavaExec) in the build file and gradle execute at the command line. I have tried both approaches and have not succeeded.
I have two problems:
(1) I cannot get the Java executable to read the system properties
Whether I do this:
build.gradle:
apply plugin: 'application'
mainClassName = "com.mycompany.MyMain"
Command line:
gradle run -Dmyproperty=myvalue
Or this:
build.gradle:
task execute (type:JavaExec) {
main = "com.mycompany.MyMain"
classpath = sourceSets.main.runtimeClasspath
}
Command line:
gradle execute -Dmyproperty=myvalue
In either case, myproperty does not make it through. The code that begins running from MyMain.main (...) reads the myproperty system property as null/missing.
(2) I cannot pass command line arguments
This is probably related to the first problem. In exec-maven-plugin, for example, command line args were themselves passed in via a system property. Is that the case with Gradle, or is there another way to pass command line arguments?
How do I get these variables through? Also, is it better to use apply plugin: 'application' or task execute (type:JavaExec)?
Figured it out. The main issue is that when Gradle forks a new Java process, it does not automatically pass the environment variable values along to the new environment. One has to explicitly pass these variables via the systemProperties property of the task or plugin.
The other issue was understanding how to pass command-line args; these are via the args property on the task or plugin. As with the Maven exec-maven-plugin, they should be passed in on the command line via yet another system property, as a space-delimited list that then needs to be split() before setting args, which accepts List objects. I've named the property exec.args, which is the old Maven name.
It seems both the javaExec and application plugin approach are valid. One might favor the application plugin approach if one wants to use some of its other features (automatically putting together a distribution, etc.)
Here are the solutions:
JavaExec Approach
Command Line:
gradle execute -Dmyvariable=myvalue -Dexec.args="arg1 arg2 arg3"
build.gradle:
task execute (type:JavaExec) {
main = "com.myCompany.MyMain"
classpath = sourceSets.main.runtimeClasspath
/* Can pass all the properties: */
systemProperties System.getProperties()
/* Or just each by name: */
systemProperty "myvariable", System.getProperty("myvariable")
/* Need to split the space-delimited value in the exec.args */
args System.getProperty("exec.args", "").split()
}
Application Plugin Approach
Command Line:
gradle run -Dmyvariable=myvalue -Dexec.args="arg1 arg2 arg3"
build.gradle:
apply plugin: 'application'
mainClassName = "com.mycompany.MyMain"
run {
/* Can pass all the properties: */
systemProperties System.getProperties()
/* Or just each by name: */
systemProperty "myvariable", System.getProperty("myvariable")
/* Need to split the space-delimited value in the exec.args */
args System.getProperty("exec.args", "").split()
}
For those who might not want to pollute your application's system properties by passing unrelated Gradle props, I recommend namespacing your arguments.
tasks.withType(JavaExec) {
System.properties.each { k,v->
if (k.startsWith("prefix.")) {
systemProperty k - "prefix.", v
}
}
}
java ... -Dprefix.my.prop=true will pass my.prop
I'm new to gradle so I needed this and what is working for me with gradle 4.6 seems a little easier for the command line. Instead of parsing 1 arg string you can pass an array of args, and I found a way to pass in all property with one line as well. Combined below:
apply plugin: 'java'
apply plugin: 'org.springframework.boot' <- for my project
task runApp(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'testit.TomcatApp'
// arguments to pass to the application
// args 'myarg1 -rest' <- came in as 1 string
args = ["--myarg1 with spaces even", "--myarg2"]
// and to pass in all -D system property args:
systemProperties = System.properties
}
gradle run -Dwhatever=xxx -Dmyarg2=hey
// Java reading them:
public static void main(String[] args) {
for ( int i = 0; i < args.length; i++ )
{
logger.info( "** args [" + i + "] =" + args[i] + "=" );
}
logger.info( "** -Dwhatever =" + System.getProperty("whatever") + "=" );
logger.info( "** -Dmyarg2 =" + System.getProperty("myarg2") + "=" );
[main] INFO testit.TomcatApp - ** args [0] =--myarg1 with spaces even=
[main] INFO testit.TomcatApp - ** args [1] =--myarg2=
[main] INFO testit.TomcatApp - ** -Dwhatever =xxx=
[main] INFO testit.TomcatApp - ** -Dmyarg2 =hey=
Maybe I am late for the party, but has anyone tried with "set the prop before executing gradle"? I have tested and this works too, apparently.
myVar=myVal gradle test
For example, you can set the active profile like:
SPRING_PROFILES_ACTIVE=dev gradle test
These also work, apparently:(tested)
set myVar=myVal && gradle test # for windows
export myVar=myVal && gradle test # for linux and mac
Be wary that myVar cannot be period-separated; or else only the part before the first period will be taken as key.
Hello I am trying to pass arguments to my ImageJ PlugIn. However it seems no matter what I pass, argument string will be considered as empty by the program. I couldn't find any documentation on the internet about THAT issue.
My Java plugIn looks like this, and compiles fine.
import ij.plugin.PlugIn;
public class Test implements PlugIn {
public void run(String args) {
IJ.log("Starting plugin Test");
IJ.log("args: ." + args + ".");
}
}
I compile, make a .jar file and put it into the ImageJ plugins folder.
I can call it with the ImageJ userInterface (Plugin>Segmentation>Test) and the macro recorder will put the command used:
run("Test");
Then my code is executed, the log window pops-up as expected:
Starting plugin Test
args: ..
I can manually run the same command in a .ijm file, and get the same result.
However, when I run the following macro command:
run("Test", "my_string");
I get the same results in the log window:
Starting plugin Test
args: .. // <- I would like to get "my_string" passed there
Where it should have displayed (at least what I expect it to do)
Starting plugin Test
args: .my_string.
So my question is: how can I pass parameters to PlugIn and especially how to access them?
Many thanks
EDIT
Hey I found a way to bypass that:
Using the Macro.getOptions() : this method will retrieve the string passed in argument to the plugin.
However, I still can't find a way to pass more than 1 string argument. I tried overloading the PlugIn.run() method but it doesn't work at all.
My quick fix is to put all my arguments in 1 string, and separating them by a space. Then I split this string:
String [] arguments = Macro.getOptions().split(" ");
I don't see a more convenient way to get around that. I can't believe how stupid this situation is.
Please, if you have a better solution, feel free to share! Thanks
You are confusing the run(String arg) method in ij.plugin.Plugin with the ImageJ macro command run("command"\[, "options"\]), which calls IJ.run(String command, String options).
In the documentation for ij.plugin.Plugin#run(String arg), it says:
This method is called when the plugin is loaded. 'arg', which may be blank, is the argument specified for this plugin in IJ_Props.txt.
So, arg is an optional argument that you can use in IJ_Props.txt or in the plugins.config file of your plugin to assign different menu commands to different functions of your plugin (see also the excellent documentation on the Fiji wiki).
To make use of the options parameter when running your plugin from macro code, you should use a GenericDialog to get the options, or (as you apparently learned the hard way) use the helper function Macro.getOptions().