Example usage for org.apache.commons.cli Option getOpt

List of usage examples for org.apache.commons.cli Option getOpt

Introduction

In this page you can find the example usage for org.apache.commons.cli Option getOpt.

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:org.apache.accumulo.server.logger.LogReader.java

/**
 * Dump a Log File (Map or Sequence) to stdout. Will read from HDFS or local file system.
 * /*from  w w w  .  j  av  a 2  s .co m*/
 * @param args
 *          - first argument is the file to print
 * @throws IOException
 * @throws ParseException
 */
public static void main(String[] args) throws IOException {
    Configuration conf = CachedConfiguration.getInstance();
    FileSystem fs = TraceFileSystem
            .wrap(FileUtil.getFileSystem(conf, ServerConfiguration.getSiteConfiguration()));
    FileSystem local = TraceFileSystem.wrap(FileSystem.getLocal(conf));
    Option rowOpt = new Option("r", "--row", true, "search for a specific row");
    Option maxOpt = new Option("m", "--max-mutations", true,
            "the maximum number of mutations to print per log entry");
    Option tabletOpt = new Option("t", "--tablet", true, "key extent");
    Option rowPatternOpt = new Option("p", "--row-pattern", true,
            "search for a row that matches the given regex");
    Options options = new Options();
    options.addOption(rowOpt);
    options.addOption(maxOpt);
    options.addOption(tabletOpt);
    options.addOption(rowPatternOpt);
    CommandLine cl;
    try {
        cl = new BasicParser().parse(options, args);
    } catch (ParseException ex) {
        usage();
        return;
    }

    Matcher rowMatcher = null;
    KeyExtent ke = null;
    Text row = null;
    int max = 5;
    String[] files = cl.getArgs();
    if (files.length == 0) {
        usage();
        return;
    }
    if (cl.hasOption(rowOpt.getOpt()))
        row = new Text(cl.getOptionValue(rowOpt.getOpt()));
    if (cl.hasOption(maxOpt.getOpt()))
        max = Integer.parseInt(cl.getOptionValue(maxOpt.getOpt()));
    if (cl.hasOption(tabletOpt.getOpt())) {
        String extent = cl.getOptionValue(tabletOpt.getOpt());
        String sa[] = extent.split(";");
        ke = new KeyExtent(new Text(sa[0]), new Text(sa[1]), new Text(sa[2]));
    }
    if (cl.hasOption(rowPatternOpt.getOpt())) {
        Pattern pattern = Pattern.compile(cl.getOptionValue(rowPatternOpt.getOpt()));
        rowMatcher = pattern.matcher("");
    }

    Set<Integer> tabletIds = new HashSet<Integer>();

    for (String file : files) {

        Path path = new Path(file);
        LogFileKey key = new LogFileKey();
        LogFileValue value = new LogFileValue();

        if (fs.isFile(path)) {
            // read log entries from a simple hdfs file
            org.apache.hadoop.io.SequenceFile.Reader reader = new SequenceFile.Reader(fs, new Path(file), conf);
            while (reader.next(key, value)) {
                printLogEvent(key, value, row, rowMatcher, ke, tabletIds, max);
            }
        } else if (local.isFile(path)) {
            // read log entries from a simple file
            org.apache.hadoop.io.SequenceFile.Reader reader = new SequenceFile.Reader(local, new Path(file),
                    conf);
            while (reader.next(key, value)) {
                printLogEvent(key, value, row, rowMatcher, ke, tabletIds, max);
            }
        } else {
            try {
                // read the log entries sorted in a map file
                MultiReader input = new MultiReader(fs, conf, file);
                while (input.next(key, value)) {
                    printLogEvent(key, value, row, rowMatcher, ke, tabletIds, max);
                }
            } catch (FileNotFoundException ex) {
                SequenceFile.Reader input = new SequenceFile.Reader(local, new Path(file), conf);
                while (input.next(key, value)) {
                    printLogEvent(key, value, row, rowMatcher, ke, tabletIds, max);
                }
            }
        }
    }
}

From source file:org.apache.accumulo.server.util.VerifyTabletAssignments.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();

    Option zooKeeperInstance = new Option("z", "zooKeeperInstance", true,
            "use a zookeeper instance with the given instance name and list of zoo hosts");
    zooKeeperInstance.setArgName("name hosts");
    zooKeeperInstance.setArgs(2);//w w w.j av a 2s.co m
    opts.addOption(zooKeeperInstance);

    Option usernameOption = new Option("u", "user", true, "username (required)");
    usernameOption.setArgName("user");
    usernameOption.setRequired(true);
    opts.addOption(usernameOption);

    Option passwOption = new Option("p", "password", true,
            "password (prompt for password if this option is missing)");
    passwOption.setArgName("pass");
    opts.addOption(passwOption);

    Option verboseOption = new Option("v", "verbose", false, "verbose mode (prints locations of tablets)");
    opts.addOption(verboseOption);

    CommandLine cl = null;
    String user = null;
    String passw = null;
    Instance instance = null;
    ConsoleReader reader = new ConsoleReader();
    try {
        cl = new BasicParser().parse(opts, args);

        if (cl.hasOption(zooKeeperInstance.getOpt())
                && cl.getOptionValues(zooKeeperInstance.getOpt()).length != 2)
            throw new MissingArgumentException(zooKeeperInstance);

        user = cl.getOptionValue(usernameOption.getOpt());
        passw = cl.getOptionValue(passwOption.getOpt());

        if (cl.hasOption(zooKeeperInstance.getOpt())) {
            String[] zkOpts = cl.getOptionValues(zooKeeperInstance.getOpt());
            instance = new ZooKeeperInstance(zkOpts[0], zkOpts[1]);
        } else {
            instance = HdfsZooInstance.getInstance();
        }

        if (passw == null)
            passw = reader.readLine(
                    "Enter current password for '" + user + "'@'" + instance.getInstanceName() + "': ", '*');
        if (passw == null) {
            reader.printNewline();
            return;
        } // user canceled

        if (cl.getArgs().length != 0)
            throw new ParseException("Unrecognized arguments: " + cl.getArgList());

    } catch (ParseException e) {
        PrintWriter pw = new PrintWriter(System.err);
        new HelpFormatter().printHelp(pw, Integer.MAX_VALUE,
                "accumulo " + VerifyTabletAssignments.class.getName(), null, opts, 2, 5, null, true);
        pw.flush();
        System.exit(1);
    }

    Connector conn = instance.getConnector(user, passw.getBytes());

    for (String table : conn.tableOperations().list())
        checkTable(user, passw, table, null, cl.hasOption(verboseOption.getOpt()));

}

From source file:org.apache.ambari.servicemonitor.utils.OptionHelper.java

public static String buildParsedOptionList(CommandLine commandLine) {

    StringBuilder builder = new StringBuilder();
    for (Option option : commandLine.getOptions()) {
        builder.append(option.getOpt());
        if (option.getLongOpt() != null) {
            builder.append("/").append(option.getLongOpt());
        }//  w  ww.  j a va2s  . co m
        builder.append(": ");
        List valuesList = option.getValuesList();
        builder.append("[");
        int count = 0;
        for (Object elt : valuesList) {
            if (count > 0) {
                builder.append(", ");
            }
            builder.append('"').append(elt.toString()).append("\"");
        }
        builder.append("]\n");
    }
    return builder.toString();
}

From source file:org.apache.blur.mapreduce.lib.CsvBlurDriver.java

public static Job setupJob(Configuration configuration, ControllerPool controllerPool,
        AtomicReference<Callable<Void>> ref, String... otherArgs) throws Exception {
    CommandLine cmd = parse(otherArgs);//from   w ww  . j  a v a  2 s .co m
    if (cmd == null) {
        return null;
    }

    final String controllerConnectionStr = cmd.getOptionValue("c");
    final String tableName = cmd.getOptionValue("t");

    final Iface client = controllerPool.getClient(controllerConnectionStr);
    TableDescriptor tableDescriptor = client.describe(tableName);

    Job job = Job.getInstance(configuration, "Blur indexer [" + tableName + "]");
    job.setJarByClass(CsvBlurDriver.class);
    job.setMapperClass(CsvBlurMapper.class);

    if (cmd.hasOption("p")) {
        job.getConfiguration().set(MAPRED_COMPRESS_MAP_OUTPUT, "true");
        String codecStr = cmd.getOptionValue("p");
        COMPRESSION compression;
        try {
            compression = COMPRESSION.valueOf(codecStr.trim().toUpperCase());
        } catch (IllegalArgumentException e) {
            compression = null;
        }
        if (compression == null) {
            job.getConfiguration().set(MAPRED_MAP_OUTPUT_COMPRESSION_CODEC, codecStr.trim());
        } else {
            job.getConfiguration().set(MAPRED_MAP_OUTPUT_COMPRESSION_CODEC, compression.getClassName());
        }
    }
    if (cmd.hasOption("a")) {
        CsvBlurMapper.setAutoGenerateRecordIdAsHashOfData(job, true);
    }
    if (cmd.hasOption("A")) {
        CsvBlurMapper.setAutoGenerateRowIdAsHashOfData(job, true);
    }
    if (cmd.hasOption("S")) {
        job.setInputFormatClass(SequenceFileInputFormat.class);
    } else {
        job.setInputFormatClass(TextInputFormat.class);
    }

    if (cmd.hasOption("C")) {
        if (cmd.hasOption("S")) {
            String[] optionValues = cmd.getOptionValues("C");
            job.setInputFormatClass(CsvBlurCombineSequenceFileInputFormat.class);
            CombineFileInputFormat.setMinInputSplitSize(job, Long.parseLong(optionValues[0]));
            CombineFileInputFormat.setMaxInputSplitSize(job, Long.parseLong(optionValues[1]));
        } else {
            System.err.println("'C' can only be used with option 'S'");
            return null;
        }
    }

    if (cmd.hasOption("i")) {
        for (String input : cmd.getOptionValues("i")) {
            Path path = new Path(input);
            Set<Path> pathSet = recurisvelyGetPathesContainingFiles(path, job.getConfiguration());
            if (pathSet.isEmpty()) {
                FileInputFormat.addInputPath(job, path);
            } else {
                for (Path p : pathSet) {
                    FileInputFormat.addInputPath(job, p);
                }
            }
        }
    }
    // processing the 'I' option
    if (cmd.hasOption("I")) {
        if (cmd.hasOption("C")) {
            System.err.println("'I' and 'C' both parameters can not be used together.");
            return null;
        }
        Option[] options = cmd.getOptions();
        for (Option option : options) {
            if (option.getOpt().equals("I")) {
                String[] values = option.getValues();
                if (values.length < 2) {
                    System.err.println("'I' parameter missing minimum args of (family path*)");
                    return null;
                }
                for (String p : getSubArray(values, 1)) {
                    Path path = new Path(p);
                    CsvBlurMapper.addFamilyPath(job, values[0], path);
                    FileInputFormat.addInputPath(job, path);
                }
            }
        }
    }

    if (cmd.hasOption("s")) {
        CsvBlurMapper.setSeparator(job, StringEscapeUtils.unescapeJava(cmd.getOptionValue("s")));
    }
    if (cmd.hasOption("o")) {
        BlurOutputFormat.setOptimizeInFlight(job, false);
    }
    if (cmd.hasOption("l")) {
        BlurOutputFormat.setIndexLocally(job, false);
    }
    if (cmd.hasOption("b")) {
        int maxDocumentBufferSize = Integer.parseInt(cmd.getOptionValue("b"));
        BlurOutputFormat.setMaxDocumentBufferSize(job, maxDocumentBufferSize);
    }
    // processing the 'd' option
    Option[] options = cmd.getOptions();
    for (Option option : options) {
        if (option.getOpt().equals("d")) {
            String[] values = option.getValues();
            if (values.length < 2) {
                System.err.println("'d' parameter missing minimum args of (family columname*)");
                return null;
            }
            CsvBlurMapper.addColumns(job, values[0], getSubArray(values, 1));
        }
    }
    BlurOutputFormat.setupJob(job, tableDescriptor);
    BlurMapReduceUtil.addDependencyJars(job.getConfiguration(), Splitter.class);
    if (cmd.hasOption("r")) {
        int reducerMultiplier = Integer.parseInt(cmd.getOptionValue("r"));
        BlurOutputFormat.setReducerMultiplier(job, reducerMultiplier);
    }
    final Path output;
    if (cmd.hasOption("out")) {
        output = new Path(cmd.getOptionValue("out"));
    } else {
        UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
        String userName = currentUser.getUserName();
        output = new Path("/user/" + userName + "/.blur-" + System.currentTimeMillis());
    }
    BlurOutputFormat.setOutputPath(job, output);
    if (cmd.hasOption("import")) {
        ref.set(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                client.loadData(tableName, output.toUri().toString());
                return null;
            }
        });
    }
    return job;
}

From source file:org.apache.blur.shell.AddColumnDefinitionCommand.java

@Override
public void doit(PrintWriter out, Blur.Iface client, String[] args)
        throws CommandException, TException, BlurException {
    if (args.length < 5) {
        throw new CommandException("Invalid args: " + help());
    }/*from   ww w .  ja  v a  2s  . c om*/
    CommandLine cmd = parse(args, out);

    ColumnDefinition columnDefinition = new ColumnDefinition();
    columnDefinition.setFamily(args[2]);
    columnDefinition.setColumnName(args[3]);
    columnDefinition.setFieldType(args[4]);
    if (cmd.hasOption("s")) {
        columnDefinition.setSubColumnName(cmd.getOptionValue("s"));
    }
    if (cmd.hasOption("F")) {
        columnDefinition.setFieldLessIndexed(true);
    }
    if (cmd.hasOption("S")) {
        columnDefinition.setSortable(true);
    }
    if (cmd.hasOption("p")) {
        Option[] options = cmd.getOptions();
        for (Option option : options) {
            if (option.getOpt().equals("p")) {
                String[] values = option.getValues();
                columnDefinition.putToProperties(values[0], values[1]);
            }
        }
    }
    if (cmd.hasOption('M')) {
        columnDefinition.setMultiValueField(true);
    } else {
        columnDefinition.setMultiValueField(false);
    }

    if (!client.addColumnDefinition(args[1], columnDefinition)) {
        out.println(
                "Column Definition was not added, check to see if the column has already been added to the table.");
    }
}

From source file:org.apache.blur.shell.CreateTableCommand.java

private Map<String, String> getProps(CommandLine cmd, String opt) {
    Map<String, String> props = new HashMap<String, String>();
    Option[] options = cmd.getOptions();
    for (Option option : options) {
        if (option.getOpt().equals(opt)) {
            String[] values = option.getValues();
            props.put(values[0], values[1]);
        }/*from  w w  w.ja v  a  2 s  .c o m*/
    }
    return props;
}

From source file:org.apache.blur.shell.DiscoverFileBufferSizeUtil.java

@Override
public void doit(PrintWriter out, Iface client, String[] args)
        throws CommandException, TException, BlurException {
    CommandLine cmd = parse(args, out);/*www  .  ja  v  a2 s .  c  o m*/
    if (cmd == null) {
        throw new CommandException(name() + " missing required arguments");
    }
    Option[] options = cmd.getOptions();
    for (Option option : options) {
        out.println(option);
        String opt = option.getOpt();
        String value = option.getValue();
        System.out.println(opt + " " + value);

    }

    Path path = new Path(cmd.getOptionValue("p"));
    long size = Long.parseLong(cmd.getOptionValue("s", "1000000000"));// 1GB
    int sampleSize = Integer.parseInt(cmd.getOptionValue("S", "10"));// 10
    int warmupSize = Integer.parseInt(cmd.getOptionValue("W", "3"));// 3
    int min = Integer.parseInt(cmd.getOptionValue("n", "12"));// 12
    int max = Integer.parseInt(cmd.getOptionValue("x", "19"));// 19
    int readSamplesPerPass = Integer.parseInt(cmd.getOptionValue("r", "1000"));// 1000

    Configuration configuration = new Configuration();
    FileSystem fileSystem;
    try {
        fileSystem = path.getFileSystem(configuration);
    } catch (IOException e) {
        if (Main.debug) {
            e.printStackTrace();
        }
        throw new CommandException(e.getMessage());
    }
    Random random = new Random();
    Map<Integer, Long> writingResults;
    try {
        writingResults = runWritingTest(out, path, fileSystem, random, sampleSize, warmupSize, size, min, max);
    } catch (IOException e) {
        if (Main.debug) {
            e.printStackTrace();
        }
        throw new CommandException(e.getMessage());
    }
    Map<Integer, Long> readingResults;
    try {
        readingResults = runReadingTest(out, path, fileSystem, random, sampleSize, warmupSize, size, min, max,
                readSamplesPerPass);
    } catch (IOException e) {
        if (Main.debug) {
            e.printStackTrace();
        }
        throw new CommandException(e.getMessage());
    }

    out.println("Printing Results for Writing");
    printResults(out, writingResults);

    out.println("Printing Results for Reading");
    printResults(out, readingResults);
}

From source file:org.apache.blur.shell.ExecutePlatformCommandCommand.java

private BlurObject createBlurObject(CommandLine commandLine, CommandDescriptor descriptor)
        throws CommandException {
    Map<String, ArgumentDescriptor> arguments = new TreeMap<String, ArgumentDescriptor>(
            descriptor.getOptionalArguments());
    arguments.putAll(descriptor.getRequiredArguments());
    BlurObject blurObject = new BlurObject();
    if (commandLine == null) {
        return null;
    }// w w  w  . j  a va2 s .  c o  m
    Option[] options = commandLine.getOptions();
    for (Option option : options) {
        String name = option.getOpt();
        String value = option.getValue();
        ArgumentDescriptor argumentDescriptor = arguments.get(name);
        String type = argumentDescriptor.getType();
        blurObject.put(name, convertIfNeeded(value, type));
    }
    return blurObject;
}

From source file:org.apache.blur.shell.QueryCommandHelper.java

@SuppressWarnings("unchecked")
public static BlurQuery getBlurQuery(CommandLine commandLine) {
    Option[] options = commandLine.getOptions();
    Query query = new Query();
    if (commandLine.hasOption(QUERY)) {
        String queryString = join(Arrays.asList(commandLine.getOptionValues(QUERY)), " ");
        query.setQuery(queryString);/* www  . j  a  v  a 2 s .  co m*/
    }
    if (commandLine.hasOption(DISABLE_ROW_QUERY)) {
        query.setRowQuery(false);
    }
    if (commandLine.hasOption(SCORE_TYPE)) {
        String scoreTypeStr = commandLine.getOptionValue(SCORE_TYPE);
        ScoreType scoreType = ScoreType.valueOf(scoreTypeStr.toUpperCase());
        query.setScoreType(scoreType);
    }
    if (commandLine.hasOption(RECORD_FILTER)) {
        String recordFilter = commandLine.getOptionValue(RECORD_FILTER);
        query.setRecordFilter(recordFilter);
    }
    if (commandLine.hasOption(ROW_FILTER)) {
        String rowFilter = commandLine.getOptionValue(ROW_FILTER);
        query.setRecordFilter(rowFilter);
    }

    // String recordFilter;
    // String rowFilter;
    // String rowId;
    // long start;
    // int fetch;
    // long maxQueryTime;
    // long minimumNumberOfResults;
    // List<Facet> facets;
    // List<SortField> sortFields;

    BlurQuery blurQuery = new BlurQuery();
    blurQuery.setQuery(query);
    Selector selector = new Selector(Main.selector);
    if (!query.isRowQuery()) {
        selector.setRecordOnly(true);
    }
    blurQuery.setSelector(selector);
    blurQuery.setCacheResult(false);
    blurQuery.setUseCacheIfPresent(false);

    if (commandLine.hasOption(START)) {
        String startStr = commandLine.getOptionValue(START);
        blurQuery.setStart(Long.parseLong(startStr));
    }
    if (commandLine.hasOption(FETCH)) {
        String fetchStr = commandLine.getOptionValue(FETCH);
        blurQuery.setFetch(Integer.parseInt(fetchStr));
    }
    if (commandLine.hasOption(MAX_QUERY_TIME)) {
        String maxQueryTimeStr = commandLine.getOptionValue(MAX_QUERY_TIME);
        blurQuery.setMaxQueryTime(Long.parseLong(maxQueryTimeStr));
    }
    if (commandLine.hasOption(MINIMUM_NUMBER_OF_RESULTS)) {
        String minNumbResultsStr = commandLine.getOptionValue(MINIMUM_NUMBER_OF_RESULTS);
        blurQuery.setMinimumNumberOfResults(Long.parseLong(minNumbResultsStr));
    }
    if (commandLine.hasOption(ROW_ID)) {
        String rowId = commandLine.getOptionValue(ROW_FILTER);
        blurQuery.setRowId(rowId);
    }
    List<Facet> facets = new ArrayList<Facet>();
    for (Option option : options) {
        if (option.getOpt().equals(FACET)) {
            List<String> valuesList = option.getValuesList();
            Facet facet = new Facet();
            facet.setQueryStr(join(valuesList, " "));
            facets.add(facet);
        }
    }
    if (!facets.isEmpty()) {
        blurQuery.setFacets(facets);
    }

    List<SortField> sortFields = new ArrayList<SortField>();
    for (Option option : options) {
        if (option.getOpt().equals(SORT)) {
            List<String> valuesList = option.getValuesList();
            if (valuesList.size() == 2) {
                sortFields.add(new SortField(valuesList.get(0), valuesList.get(1), false));
            } else if (valuesList.size() == 3) {
                sortFields.add(new SortField(valuesList.get(0), valuesList.get(1),
                        Boolean.parseBoolean(valuesList.get(2))));
            } else {
                throw new RuntimeException("Sort take 2 or 3 parameters.");
            }
        }
    }
    if (!sortFields.isEmpty()) {
        blurQuery.setSortFields(sortFields);
    }

    if (Main.highlight) {
        blurQuery.getSelector().setHighlightOptions(new HighlightOptions());
    }

    return blurQuery;
}

From source file:org.apache.cassandra.contrib.stress.Stress.java

/**
 * Printing out help message/*from   w  w  w. jav  a  2s.c  o m*/
 */
public static void printHelpMessage() {
    System.out.println("Usage: ./bin/stress [options]\n\nOptions:");

    for (Object o : Session.availableOptions.getOptions()) {
        Option option = (Option) o;
        String upperCaseName = option.getLongOpt().toUpperCase();
        System.out.println(String.format("-%s%s, --%s%s%n\t\t%s%n", option.getOpt(),
                (option.hasArg()) ? " " + upperCaseName : "", option.getLongOpt(),
                (option.hasArg()) ? "=" + upperCaseName : "", option.getDescription()));
    }
}