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.oclc.firefly.hadoop.backup.Backup.java

/**
 * Entry point//from ww w  .jav a  2 s . c om
 * @param args Command line arguments
 * @throws Exception exception
 */
public static void main(String[] args) throws Exception {
    int initialReplication = 1;
    int finalReplication = 0;
    int numMaps = 2;
    int tries = 0;
    String tbl = null;
    String dest = null;
    String user = System.getProperty("user.name");
    Path destPath = null;
    CommandLineParser parser = new PosixParser();
    CommandLine cmdline = null;

    // Parse command line options
    try {
        cmdline = parser.parse(getOptions(), args);
    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println(e.getMessage());
        printOptions();
        System.exit(-1);
    }

    // Get command line options
    for (Option option : cmdline.getOptions()) {
        switch (option.getId()) {
        case 'd':
            dest = option.getValue();
            destPath = new Path(dest);
            if (!destPath.isAbsolute()) {
                throw new IllegalArgumentException("Destination path must be an absolute path");
            }

            break;
        case 'm':
            numMaps = Integer.parseInt(option.getValue());
            if (numMaps <= 0) {
                throw new IllegalArgumentException("Number of map tasks must be greater than zero.");
            }
            break;
        case 'n':
            tries = Integer.parseInt(option.getValue());
            if (tries < 0) {
                throw new IllegalArgumentException(
                        "Maximum number of tries must be greater than or equal to zero.");
            }
            break;
        case 'f':
            finalReplication = Integer.parseInt(option.getValue());
            if (finalReplication <= 0) {
                throw new IllegalArgumentException("Initial replication must be greater than zero.");
            }
            break;
        case 'r':
            initialReplication = Integer.parseInt(option.getValue());
            if (initialReplication <= 0) {
                throw new IllegalArgumentException("Initial replication must be greater than zero.");
            }
            break;
        case 't':
            tbl = option.getValue();
            break;
        case 'u':
            user = option.getValue();
            break;
        default:
            throw new IllegalArgumentException("unexpected option " + option);
        }
    }

    String[] tables = null;
    if (tbl != null) {
        tables = tbl.split(",");
    }

    Configuration srcConf = HBaseConfiguration.create();
    Configuration dstConf = HBaseConfiguration.create();

    // This allows us to copy to a separate HDFS instance
    String destDir = null;
    if (dest != null) {
        destDir = destPath.toUri().getPath();
        String fsName = null;

        if (destDir != null && destDir.length() > 0) {
            LOG.debug("destination dfs: " + dest.substring(0, dest.length() - destDir.length()));
            fsName = dest.substring(0, dest.length() - destDir.length());
        } else {
            fsName = dest;
            destDir = null;
        }

        if (fsName != null && fsName.length() > 0) {
            dstConf.set("fs.default.name", fsName);
        }
    }

    Backup backup = new Backup(srcConf, dstConf);
    backup.setInitialReplication(initialReplication);
    backup.setFinalReplication(finalReplication);
    backup.setUsername(user);
    backup.setNumMapTasks(numMaps);
    if (destDir != null) {
        backup.setBackupStoreDirectory(destDir);
    }

    LOG.info("HBase backup tool");
    LOG.info("--------------------------------------------------");
    //LOG.info("Destination fs     : " + dstConf.get("fs.default.name"));
    LOG.info("Initial replication: " + backup.getInitialReplication());
    LOG.info("Final replication  : " + backup.getFinalReplication());
    LOG.info("Number of attempts : " + ((tries == 0) ? "Until nothing left to copy" : tries));
    LOG.info("Username           : " + backup.getUsername());
    LOG.info("Number map tasks   : " + backup.getNumMapTasks());
    LOG.info("Backup store path  : " + backup.getBackupStoreDirectory());
    LOG.info("--------------------------------------------------");

    boolean success = backup.doMajorCopy(tables, tries);

    LOG.info("--------------------------------------------------");
    if (success) {
        LOG.info("Backup located at: " + backup.getBackupDirectoryPath());
        LOG.info("Backup complete");
    } else {
        LOG.info("Files located at: " + backup.getBackupDirectoryPath());
        LOG.info("Backup failed");
    }

    System.exit(success ? 0 : -1);
}

From source file:org.oclc.firefly.hadoop.backup.Import.java

/**
 * Import table entry point//w ww  .  jav  a 2  s . c  o m
 * @param args Command line arguments
 * @throws Exception If failed to read from file system
 */
public static void main(String[] args) throws Exception {
    boolean copy = false;
    boolean ignoreBadName = false;
    String inputDir = null;
    String tbl = null;
    CommandLineParser parser = new PosixParser();
    CommandLine cmdline = null;

    // Parse command line options
    try {
        cmdline = parser.parse(getOptions(), args);
    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println(e.getMessage());
        printOptions();
        System.exit(-1);
    }

    // Get command line options
    for (Option option : cmdline.getOptions()) {
        switch (option.getId()) {
        case 'b':
            ignoreBadName = true;
            break;
        case 'i':
            inputDir = option.getValue();
            break;
        case 'c':
            copy = true;
            break;
        case 't':
            tbl = option.getValue();
            break;
        default:
            throw new IllegalArgumentException("unexpected option " + option);
        }
    }

    String[] tables = null;
    Configuration conf = HBaseConfiguration.create();
    Path backupDirPath = new Path(inputDir);

    Import importer = new Import(conf, backupDirPath, ignoreBadName);
    importer.setRetainOriginal(copy);

    if (tbl == null) {
        tables = importer.getTableNames();
    } else {
        tables = tbl.split(",");
    }

    LOG.info("HBase import tool");
    LOG.info("--------------------------------------------------");
    LOG.info("Backup start time   : " + importer.getStartDate());
    LOG.info("Backup end time     : " + importer.getEndDate());
    LOG.info("Retain original copy: " + importer.getRetainOriginal());
    LOG.info("HBase location      : " + conf.get(HConstants.HBASE_DIR));
    LOG.info("Backup location     : " + backupDirPath);
    LOG.info("--------------------------------------------------");

    importer.importAll(tables);
    int totalSuccess = importer.getNumTablesImported();
    int totalFailed = importer.getNumFailedImports();

    LOG.info("Import results");
    LOG.info("--------------------------------------------------");
    LOG.info("Number of tables: " + tables.length);
    LOG.info("Imported tables : " + totalSuccess);
    LOG.info("Failed          : " + totalFailed);
    LOG.info("--------------------------------------------------");

    if (totalFailed == 0) {
        LOG.info("Import completed successfully.");
    } else if (totalSuccess > 0) {
        LOG.warn("Import completed but with errors. Please inspect manually.");
    } else {
        LOG.error("Import failed. Please inspect manually.");
        System.exit(1);
    }

    System.exit(0);
}

From source file:org.oclc.firefly.hadoop.backup.LogCopier.java

/**
 * Main//  w ww  . j a  v a 2 s.  co m
 * @param args Command line arguments
 * @throws Exception If failed to read from file system
 */
public static void main(String[] args) throws Exception {
    String destDirectory = null;
    long frequency = DEFAULT_FREQUENCY;
    long threads = DEFAULT_NUM_THREADS;
    long dtl = 0L;
    CommandLineParser parser = new PosixParser();
    CommandLine cmdline = null;

    // Parse command line options
    try {
        cmdline = parser.parse(getOptions(), args);
    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println(e.getMessage());
        printOptions();
        System.exit(-1);
    }

    // Get command line options
    for (Option option : cmdline.getOptions()) {
        switch (option.getId()) {
        case 'd':
            destDirectory = option.getValue();
            break;
        case 'm':
            frequency = Long.parseLong(option.getValue());
            if (frequency <= 0) {
                throw new IllegalArgumentException("Minutes must be greater than 0");
            }
            break;
        case 'l':
            dtl = Long.parseLong(option.getValue());
            if (dtl < 0) {
                throw new IllegalArgumentException("Log days-to-live Must be non-negative");
            }
            break;
        case 't':
            threads = Long.parseLong(option.getValue());
            if (threads < 0) {
                throw new IllegalArgumentException("Number of threads must be greater than 0");
            }
            break;
        default:
            throw new IllegalArgumentException("unexpected option " + option);
        }
    }

    LogCopier copier = new LogCopier(destDirectory, frequency);
    copier.setLogDaysToLive(dtl);
    copier.setNumberThreads(threads);

    LOG.info("--------------------------------------------------");
    LOG.info("Copy frequency    : " + copier.getCopyFrequency() + " minutes");
    LOG.info("Archive directory : " + copier.getArchiveDirectory());
    LOG.info("Log days to live  : " + copier.getLogDaysToLive() + " days");
    LOG.info("Copy threads      : " + copier.getNumberThreads());
    LOG.info("--------------------------------------------------");

    copier.run();
}

From source file:org.onebusaway.gtfs_merge.GtfsMergerMain.java

private void processOptions(CommandLine cli, GtfsMerger merger) {

    OptionHandler currentOptionHandler = null;
    AbstractEntityMergeStrategy mergeStrategy = null;

    for (Option option : cli.getOptions()) {
        if (option.getOpt().equals(ARG_FILE)) {
            String filename = option.getValue();
            Class<?> entityClass = _entityClassesByFilename.get(filename);
            if (entityClass == null) {
                throw new IllegalStateException("unknown GTFS filename: " + filename);
            }//www .  j av  a  2  s.  c  o m
            mergeStrategy = getMergeStrategyForEntityClass(entityClass, merger);
            currentOptionHandler = getOptionHandlerForEntityClass(entityClass);
        } else {
            if (currentOptionHandler == null) {
                throw new IllegalArgumentException(
                        "you must specify a --file argument first before specifying file-specific arguments");
            }
            currentOptionHandler.handleOption(option, mergeStrategy);
        }
    }
}

From source file:org.onebusaway.gtfs_transformer.GtfsTransformerMain.java

private Option[] getOptionsInCommandLineOrder(CommandLine cli, String[] originalArgs) {

    Option[] options = cli.getOptions();
    List<Ordered<Option>> orderedOptions = new ArrayList<Ordered<Option>>();

    for (Option option : options) {

        String argName = option.getOpt();
        int optionPosition = originalArgs.length;

        for (int i = 0; i < originalArgs.length; i++) {
            if (originalArgs[i].endsWith(argName)) {
                optionPosition = i;/* ww w.  java 2s.  c  om*/
                break;
            }
        }

        orderedOptions.add(new Ordered<Option>(option, optionPosition));
    }

    Collections.sort(orderedOptions);
    options = new Option[options.length];

    for (int i = 0; i < options.length; i++)
        options[i] = orderedOptions.get(i).getObject();

    return options;
}

From source file:org.ow2.proactive.scheduler.authentication.ManageUsers.java

public static void manageUsers(String... args) throws ManageUsersException {
    SecurityManagerConfigurator.configureSecurityManager(
            CreateCredentials.class.getResource("/all-permissions.security.policy").toString());

    Console console = System.console();
    /**//from w  w  w  .j  av  a 2s .  c  om
     * default values
     */
    String pubKeyPath = null;
    PublicKey pubKey = null;
    UserInfo userInfo = new UserInfo();
    String loginFilePath = getLoginFilePath();
    String groupFilePath = getGroupFilePath();
    String sourceLoginFilePath = null;
    String sourceGroupFilePath = null;
    Action action = null;

    Options options = new Options();

    CommandLine cmd = getCommandLine(args, loginFilePath, groupFilePath, options);

    if (cmd.hasOption(HELP_OPTION_NAME) || cmd.getOptions().length == 0) {
        displayHelp(options);
        return;
    }

    action = Action.getAction(cmd);

    if (cmd.hasOption(LOGIN_OPTION_NAME)) {
        userInfo.setLogin(cmd.getOptionValue(LOGIN_OPTION_NAME));
    }
    if (cmd.hasOption(PWD_OPTION_NAME)) {
        userInfo.setPassword(cmd.getOptionValue(PWD_OPTION_NAME));
    }
    if (cmd.hasOption(GROUPS_OPTION_NAME)) {
        String groupString = cmd.getOptionValue(GROUPS_OPTION_NAME);
        userInfo.setGroups(Arrays.asList(groupString.split(",")));
    }

    if (cmd.hasOption(LOGINFILE_OPTION_NAME)) {
        loginFilePath = cmd.getOptionValue(LOGINFILE_OPTION_NAME);
    }
    if (cmd.hasOption(GROUPFILE_OPTION_NAME)) {
        groupFilePath = cmd.getOptionValue(GROUPFILE_OPTION_NAME);
    }
    if (cmd.hasOption(KEYFILE_OPTION_NAME)) {
        pubKeyPath = cmd.getOptionValue(KEYFILE_OPTION_NAME);
    }

    if (cmd.hasOption(SOURCE_LOGINFILE_OPTION_NAME)) {
        if (action == Action.DELETE) {
            exitWithErrorMessage("Cannot use action delete with source login file.", null, null);
        }
        if (!cmd.hasOption(SOURCE_GROUPFILE_OPTION_NAME) && action == Action.CREATE) {
            exitWithErrorMessage(
                    "Source group file must be provided when creating users with source login file.", null,
                    null);
        }
        sourceLoginFilePath = cmd.getOptionValue(SOURCE_LOGINFILE_OPTION_NAME);
        userInfo = null;
    }
    if (cmd.hasOption(SOURCE_GROUPFILE_OPTION_NAME)) {
        if (action == Action.DELETE) {
            exitWithErrorMessage("Cannot use action delete with source group file.", null, null);
        }
        if (!cmd.hasOption(SOURCE_LOGINFILE_OPTION_NAME) && action == Action.CREATE) {
            exitWithErrorMessage(
                    "Source login file must be provided when creating users with source group file.", null,
                    null);
        }
        sourceGroupFilePath = cmd.getOptionValue(SOURCE_GROUPFILE_OPTION_NAME);
        userInfo = null;
    }

    if (pubKeyPath == null) {
        pubKeyPath = getPublicKeyFilePath();
    }

    try {
        pubKey = Credentials.getPublicKey(pubKeyPath);
    } catch (KeyException e) {
        exitWithErrorMessage("Could not retrieve public key from '" + pubKeyPath, null, e);
    }
    boolean nonInteractive = checkInteractivity(userInfo, sourceLoginFilePath, sourceGroupFilePath, action);

    if (!nonInteractive) {
        askInteractively(console, userInfo, action);
    }

    updateAccounts(pubKey, userInfo, loginFilePath, groupFilePath, action, sourceLoginFilePath,
            sourceGroupFilePath);
}

From source file:org.ow2.proactive_grid_cloud_portal.cli.CommandFactory.java

protected Map<String, Command> commandMapInstance(CommandLine cli,
        final Map<String, CommandSet.Entry> supportedCommandEntryMap) {
    Map<String, Command> cliCommands = new HashMap<>();
    for (Option o : cli.getOptions()) {
        cliCommands.put(o.getOpt(), getCommandForOption(o, supportedCommandEntryMap));
    }// w w  w  .  ja v  a 2s .  c  o  m
    return cliCommands;
}

From source file:org.parallelj.launching.transport.tcp.command.AbstractLaunchTcpCommand.java

public RemoteProgram parseCommandLine(final String... args) throws ParseException, OptionException {
    // Get sorted options
    final List<IOption> ioptions = getOptions();
    final Options options = new Options();
    for (IOption ioption : ioptions) {
        options.addOption(ioption.getOption());
    }/*from  www .  j ava 2s. com*/

    // create the command line parser
    final CommandLineParser parser = new PosixParser();

    // parse the command line arguments
    // CommandLine cmdLine = parser.parse(options, args);
    final CommandLine cmdLine = parser.parse(options, args);
    // As Options are reinitialized after parsing,
    // we need to re-affect IOption.option
    for (Option option : cmdLine.getOptions()) {
        for (IOption ioption : getOptions()) {
            if (ioption.getOption().getOpt().equals(option.getOpt())) {
                ioption.setOption(option);
                break;
            }
        }
    }

    // First, we need to get the IIdOption to get the Program
    // We are sure this option is present as it it mandatory!
    IIdOption idOption = null;
    for (IOption ioption : ioptions) {
        if (ioption instanceof IIdOption) {
            idOption = (IIdOption) ioption;
            break;
        }
    }
    final RemoteProgram remoteProgram = idOption.getProgram();

    // Check all defined Options with the selected Program
    try {
        for (IOption ioption : ioptions) {
            ioption.ckeckOption(remoteProgram);
        }
        return remoteProgram;
    } catch (ParserException e) {
        throw new OptionException(e.getFormatedMessage());
    }
}

From source file:org.pepstock.jem.commands.util.ArgumentsParser.java

/**
 * Parses all arguments passed by command line.<br>
 * Creates all possible arguments with explanation to show in case of error.
 * //from  ww w .  ja  v  a2s  . c  o m
 * @param args arguments of main method
 * @return properties with all arguments
 * @throws ParseException if same args are missing or wrong
 */
public Properties parseArg(String[] args) throws ParseException {

    // creates all possible commands options

    // -help options
    Option help = new Option("help", "print this message");

    // loads all created options
    Options allOptions = new Options();
    allOptions.addOption(help);

    for (Option opt : options) {
        allOptions.addOption(opt);
    }
    // creates command line parser
    CommandLineParser parser = new PosixParser();
    CommandLine line;
    try {
        Properties properties = new Properties();
        // parses line
        line = parser.parse(allOptions, args);
        // checks if asked for help. If yes, prints help
        if ((line.getOptions().length == 1) && line.hasOption("help")) {
            StringWriter writer = new StringWriter();
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(new PrintWriter(writer), HelpFormatter.DEFAULT_WIDTH, getCommandLine(), "",
                    allOptions, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, "");
            LogAppl.getInstance().emit(NodeMessage.JEMC056I, writer.getBuffer());
        } else {
            Option[] optionsLine = line.getOptions();
            for (int i = 0; i < optionsLine.length; i++) {
                String key = optionsLine[i].getArgName();
                String value;
                // to avoid null pointer exception in case of option line
                // with no arg
                if (optionsLine[i].hasArg()) {
                    value = optionsLine[i].getValue();
                } else {
                    value = "";
                }

                properties.setProperty(key, value);
            }
        }
        return properties;
    } catch (ParseException e) {
        // if exception, returns -help command
        // because if is here has found an error on arguments
        StringWriter writer = new StringWriter();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(new PrintWriter(writer), HelpFormatter.DEFAULT_WIDTH, getCommandLine(), "",
                allOptions, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, "");
        LogAppl.getInstance().emit(NodeMessage.JEMC056I, writer.getBuffer());
        throw e;
    }

}

From source file:org.pooledtimeseries.PoT.java

public static void main(String[] args) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    Option fileOpt = OptionBuilder.withArgName("file").hasArg().withLongOpt("file")
            .withDescription("Path to a single file").create('f');

    Option dirOpt = OptionBuilder.withArgName("directory").hasArg().withLongOpt("dir")
            .withDescription("A directory with image files in it").create('d');

    Option helpOpt = OptionBuilder.withLongOpt("help").withDescription("Print this message.").create('h');

    Option pathFileOpt = OptionBuilder.withArgName("path file").hasArg().withLongOpt("pathfile")
            .withDescription(/* ww  w .java 2s  . c  o m*/
                    "A file containing full absolute paths to videos. Previous default was memex-index_temp.txt")
            .create('p');

    Option outputFileOpt = OptionBuilder.withArgName("output file").withLongOpt("outputfile").hasArg()
            .withDescription("File containing similarity results. Defaults to ./similarity.txt").create('o');

    Option jsonOutputFlag = OptionBuilder.withArgName("json output").withLongOpt("json")
            .withDescription("Set similarity output format to JSON. Defaults to .txt").create('j');

    Option similarityFromFeatureVectorsOpt = OptionBuilder
            .withArgName("similarity from FeatureVectors directory")
            .withLongOpt("similarityFromFeatureVectorsDirectory").hasArg()
            .withDescription("calculate similarity matrix from given directory of feature vectors").create('s');

    Options options = new Options();
    options.addOption(dirOpt);
    options.addOption(pathFileOpt);
    options.addOption(fileOpt);
    options.addOption(helpOpt);
    options.addOption(outputFileOpt);
    options.addOption(jsonOutputFlag);
    options.addOption(similarityFromFeatureVectorsOpt);

    // create the parser
    CommandLineParser parser = new GnuParser();

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String directoryPath = null;
        String pathFile = null;
        String singleFilePath = null;
        String similarityFromFeatureVectorsDirectory = null;
        ArrayList<Path> videoFiles = null;

        if (line.hasOption("dir")) {
            directoryPath = line.getOptionValue("dir");
        }

        if (line.hasOption("pathfile")) {
            pathFile = line.getOptionValue("pathfile");
        }

        if (line.hasOption("file")) {
            singleFilePath = line.getOptionValue("file");
        }

        if (line.hasOption("outputfile")) {
            outputFile = line.getOptionValue("outputfile");
        }

        if (line.hasOption("json")) {
            outputFormat = OUTPUT_FORMATS.JSON;
        }

        if (line.hasOption("similarityFromFeatureVectorsDirectory")) {
            similarityFromFeatureVectorsDirectory = line
                    .getOptionValue("similarityFromFeatureVectorsDirectory");
        }

        if (line.hasOption("help")
                || (line.getOptions() == null || (line.getOptions() != null && line.getOptions().length == 0))
                || (directoryPath != null && pathFile != null && !directoryPath.equals("")
                        && !pathFile.equals(""))) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("pooled_time_series", options);
            System.exit(1);
        }

        if (directoryPath != null) {
            File dir = new File(directoryPath);
            List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE,
                    TrueFileFilter.INSTANCE);
            videoFiles = new ArrayList<Path>(files.size());

            for (File file : files) {
                String filePath = file.toString();

                // When given a directory to load videos from we need to ensure that we
                // don't try to load the of.txt and hog.txt intermediate result files
                // that results from previous processing runs.
                if (!filePath.contains(".txt")) {
                    videoFiles.add(file.toPath());
                }
            }

            LOG.info("Added " + videoFiles.size() + " video files from " + directoryPath);

        }

        if (pathFile != null) {
            Path list_file = Paths.get(pathFile);
            videoFiles = loadFiles(list_file);
            LOG.info("Loaded " + videoFiles.size() + " video files from " + pathFile);
        }

        if (singleFilePath != null) {
            Path singleFile = Paths.get(singleFilePath);
            LOG.info("Loaded file: " + singleFile);
            videoFiles = new ArrayList<Path>(1);
            videoFiles.add(singleFile);
        }

        if (similarityFromFeatureVectorsDirectory != null) {
            File dir = new File(similarityFromFeatureVectorsDirectory);
            List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE,
                    TrueFileFilter.INSTANCE);
            videoFiles = new ArrayList<Path>(files.size());

            for (File file : files) {
                String filePath = file.toString();

                // We need to load only the *.of.txt and *.hog.txt values
                if (filePath.endsWith(".of.txt")) {
                    videoFiles.add(file.toPath());
                }

                if (filePath.endsWith(".hog.txt")) {
                    videoFiles.add(file.toPath());
                }
            }

            LOG.info("Added " + videoFiles.size() + " feature vectors from "
                    + similarityFromFeatureVectorsDirectory);
            evaluateSimilarity(videoFiles, 1);
        } else {
            evaluateSimilarity(videoFiles, 0);
        }
        LOG.info("done.");

    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }

}