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

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

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:edu.odu.cs.cs350.yellow1.ui.cli.ClI.java

/**
 * Process the arguments received from the user
 * If the required arguments are not received throws an exception<br> with a message containing the list of argument not received 
 * @throws RequireArgumentsNotRecieved /*  w  w w . j a v a2s . c  om*/
 */
public void parse() throws RequireArgumentsNotRecieved {
    clp = new BasicParser();

    try {
        cmd = clp.parse(options, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formater = new HelpFormatter();
            formater.printHelp(
                    "-src [SOURCE FOLDER] -mutF [SOURCE FILE] -testSte [TEST SUITE PATH] -goldOut [GOLD VERSION OUTPUT]",
                    options);
            System.out.println(
                    "To read output log: [Changed File] ,, [Start Index] ,, [Stop Index] ,, [Original Token] ,, [Mutated Token] ;;");
            System.exit(0);
        } else {
            for (Option option : cmd.getOptions()) {
                System.out.println(option.getOpt() + " " + option.getValue());
                recievedArgutments.put(option.getOpt(), option.getValue());
            }
        }

        for (String key : recievedArgutments.keySet()) {
            if (requiredArgs.contains(key)) {
                requiredArgs.remove(key);
            }
        }

        if (!requiredArgs.isEmpty()) {
            throw new RequireArgumentsNotRecieved(
                    "The required arguments: " + requiredArgs.toString() + " were not recieved");
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.aliyun.odps.mapred.cli.OptionParser.java

public void parse(String[] args)
        throws ParseException, FileNotFoundException, ClassNotFoundException, OdpsException {
    CommandLineParser parser = new BasicParser();

    if (args == null || args.length <= 0) {
        throw new UnsupportedOperationException("Main class not specified.");
    }/*  www.  j ava  2 s.  c o  m*/

    CommandLine cmd = parser.parse(options, args, true);

    // Config load order: default file -> specified by file names -> specified
    // by kv pairs.
    OdpsConf odpsConf = new OdpsConf();
    if (cmd.hasOption("odps")) {
        String odpsconf = cmd.getOptionValue("odps");
        File conf = new File(odpsconf);
        InputStream in = new FileInputStream(conf);
        odpsConf.addResource(in);
    }

    if (cmd.hasOption("odpsconf")) {
        String[] odpsconf = cmd.getOptionValues("odpsconf");
        for (String conf : odpsconf) {
            String[] kv = conf.split("=", 2);
            odpsConf.set(kv[0], kv[1]);
        }
    }

    Account account = getAccount(odpsConf);
    Odps odps = new Odps(account);
    odps.setDefaultProject(odpsConf.getProjName());
    if (odpsConf.getEndpoint() != null) {
        odps.setEndpoint(odpsConf.getEndpoint());
    }
    ss.setOdps(odps);

    if (cmd.hasOption("job")) {
        String jobconf = cmd.getOptionValue("job");
        File conf = new File(jobconf);
        InputStream in = new FileInputStream(conf);
        ss.getDefaultJob().addResource(in);
    }

    if (cmd.hasOption("jobconf")) {
        String[] jobconfs = cmd.getOptionValues("jobconf");
        for (String conf : jobconfs) {
            String[] kv = conf.split("=", 2);
            ss.getDefaultJob().set(kv[0], kv[1]);
        }
    }

    if (cmd.hasOption("aliases")) {
        String aliases = cmd.getOptionValue("aliases");
        Map<String, String> map;
        try {
            map = JSON.parseObject(aliases, Map.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        ss.setAliases(map);
    }

    if (cmd.hasOption("resources")) {
        String resources = cmd.getOptionValue("resources");
        ss.getDefaultJob().setResources(resources);
    }

    if (cmd.hasOption("local")) {
        ss.setLocalRun(true);
    }

    String[] remain = cmd.getArgs();
    if (remain == null || remain.length <= 0) {
        throw new UnsupportedOperationException("Main class not specified.");
    }
    mainClass = Class.forName(remain[0]);
    if (remain.length > 1) {
        arguments = Arrays.copyOfRange(remain, 1, remain.length);
    } else {
        arguments = new String[0];
    }

}

From source file:com.asakusafw.windgate.bootstrap.WindGateAbort.java

static Configuration parseConfiguration(String[] args) throws ParseException {
    assert args != null;
    LOG.debug("Analyzing WindGateAbort bootstrap arguments: {}", Arrays.toString(args));

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, args);

    String profile = cmd.getOptionValue(OPT_PROFILE.getOpt());
    LOG.debug("WindGate profile: {}", profile);
    String sessionId = cmd.getOptionValue(OPT_SESSION_ID.getOpt());
    LOG.debug("WindGate sessionId: {}", sessionId);
    String plugins = cmd.getOptionValue(OPT_PLUGIN.getOpt());
    LOG.debug("WindGate plugin: {}", plugins);

    LOG.debug("Loading plugins: {}", plugins);
    List<File> pluginFiles = CommandLineUtil.parseFileList(plugins);
    ClassLoader loader = CommandLineUtil.buildPluginLoader(WindGateAbort.class.getClassLoader(), pluginFiles);

    Configuration result = new Configuration();

    LOG.debug("Loading profile: {}", profile);
    try {/*from  w ww.j  a va  2  s .  c o  m*/
        ProfileContext context = ProfileContext.system(loader);
        URI uri = CommandLineUtil.toUri(profile);
        Properties properties = CommandLineUtil.loadProperties(uri, loader);
        result.profile = GateProfile.loadFrom(CommandLineUtil.toName(uri), properties, context);
    } catch (Exception e) {
        throw new IllegalArgumentException(MessageFormat.format("Invalid profile \"{0}\".", profile), e);
    }
    if (sessionId == null || sessionId.isEmpty()) {
        result.sessionId = null;
    } else {
        result.sessionId = sessionId;
    }

    LOG.debug("Analyzed WindGateAbort bootstrap arguments");
    return result;
}

From source file:me.qcarver.wumpus.Configuration.java

/**
 * Parses command line arguments into an object. After invoking this method
 * Use getters in this class to query the values of command line arguments.
 *
 * @param args/*from   ww  w .ja  va2s.c  o  m*/
 */
void parse(String[] args) {
    this.options = new Options();
    options.addOption("a", "automated", false, "automated agent");
    options.addOption("r", "arrows", true, "number of arrows in quiver, " + "default is " + arrows);
    options.addOption("b", "bumpers", true, "% chance a room is a " + "bumper room, default is " + bumpers);
    options.addOption("g", "graphic", false,
            "graphic mode, default is " + ((uiMode == UiMode.TEXT) ? "false" : "true"));
    options.addOption("d", "dimension", true,
            "the x & y dimensions of " + "the cave, default is " + gridDimension);
    options.addOption("p", "possible", false,
            "guarantee a safe path " + " to gold, default is " + (possible ? "true" : "false"));
    options.addOption("h", "help", false, "print this message");

    CommandLine cmd = null;
    Agent agent = null;
    WumpusWorld wumpusWorld = null;

    CommandLineParser parser = new BasicParser();
    try {
        cmd = parser.parse(options, args);
        help = (cmd.hasOption("h")) ? true : false;
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Wumpus World", WumpusWorld.class.getSimpleName() + " [options]", options, "",
                true);
    }
    //if isn't true by necesity.. did user request?
    if (!help) {
        uiMode = (cmd.hasOption("g") ? UiMode.GUI : UiMode.TEXT);
    }
    playMode = (cmd.hasOption("a") ? PlayMode.AUTOMATED : PlayMode.HUMAN);
    try {
        gridDimension = (cmd.hasOption("d") ? Integer.parseInt(cmd.getOptionValue("dimension"))
                : gridDimension);
    } catch (NumberFormatException e) {
        System.err.println("Couln't parse guiDimension parameter, going " + "with default " + gridDimension);
    }
    try {
        arrows = (cmd.hasOption("r") ? Integer.parseInt(cmd.getOptionValue("arrows")) : arrows);
    } catch (NumberFormatException e) {
        System.err.println("Couln't parse arrows parameter, going " + "with default " + arrows);
    }
    try {
        bumpers = (cmd.hasOption("b") ? Integer.parseInt(cmd.getOptionValue("bumpers")) : bumpers);
        if (bumpers > BUMPERS_MAX) {
            System.err.println("Bumpers value to high, " + "try between 0 and " + BUMPERS_MAX);
            throw new NumberFormatException();
        }
    } catch (NumberFormatException e) {
        System.err.println("Couln't parse bumpers parameter, going " + "with default " + bumpers);
    }
    possible = (cmd.hasOption("p") ? true : false);
}

From source file:com.beaconhill.s3cp.CmdLine.java

CommandLine parseCmdLine(Options options, String[] args) {
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;/*  w w w.j av a2s .  c o  m*/
    try {
        cmd = parser.parse(options, args);
    } catch (MissingOptionException missingEx) {
        System.err.println(missingEx.getMessage());
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return cmd;
}

From source file:com.asakusafw.testdriver.tools.runner.BatchTestPreparator.java

static Conf parseArguments(String[] args) throws ParseException {
    assert args != null;
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, args);

    Conf conf = new Conf();
    String importerClass = cmd.getOptionValue(OPT_IMPORTER.getLongOpt());
    try {//w ww.j a  v  a2  s .  c  o  m
        conf.importer = Class.forName(importerClass).asSubclass(ImporterDescription.class).newInstance();
    } catch (Exception e) {
        throw new IllegalArgumentException(
                MessageFormat.format(Messages.getString("BatchTestPreparator.errorInvalidImporterDescription"), //$NON-NLS-1$
                        importerClass),
                e);
    }
    conf.data = cmd.getOptionValue(OPT_DATA.getLongOpt());
    conf.context = new TestDriverContext(conf.importer.getClass());

    Properties arguments = cmd.getOptionProperties(OPT_ARGUMENT.getOpt());
    conf.context.getBatchArgs().putAll(toMap(arguments));

    Properties properties = cmd.getOptionProperties(OPT_PROPERTY.getOpt());
    conf.context.getExtraConfigurations().putAll(toMap(properties));

    return conf;
}

From source file:com.github.joemcintyre.pdffinish.Main.java

/**
 * Process command line arguments./*from   w  ww.  j  a v a2s .  c o m*/
 * @param args Command line arguments.
 * @return Command object, or null on error.
 */
private static CommandLine processCommandLine(String args[]) {
    CommandLine cmd = null;

    boolean valid = false;
    CommandLineParser parser = new BasicParser();
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("v") || cmd.hasOption("h")) {
            return (cmd);
        } else {
            if (cmd.hasOption("s")) {
                if (cmd.hasOption("i")) {
                    if (cmd.hasOption("o") || cmd.hasOption("c")) {
                        System.out.println("Cannot specify config or output file with show option");
                    } else {
                        valid = true;
                    }
                } else {
                    System.out.println("Missing input file for show option");
                }
            } else {
                if (cmd.hasOption("i") && cmd.hasOption("o") && cmd.hasOption("c")) {
                    valid = true;
                } else {
                    System.out.println("Must specify input, output and configuration files");
                }
            }

            if (valid == false) {
                return (null);
            }
        }
    } catch (ParseException e) {
        System.out.println("Error processing command: " + e);
        return (null);
    }

    return (cmd);
}

From source file:homework.sample.Sample2Driver.java

private int parseArguements(String[] args, Job job) throws Exception {
    ////////////////////////////////////////
    //  ??  ?./*  w  ww.j  a v a2  s  . c  om*/
    ////////////////////////////////////////

    Options options = getOptions();
    HelpFormatter formatter = new HelpFormatter();
    if (args.length == 0) {
        formatter.printHelp("org.openflamingo.hadoop jar <JAR> " + getClass().getName(), options, true);
        return -1;
    }

    //  ??? .
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    // ? ?.
    for (String[] requiredOption : requiredOptions) {
        if (!cmd.hasOption(requiredOption[0])) {
            formatter.printHelp("org.openflamingo.hadoop jar <JAR> " + getClass().getName(), options, true);
            return -1;
        }
    }

    ////////////////////////////////////////
    // ? Hadoop Configuration? 
    ////////////////////////////////////////

    if (cmd.hasOption("i")) {
        FileInputFormat.addInputPaths(job, cmd.getOptionValue("i"));
    }

    if (cmd.hasOption("o")) {
        FileOutputFormat.setOutputPath(job, new Path(cmd.getOptionValue("o")));
    }

    if (cmd.hasOption("d")) {
        job.getConfiguration().set("delimiter", cmd.getOptionValue("d"));
    }

    // ?     .
    if (cmd.hasOption("od")) {
        if (HdfsUtils.isExist(cmd.getOptionValue("o"))) {
            HdfsUtils.deleteFromHdfs(cmd.getOptionValue("o"));
        }
    }

    return 0;
}

From source file:com.asakusafw.testdriver.tools.runner.BatchTestCollector.java

static Conf parseArguments(String[] args) throws ParseException {
    assert args != null;
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, args);

    Conf conf = new Conf();
    String importerClass = cmd.getOptionValue(OPT_EXPORTER.getLongOpt());
    try {/*w ww . j  av a 2s. c o  m*/
        conf.exporter = Class.forName(importerClass).asSubclass(ExporterDescription.class).newInstance();
    } catch (Exception e) {
        throw new IllegalArgumentException(
                MessageFormat.format(Messages.getString("BatchTestCollector.errorInvalidExporterDescription"), //$NON-NLS-1$
                        importerClass),
                e);
    }
    conf.output = cmd.getOptionValue(OPT_OUTPUT.getLongOpt());
    conf.context = new TestDriverContext(conf.exporter.getClass());

    Properties arguments = cmd.getOptionProperties(OPT_ARGUMENT.getOpt());
    conf.context.getBatchArgs().putAll(toMap(arguments));

    Properties properties = cmd.getOptionProperties(OPT_PROPERTY.getOpt());
    conf.context.getExtraConfigurations().putAll(toMap(properties));

    return conf;
}

From source file:com.asakusafw.dmdl.java.Main.java

static Configuration configure(String[] args) throws ParseException {
    assert args != null;
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, args);
    String output = cmd.getOptionValue(OPT_OUTPUT.getOpt());
    String packageName = cmd.getOptionValue(OPT_PACKAGE.getOpt());
    Charset sourceEnc = parseCharset(cmd.getOptionValue(OPT_SOURCE_ENCODING.getOpt()));
    Charset targetEnc = parseCharset(cmd.getOptionValue(OPT_TARGET_ENCODING.getOpt()));
    String sourcePaths = cmd.getOptionValue(OPT_SOURCE_PATH.getOpt());
    String plugin = cmd.getOptionValue(OPT_PLUGIN.getOpt());

    File outputDirectory = new File(output);
    DmdlSourceRepository source = buildRepository(parseFileList(sourcePaths), sourceEnc);
    ClassLoader serviceLoader = buildPluginLoader(Main.class.getClassLoader(), parseFileList(plugin));

    ModelFactory factory = Models.getModelFactory();
    return new Configuration(factory, source, Models.toName(factory, packageName),
            new Filer(outputDirectory, targetEnc), serviceLoader, Locale.getDefault());
}