I want something like:
java programName -jobs1 -C 10 -W 20
java programName -job2
java programName -job3
With contents:
Option o1 = new Option("job2", "some desc");
Option o2 = new Option("job3" , "(some desc")
Option o3 = OptionBuilder.hasArgs(2).withArgName( "W" ).withArgName("C").withDescription( "Some desc" ).create("job1")
Option o4 = new Option("help");
Options os = new Options().addOption(o1).addOption(o2).addOption(o3).addOption(o4).
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "ProgramName", options );
...where the output is:
Usage ProgramName
-job1 <c> Some Desc
-job2 Some desc
-job3 Some desc
-help Print this message
I expect for -job1 it should print -job1 -C <> -W <>
Am I missing something? It doesn't work with more than one argument. By the way, I used commons-cli 1.2.
You cannot have context-sensitive arguments. You can have the arguments: job1, job2, job3, C & W, but you cannot say (through the library) that C & W are only valid for job1.
If job1/2/3 are mutually exclusive, create an OptionGroup. Then in code, make sure C & W are only given for job1.
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.HelpFormatter;
public class StackOverflowExample
{
public static final String JOB1 = "job1";
public static final Option job1 =
OptionBuilder.hasArg(false)
.isRequired(false)
.withDescription("description of job1")
.create(JOB1);
public static final String JOB2 = "job2";
public static final Option job2 =
OptionBuilder.hasArg(false)
.isRequired(false)
.withDescription("description of job2")
.create(JOB2);
public static final String JOB3 = "job3";
public static final Option job3 =
OptionBuilder.hasArg(false)
.isRequired(false)
.withDescription("description of job3")
.create(JOB3);
public static final String MY_C = "C";
public static final Option my_c =
OptionBuilder.hasArg(true)
.withArgName("count")
.isRequired(false)
.withDescription("description of C")
.create(MY_C);
public static final String MY_W = "W";
public static final Option my_w =
OptionBuilder.hasArg(true)
.withArgName("width")
.isRequired(false)
.withDescription("description of W")
.create(MY_W);
public static void main(String[] args)
{
Options options = new Options();
OptionGroup optgrp = new OptionGroup();
optgrp.addOption(job1);
optgrp.addOption(job2);
optgrp.addOption(job3);
options.addOptionGroup(optgrp);
options.addOption(my_c);
options.addOption(my_w);
try {
CommandLineParser parser = new GnuParser();
CommandLine cmdline = parser.parse(options, args);
if (((cmdline.hasOption(MY_C)) || (cmdline.hasOption(MY_W))) &&
(! cmdline.hasOption(JOB1))) {
HelpFormatter help = new HelpFormatter();
help.printHelp("cmdname", options);
System.exit(-1);
}
System.out.println("OK");
}
catch (Exception ex) {
ex.printStackTrace();
System.exit(-1);
}
}
}
Which produces the following output:
<~/sandbox/CoreUtils/scratch> $ javac -d . -cp ~/sandbox/CoreUtils/lib/commons-cli-1.2.jar:. StackOverflowExample.java
<~/sandbox/CoreUtils/scratch> $ java -cp ~/sandbox/CoreUtils/lib/commons-cli-1.2.jar:. StackOverflowExample -C foo -job1
OK
<~/sandbox/CoreUtils/scratch> $ java -cp ~/sandbox/CoreUtils/lib/commons-cli-1.2.jar:. StackOverflowExample -C foo -job2
usage: cmdname
-C <count> description of C
-job1 description of job1
-job2 description of job2
-job3 description of job3
-W <width> description of W
Related
How does java run a batch file in the background?
I have a batch file with the following content
#echo off
:start
start /b cmd /c example.exe -c config >nul 2>&1
goto :eof
In fact, I run this code under the command line, it can run in the background, but it seems that the "execution" of the java call will hang on the console on the idea, I am a java novice and I don't know the principle.
java code:
package com.example;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
public class Example {
public static void main(String[] args) throws Exception{
System.out.println("Hello World");
System.out.println("Started.");
String script_path = "";
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
System.out.println(isWindows);
if (isWindows) {
System.out.println("it's Windows");
script_path = "c:/users/test-running/desktop/example.bat";
CommandLine cmdLine = new CommandLine("cmd");
cmdLine.addArgument(script_path);
cmdLine.addArgument("start").addArgument("server");
DefaultExecutor executor = new DefaultExecutor();
executor.execute(cmdLine);
System.out.println("Finished.");
} else {
System.out.println("it's Linux");
script_path = "/Users/seth/Downloads/example.sh";
CommandLine cmdLine = new CommandLine("/bin/bash");
cmdLine.addArgument(script_path);
cmdLine.addArgument("start").addArgument("server");
DefaultExecutor executor = new DefaultExecutor();
executor.execute(cmdLine);
System.out.println("Finished.");
}
}
}
So does anyone know what java is doing? Or is the syntax of the batch file wrong?
For every command I have a concrete class which implement certain interface.
For example:
public class FooCommand implements Command{
#Parameter(names = {"-?","--help"}, description = "display this help",help = true)
private boolean helpRequested = false;
...
}
And this is the usage message I get:
Usage: foo-command [options]
Options:
-?, --help
display this help
How can I add description to command (but not to option). For example I want to get such usage message:
Usage: foo-command [options] - This command is used as base foo
Options:
-?, --help
display this help
EDIT I have foo-command, boo-command, lala-command. However, all these commands are separate and are not within one main command (by other words this is not like git clone ...).
This is the way I get usage
JCommander jCommander=new JCommander(command, args);
jCommander.setProgramName(commandName);//for example foo-command
StringBuilder builder=new StringBuilder();
jCommander.usage(builder);
Following snippet might be a starting point for what you are looking for.
#Parameters(commandDescription = "foo-command short description")
public class FooCommand implements Command {
#Parameter(names = {"-?", "--help"}, description = "display this help",
help = true)
private boolean helpRequested = false;
#Parameter(description = "This command is used as base foo")
public List<String> commandOptions;
// your command code goes below
}
public class CommandMain {
public static void main(String[] args) {
JCommander jc = new JCommander();
jc.setProgramName(CommandMain.class.getSimpleName());
FooCommand foo = new FooCommand();
jc.addCommand("foo-command", foo);
// display the help
jc.usage();
}
}
output
Usage: CommandMain [options] [command] [command options]
Commands:
foo-command foo-command short description
Usage: foo-command [options] This command is used as base foo
Options:
-?, --help
display this help
Default: false
Also have a look at: JCommander command syntax
edit Show the description for a command itself. The annotation #Parameters(commandDescription = "foo-command short description") on the class FooCommand can be omitted in that case.
Command command = new FooCommand();
JCommander jc = new JCommander(command, args);
jc.setProgramName("foo-command");
StringBuilder builder = new StringBuilder();
jc.usage(builder);
System.out.println(builder);
output
Usage: foo-command [options] This command is used as base foo
Options:
-?, --help
display this help
Default: false
I have a self-contained Java application packaged with the javapackager tool (version 8.0, Windows). How do I pass it system property values at application runtime (not at package time) on the command line?
The doc does not seem to address this.
I tried the standard Java way as in:
mypackagedapp.exe -Dmyprop=myvalue
but that does not appear to have an effect.
Here is a code that validates if an argument exists in the command line.
See if the next code can help you.
public static void main(final String[] args) throws Exception {
CommandLine line = validateArgs(args);
if (null == line) {
return;
}
}
private static CommandLine validateArgs(String[] args) {
Options flags = getArgs();
CommandLineParser parser = new BasicParser();
CommandLine line = null;
try {
// parse the command line arguments
line = parser.parse(flags, args);
if (line == null) {
return null;
}
} catch (ParseException exp) {
System.out.println(exp.getMessage());
}
return line;
}
static Options getArgs() {
Options flags = new Options();
Option dmyprop = OptionBuilder.withArgName("dmyprop")
.hasArg()
.withDescription("add description")
.create("Dmyprop");
flags.addOption(dmyprop);
return flags;
}
In order to get environment variable you need to use:
String env = System.getenv(option);
where option is your desired environment variable.
Hope it helped.
i want to do groovy file call in java
my source:
ex.groovy
def swingBuilder = new SwingBuilder()
swingBuilder.edt {
frame(title: 'ex', size: [200, 150], show: true) {
borderLayout(vgap: 5)
panel(constraints: BorderLayout.CENTER, border: emptyBorder(10)) {
button "a"
button "b"
}
}
}
ex1.java
class ex1{
public static void main(String[] args)throws Exception {
File sourceFile = new File("mypath/ex.groovy");
ClassLoader clo = jview.class.getClassLoader();
GroovyClassLoader classLoader = new GroovyClassLoader(clo);
Class groovy = classLoader.parseClass(sourceFile);
GroovyObject groovyob = (GroovyObject)groovy.newInstance();
groovyob.invokeMethod("run", null);
}
}
how do i?
help please..
You could use GroovyShell (if required with Binding)
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
public class ex1 {
public static void main(String[] args) {
Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
shell.evaluate("mypath/ex.groovy");
}
Task: execute groovy script with Groovy sandbox:
http://groovy.codehaus.org/api/overview-summary.html
http://groovy-sandbox.kohsuke.org/
Groovy Script to execute:
query.reverse(); // QUERY is a some string that should be reversed
File "GroovyScriptSandbox.groovy" should get two parameters(script and values for this script):
package test.my.groovy.sandbox
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.ImportCustomizer
import org.codehaus.groovy.control.customizers.SecureASTCustomizer
import org.springframework.stereotype.Component
#Component
class GroovyScriptSandbox {
def config
def shell
public String runScript(final String script, final String query) {
final ImportCustomizer imports = new ImportCustomizer()
.addStarImports('groovyx.net.http')
.addStaticStars('groovyx.net.http.ContentType', 'groovyx.net.http.Method')
config = new CompilerConfiguration()
config.addCompilationCustomizers(imports)
def newScript = "{ query -> " + script + "}"
shell = new GroovyShell(config)
def clos = shell.evaluate(newScript)
return clos.call(query)
}
}
Java method that executes "GroovyScriptSandbox.groovy":
#Resource
private GroovyScriptSandbox groovyScriptSandbox;
#RequestMapping(value = "/run", method = RequestMethod.POST)
#ResponseBody
public String runScript(#RequestParam("script") final String script,
#RequestParam("query") final String query) {
return groovyScriptSandbox.runScript(script, query);
}
In that case all works fine:
Java controller getting script parameter equal "query.reverse()" and query parameter equals "0123"
Groovy file executes script "query.reverse()" in sandbox where query equals "0123"
Result equals "3210"
Question:
I'm trying to replace "GroovyScriptSandbox.groovy" file with "GroovyScriptSandbox.java" and I don't know how to write the same groovy code in Java.
Finally found solution:
public String scriptRunner(final String script, final String query) {
final ImportCustomizer imports = new ImportCustomizer();
imports.addStaticStars("java.lang.Math");
imports.addStarImports("groovyx.net.http");
imports.addStaticStars("groovyx.net.http.ContentType", "groovyx.net.http.Method");
final SecureASTCustomizer secure = new SecureASTCustomizer();
secure.setClosuresAllowed(true);
final CompilerConfiguration config = new CompilerConfiguration();
config.addCompilationCustomizers(imports, secure);
final Binding intBinding = new Binding(); // alow parameters in the script
intBinding.setVariable("query", query);
final GroovyShell shell = new GroovyShell(intBinding, config); // create shall
// code execution
final Object clos = shell.evaluate(script);
if (clos == null) {
return "No result avalible!";
}
return clos.toString();
}