com.beust.jcommander.JCommander

Here are the examples of the java api com.beust.jcommander.JCommander taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

321 Examples 7

19 Source : StartupOptions.java
with Apache License 2.0
from zpochen

public static StartupOptions parse(String[] cliArgs) {
    logger.debug("Parsing arguments.");
    StartupOptions args = new StartupOptions();
    JCommander jc = new JCommander(args, cliArgs);
    if (args.help) {
        jc.usage();
        System.exit(0);
    }
    return args;
}

19 Source : HelpFormatter.java
with GNU General Public License v3.0
from yuanxzhang

private List<ParameterDescription> getSortedParameters(JCommander jc) {
    List<ParameterDescription> parameters = Lists.newArrayList(jc.getParameters());
    final Pattern pattern = Pattern.compile("^-*(.*)$");
    Collections.sort(parameters, new Comparator<ParameterDescription>() {

        @Override
        public int compare(ParameterDescription o1, ParameterDescription o2) {
            String s1;
            Matcher matcher = pattern.matcher(o1.getParameter().names()[0]);
            if (matcher.matches()) {
                s1 = matcher.group(1);
            } else {
                throw new IllegalStateException();
            }
            String s2;
            matcher = pattern.matcher(o2.getParameter().names()[0]);
            if (matcher.matches()) {
                s2 = matcher.group(1);
            } else {
                throw new IllegalStateException();
            }
            return s1.compareTo(s2);
        }
    });
    return parameters;
}

19 Source : HelpFormatter.java
with GNU General Public License v3.0
from yuanxzhang

@Nonnull
private static ExtendedParameters getExtendedParameters(JCommander jc) {
    ExtendedParameters anno = jc.getObjects().get(0).getClreplaced().getAnnotation(ExtendedParameters.clreplaced);
    if (anno == null) {
        throw new IllegalStateException("All commands should have an ExtendedParameters annotation");
    }
    return anno;
}

19 Source : HelpFormatter.java
with GNU General Public License v3.0
from yuanxzhang

@Nonnull
public String format(@Nonnull JCommander... jc) {
    return format(Arrays.asList(jc));
}

19 Source : HelpFormatter.java
with GNU General Public License v3.0
from yuanxzhang

@Nonnull
private static String getPostfixDescription(@Nonnull JCommander jc) {
    return getExtendedParameters(jc).postfixDescription();
}

19 Source : HelpFormatter.java
with GNU General Public License v3.0
from yuanxzhang

@Nonnull
private static List<String> getCommandAliases(JCommander jc) {
    return Lists.newArrayList(getExtendedParameters(jc).commandAliases());
}

19 Source : HelpFormatter.java
with GNU General Public License v3.0
from yuanxzhang

private static boolean includeParametersInUsage(@Nonnull JCommander jc) {
    return getExtendedParameters(jc).includeParametersInUsage();
}

19 Source : ExtendedCommands.java
with GNU General Public License v3.0
from yuanxzhang

@Nullable
public static JCommander getSubcommand(JCommander jc, String commandName) {
    if (jc.getCommands().containsKey(commandName)) {
        return jc.getCommands().get(commandName);
    } else {
        for (JCommander command : jc.getCommands().values()) {
            for (String alias : commandAliases(command)) {
                if (commandName.equals(alias)) {
                    return command;
                }
            }
        }
    }
    return null;
}

19 Source : ExtendedCommands.java
with GNU General Public License v3.0
from yuanxzhang

@Nonnull
public static String postfixDescription(JCommander jc) {
    return postfixDescription(jc.getObjects().get(0));
}

19 Source : ExtendedCommands.java
with GNU General Public License v3.0
from yuanxzhang

public static boolean includeParametersInUsage(JCommander jc) {
    return includeParametersInUsage(jc.getObjects().get(0));
}

19 Source : ExtendedCommands.java
with GNU General Public License v3.0
from yuanxzhang

public static void addExtendedCommand(JCommander jc, Command command) {
    jc.addCommand(commandName(command), command, commandAliases(command));
    command.setupCommand(command.getJCommander());
}

19 Source : ExtendedCommands.java
with GNU General Public License v3.0
from yuanxzhang

@Nonnull
public static String commandName(JCommander jc) {
    return getExtendedParameters(jc.getObjects().get(0)).commandName();
}

19 Source : ExtendedCommands.java
with GNU General Public License v3.0
from yuanxzhang

@Nonnull
public static String[] commandAliases(JCommander jc) {
    return commandAliases(jc.getObjects().get(0));
}

19 Source : Command.java
with GNU General Public License v3.0
from yuanxzhang

protected void setupCommand(JCommander jc) {
}

19 Source : PMDCommandLineInterface.java
with GNU Lesser General Public License v2.1
from yangziwen

public static String buildUsageText(JCommander jcommander) {
    StringBuilder usage = new StringBuilder();
    String allCommandsDescription = null;
    if (jcommander != null && jcommander.getCommands() != null) {
        for (String command : jcommander.getCommands().keySet()) {
            allCommandsDescription += jcommander.getCommandDescription(command) + PMD.EOL;
        }
    }
    // TODO: Externalize that to a file available within the clreplacedpath ? - with a poor's man templating ?
    String fullText = PMD.EOL + "Mandatory arguments:" + PMD.EOL + "1) A java source code filename or directory" + PMD.EOL + "2) A report format " + PMD.EOL + "3) A ruleset filename or a comma-delimited string of ruleset filenames" + PMD.EOL + PMD.EOL + "For example: " + PMD.EOL + getWindowsLaunchCmd() + " -d c:\\my\\source\\code -f html -R java-unusedcode" + PMD.EOL + PMD.EOL;
    fullText += supportedVersions() + PMD.EOL;
    if (allCommandsDescription != null) {
        fullText += "Optional arguments that may be put before or after the mandatory arguments: " + PMD.EOL + allCommandsDescription + PMD.EOL;
    }
    fullText += "Available report formats and their configuration properties are:" + PMD.EOL + getReports() + PMD.EOL + getExamples() + PMD.EOL + PMD.EOL + PMD.EOL;
    return fullText += usage.toString();
}

19 Source : Main.java
with Apache License 2.0
from wso2-attic

public static void main(String... argv) {
    // exit if no args
    if (argv.length == 0) {
        return;
    }
    String rootCommand = argv[0];
    // if no command is given, display root level help
    if (argv.length == 1) {
        argv[0] = "--help";
    }
    // remove the root command and preplaced following arguments forward
    if (argv.length > 1) {
        argv = Arrays.copyOfRange(argv, 1, argv.length);
    }
    // 1. Build the parse tree
    JCommander parserTreeRoot = buildCommanderTree(rootCommand);
    try {
        // 2. Parse the input
        parseInput(parserTreeRoot, rootCommand, argv);
        // 3. Traverse the parse tree and execute the matched command
        findLeafCommand(parserTreeRoot).execute();
    } catch (BrokerClientException e) {
        printBrokerClientException(e, outStream);
    }
}

19 Source : AbstractCmd.java
with Apache License 2.0
from wso2-attic

public void setSelfJCommander(JCommander selfJCommander) {
    this.selfJCommander = selfJCommander;
}

19 Source : InitCmd.java
with Apache License 2.0
from wso2

@Override
public void setParentCmdParser(JCommander parentCmdParser) {
}

19 Source : CommandLine.java
with Apache License 2.0
from viclovsky

private void printUsage(final JCommander commander) {
    commander.usage();
}

19 Source : CleanM2.java
with BSD 3-Clause "New" or "Revised" License
from techpavan

private static File evaluateM2Path(JCommander jCommander) {
    String m2Path = defaultString(argData.getM2Path(), concat(USER_HOME, ".m2"));
    File m2Dir = new File(m2Path);
    File repoDir = new File(m2Path, "repository");
    if (!m2Dir.exists() || !repoDir.exists()) {
        log.error("Valid Maven repository could not be found. Please provide a valid input.");
        jCommander.usage();
        System.exit(1);
    }
    return repoDir;
}

19 Source : AppCommander.java
with Apache License 2.0
from sean-liang

/**
 * Parse command-line arguments.
 *
 * @author sean
 */
public clreplaced AppCommander {

    // main command
    private final CommandMain main = new CommandMain();

    // validate command
    private final CommandValidate validate = new CommandValidate();

    // export command
    private final CommandExport export = new CommandExport();

    private final JCommander commander;

    private AppCommander() {
        this.commander = JCommander.newBuilder().addObject(main).addCommand("validate", validate).addCommand("export", export).build();
    }

    public CommandMain getMain() {
        return main;
    }

    public CommandValidate getValidate() {
        return validate;
    }

    public CommandExport getExport() {
        return export;
    }

    public String getCommand() {
        return this.commander.getParsedCommand();
    }

    public void printUsage() {
        this.commander.usage();
    }

    /**
     * Parse command-line arguments.
     *
     * @param args
     *            Command-line arguments
     *
     * @return Parsed argument object
     */
    public static AppCommander parse(final String... args) {
        final AppCommander c = new AppCommander();
        c.commander.parse(args);
        if (c.getMain().isHelp()) {
            c.printUsage();
        }
        return c;
    }
}

19 Source : OffsetStatus.java
with BSD 3-Clause "New" or "Revised" License
from salesforce

public static void main(String[] argv) {
    Args args = new Args();
    JCommander jCommander = JCommander.newBuilder().programName(OffsetStatus.clreplaced.getSimpleName()).addObject(args).build();
    try {
        jCommander.parse(argv);
    } catch (Exception e) {
        jCommander.usage();
        throw e;
    }
    if (args.help) {
        jCommander.usage();
        return;
    }
    new OffsetStatus(args).run();
}

19 Source : MirusOffsetTool.java
with BSD 3-Clause "New" or "Revised" License
from salesforce

public static void main(String[] argv) throws IOException {
    Args args = new Args();
    JCommander jCommander = JCommander.newBuilder().programName(MirusOffsetTool.clreplaced.getSimpleName()).addObject(args).build();
    try {
        jCommander.parse(argv);
    } catch (Exception e) {
        jCommander.usage();
        throw e;
    }
    if (args.help) {
        jCommander.usage();
        return;
    }
    if (args.resetOffsets && (args.fromFile == null || args.fromFile.isEmpty())) {
        throw new ParameterException("--reset-offsets requires --from-file to be set");
    }
    if (args.showNullOffsets && !args.describe) {
        throw new ParameterException("--show-nulls requires --describe to be set");
    }
    MirusOffsetTool mirusOffsetTool = newOffsetTool(args);
    mirusOffsetTool.run();
}

19 Source : InvalidCommandApplication.java
with Apache License 2.0
from rupert-madden-abbott

@Bean
public JCommander jCommander() {
    JCommander jCommander = new JCommander();
    jCommander.addCommand(new InvalidCommand());
    return jCommander;
}

19 Source : JCommanderController.java
with Apache License 2.0
from rupert-madden-abbott

/**
 * A controller for commands.
 */
public clreplaced JCommanderController {

    private final JCommander jCommander;

    public JCommanderController(final JCommander jCommander) {
        this.jCommander = jCommander;
    }

    /**
     * Execute the command selected on the command line.
     * <p>
     * This method will parse the parsed in command line args and expect them to select an already
     * configured command. It will also expect that command to implement the {@link Command} interface
     * and will call it's run method.
     *
     * @param args the command line args
     * @throws Exception if something went wrong during command execution
     */
    public void execute(final String[] args) throws Exception {
        Map<String, JCommander> commands = getCommands();
        String commandName = getCommandName(args);
        Command command = toCommand(commandName, commands);
        command.run();
    }

    private String getCommandName(final String[] args) {
        if (args == null || args.length < 1) {
            throw new InvalidUseException("No command line arguments were provided.", getUsage());
        }
        try {
            jCommander.parse(args);
            return jCommander.getParsedCommand();
        } catch (ParameterException e) {
            throw new InvalidUseException(e.getMessage(), getUsage(), e);
        }
    }

    private Map<String, JCommander> getCommands() {
        Map<String, JCommander> commands = jCommander.getCommands();
        if (commands.isEmpty()) {
            throw new IllegalStateException("No Command implementing beans have been defined.");
        }
        return commands;
    }

    private Command toCommand(String commandName, Map<String, JCommander> commands) {
        Object command = commands.get(commandName).getObjects().get(0);
        if (!(command instanceof Command)) {
            throw new IllegalStateException("The selected command '" + commandName + "' does not implement the Command interface.");
        }
        return (Command) command;
    }

    /**
     * Extracts the usage string from JCommander's parser.
     *
     * @return the usage string.
     */
    private String getUsage() {
        final StringBuilder usage = new StringBuilder();
        jCommander.getUsageFormatter().usage(usage);
        return usage.toString();
    }
}

19 Source : ConfigArgs.java
with Apache License 2.0
from quarantyne

public static ConfigArgs parse(String... args) {
    ConfigArgs configArgs = new ConfigArgs();
    JCommander jCommander = new JCommander(configArgs);
    jCommander.parse(args);
    if (configArgs.help) {
        jCommander.usage();
        System.exit(0);
    }
    return configArgs;
}

19 Source : Application.java
with MIT License
from porunov

public static void main(String[] args) {
    Parameters parameters = new Parameters();
    JCommander jCommander = JCommander.newBuilder().addObject(parameters).build();
    try {
        jCommander.parse(args);
    } catch (Exception e) {
        LOG.error("An error occurred while parsing parameters.", e);
        System.out.print(CommandExecutor.RESULT_ERROR);
        return;
    }
    jCommander.setProgramName("java -jar acme_client.jar");
    if (parameters.isHelp()) {
        printHelpInfo(jCommander);
        return;
    }
    if (parameters.isVersion()) {
        printVersion();
        return;
    }
    setupLogDirectory(parameters);
    configureLogger(parameters.getLogDir(), (checkLogLevel(parameters.getLogLevel())) ? parameters.getLogLevel() : "WARN", LOGBACK_CONF);
    if (!parameters.verifyRequirements()) {
        System.out.print(CommandExecutor.RESULT_ERROR);
        return;
    }
    new CommandExecutor(parameters).execute();
}

19 Source : Application.java
with MIT License
from porunov

private static void printHelpInfo(JCommander jCommander) {
    StringBuilder usage = new StringBuilder();
    jCommander.usage(usage);
    System.out.println(usage.toString());
    String format = "%10s%n";
    System.out.format(format, Parameters.MAIN_USAGE.toString());
}

19 Source : DesignerStarter.java
with BSD 2-Clause "Simplified" License
from pmd

private static String getHelpText(JCommander jCommander) {
    StringBuilder sb = new StringBuilder();
    jCommander.usage(sb, " ");
    sb.append("\n");
    sb.append("\n");
    sb.append("PMD Rule Designer\n");
    sb.append("-----------------\n");
    sb.append("\n");
    sb.append("The Rule Designer is a graphical tool that helps PMD users develop their custom rules.\n");
    sb.append("\n");
    sb.append("\n");
    sb.append("Source & README: https://github.com/pmd/pmd-designer\n");
    sb.append("Usage doreplacedentation: https://pmd.github.io/latest/pmd_userdocs_extending_designer_reference.html");
    return sb.toString();
}

19 Source : JCommanderWrapper.java
with Apache License 2.0
from pkilller

public clreplaced JCommanderWrapper<T> {

    private final JCommander jc;

    public JCommanderWrapper(T obj) {
        this.jc = JCommander.newBuilder().addObject(obj).build();
    }

    public boolean parse(String[] args) {
        try {
            jc.parse(args);
            return true;
        } catch (ParameterException e) {
            System.err.println("Arguments parse error: " + e.getMessage());
            printUsage();
            return false;
        }
    }

    public void overrideProvided(T obj) {
        List<ParameterDescription> fieldsParams = jc.getParameters();
        List<ParameterDescription> parameters = new ArrayList<>(1 + fieldsParams.size());
        parameters.add(jc.getMainParameterValue());
        parameters.addAll(fieldsParams);
        for (ParameterDescription parameter : parameters) {
            if (parameter.isreplacedigned()) {
                // copy replacedigned field value to obj
                Parameterized parameterized = parameter.getParameterized();
                Object val = parameterized.get(parameter.getObject());
                parameterized.set(obj, val);
            }
        }
    }

    public void printUsage() {
        // print usage in not sorted fields order (by default its sorted by description)
        PrintStream out = System.out;
        out.println();
        out.println("jadx - dex to java decompiler, version: " + JadxDecompiler.getVersion());
        out.println();
        out.println("usage: jadx [options] " + jc.getMainParameterDescription());
        out.println("options:");
        List<ParameterDescription> params = jc.getParameters();
        Map<String, ParameterDescription> paramsMap = new LinkedHashMap<>(params.size());
        int maxNamesLen = 0;
        for (ParameterDescription p : params) {
            paramsMap.put(p.getParameterized().getName(), p);
            int len = p.getNames().length();
            if (len > maxNamesLen) {
                maxNamesLen = len;
            }
        }
        JadxCLIArgs args = (JadxCLIArgs) jc.getObjects().get(0);
        for (Field f : getFields(args.getClreplaced())) {
            String name = f.getName();
            ParameterDescription p = paramsMap.get(name);
            if (p == null) {
                continue;
            }
            StringBuilder opt = new StringBuilder();
            opt.append("  ").append(p.getNames());
            addSpaces(opt, maxNamesLen - opt.length() + 3);
            opt.append("- ").append(p.getDescription());
            addDefaultValue(args, f, opt);
            out.println(opt);
        }
        out.println("Example:");
        out.println("  jadx -d out clreplacedes.dex");
    }

    /**
     * Get all declared fields of the specified clreplaced and all super clreplacedes
     *
     * @param clazz
     * @return
     */
    private List<Field> getFields(Clreplaced<?> clazz) {
        List<Field> fieldList = new LinkedList<>();
        while (clazz != null) {
            fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclreplaced();
        }
        return fieldList;
    }

    private void addDefaultValue(JadxCLIArgs args, Field f, StringBuilder opt) {
        Clreplaced<?> fieldType = f.getType();
        if (fieldType == int.clreplaced) {
            try {
                int val = f.getInt(args);
                opt.append(" (default: ").append(val).append(')');
            } catch (Exception e) {
            // ignore
            }
        }
        if (fieldType == String.clreplaced) {
            try {
                String val = (String) f.get(args);
                if (val != null) {
                    opt.append(" (default: ").append(val).append(')');
                }
            } catch (Exception e) {
            // ignore
            }
        }
    }

    private static void addSpaces(StringBuilder str, int count) {
        for (int i = 0; i < count; i++) {
            str.append(' ');
        }
    }
}

19 Source : Application.java
with Apache License 2.0
from nlpub

/**
 * Watset command-line interface.
 */
public final clreplaced Application implements Runnable {

    /**
     * Status of command-line argument parsing.
     */
    public enum ParseStatus {

        /**
         * A command has been parsed successfully.
         */
        COMMAND,
        /**
         * No command has been found.
         */
        EMPTY,
        /**
         * No command has been found, but the version has been requested.
         */
        EMPTY_BUT_VERSION
    }

    /**
     * The command-line argument parser.
     */
    private final JCommander jc;

    /**
     * The parsing status.
     */
    private ParseStatus status = ParseStatus.EMPTY;

    /**
     * Watset command-line interface entry point.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {
        final var app = new Application();
        switch(app.parse(args)) {
            case COMMAND:
            case EMPTY_BUT_VERSION:
                app.run();
                break;
            default:
                app.jc.usage();
                System.exit(1);
                break;
        }
    }

    /**
     * Create an instance of the Watset command-line interface.
     */
    public Application() {
        final var parameters = new Command.MainParameters();
        // TODO: Use the main argument for --input instead of the named one.
        jc = JCommander.newBuilder().addObject(parameters).addCommand("empty", new ProvidedClusteringCommand(parameters, "empty")).addCommand("singleton", new ProvidedClusteringCommand(parameters, "singleton")).addCommand("together", new ProvidedClusteringCommand(parameters, "together")).addCommand("components", new ProvidedClusteringCommand(parameters, "components")).addCommand("kst", new KSpanningTreeCommand(parameters)).addCommand("spectral", new SpectralClusteringCommand(parameters)).addCommand("cw", new ChineseWhispersCommand(parameters)).addCommand("mcl", new MarkovClusteringCommand(parameters)).addCommand("mcl-bin", new MarkovClusteringExternalCommand(parameters)).addCommand("embed", new EmbeddingCommand(parameters)).addCommand("senses", new SensesCommand(parameters)).addCommand("graph", new GraphCommand(parameters)).addCommand("embedsenses", new SenseEmbeddingCommand(parameters)).addCommand("watset", new WatsetCommand(parameters)).addCommand("maxmax", new ProvidedClusteringCommand(parameters, "maxmax")).addCommand("pairwise", new PairwiseCommand(parameters)).addCommand("purity", new PurityCommand(parameters)).addCommand("version", new VersionCommand(parameters)).build();
    }

    /**
     * Parse the command-line arguments.
     *
     * @param args the command-line arguments
     * @return the status
     */
    public ParseStatus parse(String... args) {
        status = ParseStatus.EMPTY;
        jc.parse(args);
        final var parameters = (Command.MainParameters) jc.getObjects().get(0);
        if (nonNull(jc.getParsedCommand())) {
            status = ParseStatus.COMMAND;
        } else if (parameters.version) {
            status = ParseStatus.EMPTY_BUT_VERSION;
        }
        return status;
    }

    /**
     * Run the parsed command.
     */
    @Override
    public void run() {
        final var command = status == ParseStatus.EMPTY_BUT_VERSION ? "version" : requireNonNull(jc.getParsedCommand(), "command should not be null");
        run(command);
    }

    /**
     * Run the specified command.
     *
     * @param command the command
     */
    public void run(String command) {
        final var objects = jc.getCommands().get(command).getObjects();
        final var runnable = (Command) objects.get(0);
        runnable.run();
    }
}

19 Source : CerberusHelp.java
with Apache License 2.0
from Nike-Inc

/**
 * Clreplaced for printing CLI help and usage.
 */
public clreplaced CerberusHelp {

    private JCommander commander;

    public CerberusHelp(JCommander commander) {
        this.commander = commander;
    }

    public void print() {
        String commandName = commander.getParsedCommand();
        if (StringUtils.isNotBlank(commandName)) {
            commander.usage(commandName);
        } else {
            printCustomUsage();
        }
    }

    /**
     * Usage with nicer formatting than we get out of JCommander by default
     */
    private void printCustomUsage() {
        StringBuilder sb = new StringBuilder("Usage: cerberus [options] [command] [command options]\n");
        String indent = "";
        // indenting
        int descriptionIndent = 6;
        int indentCount = indent.length() + descriptionIndent;
        int longestName = 0;
        List<ParameterDescription> sorted = Lists.newArrayList();
        for (ParameterDescription pd : commander.getParameters()) {
            if (!pd.getParameter().hidden()) {
                sorted.add(pd);
                // + to have an extra space between the name and the description
                int length = pd.getNames().length() + 2;
                if (length > longestName) {
                    longestName = length;
                }
            }
        }
        sb.append(indent).append("  Options:\n");
        sorted.stream().sorted((p0, p1) -> p0.getLongestName().compareTo(p1.getLongestName())).forEach(pd -> {
            WrappedParameter parameter = pd.getParameter();
            sb.append(indent).append("  " + (parameter.required() ? "* " : "  ") + Chalk.on(pd.getNames()).green().bold().toString() + "\n");
            wrapDescription(sb, indentCount, s(indentCount) + pd.getDescription());
            Object def = pd.getDefault();
            if (def != null) {
                String displayedDef = StringUtils.isBlank(def.toString()) ? "<empty string>" : def.toString();
                sb.append("\n" + s(indentCount)).append("Default: " + Chalk.on(displayedDef).yellow().bold().toString());
            }
            Clreplaced<?> type = pd.getParameterized().getType();
            if (type.isEnum()) {
                String values = EnumSet.allOf((Clreplaced<? extends Enum>) type).toString();
                sb.append("\n" + s(indentCount)).append("Possible Values: " + Chalk.on(values).yellow().bold().toString());
            }
            sb.append("\n");
        });
        System.out.println(sb.toString());
        System.out.print("  ");
        printCommands();
    }

    private void printCommands() {
        System.out.println("Commands, use cerberus [-h, --help] [command name] for more info:");
        commander.getCommands().keySet().stream().sorted().forEach(command -> {
            String msg = String.format("    %s, %s", Chalk.on(command).green().bold().toString(), commander.getCommandDescription(command));
            System.out.println(msg);
        });
    }

    private String s(int count) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < count; i++) {
            result.append(" ");
        }
        return result.toString();
    }

    private void wrapDescription(StringBuilder out, int indent, String description) {
        int max = 79;
        String[] words = description.split(" ");
        int current = 0;
        int i = 0;
        while (i < words.length) {
            String word = words[i];
            if (word.length() > max || current + 1 + word.length() <= max) {
                out.append(word).append(" ");
                current += word.length() + 1;
            } else {
                out.append("\n").append(s(indent)).append(word).append(" ");
                current = indent + 1 + word.length();
            }
            i++;
        }
    }
}

19 Source : Cli.java
with Apache License 2.0
from networknt

public static void main(String... argv) throws Exception {
    try {
        Cli cli = new Cli();
        JCommander jCommander = JCommander.newBuilder().addObject(cli).build();
        jCommander.parse(argv);
        cli.run(jCommander);
    } catch (ParameterException e) {
        System.out.println("Command line parameter error: " + e.getLocalizedMessage());
        e.usage();
    }
}

19 Source : MonitorCommand.java
with Apache License 2.0
from NationalSecurityAgency

@Override
public void run(JCommander jc) {
    setup();
    try {
        do {
            LOG.info(new Date().toString());
            collectEndpointData();
            if (getMonitor()) {
                TimeUnit.SECONDS.sleep(getSleepInterval());
            }
        } while (getMonitor());
    } catch (InterruptedException e) {
    // nothing to log here, command was terminated
    }
}

19 Source : LayrryLauncher.java
with Apache License 2.0
from moditect

private static void printUsage(JCommander jCommander) {
    jCommander.usage();
    StringBuilder sb = new StringBuilder("Supported config formats are ").append(getSupportedConfigFormats());
    jCommander.getConsole().println(sb.toString());
}

19 Source : Application.java
with Apache License 2.0
from matthiaszimmermann

private void parseCommandLine(String[] args) {
    JCommander cmd = new JCommander(this, args);
    cmd.setProgramName(COMMAND_NAME);
    if (help) {
        cmd.usage();
        System.exit(0);
    }
}

19 Source : TrajSuiteCommands.java
with MIT License
from lukehb

@Override
protected CLICommand[] createCommands(JCommander jCommander, Object... objects) {
    ArrayList<CLICommand> commands = new ArrayList<>();
    for (Object constructorData : objects) {
        if (constructorData instanceof TrajsuiteLayers) {
            // commands.add(new ListEnreplacedyHierarchyCommand((TrajsuiteLayers) constructorData));
            break;
        }
    }
    CLICommand[] commandArr = new CLICommand[commands.size()];
    return commands.toArray(commandArr);
}

19 Source : StopMoveCommandListing.java
with MIT License
from lukehb

@Override
protected CLICommand[] createCommands(JCommander jc, Object... args) {
    return new CLICommand[] { new FindStopsMovesPOSMIT(), new FindStopsMovesGBSMoT(), new FindStopsMovesCBSMoT() };
}

19 Source : ToolUtil.java
with Apache License 2.0
from hugegraph

public static String commandUsage(JCommander jCommander) {
    StringBuilder sb = new StringBuilder();
    jCommander.usage(sb);
    return sb.toString();
}

19 Source : HugeGraphCommand.java
with Apache License 2.0
from hugegraph

private void execute(String[] args) {
    JCommander jCommander = this.parseCommand(args);
    this.execute(jCommander.getParsedCommand(), jCommander);
}

19 Source : LoadUtil.java
with Apache License 2.0
from hugegraph

public static void exitWithUsage(JCommander commander, int code) {
    commander.usage();
    System.exit(code);
}

19 Source : Main.java
with Apache License 2.0
from HPI-Information-Systems

public static void main(String[] args) {
    // Parse the command-line args.
    MasterCommand masterCommand = new MasterCommand();
    SlaveCommand slaveCommand = new SlaveCommand();
    JCommander jCommander = JCommander.newBuilder().addCommand("master", masterCommand).addCommand("slave", slaveCommand).build();
    try {
        jCommander.parse(args);
        if (jCommander.getParsedCommand() == null) {
            throw new ParameterException("No command given.");
        }
        // Start a master or slave.
        switch(jCommander.getParsedCommand()) {
            case "master":
                startMaster(masterCommand);
                break;
            case "slave":
                startSlave(slaveCommand);
                break;
            default:
                throw new replacedertionError();
        }
    } catch (ParameterException e) {
        System.out.printf("Could not parse args: %s\n", e.getMessage());
        if (jCommander.getParsedCommand() == null) {
            jCommander.usage();
        } else {
            jCommander.usage(jCommander.getParsedCommand());
        }
        System.exit(1);
    }
}

19 Source : OptionsParser.java
with Apache License 2.0
from HotelsDotCom

/**
 * The OptionsParser parses out the command-line options preplaceded to S3MapReduceCp and interprets those specific to
 * S3MapReduceCp to create an Options object.
 */
public clreplaced OptionsParser {

    private final S3MapReduceCpOptions options = new S3MapReduceCpOptions();

    private final JCommander jCommander = new JCommander(options);

    /**
     * The parse method parses the command-line options and creates a corresponding Options object.
     *
     * @param args Command-line arguments
     * @return The Options object, corresponding to the specified command-line.
     * @throws IllegalArgumentException Thrown if the parse fails.
     */
    public S3MapReduceCpOptions parse(String... args) throws IllegalArgumentException {
        try {
            jCommander.parse(args);
        } catch (Exception e) {
            throw new IllegalArgumentException("Unable to parse arguments: " + Arrays.toString(args), e);
        }
        if (options.isHelp()) {
            return options;
        }
        for (Path source : options.getSources()) {
            if (!source.isAbsolute()) {
                throw new IllegalArgumentException("Source paths must be absolute: " + Arrays.toString(args));
            }
        }
        if (!options.getTarget().isAbsolute()) {
            throw new IllegalArgumentException("Destination URI must be absolute: " + Arrays.toString(args));
        }
        if (options.getCredentialsProvider() != null && !options.getCredentialsProvider().isAbsolute()) {
            throw new IllegalArgumentException("Credentials provider URI must be absolute: " + Arrays.toString(args));
        }
        if (options.getMaxMaps() <= 0) {
            options.setMaxMaps(1);
        }
        if (options.getLogPath() != null && !options.getLogPath().isAbsolute()) {
            throw new IllegalArgumentException("Log path must be absolute: " + Arrays.toString(args));
        }
        return options;
    }

    public void usage() {
        jCommander.usage();
    }
}

19 Source : PubsubEmulatorServer.java
with Apache License 2.0
from GoogleCloudPlatform

/**
 * Initialize and start the PubsubEmulatorServer.
 *
 * <p>To set an external configuration file must be considered argument
 * `configuration.location=/to/path/application.yaml` the properties will be merged.
 */
public static void main(String[] args) {
    Args argObject = new Args();
    JCommander jCommander = JCommander.newBuilder().addObject(argObject).build();
    jCommander.parse(args);
    if (argObject.help) {
        jCommander.usage();
        return;
    }
    Injector injector = Guice.createInjector(new DefaultModule(argObject.configurationFile, argObject.pubSubFile));
    PubsubEmulatorServer pubsubEmulatorServer = injector.getInstance(PubsubEmulatorServer.clreplaced);
    try {
        pubsubEmulatorServer.start();
        pubsubEmulatorServer.blockUntilShutdown();
    } catch (IOException | InterruptedException e) {
        logger.atSevere().withCause(e).log("Unexpected server failure");
    }
}

19 Source : CliOptionsModule.java
with Apache License 2.0
from google

/**
 * A Guice module that parses CLI arguments for all {@link CliOption} implementations at runtime.
 *
 * <p>This module relies on the {@link io.github.clreplacedgraph.ClreplacedGraph} scan results to identify all
 * {@link CliOption} implementations at runtime. Each implementation is bound to a singleton object
 * of that impl and registered to JCommander for CLI parsing.
 */
public final clreplaced CliOptionsModule extends AbstractModule {

    private static final GoogleLogger logger = GoogleLogger.forEnclosingClreplaced();

    private static final String CLI_OPTION_INTERFACE = "com.google.tsunami.common.cli.CliOption";

    private final ScanResult scanResult;

    private final String[] args;

    private final JCommander jCommander;

    public CliOptionsModule(ScanResult scanResult, String programName, String[] args) {
        this.scanResult = checkNotNull(scanResult);
        this.args = checkNotNull(args);
        this.jCommander = new JCommander();
        jCommander.setProgramName(programName);
    }

    @Override
    protected void configure() {
        // For each CliOption installed at runtime, bind a singleton instance and register the instance
        // to JCommander for parsing.
        ImmutableList.Builder<CliOption> cliOptions = ImmutableList.builder();
        for (ClreplacedInfo clreplacedInfo : scanResult.getClreplacedesImplementing(CLI_OPTION_INTERFACE).filter(clreplacedInfo -> !clreplacedInfo.isInterface())) {
            logger.atInfo().log("Found CliOption: %s", clreplacedInfo.getName());
            CliOption cliOption = bindCliOption(clreplacedInfo.loadClreplaced(CliOption.clreplaced));
            jCommander.addObject(cliOption);
            cliOptions.add(cliOption);
        }
        // Parse command arguments or die.
        try {
            jCommander.parse(args);
            cliOptions.build().forEach(CliOption::validate);
        } catch (ParameterException e) {
            jCommander.usage();
            throw e;
        }
    }

    private <T> T bindCliOption(Clreplaced<T> cliOptionClreplaced) {
        try {
            Constructor<T> cliOptionCtor = cliOptionClreplaced.getDeclaredConstructor();
            // Always create an instance of the CliOption regardless of scope.
            cliOptionCtor.setAccessible(true);
            T cliOption = cliOptionCtor.newInstance();
            bind(cliOptionClreplaced).toInstance(cliOption);
            return cliOption;
        } catch (ReflectiveOperationException e) {
            throw new replacedertionError(String.format("CliOption '%s' must be constructable via a no-argument constructor", cliOptionClreplaced.getTypeName()), e);
        }
    }
}

19 Source : PasswordGenerator.java
with Apache License 2.0
from gocd

void printUsageAndExit(int exitCode, CliArguments cliArguments) {
    JCommander jCommander = new JCommander(cliArguments);
    jCommander.setProgramName("java -jar " + jarName());
    jCommander.usage();
    System.exit(exitCode);
}

19 Source : Help.java
with Apache License 2.0
from fabric8-updatebot

public void setCommander(JCommander commander) {
    this.commander = commander;
}

19 Source : Application.java
with Apache License 2.0
from epam

public static JCommander parseAndValidateArguments(Object object, String[] args) {
    JCommander jcom;
    try {
        jcom = new JCommander(object, args);
    } catch (ParameterException e) {
        LOGGER.error(e.getLocalizedMessage() + "\nPreplaced --help to see details");
        return null;
    }
    return jcom;
}

19 Source : Application.java
with Apache License 2.0
from epam

public static void main(String[] args) {
    Application app = new Application();
    JCommander jcom = parseAndValidateArguments(app, args);
    if (jcom == null) {
        System.exit(ILLEGAL_INPUT_RETURN_CODE);
    }
    if (app.help) {
        jcom.usage();
        return;
    }
    try {
        app.run();
    } catch (IllegalArgumentException e) {
        LOGGER.error(e.getLocalizedMessage());
        System.exit(ILLEGAL_INPUT_RETURN_CODE);
    }
}

19 Source : Main.java
with GNU General Public License v3.0
from EdwardRaff

public void run(String... args) throws IOException, InterruptedException {
    JCommander jc = new JCommander(this);
    jc.parse(args);
    ex = Executors.newWorkStealingPool(Math.max(1, threads));
    if (!alt_output.getPath().equals(""))
        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(alt_output)), true));
    // collect all the files we will be hashing
    List<File> toHash = new ArrayList<>();
    for (File candidate : parameters) if (candidate.isFile())
        toHash.add(candidate);
    else if (candidate.isDirectory() && goDeep)
        Files.walk(candidate.toPath()).filter(Files::isRegularFile).forEach(c -> toHash.add(c.toFile()));
    if (toCompare) {
        if (parameters.size() > 2 || parameters.isEmpty())
            throw new IllegalArgumentException("Can only compare at most two indexes at a time!");
        List<int[]> hashesA = new ArrayList<>();
        List<String> filesA = new ArrayList<>();
        List<int[]> hashesB = new ArrayList<>();
        List<String> filesB = new ArrayList<>();
        readHashesFromFile(parameters.get(0), hashesA, filesA);
        if (parameters.size() == 2)
            readHashesFromFile(parameters.get(1), hashesB, filesB);
        else {
            hashesB = hashesA;
            filesB = filesA;
        }
        compare(hashesA, filesA, hashesB, filesB);
    } else if (genCompare)
        genComp(toHash);
    else
        hashFiles(toHash);
    ex.shutdownNow();
}

See More Examples