Example usage for org.apache.commons.cli CommandLine getOptions

List of usage examples for org.apache.commons.cli CommandLine getOptions

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getOptions.

Prototype

public Option[] getOptions() 

Source Link

Document

Returns an array of the processed Option s.

Usage

From source file:org.eclipse.emf.mwe.core.WorkflowRunner.java

/**
 * Print usage information and terminate the program.
 * // w  w  w.  ja  v  a2  s .c  o m
 * @param options
 */
protected void wrongCall(final CommandLine line) {
    Options options = new Options();
    for (Option o : line.getOptions())
        options.addOption(o);
    final HelpFormatter formatter = new HelpFormatter();
    formatter
            .printHelp("java " + WorkflowRunner.class.getName() + " some_workflow_file.mwe [options]\nor\njava "
                    + WorkflowRunner.class.getName() + " some_workflow_file.oaw [options]\n", options);
    System.exit(0);
}

From source file:org.efaps.cli.StartUp.java

/**
 * The main method./* w  w  w. j a  va2 s .  co m*/
 *
 * @param _args the arguments
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void main(final String[] _args) throws IOException {
    LOG.info("Startup at {}", new Date());

    final Options options = new Options()
            .addOption(
                    Option.builder("l").numberOfArgs(2).desc("set login information").longOpt("login").build())
            .addOption(Option.builder("u").numberOfArgs(1).desc("set url").longOpt("url").build())
            .addOption(Option.builder("ll").numberOfArgs(1)
                    .desc("set Log Level, One of 'ALL','TRACE','DEBUG','INFO','WARN','ERROR', 'OFF'")
                    .longOpt("logLevel").build())
            .addOption(Option.builder("h").desc("print this help information").longOpt("help").build());

    final CommandLineParser parser = new DefaultParser();
    try {
        final CommandLine cmd = parser.parse(options, _args);

        if (cmd.hasOption("h")) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("eFaps-CLI", options);
        } else {
            final Shell shell = ShellBuilder.shell("eFaps").behavior()
                    .setHistoryFile(new File(System.getProperty("user.home") + "/.eFapsCLI", "history"))
                    .addHandler(ContextHandler.get()).addHandler(new CommandHandler())
                    .addHandler(new MessageResolver()).addHandler(new EQLHandler())
                    .addHandler(EQLObserver.get()).addHandler(new EQLCandidatesChooser())
                    .addHandler(new EQLFilter()).build();
            shell.setAppName("\"eFaps Command Line Interface\"");

            for (final Option opt : cmd.getOptions()) {
                switch (opt.getOpt()) {
                case "l":
                    shell.getEnvironment().setVariable(CLISettings.USER, opt.getValue(0));
                    shell.getEnvironment().setVariable(CLISettings.PWD, opt.getValue(1));
                    break;
                case "u":
                    shell.getEnvironment().setVariable(CLISettings.URL, opt.getValue());
                    break;
                case "ll":
                    LOG.info("Setting Log level to {}", opt.getValue());
                    final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
                            .getLogger(Logger.ROOT_LOGGER_NAME);
                    root.setLevel(Level.toLevel(opt.getValue()));
                    LOG.info("ROOT Log level set to {}", root.getLevel());
                    break;
                default:
                    break;
                }
            }
            shell.processLine("company " + ContextHandler.FAKECOMPANY);
            shell.commandLoop();
        }
    } catch (final ParseException e) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("eFaps-CLI", options);
        LOG.error("ParseException", e);
    } catch (final CLIException e) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("eFaps-CLI", options);
        LOG.error("ParseException", e);
    }
}

From source file:org.entando.edo.parser.CommandlineParser.java

/**
 * Setta le opzioni e pulisce args!/*  ww w.  j  a v  a2  s  .  co m*/
 * @param cl
 * @param edoBean
 * @param args
 * @return
 * @throws IllegalArgumentException
 */
private String[] processCommandline(CommandLine cl, EdoBuilder edoBuilder, String[] args)
        throws IllegalArgumentException {
    if (cl.hasOption(OPTION_BASE_DIR)) {
        String baseDir = cl.getOptionValue(OPTION_BASE_DIR);
        if (StringUtils.isNotBlank(baseDir)) {
            if (baseDir.endsWith(File.separator)) {
                baseDir = StringUtils.removeEnd(baseDir, File.separator);
            }
            edoBuilder.setBaseDir(baseDir);
        }
    }
    _logger.debug("baseDir is: '{}'", edoBuilder.getBaseDir());

    if (cl.hasOption(OPTION_PERMISSION)) {
        String perm = cl.getOptionValue(OPTION_PERMISSION);
        if (StringUtils.isNotBlank(perm)) {
            edoBuilder.setPermission(perm);
        }
    }
    _logger.debug("permission is: '{}'", edoBuilder.getPermission());

    String packageName = null;
    if (cl.hasOption(OPTION_PACKAGE)) {
        String packageNameParam = cl.getOptionValue(OPTION_PACKAGE);
        if (StringUtils.isNotBlank(packageNameParam)) {
            if (PackageValidator.isValidPackageName(packageNameParam)) {
                packageName = packageNameParam;
            } else {
                _logger.error("invalid package name specified: {}", packageName);
                throw new IllegalArgumentException("invalid package name specified: " + packageName);
            }
        }
    } else {
        _logger.trace("auto generate packagename");
        if (!cl.getArgList().isEmpty()) {
            packageName = "org.entando.entando.plugins.jp" + cl.getArgs()[0].toLowerCase();
        } else {
            _logger.warn("Unable to generate the default package name. No enough args");
        }
    }

    edoBuilder.setPackageName(packageName);
    _logger.debug("packagename: is '{}'", edoBuilder.getPackageName());

    args = Arrays.copyOfRange(args, cl.getOptions().length, args.length);
    return args;
}

From source file:org.evosuite.executionmode.TestGeneration.java

public static List<List<TestGenerationResult>> executeTestGeneration(Options options, List<String> javaOpts,
        CommandLine line) {

    Strategy strategy = getChosenStrategy(javaOpts, line);

    if (strategy == null) {
        strategy = Strategy.EVOSUITE;//  w  w  w . j  a v  a  2s  . com
    }

    List<List<TestGenerationResult>> results = new ArrayList<List<TestGenerationResult>>();

    if (line.getOptions().length == 0) {
        Help.execute(options);
        return results;
    }

    String cp = ClassPathHandler.getInstance().getTargetProjectClasspath();
    if (cp == null || cp.isEmpty()) {
        LoggingUtils.getEvoLogger().error(
                "No classpath has been defined for the target project.\nOn the command line you can set it with the -projectCP option\n");
        Help.execute(options);
        return results;
    }

    if (line.hasOption("class")) {
        results.addAll(generateTests(strategy, line.getOptionValue("class"), javaOpts));
    } else if (line.hasOption("prefix")) {
        results.addAll(generateTestsPrefix(strategy, line.getOptionValue("prefix"), javaOpts));
    } else if (line.hasOption("target")) {
        String target = line.getOptionValue("target");
        results.addAll(generateTestsTarget(strategy, target, javaOpts));
    } else if (EvoSuite.hasLegacyTargets()) {
        results.addAll(generateTestsLegacy(strategy, javaOpts));
    } else {
        LoggingUtils.getEvoLogger()
                .error("Please specify either target class ('-class' option), prefix ('-prefix' option), or "
                        + "classpath entry ('-target' option)\n");
        Help.execute(options);
    }
    return results;
}

From source file:org.fcrepo.importexport.ArgParser.java

/**
 * This method writes the configuration file to disk.  The current
 * implementation omits the user/password information.
 * @param args to be persisted//from  w  w  w.jav a 2s.c om
 */
private void saveConfig(final CommandLine cmd) {
    final File configFile = new File(System.getProperty("java.io.tmpdir"), CONFIG_FILE_NAME);

    // Leave existing config file alone
    if (configFile.exists()) {
        logger.info("Configuration file exists, new file will NOT be created: {}", configFile.getPath());
        return;
    }

    // Write config to file
    try (final BufferedWriter configWriter = new BufferedWriter(new FileWriter(configFile));) {
        for (Option option : cmd.getOptions()) {
            // write out all but the username/password
            if (!option.getOpt().equals("u")) {
                configWriter.write("-" + option.getOpt());
                configWriter.newLine();
                if (option.getValue() != null) {
                    configWriter.write(option.getValue());
                    configWriter.newLine();
                }
            }
        }

        logger.info("Saved configuration to: {}", configFile.getPath());

    } catch (IOException e) {
        throw new RuntimeException("Unable to write configuration file due to: " + e.getMessage(), e);
    }
}

From source file:org.finra.datagenerator.samples.CmdLine.java

/**
 * Parse command line arguments for the example
 *
 * @param args Command-line arguments for HDFS example
 * @return a ChartExec object resulting from the parsing of command-line options
 * @throws ParseException when args cannot be parsed
 * @throws IOException    when input file cannot be found
 *//*from  w  ww  .  j  av a  2s. c o  m*/
public Engine parseCommandLine(final String[] args) throws ParseException, IOException {
    // create the command line parser
    CommandLineParser parser = new GnuParser();

    // create the Options
    final Options options = new Options().addOption("h", "help", false, "print help.")
            .addOption("i", "inputfile", true, "the scxml input file")
            .addOption("n", "numberoftimes", true,
                    "an integer, the number of TIME to run the template of a row")
            .addOption("H", "hdfssequencefile", true, "the path of the hdfs sequence file to write to")
            .addOption("L", "loglevel", true, "set the log level")
            .addOption("s", "maxscenarios", true, "Maximum number of scenarios to generate. Default 10,000")
            .addOption("m", "minbootstrapstates", true,
                    "Minimum number of states to explore using BFS before using parallel DFS search. Default is 0"
                            + " (no BFS).");

    CommandLine cmd = parser.parse(options, args);
    Engine chartExec = new SCXMLEngine();
    hdfsDist = new HDFSDistributor();

    if (cmd.hasOption("i")) {
        Path inFile = new Path(cmd.getOptionValue('i'));
        FileSystem fs = FileSystem.get(this.getConf());
        FSDataInputStream in = fs.open(inFile);
        String model = IOUtils.toString(in, "UTF-8");

        chartExec.setModelByText(model);
        hdfsDist.setStateMachineText(model);
    } else {
        System.err.println("\nERROR: you must state option -i with an input file\n");
    }

    int n = 1;
    if (cmd.hasOption("n")) {
        n = Integer.valueOf(cmd.getOptionValue("n"));
    }

    if (cmd.hasOption("h") || cmd.getOptions().length == 0) {
        printHelp(options);
    }

    if (cmd.hasOption('L')) {
        LogInitializer.initialize(cmd.getOptionValue('L'));
    } else {
        LogInitializer.initialize("WARN");
    }

    if (cmd.hasOption('m')) {
        String stringValue = cmd.getOptionValue('m');
        if (StringUtils.isNotEmpty(stringValue)) {
            chartExec.setBootstrapMin(Integer.parseInt(stringValue));
        } else {
            System.err.println("Unparsable numeric value for option 'm':" + stringValue);
        }
    }

    long maxLines = 0;
    if (cmd.hasOption('s')) {
        String stringValue = cmd.getOptionValue('s');
        maxLines = Long.valueOf(stringValue);

        if (StringUtils.isNotEmpty(stringValue)) {
            hdfsDist.setMaxNumberOfLines(maxLines);
        } else {
            System.err.println("Unparsable numeric value for option 's':" + stringValue);
        }
    } else if (!cmd.hasOption('s')) {
        maxLines = 10000;
        hdfsDist.setMaxNumberOfLines(maxLines);
    }

    LineCountManager jetty = new LineCountManager(maxLines, 500000);
    jetty.prepareServer();
    jetty.prepareStatus();
    hdfsDist = hdfsDist.setFileRoot("brownbag_demo")
            .setReportingHost(jetty.getHostName() + ":" + jetty.getListeningPort());

    return chartExec;
}

From source file:org.grycap.gpf4med.Gpf4MedContainer.java

public static void main(final String[] args) {
    // load logging bridges
    LogManager.INSTANCE.preload();

    // parse arguments      
    final Options options = new Options();
    CommandLine cmd = null;
    try {//w  w  w.j a  va  2s .  co m
        cmd = parseParameters(args, options);
    } catch (Exception e) {
        System.err.println("Parsing options failed. Reason: " + e.getLocalizedMessage());
        System.exit(1);
    }

    if (cmd.getOptions() == null || cmd.hasOption(HELP_OPTION)) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Gpf4MedContainer.class.getSimpleName(), options, true);
        System.exit(0);
    }

    if (cmd.hasOption(VERSION_OPTION)) {
        System.out.println(CONTAINER_NAME + " - Version " + CONTAINER_VERSION);
        System.exit(0);
    }

    boolean daemon = false;
    if (cmd.hasOption(DAEMON_OPTION[0])) {
        daemon = true;
    }

    final Collection<URL> config = new ArrayList<URL>();
    if (cmd.hasOption(CONFIG_OPTION[0])) {
        try {
            final String configDir = cmd.getOptionValue(CONFIG_OPTION[0]);
            if (StringUtils.isNotBlank(configDir)) {
                final Collection<File> configFiles = FileUtils.listFiles(new File(configDir),
                        new String[] { "xml" }, false);
                for (final File file : configFiles) {
                    config.add(file.toURI().toURL());
                }
            } else {
                throw new IllegalArgumentException("Parameter " + DIR_PROP + " is expected");
            }
        } catch (Exception e) {
            System.err.println("Configuration load failed with error: " + e.getLocalizedMessage());
            System.exit(1);
        }
    }

    // setup configuration URLs
    ConfigurationManager.INSTANCE.setup(config);

    // start service
    final Gpf4MedService service = SingletonService.INSTANCE.service();

    if (daemon) {
        try {
            Thread.currentThread().join();
        } catch (Exception e) {
        }
    } else {
        System.out.println();
        System.out.println(String.format(
                Gpf4MedService.SERVICE_NAME
                        + " started with WADL available at %sapplication.wadl\nHit enter to stop it...",
                service.getBaseUri()));
        try {
            System.in.read();
        } catch (IOException ignore) {
        }
    }

    System.exit(0);
}

From source file:org.jboss.windup.WindupMain.java

public void processInput(CommandLine line, Options options) {
    // automatically generate the help statement

    try {/*from   www. j av  a2 s. c o m*/
        // parse the command line arguments

        if (line.getOptions().length < 1) {
            HELP_FORMATTER.printHelp(WINDUP_COMMAND, options);
        } else {
            // Map the environment settings from the input arguments.
            WindupEnvironment settings = new WindupEnvironment();
            if (line.hasOption("javaPkgs")) {
                settings.setPackageSignature(line.getOptionValue("javaPkgs"));
            }
            if (line.hasOption("excludePkgs")) {
                settings.setExcludeSignature(line.getOptionValue("excludePkgs"));
            }

            if (line.hasOption("targetPlatform")) {
                settings.setTargetPlatform(line.getOptionValue("targetPlatform"));
            }

            if (line.hasOption("fetchRemote")) {
                settings.setFetchRemote(line.getOptionValue("fetchRemote"));
            }

            String inputLocation = line.getOptionValue("input");
            inputLocation = StringUtils.trim(inputLocation);
            File inputPath = new File(inputLocation);

            File outputPath = null;
            String outputLocation = line.getOptionValue("output");
            outputLocation = StringUtils.trim(outputLocation);
            if (StringUtils.isNotBlank(outputLocation)) {
                outputPath = new File(outputLocation);
            }

            boolean isSource = false;
            if (BooleanUtils.toBoolean(line.getOptionValue("source"))) {
                isSource = true;
            }
            settings.setSource(isSource);

            boolean captureLog = false;
            if (BooleanUtils.toBoolean(line.getOptionValue("captureLog"))) {
                captureLog = true;
            }

            String logLevel = line.getOptionValue("logLevel");
            logLevel = StringUtils.trim(logLevel);

            settings.setCaptureLog(captureLog);
            settings.setLogLevel(logLevel);

            // Run Windup.
            ReportEngine engine = new ReportEngine(settings);
            engine.process(inputPath, outputPath);
        }
    } catch (FileNotFoundException e) {
        LOG.error("Input does not exist:" + e.getMessage(), e);
        HELP_FORMATTER.printHelp(WINDUP_COMMAND, options);
    } catch (IOException e) {
        LOG.error("Exception while writing report: " + e.getMessage(), e);
        HELP_FORMATTER.printHelp(WINDUP_COMMAND, options);
    }
}

From source file:org.jcryptool.commands.core.HelpCommand.java

/**
 * Recovers the command line form of which a CommandLine object could've originated from. Assumes, that all options
 * have been stated in short form.//from  ww  w  .j  a  v a  2 s  . com
 *
 * @param commandName the name of the command
 * @param cmdLine the CommandLine object to parse
 * @return a command line, which would parse to a CommandLine object equal to the given one.
 */
public static String reverseCommandline(String commandName, CommandLine cmdLine) {
    StringBuilder builder = new StringBuilder();
    builder.append(commandName);
    for (String arg : cmdLine.getArgs()) {
        builder.append(" " + arg); //$NON-NLS-1$
    }

    for (Option option : cmdLine.getOptions()) {
        builder.append(" -" + option.getOpt()); //$NON-NLS-1$
        for (int i = 0; i < option.getArgs(); i++) {
            builder.append(" " + (option.getValue(i).contains(" ") ? "\"" + option.getValue(i) + "\"" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
                    : option.getValue(i)));
        }
    }

    return builder.toString();
}

From source file:org.jf.baksmali.main.java

/**
 * Run!//from  w w w.ja v a 2  s  .c o m
 */
public static void main(String[] args) throws IOException {
    Locale locale = new Locale("en", "US");
    Locale.setDefault(locale);

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        usage();
        return;
    }

    baksmaliOptions options = new baksmaliOptions();

    boolean disassemble = true;
    boolean doDump = false;
    String dumpFileName = null;
    boolean setBootClassPath = false;

    String[] remainingArgs = commandLine.getArgs();
    Option[] clOptions = commandLine.getOptions();

    for (int i = 0; i < clOptions.length; i++) {
        Option option = clOptions[i];
        String opt = option.getOpt();

        switch (opt.charAt(0)) {
        case 'v':
            version();
            return;
        case '?':
            while (++i < clOptions.length) {
                if (clOptions[i].getOpt().charAt(0) == '?') {
                    usage(true);
                    return;
                }
            }
            usage(false);
            return;
        case 'o':
            options.outputDirectory = commandLine.getOptionValue("o");
            break;
        case 'p':
            options.noParameterRegisters = true;
            break;
        case 'l':
            options.useLocalsDirective = true;
            break;
        case 's':
            options.useSequentialLabels = true;
            break;
        case 'b':
            options.outputDebugInfo = false;
            break;
        case 'd':
            options.bootClassPathDirs.add(option.getValue());
            break;
        case 'f':
            options.addCodeOffsets = true;
            break;
        case 'r':
            String[] values = commandLine.getOptionValues('r');
            int registerInfo = 0;

            if (values == null || values.length == 0) {
                registerInfo = baksmaliOptions.ARGS | baksmaliOptions.DEST;
            } else {
                for (String value : values) {
                    if (value.equalsIgnoreCase("ALL")) {
                        registerInfo |= baksmaliOptions.ALL;
                    } else if (value.equalsIgnoreCase("ALLPRE")) {
                        registerInfo |= baksmaliOptions.ALLPRE;
                    } else if (value.equalsIgnoreCase("ALLPOST")) {
                        registerInfo |= baksmaliOptions.ALLPOST;
                    } else if (value.equalsIgnoreCase("ARGS")) {
                        registerInfo |= baksmaliOptions.ARGS;
                    } else if (value.equalsIgnoreCase("DEST")) {
                        registerInfo |= baksmaliOptions.DEST;
                    } else if (value.equalsIgnoreCase("MERGE")) {
                        registerInfo |= baksmaliOptions.MERGE;
                    } else if (value.equalsIgnoreCase("FULLMERGE")) {
                        registerInfo |= baksmaliOptions.FULLMERGE;
                    } else {
                        usage();
                        return;
                    }
                }

                if ((registerInfo & baksmaliOptions.FULLMERGE) != 0) {
                    registerInfo &= ~baksmaliOptions.MERGE;
                }
            }
            options.registerInfo = registerInfo;
            break;
        case 'c':
            String bcp = commandLine.getOptionValue("c");
            if (bcp != null && bcp.charAt(0) == ':') {
                options.addExtraClassPath(bcp);
            } else {
                setBootClassPath = true;
                options.setBootClassPath(bcp);
            }
            break;
        case 'x':
            options.deodex = true;
            break;
        case 'm':
            options.noAccessorComments = true;
            break;
        case 'a':
            options.apiLevel = Integer.parseInt(commandLine.getOptionValue("a"));
            break;
        case 'j':
            options.jobs = Integer.parseInt(commandLine.getOptionValue("j"));
            break;
        case 'i':
            String rif = commandLine.getOptionValue("i");
            options.setResourceIdFiles(rif);
            break;
        case 'N':
            disassemble = false;
            break;
        case 'D':
            doDump = true;
            dumpFileName = commandLine.getOptionValue("D");
            break;
        case 'I':
            options.ignoreErrors = true;
            break;
        case 'T':
            options.inlineResolver = new CustomInlineMethodResolver(options.classPath,
                    new File(commandLine.getOptionValue("T")));
            break;
        default:
            assert false;
        }
    }

    if (remainingArgs.length != 1) {
        usage();
        return;
    }

    if (options.jobs <= 0) {
        options.jobs = Runtime.getRuntime().availableProcessors();
        if (options.jobs > 6) {
            options.jobs = 6;
        }
    }

    if (options.apiLevel >= 17) {
        options.checkPackagePrivateAccess = true;
    }

    String inputDexFileName = remainingArgs[0];

    File dexFileFile = new File(inputDexFileName);
    if (!dexFileFile.exists()) {
        System.err.println("Can't find the file " + inputDexFileName);
        System.exit(1);
    }

    //Read in and parse the dex file
    DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexFileFile, options.apiLevel);

    if (dexFile.isOdexFile()) {
        if (!options.deodex) {
            System.err.println("Warning: You are disassembling an odex file without deodexing it. You");
            System.err.println("won't be able to re-assemble the results unless you deodex it with the -x");
            System.err.println("option");
            options.allowOdex = true;
        }
    } else {
        options.deodex = false;
    }

    if (!setBootClassPath && (options.deodex || options.registerInfo != 0)) {
        if (dexFile instanceof DexBackedOdexFile) {
            options.bootClassPathEntries = ((DexBackedOdexFile) dexFile).getDependencies();
        } else {
            options.bootClassPathEntries = getDefaultBootClassPathForApi(options.apiLevel);
        }
    }

    if (options.inlineResolver == null && dexFile instanceof DexBackedOdexFile) {
        options.inlineResolver = InlineMethodResolver
                .createInlineMethodResolver(((DexBackedOdexFile) dexFile).getOdexVersion());
    }

    boolean errorOccurred = false;
    if (disassemble) {
        errorOccurred = !baksmali.disassembleDexFile(dexFile, options);
    }

    if (doDump) {
        if (dumpFileName == null) {
            dumpFileName = commandLine.getOptionValue(inputDexFileName + ".dump");
        }
        dump.dump(dexFile, dumpFileName, options.apiLevel);
    }

    if (errorOccurred) {
        System.exit(1);
    }
}