EzDevInfo.com

jcommander

Command line parsing framework for Java

How to execute the parsed command with jcommander?

I'm using JCommander to interact with the user on the command line.

The JCommander setup looks like the following:

JCommander jCommander = new JCommander();
jCommander.addCommand(new Command1());
jCommander.addCommand(new Command2());
jCommander.addCommand(new Command3());

Scanner scanner = new Scanner(System.in);
jCommander.usage();
jCommander.parse(splitAsArgs(scanner.nextLine())));

Now I can use getParsedCommand() to retrieve the name of the command being parsed.

My problem is that it seems very difficult to translate the returned String to the actual object that was passed to addCommand. I could hold a map externally, that does this kind of translation, but that is redundant since all this is already known by jcommander.

How shall I translate from the name of the parsed command back to command object itself?

Usually all my commands I pass to jcommander implement Runnable or something similiar. So if jcommander would allow me to access the object that was parsed, it would make my life much easier.


Source: (StackOverflow)

Pass an argument that starts with '@' to jcommander

I am using JCommander(version 1.32) to parse command line arguments passed to a java application(let's call it app). The problem I have is that one of the arguments I need to pass begins with @ and as can be seen here there is a special syntax for @. Thus calling the app with app @arg fails with

Could not read file arg: java.io.FileNotFoundException: arg (No such file or directory).

Reading through this information I tried placing my arguments in a file but apparently the "@ syntax" is recursive thus even when I place @arg in a file my program fails with the same error.

Is there a way to pass an argument that begins with @ to a program that uses jcommander? Is there a way to disable the @ syntax?


Source: (StackOverflow)

Advertisements

How to add command line parameter dependency using JCommander?

I am using JCommander for command line parameters parsing. I would like to add parameter dependency, but from the JCommander documentation, I am not able to find out if it is even supported. Has anyone tried it ? For example, java -jar Some.jar -a Foo -b Hola So, option -b shall only accompany with option -a.

This is supported in args4j http://args4j.kohsuke.org/args4j/apidocs/org/kohsuke/args4j/Option.html#depends() However, I can't use args4j because it does not support multiple values as JCommander. http://jcommander.org/apidocs/com/beust/jcommander/Parameter.html#names()

Thanks


Source: (StackOverflow)

Save parameters parsed by JCommander to file

Is it possible in JCommander to save class annotated with jcommander.Parameter to file, so one could create new object, using @ syntax to read from file?

For example, if I have annotated class

class IndexerCommandLineParameters {
    @Parameter(names = { "-s", "--source" }, description = "Source file or directory of audio files (*.wav or *.mp3). MUST BE 16bit!", required=true)
    public String source;

    @Parameter(names = { "-d", "--destination" }, description = "Destination file or directory (type must match source type).", required=true)
    public String destination;

    @Parameter(names = { "-v", "--verbositiy" }, description = "Verbosity in stderr: 0 - print only file processing errors, 1 - print indexing progress")
    public int verbositiy=1;

    @Parameter(names = {"-f", "--force"}, description = "Force to reindex alredy indexed fiels")
    public boolean reindex = true;

    @Parameter(names = {"-h", "--help"}, description = "Force to reindex alredy indexed fiels", help = true)
    private boolean help;
}

And class initialization

IndexerCommandLineParameters p = new IndexerCommandLineParameters();
JCommander c=new JCommander(p);
c.parse("-s", "xxxxx","-d", "yyyyy");
p.verbositiy=2;

I want to create file, that contains something like

-s xxxxx -d yyyyy -v 3 -f

I know I can create .toString() or something similar in each class, but I was looking for something more general, where I don't have to add some code to each annotated class.


Source: (StackOverflow)

validateWith is undefined for the annotation type Parameter (JCommander)

I get an error in Eclipse while trying a simple example with the JCommander package. The error says:

The attribute validateWith is undefined for the annotation type Parameter

and the code I'm using is the following:

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import com.beust.jcommander.*;
import com.beust.jcommander.validators.PositiveInteger;

public class JCommanderExample {

    @Parameter(names = { "-sp", "-semAndPrec"},  validateWith = CorrectPathValidator.class)
    private Path semAndPrec;

}

Of course I have provided the CorrectPathValidator class as described in the documentation at http://jcommander.org/#Parameter_validation.

Here is the class:

import java.nio.file.Paths;

import com.beust.jcommander.IParameterValidator;
import com.beust.jcommander.ParameterException;

public class CorrectPathValidator implements IParameterValidator {
    public void validate(String name, String value) throws ParameterException {
        try {
            Paths.get(value);
        } catch (Exception e) {
            String error = "Parameter " + name + " should be a path (found "
                    + value + ")";
            throw new ParameterException(error);
        }
    }
}

Apparently I'm missing something, but the example at http://jcommander.org/#Parameter_validation appears to be identical to what I tried:

@Parameter(names = "-age", validateWith = PositiveInteger.class)
private Integer age;

Can someone please tell me why I get the error?


Source: (StackOverflow)

Passing several -property options to PMD?

I'm trying to get PMD to run as an External Tool in my IntelliJ IDE. According to the PMD docs, I need to pass three -P or -property options to PMD when using the ideaj report output format (which is compatible with IntelliJ). However, PMD only allows me to pass in one -P, it errors out when passing in more than one.

Any idea how to do this? Has anyone got a working example?

P.S.: Looks like PMD is using JCommander for parameter parsing, but I'm not entirely sure it's implemented to handle several name-value-pairs for -P:

@Parameter(names = { "-property", "-P" }, description = "{name}={value}: Define a property for the report format.", converter = PropertyConverter.class)
private Properties properties = new Properties();
//...

// this has to be a public static class, so that JCommander can use it!
public static class PropertyConverter implements IStringConverter<Properties> {

    private static final char SEPARATOR = '=';

    public Properties convert(String value) {
        int indexOfSeparator = value.indexOf(SEPARATOR);
        if (indexOfSeparator < 0) {
            throw new ParameterException(
                    "Property name must be separated with an = sign from it value: name=value.");
        }
        String propertyName = value.substring(0, indexOfSeparator);
        String propertyValue = value.substring(indexOfSeparator + 1);
        Properties properties = new Properties();
        properties.put(propertyName, propertyValue);
        return properties;
    }
}

Source: (StackOverflow)

Command with hidden option and specified value

I want to run JCommander application using hidden option

command  subcommand [--key] "value"

But I want to hide only [--key] to get line this this

command  subcommand "value"

Is it possible to do?


Source: (StackOverflow)

"grep like" CLI using JCommander

I'm trying JCommander for the first time and I can't seem to adjust it to my needs.
I am trying to define a CLI similar in concept to that of the grep command:

command [options] PATTERN [FILE ...]

Usage example:

command -debug "[A-Z]*" *.xml

But, JCommander does not allow more than one "Main" parameter, so I cannot define both PATTERN and FILE as main parameters - which means I need to do something like:

command -debug -p "[A-Z]*" *.xml - meaning to include the pattern as an option (-p "[A-Z]*")

My question - is there a way around this, or should I consider another solution instead of JCommander?


Source: (StackOverflow)

jCommander - Next Parameter is considered as a value

I have a problem with the JCommander. I want the program to throw an Exception, if the required parameter iam testing has no value. This Exception i want occurs when i forget to add a value to the last parameter.

Example(note: all Parameters are required and strings):

--user hugo --password boss --confirmPassword //no value

com.beust.jcommander.ParameterException: Expected a value after parameter --comfirmPassword

If i forget to add a value to the other parameters, the next parameter is considered as the value.

--user --password --confirmPassword hugo
//--password is considered as the value of user

In consequence of this behavior, --password can no longer be found and i get the wrong Exception.

com.beust.jcommander.ParameterException: the following options are required: --password

Is there a way to tell jCommander that he should not consider the next parameter as a value?


Source: (StackOverflow)

Override a delegate parameter in JCommander

I am using JCommander to parse CLI. I have an option in my commands that is required for majority of the commands and not required for a couple of them. Consider the following:

class Delegate {
  @Parameter(names = "-port")
  private int port;
}

class MainParams {
  @Parameter(names = "-v")
  private boolean verbose;

  @ParametersDelegate // I want to mark -port as required for this command.
  private Delegate delegate = new Delegate();
}

Is it possible for me to have required=true for -port option in MainParams? I need it to be false for all other commands it is used in.


Source: (StackOverflow)

Argument option using JCommander

I'm new with JCommander and I'm trying to use it in my JAVA Command Line Application.

Fisrt thing I did is I've created my CommandLineArguments class.

Now, I'm trying to print options given with arguments in command line. But I think I'm missing something.

Here is my main class :

public static void main(String[] args) {


    String[] argv={"-h","host"};
    CommandLineArguments arguments=new CommandLineArguments();
    JCommander commands= new JCommander(arguments);

    try {

        commands.parse(argv);

        System.out.println(commands.getParsedCommand());


    } catch (Exception e) {
        System.out.println(e.getMessage());
        commands.usage();
    }
}

Once I run this class, I got : null as output. Seems like getParsedCommand() is not used as it should.

Can someone tell me how to use JCOmmmander methods correctly so I can see options given with arguments?

What I'm trying to do here is, once the user runs java -jar myApp.jar -port portNumber -h hostname -d database -c collection I wanna be able to get portNumber hostname database and collection value so I can establish a connexion and send queries.

Hope I was clear enough.

Ismail


Source: (StackOverflow)

How to add listener event to JComboBox in Java

I need to know how to effectively add a mouse event to a JComboBox or any other approach that works. I found some possible solutions here and also different sites but I can't get it to work. It seems that mouseEvent is not appropriate to use on JComboBox as it is a compound component. I found a possible solution for a compound component but also doesn't work. So below is my code that works when I use a text field. Any ideas of which approach should I use? Thanks

    private void updateReviewers() {
        jComboBox_reviewer.addMouseListener(new MouseListener() {

        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("clicked");
        }

        @Override
        public void mousePressed(MouseEvent e) {
            System.out.println("pressed");
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            System.out.println("released");
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            System.out.println("entered");
        }

        @Override
        public void mouseExited(MouseEvent e) {
            System.out.println("exited");
        }

    }
    );

}

Source: (StackOverflow)

JCommander parameter validation aware of other parameters

I'm using JCommander to parse command line params. I validate parameters using:

public class SomeClass implements IParameterValidator {
    public void validate(String name, String value) throws ParameterException { 
    ...
}

I ran into edge cases, when it would be helpful if the block of code above could know what are the other command line params supplied for the application, not just that one. Is it possible with JCommander at all?

I can achieve my goals with JCommander Commands, but this is not as flexible as the desired solution.


Source: (StackOverflow)

JCommander camelCase commands

I can't make camelCase JCommander commands work. Although I haven't seen in the documentation it is not supported, I haven't also seen any working example of JCommander with camelCase command.

It looks like command class called CommandSome implicitly assumes command to be some. Also CommandSomeOther assumes command to be some - ignores Other suffix.

Does anyone have any idea how to make it work?


Source: (StackOverflow)

How to print help using jcommander?

How to print help using jcommander?

I couldn't find an API for this.


Source: (StackOverflow)