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

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

Introduction

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

Prototype

public Object getParsedOptionValue(String opt) throws ParseException 

Source Link

Document

Return a version of this Option converted to a particular type.

Usage

From source file:org.apache.felix.ipojo.task.IPojoc.java

private void readMetadataOption(final CommandLine cmd) throws Exception {
    // Retrieve the metadata file
    if (cmd.hasOption("m")) {
        m_metadata = (File) cmd.getParsedOptionValue("m");
        if (m_metadata != null && !m_metadata.isFile()) {
            throw new Exception(format("The metadata option must be an existing file, '%s' does not exist",
                    cmd.getOptionValue('m')));
        }/*w  ww  .j  a  v a  2  s.c  om*/
        System.out.println("metadata file  => " + m_metadata.getAbsolutePath());
    } else {
        System.out.println("metadata file  => no metadata file");
    }
}

From source file:org.apache.felix.ipojo.task.IPojoc.java

private void readOutputOption(final CommandLine cmd) throws Exception {
    // Retrieve output file
    if (cmd.hasOption("o")) {
        try {//from ww w.  ja  v  a2  s  .c o m
            m_output = (File) cmd.getParsedOptionValue("o");
        } catch (ParseException pe) {
            throw new Exception(format("The output option must be an existing file, '%s' does not exist",
                    cmd.getOptionValue('o')));
        }
        System.out.println("output file    => " + m_output.getAbsolutePath());
    } else {
        // Inline replacement
        // We create a temporary file marked by a __ prefix
        // It will be substituted upon success.
        m_output = new File("__" + m_input.getName());
        System.out.println("output file    => " + m_input.getAbsolutePath());
    }
}

From source file:org.apache.felix.ipojo.task.IPojoc.java

private void readInputOption(final CommandLine cmd) throws Exception {
    // Check that the input file exist
    m_input = (File) cmd.getParsedOptionValue("i");
    if (m_input == null || !m_input.isFile()) {
        throw new Exception(format("The input option must be an existing file, '%s' does not exist",
                cmd.getOptionValue('i')));
    }//from www  .  j  a v a 2 s .c o  m
    System.out.println("input file     => " + m_input.getAbsolutePath());
}

From source file:org.apache.hadoop.hbase.client.HBaseFsck.java

/**
 * Main program//from   w w w.j  ava 2s  . c  o  m
 *
 * @param args
 * @throws ParseException
 */
public static void main(String[] args)
        throws IOException, MasterNotRunningException, InterruptedException, ParseException {

    Options opt = new Options();
    opt.addOption(OptionBuilder.withArgName("property=value").hasArg()
            .withDescription("Override HBase Configuration Settings").create("D"));
    opt.addOption(OptionBuilder.withArgName("timeInSeconds").hasArg()
            .withDescription("Ignore regions with metadata updates in the last {timeInSeconds}.")
            .withType(PatternOptionBuilder.NUMBER_VALUE).create("timelag"));
    opt.addOption(OptionBuilder.withArgName("timeInSeconds").hasArg()
            .withDescription("Stop scan jobs after a fixed time & analyze existing data.")
            .withType(PatternOptionBuilder.NUMBER_VALUE).create("timeout"));
    opt.addOption("fix", false, "Try to fix some of the errors.");
    opt.addOption("y", false, "Do not prompt for reconfirmation from users on fix.");
    opt.addOption("w", false, "Try to fix warnings as well as errors.");
    opt.addOption("summary", false, "Print only summary of the tables and status.");
    opt.addOption("detail", false, "Display full report of all regions.");
    opt.addOption("checkRegionInfo", false, "Check if .regioninfo is consistent with .META.");
    opt.addOption("h", false, "Display this help");
    CommandLine cmd = new GnuParser().parse(opt, args);

    // any unknown args or -h
    if (!cmd.getArgList().isEmpty() || cmd.hasOption("h")) {
        new HelpFormatter().printHelp("hbck", opt);
        return;
    }

    Configuration conf = HBaseConfiguration.create();
    conf.set("fs.defaultFS", conf.get("hbase.rootdir"));

    if (cmd.hasOption("D")) {
        for (String confOpt : cmd.getOptionValues("D")) {
            String[] kv = confOpt.split("=", 2);
            if (kv.length == 2) {
                conf.set(kv[0], kv[1]);
                LOG.debug("-D configuration override: " + kv[0] + "=" + kv[1]);
            } else {
                throw new ParseException("-D option format invalid: " + confOpt);
            }
        }
    }
    if (cmd.hasOption("timeout")) {
        Object timeout = cmd.getParsedOptionValue("timeout");
        if (timeout instanceof Long) {
            conf.setLong(HConstants.HBASE_RPC_TIMEOUT_KEY, ((Long) timeout).longValue() * 1000);
        } else {
            throw new ParseException("-timeout needs a long value.");
        }
    }

    // create a fsck object
    HBaseFsck fsck = new HBaseFsck(conf);
    fsck.setTimeLag(HBaseFsckRepair.getEstimatedFixTime(conf));

    if (cmd.hasOption("details")) {
        fsck.displayFullReport();
    }
    if (cmd.hasOption("timelag")) {
        Object timelag = cmd.getParsedOptionValue("timelag");
        if (timelag instanceof Long) {
            fsck.setTimeLag(((Long) timelag).longValue() * 1000);
        } else {
            throw new ParseException("-timelag needs a long value.");
        }
    }
    if (cmd.hasOption("fix")) {
        fsck.setFixState(FixState.ERROR);
    }
    if (cmd.hasOption("w")) {
        fsck.setFixState(FixState.ALL);
    }
    if (cmd.hasOption("y")) {
        fsck.setPromptResponse(true);
    }
    if (cmd.equals("summary")) {
        fsck.setSummary();
    }
    if (cmd.hasOption("checkRegionInfo")) {
        checkRegionInfo = true;
    }

    int code = -1;
    try {
        // do the real work of fsck
        code = fsck.doWork();
        // If we have tried to fix the HBase state, run fsck again
        // to see if we have fixed our problems
        if (fsck.shouldRerun()) {
            fsck.setFixState(FixState.NONE);
            long fixTime = HBaseFsckRepair.getEstimatedFixTime(conf);
            if (fixTime > 0) {
                LOG.info("Waiting " + StringUtils.formatTime(fixTime)
                        + " before checking to see if fixes worked...");
                Thread.sleep(fixTime);
            }
            code = fsck.doWork();
        }
    } catch (InterruptedException ie) {
        LOG.info("HBCK was interrupted by user. Exiting...");
        code = -1;
    }

    Runtime.getRuntime().exit(code);
}

From source file:org.apache.nutch.tools.CommonCrawlDataDumper.java

@Override
public int run(String[] args) throws Exception {
    Option helpOpt = new Option("h", "help", false, "show this help message.");
    // argument options
    @SuppressWarnings("static-access")
    Option outputOpt = OptionBuilder.withArgName("outputDir").hasArg()
            .withDescription("output directory (which will be created) to host the CBOR data.")
            .create("outputDir");
    // WARC format
    Option warcOpt = new Option("warc", "export to a WARC file");

    @SuppressWarnings("static-access")
    Option segOpt = OptionBuilder.withArgName("segment").hasArgs()
            .withDescription("the segment or directory containing segments to use").create("segment");
    // create mimetype and gzip options
    @SuppressWarnings("static-access")
    Option mimeOpt = OptionBuilder.isRequired(false).withArgName("mimetype").hasArgs()
            .withDescription("an optional list of mimetypes to dump, excluding all others. Defaults to all.")
            .create("mimetype");
    @SuppressWarnings("static-access")
    Option gzipOpt = OptionBuilder.withArgName("gzip").hasArg(false)
            .withDescription("an optional flag indicating whether to additionally gzip the data.")
            .create("gzip");
    @SuppressWarnings("static-access")
    Option keyPrefixOpt = OptionBuilder.withArgName("keyPrefix").hasArg(true)
            .withDescription("an optional prefix for key in the output format.").create("keyPrefix");
    @SuppressWarnings("static-access")
    Option simpleDateFormatOpt = OptionBuilder.withArgName("SimpleDateFormat").hasArg(false)
            .withDescription("an optional format for timestamp in GMT epoch milliseconds.")
            .create("SimpleDateFormat");
    @SuppressWarnings("static-access")
    Option epochFilenameOpt = OptionBuilder.withArgName("epochFilename").hasArg(false)
            .withDescription("an optional format for output filename.").create("epochFilename");
    @SuppressWarnings("static-access")
    Option jsonArrayOpt = OptionBuilder.withArgName("jsonArray").hasArg(false)
            .withDescription("an optional format for JSON output.").create("jsonArray");
    @SuppressWarnings("static-access")
    Option reverseKeyOpt = OptionBuilder.withArgName("reverseKey").hasArg(false)
            .withDescription("an optional format for key value in JSON output.").create("reverseKey");
    @SuppressWarnings("static-access")
    Option extensionOpt = OptionBuilder.withArgName("extension").hasArg(true)
            .withDescription("an optional file extension for output documents.").create("extension");
    @SuppressWarnings("static-access")
    Option sizeOpt = OptionBuilder.withArgName("warcSize").hasArg(true).withType(Number.class)
            .withDescription("an optional file size in bytes for the WARC file(s)").create("warcSize");
    @SuppressWarnings("static-access")
    Option linkDbOpt = OptionBuilder.withArgName("linkdb").hasArg(true)
            .withDescription("an optional linkdb parameter to include inlinks in dump files").isRequired(false)
            .create("linkdb");

    // create the options
    Options options = new Options();
    options.addOption(helpOpt);//from www  .  j  a v  a  2  s . c  o  m
    options.addOption(outputOpt);
    options.addOption(segOpt);
    // create mimetypes and gzip options
    options.addOption(warcOpt);
    options.addOption(mimeOpt);
    options.addOption(gzipOpt);
    // create keyPrefix option
    options.addOption(keyPrefixOpt);
    // create simpleDataFormat option
    options.addOption(simpleDateFormatOpt);
    options.addOption(epochFilenameOpt);
    options.addOption(jsonArrayOpt);
    options.addOption(reverseKeyOpt);
    options.addOption(extensionOpt);
    options.addOption(sizeOpt);
    options.addOption(linkDbOpt);

    CommandLineParser parser = new GnuParser();
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("help") || !line.hasOption("outputDir") || (!line.hasOption("segment"))) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(CommonCrawlDataDumper.class.getName(), options, true);
            return 0;
        }

        File outputDir = new File(line.getOptionValue("outputDir"));
        File segmentRootDir = new File(line.getOptionValue("segment"));
        String[] mimeTypes = line.getOptionValues("mimetype");
        boolean gzip = line.hasOption("gzip");
        boolean epochFilename = line.hasOption("epochFilename");

        String keyPrefix = line.getOptionValue("keyPrefix", "");
        boolean simpleDateFormat = line.hasOption("SimpleDateFormat");
        boolean jsonArray = line.hasOption("jsonArray");
        boolean reverseKey = line.hasOption("reverseKey");
        String extension = line.getOptionValue("extension", "");
        boolean warc = line.hasOption("warc");
        long warcSize = 0;

        if (line.getParsedOptionValue("warcSize") != null) {
            warcSize = (Long) line.getParsedOptionValue("warcSize");
        }
        String linkdbPath = line.getOptionValue("linkdb");
        File linkdb = linkdbPath == null ? null : new File(linkdbPath);

        CommonCrawlConfig config = new CommonCrawlConfig();
        config.setKeyPrefix(keyPrefix);
        config.setSimpleDateFormat(simpleDateFormat);
        config.setJsonArray(jsonArray);
        config.setReverseKey(reverseKey);
        config.setCompressed(gzip);
        config.setWarcSize(warcSize);
        config.setOutputDir(line.getOptionValue("outputDir"));

        if (!outputDir.exists()) {
            LOG.warn("Output directory: [" + outputDir.getAbsolutePath() + "]: does not exist, creating it.");
            if (!outputDir.mkdirs())
                throw new Exception("Unable to create: [" + outputDir.getAbsolutePath() + "]");
        }

        CommonCrawlDataDumper dumper = new CommonCrawlDataDumper(config);

        dumper.dump(outputDir, segmentRootDir, linkdb, gzip, mimeTypes, epochFilename, extension, warc);

    } catch (Exception e) {
        LOG.error(CommonCrawlDataDumper.class.getName() + ": " + StringUtils.stringifyException(e));
        e.printStackTrace();
        return -1;
    }

    return 0;
}

From source file:org.dcm4che.tool.dcm2dcm.Dcm2Dcm.java

public static void main(String[] args) {
    try {/*  ww  w .  j  a  v  a2s  .co m*/
        CommandLine cl = parseComandLine(args);
        Dcm2Dcm main = new Dcm2Dcm();
        main.setEncodingOptions(CLIUtils.encodingOptionsOf(cl));
        if (cl.hasOption("F")) {
            if (transferSyntaxOf(cl, null) != null)
                throw new ParseException(rb.getString("transfer-syntax-no-fmi"));
            main.setTransferSyntax(UID.ImplicitVRLittleEndian);
            main.setWithoutFileMetaInformation(true);
        } else {
            main.setTransferSyntax(transferSyntaxOf(cl, UID.ExplicitVRLittleEndian));
            main.setRetainFileMetaInformation(cl.hasOption("f"));
        }

        if (cl.hasOption("verify"))
            main.addCompressionParam("maxPixelValueError", cl.getParsedOptionValue("verify"));

        if (cl.hasOption("verify-block"))
            main.addCompressionParam("avgPixelValueBlockSize", cl.getParsedOptionValue("verify-block"));

        if (cl.hasOption("q"))
            main.addCompressionParam("compressionQuality", cl.getParsedOptionValue("q"));

        if (cl.hasOption("Q"))
            main.addCompressionParam("encodingRate", cl.getParsedOptionValue("Q"));

        String[] cparams = cl.getOptionValues("C");
        if (cparams != null)
            for (int i = 0; i < cparams.length;)
                main.addCompressionParam(cparams[i++], toValue(cparams[i++]));

        @SuppressWarnings("unchecked")
        final List<String> argList = cl.getArgList();
        int argc = argList.size();
        if (argc < 2)
            throw new ParseException(rb.getString("missing"));
        File dest = new File(argList.get(argc - 1));
        if ((argc > 2 || new File(argList.get(0)).isDirectory()) && !dest.isDirectory())
            throw new ParseException(MessageFormat.format(rb.getString("nodestdir"), dest));
        for (String src : argList.subList(0, argc - 1))
            main.mtranscode(new File(src), dest);
    } catch (ParseException e) {
        System.err.println("dcm2dcm: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("dcm2dcm: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:org.dcm4che.tool.dcm2jpg.Dcm2Jpg.java

public static void main(String[] args) {
    try {//from   w w  w. ja v  a2  s. co  m
        CommandLine cl = parseComandLine(args);
        Dcm2Jpg main = new Dcm2Jpg();
        main.initImageWriter(cl.getOptionValue("F", "JPEG"), cl.getOptionValue("suffix"),
                cl.getOptionValue("E"), cl.getOptionValue("C"), (Number) cl.getParsedOptionValue("q"));
        if (cl.hasOption("frame"))
            main.setFrame(((Number) cl.getParsedOptionValue("frame")).intValue());
        if (cl.hasOption("c"))
            main.setWindowCenter(((Number) cl.getParsedOptionValue("c")).floatValue());
        if (cl.hasOption("w"))
            main.setWindowWidth(((Number) cl.getParsedOptionValue("w")).floatValue());
        if (cl.hasOption("window"))
            main.setWindowIndex(((Number) cl.getParsedOptionValue("window")).intValue() - 1);
        if (cl.hasOption("voilut"))
            main.setVOILUTIndex(((Number) cl.getParsedOptionValue("voilut")).intValue() - 1);
        if (cl.hasOption("overlays"))
            main.setOverlayActivationMask(parseHex(cl.getOptionValue("overlays")));
        if (cl.hasOption("ovlygray"))
            main.setOverlayGrayscaleValue(parseHex(cl.getOptionValue("ovlygray")));
        main.setPreferWindow(!cl.hasOption("uselut"));
        main.setAutoWindowing(!cl.hasOption("noauto"));
        main.setPresentationState(loadDicomObject((File) cl.getParsedOptionValue("ps")));
        @SuppressWarnings("unchecked")
        final List<String> argList = cl.getArgList();
        int argc = argList.size();
        if (argc < 2)
            throw new ParseException(rb.getString("missing"));
        File dest = new File(argList.get(argc - 1));
        if ((argc > 2 || new File(argList.get(0)).isDirectory()) && !dest.isDirectory())
            throw new ParseException(MessageFormat.format(rb.getString("nodestdir"), dest));
        for (String src : argList.subList(0, argc - 1))
            main.mconvert(new File(src), dest);
    } catch (ParseException e) {
        System.err.println("dcm2jpg: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("dcm2jpg: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:org.hashes.ui.HashesCli.java

private static Configuration buidConfiguration(final CommandLine cmd)
        throws MalformedURLException, ParseException {

    @SuppressWarnings("unchecked")
    final List<String> arguments = cmd.getArgList();

    if ((arguments == null) || arguments.isEmpty()) {
        throw new ParseException("Missing required option: url");
    } else if (arguments.size() > 1) {
        LOG.warn("Multiple urls are not allowed. Using: " + arguments.get(0));
    }//from   ww  w.  j  ava2  s  . c  om

    final URL url = new URL(arguments.get(0));

    // required fields
    final ConfigurationBuilder builder = new ConfigurationBuilder(url.getHost());

    // optional fields
    // URL
    builder.withSchemeName(url.getProtocol());
    final int port = url.getPort();
    if (port != -1) {
        builder.withPort(port);
    }
    final String path = url.getPath();
    if (!path.isEmpty()) {
        builder.withPath(path);
    }

    // algorithm
    final AbstractCollisionGenerator algorithm = getCollisionGenerator(cmd);
    if (algorithm != null) {
        builder.withCollisionGenerator(algorithm);
    }

    if (cmd.hasOption(CliOption.PROGRESS_BAR.getOption().getOpt())) {
        builder.withProgressMonitorFactory(new SysOutProgressMonitorFactory());
    }

    final String saveKeys = (String) cmd.getParsedOptionValue(CliOption.SAVE_KEYS.getOption().getOpt());
    if (saveKeys != null) {
        builder.saveCollisionsToFile(new File(saveKeys));
    }

    if (cmd.hasOption(CliOption.WAIT.getOption().getOpt())) {
        builder.waitForResponse();
    }

    if (cmd.hasOption(CliOption.NEW.getOption().getOpt())) {
        builder.generateNewKeys();
    }

    if (cmd.hasOption(CliOption.KEYS.getOption().getOpt())) {
        final Object keys = cmd.getParsedOptionValue(CliOption.KEYS.getOption().getOpt());
        final int numberOfkeys = ((Number) keys).intValue();
        if (numberOfkeys <= 0) {
            throw new ParseException("The number of keys should be greater than 0");
        }
        builder.withNumberOfKeys(numberOfkeys);
    }

    if (cmd.hasOption(CliOption.REQUESTS.getOption().getOpt())) {
        final Object requests = cmd.getParsedOptionValue(CliOption.REQUESTS.getOption().getOpt());
        final int numberOfRequests = ((Number) requests).intValue();
        if (numberOfRequests <= 0) {
            throw new ParseException("The number of requests should be greater than 0");
        }
        builder.withRequestsPerClient(numberOfRequests);
    }

    if (cmd.hasOption(CliOption.CLIENTS.getOption().getOpt())) {
        final Object clients = cmd.getParsedOptionValue(CliOption.CLIENTS.getOption().getOpt());
        final int numberOfClients = ((Number) clients).intValue();
        if (numberOfClients <= 0) {
            throw new ParseException("The number of clients should be greater than 0");
        }
        builder.withNumberOfClients(numberOfClients);
    }

    if (cmd.hasOption(CliOption.CONNECTION_TIMEOUT.getOption().getOpt())) {
        final Object timeout = cmd.getParsedOptionValue(CliOption.CONNECTION_TIMEOUT.getOption().getOpt());
        final int connectionTimeout = ((Number) timeout).intValue();
        if (connectionTimeout < 0) {
            throw new ParseException("The connection timeout should be greater than or equal to 0");
        }
        builder.withConnectTimeout(connectionTimeout * MILLIS_IN_SECOND);
    }

    if (cmd.hasOption(CliOption.READ_TIMEOUT.getOption().getOpt())) {
        final Object timeout = cmd.getParsedOptionValue(CliOption.READ_TIMEOUT.getOption().getOpt());
        final int readTimeout = ((Number) timeout).intValue();
        if (readTimeout < 0) {
            throw new ParseException("The read timeout should be greater than or equal to 0");
        }
        builder.withReadTimeout(readTimeout * MILLIS_IN_SECOND);
    }

    if (cmd.hasOption(CliOption.HEADER.getOption().getOpt())) {
        for (final String value : cmd.getOptionValues(CliOption.HEADER.getOption().getOpt())) {
            final String[] header = value.split(HEADER_SEPARATOR);
            // trim headers
            for (int i = 0; i < header.length; i++) {
                header[i] = header[i].trim();
            }

            if (header.length != 2 || header[0].isEmpty() || header[1].isEmpty()) {
                throw new ParseException("Malformed HTTP header: " + value);
            }

            builder.withHTTPHeader(header[0], header[1]);
        }
    }

    return builder.build();
}

From source file:org.hashes.ui.HashesCli.java

private static Integer getMITMWorkerThreads(final CommandLine cmd) throws ParseException {
    Integer mitmWorkerThreads = null;

    if (cmd.hasOption(CliOption.MITM_WORKER_THREADS.getOption().getOpt())) {
        mitmWorkerThreads = ((Number) cmd
                .getParsedOptionValue(CliOption.MITM_WORKER_THREADS.getOption().getOpt())).intValue();
        if (mitmWorkerThreads <= 0) {
            throw new ParseException("The number of MITM workers should be greater than 0");
        }/*from ww  w .  j a va2  s .  com*/
    }

    return mitmWorkerThreads;
}

From source file:org.hashes.ui.HashesCli.java

private static AbstractCollisionGenerator getCollisionGenerator(final CommandLine cmd) throws ParseException {
    AbstractCollisionGenerator algorithm = null;

    if (cmd.hasOption(CliOption.JAVA.getOption().getOpt())) {

        algorithm = new DJBX31ACollisionGenerator();
    } else if (cmd.hasOption(CliOption.PHP.getOption().getOpt())) {

        algorithm = new DJBX33ACollisionGenerator();
    } else if (cmd.hasOption(CliOption.ASP.getOption().getOpt())) {

        final String seed = (String) cmd.getParsedOptionValue(CliOption.ASP.getOption().getOpt());
        final Integer workerThreads = getMITMWorkerThreads(cmd);
        algorithm = new DJBX33XCollisionGenerator(seed, workerThreads);
    } else if (cmd.hasOption(CliOption.V8.getOption().getOpt())) {

        final String seed = (String) cmd.getParsedOptionValue(CliOption.V8.getOption().getOpt());
        final Integer workerThreads = getMITMWorkerThreads(cmd);
        algorithm = new V8CollisionGenerator(seed, workerThreads);
    }/* w ww . ja va 2s  .  c  om*/

    return algorithm;
}