Example usage for org.apache.commons.cli DefaultParser DefaultParser

List of usage examples for org.apache.commons.cli DefaultParser DefaultParser

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:gobblin.runtime.cli.PublicMethodsCliObjectFactory.java

@Override
public T buildObject(String[] args, int offset, boolean printUsage, String usage) throws IOException {
    Options options = new Options();
    options.addOption(HELP);/*from  www  .j a v a  2  s .co m*/
    options.addOption(USE_LOG);
    for (Option opt : getOptions().getOptions()) {
        options.addOption(opt);
    }

    CommandLine cli;
    try {
        CommandLineParser parser = new DefaultParser();
        cli = parser.parse(options, Arrays.copyOfRange(args, offset, args.length));
    } catch (ParseException pe) {
        if (printUsage) {
            System.out.println("Command line parse exception: " + pe.getMessage());
            printUsage(usage, options);
        }
        throw new IOException(pe);
    }

    if (cli.hasOption(HELP.getOpt())) {
        if (printUsage) {
            printUsage(usage, options);
        }
        throw new HelpArgumentFound();
    }

    try {
        return buildObject(cli);
    } catch (Throwable t) {
        if (cli.hasOption(USE_LOG.getOpt())) {
            log.error("Failed to instantiate " + this.klazz.getName(), t);
        } else {
            System.out.println("Error: " + t.getMessage());
        }
        if (printUsage) {
            printUsage(usage, options);
        }
        throw new IOException(t);
    }
}

From source file:dumpsection.Main.java

public void start(String[] args) throws org.apache.commons.cli.ParseException {
    final String fileName;
    final Long limit;

    System.out.println("args   : " + dumpArgs(args));

    final Option fileNameOption = Option.builder("f").required().longOpt("filename").desc("ts??")
            .hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit")
            .desc("??(???????EOF??)").hasArg()
            .type(Long.class).build();

    Options opts = new Options();
    opts.addOption(fileNameOption);//from w w  w .  ja  v a  2s .  c  o  m
    opts.addOption(limitOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        // handle interface option.
        fileName = cl.getOptionValue(fileNameOption.getOpt());
        if (fileName == null) {
            throw new ParseException("????????");
        }

        // handlet destination option.
        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = null;
        } finally {
            limit = xl;
        }

        final PROGRAM_ID pids = PROGRAM_ID.SDT_OR_BAT;

        System.out.println("Starting application...");
        System.out.println("filename   : " + fileName);
        System.out.println("limit : " + limit);

        // your code
        TsReader reader;
        if (limit == null) {
            reader = new TsReader(new File(fileName), pids.getPids());
        } else {
            reader = new TsReader(new File(fileName), pids.getPids(), limit);
        }

        Map<Integer, List<TsPacketParcel>> ret = reader.getPackets();

        for (Integer pid : ret.keySet()) {
            try (FileWriter writer = new FileWriter(fileName + "_" + Integer.toHexString(pid) + "_SDT.txt")) {
                SectionReconstructor sr = new SectionReconstructor(ret.get(pid), pid);
                for (Section s : sr.getSections()) {
                    String text = Hex.encodeHexString(s.getData());
                    writer.write(text + "\n");
                }
                writer.flush();
            } catch (IOException ex) {
                LOG.fatal("", ex);
            }
        }

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    } catch (FileNotFoundException ex) {
        LOG.fatal("?????", ex);
    }
}

From source file:alluxio.shell.command.AbstractShellCommand.java

@Override
public CommandLine parseAndValidateArgs(String... args) {
    Options opts = getOptions();/*from ww w . ja  v a 2 s  .c o  m*/
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;

    try {
        cmd = parser.parse(opts, args, true /* stopAtNonOption */);
    } catch (ParseException e) {
        // TODO(ifcharming): improve the error message when an unregistered option appears
        System.err.println("Unable to parse input args: " + e.getMessage());
        return null;
    }

    if (!validateArgs(cmd.getArgs())) {
        return null;
    }
    return cmd;
}

From source file:epgtools.dumpservicefromnit.Main.java

public void start(String[] args)
        throws org.apache.commons.cli.ParseException, FileNotFoundException, IOException {
    final byte[] sectionByte;
    final SERVICE_TYPE serviceType;
    final Option sectionDumpOption = Option.builder("s").required().longOpt("section")
            .desc("?hex").hasArg().type(String.class).build();

    final Option serviceTypeOption = Option.builder("t").required(false).longOpt("servicetype")
            .desc("?").hasArg().type(Integer.class).build();

    Options opts = new Options();
    opts.addOption(sectionDumpOption);//ww  w  .ja  va2 s . c  om
    opts.addOption(serviceTypeOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        try {
            sectionByte = Hex.decodeHex(cl.getOptionValue(sectionDumpOption.getOpt()).toCharArray());
        } catch (DecoderException ex) {
            LOG.error(ex);
            throw new ParseException("hex??????");
        }

        serviceType = SERVICE_TYPE
                .reverseLookUp(Integer.parseInt(cl.getOptionValue(serviceTypeOption.getOpt()), 16));

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    }

    LOG.info("Starting application...");
    LOG.info("section           : " + Hex.encodeHexString(sectionByte));
    LOG.info("service type      : " + serviceType);

    Section section = new Section(sectionByte);

    if (section.checkCRC() != CRC_STATUS.NO_CRC_ERROR) {
        LOG.error("CRC??");
    }

    if (section.getTable_id_const() != TABLE_ID.NIT_THIS_NETWORK
            && section.getTable_id_const() != TABLE_ID.NIT_OTHER_NETWORK) {
        LOG.error("NIT?????");
    }

    NetworkInformationTableBody nitbody = (NetworkInformationTableBody) section.getSectionBody();

    final int networkId = nitbody.getNetwork_id();
    LOG.info("networkId = " + Integer.toHexString(networkId));

    for (Descriptor d1 : nitbody.getDescriptors_loop().getDescriptors_loopList()) {
        final String networkName;
        if (d1.getDescriptor_tag_const() == DESCRIPTOR_TAG.NETWORK_NAME_DESCRIPTOR) {
            final NetworkNameDescriptor nnd = (NetworkNameDescriptor) d1;
            networkName = nnd.getChar_String();
            LOG.info("networkName = " + networkName);
        }
    }

    final List<TransportStreamLoop> tsLoopList = nitbody.getTransport_streams_loop();

    for (TransportStreamLoop tsLoop : tsLoopList) {
        final int transportStreamId = tsLoop.getTransport_stream_id();
        LOG.info("transportStreamId = " + Integer.toHexString(transportStreamId));
        final int originalNetworkId = tsLoop.getOriginal_network_id();
        LOG.info("originalNetworkId = " + Integer.toHexString(originalNetworkId));
        final DescriptorsLoop dloop = tsLoop.getDescriptors_loop();
        final List<Descriptor> dList = dloop.getDescriptors_loopList();
        for (Descriptor desc : dList) {

            if (desc.getDescriptor_tag_const() == DESCRIPTOR_TAG.SERVICE_LIST_DESCRIPTOR) {
                ServiceListDescriptor sd = (ServiceListDescriptor) desc;
                List<Service> svList = sd.getServiceList();
                for (Service service : svList) {
                    if (service.getService_type_Enum() == serviceType) {
                        final int serviceId = service.getService_id();
                        LOG.info("serviceId = " + Integer.toHexString(serviceId));
                    }
                }
            }
        }
    }

}

From source file:ai.grakn.migration.base.MigrationOptions.java

protected void parse(String[] args) {
    try {//from   w w  w  .j ava  2 s .com
        CommandLineParser parser = new DefaultParser();
        command = parser.parse(options, args);
        numberOptions = command.getOptions().length;
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}

From source file:lu.uni.adtool.tools.Clo.java

/**
 * Class used to parse command line options. Returns true if GUI window should
 * be shown/*from ww  w  .j  a va  2 s  .c om*/
 */
public boolean parse(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
            return false;
        } else if (cmd.hasOption("v")) {
            version();
            return false;
        } else if (cmd.hasOption("o")) {
            this.toOpen = cmd.getOptionValues("o");
            if (this.toOpen != null && this.toOpen.length == 0) {
                this.toOpen = null;
            }
        }
        if (cmd.hasOption("i") && cmd.hasOption("x") || cmd.hasOption("i") && cmd.hasOption("d")
                && (cmd.getOptionValue("d", "0").equals("?") || cmd.getOptionValue("d", "0").equals("q"))) {
            ImportExport exporter = new ImportExport();
            if (cmd.hasOption("D")) {
                exporter.setNoDerivedValues(true);
            }
            if (cmd.hasOption("m")) {
                exporter.setMarkEditable(true);
            }
            if (cmd.hasOption("r")) {
                String r = cmd.getOptionValue("r");
                try {
                    int x = Integer.parseInt(r);
                    if (x > 0) {
                        exporter.setExportRanking(x);
                    } else {
                        System.err.println(Options.getMsg("clo.wrongrank"));
                    }
                } catch (NumberFormatException e) {
                    System.err.println(Options.getMsg("clo.wrongrank"));
                }
            }
            if (cmd.hasOption("L")) {
                exporter.setNoLabels(true);
            }
            if (cmd.hasOption("C")) {
                exporter.setNoComputedValues(true);
            }
            if (cmd.hasOption("s")) {
                String size = cmd.getOptionValue("s");
                int index = size.indexOf('x');
                if (index > 0) {
                    try {
                        int x = Integer.parseInt(size.substring(0, index));
                        int y = Integer.parseInt(size.substring(index + 1));
                        exporter.setViewPortSize(new Dimension(x, y));
                    } catch (NumberFormatException e) {
                        System.err.println(Options.getMsg("clo.wrongsize"));
                    }
                }
            }
            if (cmd.hasOption("d")) {
                String[] domainIds = cmd.getOptionValues("d");

                if (domainIds != null) {
                    // if (domainId == "?" || domainId=="q") {
                    // System.out.println(new Integer(exporter.countDomains(fileName)));
                    // return false;
                    // }
                    exporter.setExportDomainStr(domainIds);
                }
            }
            String fileName = cmd.getOptionValue("i");
            if (fileName != null && exporter.doImport(fileName)) {
                fileName = cmd.getOptionValue("x");
                if (fileName != null) {
                    exporter.doExport(fileName);
                }
            }
            return toOpen != null;
        }
        if (cmd.getOptions().length > 0) {
            System.err.println(Options.getMsg("clo.wrongCombination") + ".");
            help();
            return false;
        }
    } catch (ParseException e) {
        System.err.println(Options.getMsg("clo.parseError") + ": " + e.toString());
        help();
        return false;
    }
    return true;
}

From source file:com.yahoo.athenz.example.zts.tls.client.ZTSTLSClientAccessToken.java

private static CommandLine parseCommandLine(String[] args) {

    Options options = new Options();

    Option domain = new Option("d", "domain", true, "domain name");
    domain.setRequired(true);/*from  w  w  w  .  j ava 2 s  .com*/
    options.addOption(domain);

    Option key = new Option("k", "key", true, "private key path");
    key.setRequired(true);
    options.addOption(key);

    Option cert = new Option("c", "cert", true, "certficate path");
    cert.setRequired(true);
    options.addOption(cert);

    Option trustStore = new Option("t", "trustStorePath", true, "CA TrustStore path");
    trustStore.setRequired(true);
    options.addOption(trustStore);

    Option trustStorePassword = new Option("p", "trustStorePassword", true, "CA TrustStore password");
    trustStorePassword.setRequired(true);
    options.addOption(trustStorePassword);

    Option ztsUrl = new Option("z", "ztsurl", true, "ZTS Server url");
    ztsUrl.setRequired(true);
    options.addOption(ztsUrl);

    Option idTokenService = new Option("s", "idTokenService", true, "ID Token Service Name");
    idTokenService.setRequired(false);
    options.addOption(idTokenService);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("zts-tls-client", options);
        System.exit(1);
    }

    return cmd;
}

From source file:jmxbf.java

/**
* @param args/*from w w  w  .j  a  v a 2s.c  o  m*/
* @return
*/
private static CommandLine getParsedCommandLine(String[] args) {
    Options options = new Options();

    Option host = new Option("h", "host", true, "The JMX server IP address.");
    host.setRequired(true);
    options.addOption(host);

    Option port = new Option("p", "port", true, "The JMX server listening port.");
    port.setRequired(true);
    options.addOption(port);

    Option usernames = new Option("uf", "usernames-file", true, "File including the usernames, one per line.");
    usernames.setRequired(true);
    options.addOption(usernames);

    Option passwords = new Option("pf", "passwords-file", true, "File including the passwords, one per line.");
    passwords.setRequired(true);
    options.addOption(passwords);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("jmxbf", options);
        return null;
        //System.exit(1)

    }
    return cmd;
}

From source file:ap.attack.ArgumentsHandler.java

public void parseArguments(String[] args) {
    Options options = createOptions();/*from  w  w  w .j  av  a 2s  .  c  o  m*/
    HelpFormatter formatter = new HelpFormatter();
    //formatter.printHelp( "sfera" , options );
    CommandLineParser parser = new DefaultParser();
    if (args.length == 1 && args[0] == "-h") {
        formatter.printHelp("SFERA", options);
        System.exit(0);
    }
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("o")) {
            workdir = line.getOptionValue("o");
        }
        if (line.hasOption("kd")) {
            kd = line.getOptionValue("kd");
        }
        if (line.hasOption("ud")) {
            ud = line.getOptionValue("ud");
        }
        if (line.hasOption("d")) {
            dataset = line.getOptionValue("d");
        }
        if (line.hasOption("ups")) {
            ups = line.getOptionValue("ups");
        }
        if (line.hasOption("upe")) {
            upe = line.getOptionValue("upe");
        }
        if (line.hasOption("kps")) {
            kps = line.getOptionValue("kps");
        }
        if (line.hasOption("kpe")) {
            kpe = line.getOptionValue("kpe");
        }
        if (line.hasOption("c")) {
            cellSize = line.getOptionValue("c");
        }
        if (line.hasOption("di")) {
            diameter = line.getOptionValue("d");
        }
        if (line.hasOption("dt")) {
            duration = line.getOptionValue("t");
        }
        if (line.hasOption("h")) {
            formatter.printHelp("SFERA", options);
            System.exit(0);
        }
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        formatter.printHelp("SFERA", options);
        System.exit(1);
    }
}

From source file:com.sqs.tq.fdc.config.CmdLineConfig.java

private CommandLine parse(Options os, boolean allowOtherOptions) {
    try {/*ww w .  j  a v a  2 s. co  m*/
        CommandLineParser parser = new DefaultParser();
        return parser.parse(os, theArgs, allowOtherOptions);
    } catch (ParseException ex) {
        error = ex.getMessage();
        return null;
    }
}