Search in sources :

Example 71 with DefaultParser

use of org.apache.commons.cli.DefaultParser in project incubator-gobblin by apache.

the class GobblinAWSTaskRunner method main.

public static void main(String[] args) throws Exception {
    final Options options = buildOptions();
    try {
        final CommandLine cmd = new DefaultParser().parse(options, args);
        if (!cmd.hasOption(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME) || !cmd.hasOption(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME) || !cmd.hasOption(GobblinAWSConfigurationKeys.APP_WORK_DIR)) {
            printUsage(options);
            System.exit(1);
        }
        if (System.getProperty("log4j.configuration") == null) {
            Log4jConfigHelper.updateLog4jConfiguration(GobblinTaskRunner.class, GobblinAWSConfigurationKeys.GOBBLIN_AWS_LOG4J_CONFIGURATION_FILE);
        }
        LOGGER.info(JvmUtils.getJvmInputArguments());
        final String applicationName = cmd.getOptionValue(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME);
        final String helixInstanceName = cmd.getOptionValue(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME);
        final String appWorkDir = cmd.getOptionValue(GobblinAWSConfigurationKeys.APP_WORK_DIR);
        final GobblinTaskRunner gobblinTaskRunner = new GobblinAWSTaskRunner(applicationName, helixInstanceName, ConfigFactory.load(), Optional.of(new Path(appWorkDir)));
        gobblinTaskRunner.start();
    } catch (ParseException pe) {
        printUsage(options);
        System.exit(1);
    }
}
Also used : Path(org.apache.hadoop.fs.Path) Options(org.apache.commons.cli.Options) CommandLine(org.apache.commons.cli.CommandLine) GobblinTaskRunner(org.apache.gobblin.cluster.GobblinTaskRunner) ParseException(org.apache.commons.cli.ParseException) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 72 with DefaultParser

use of org.apache.commons.cli.DefaultParser in project ranger by apache.

the class RangerPluginPerfTester method parseArguments.

static boolean parseArguments(final String[] args) {
    boolean ret = false;
    options.addOption("h", "help", false, "show help.");
    options.addOption("s", "service-type", true, "Service-Type");
    options.addOption("n", "service-name", true, "Ranger service-name ");
    options.addOption("a", "app-id", true, "Application-Id");
    options.addOption("r", "ranger-host", true, "Ranger host-name");
    options.addOption("t", "socket-read-timeout", true, "Read timeout on socket in milliseconds");
    options.addOption("p", "polling-interval", true, "Polling Interval in milliseconds");
    options.addOption("c", "policy-cache-dir", true, "Policy-Cache directory ");
    options.addOption("e", "policy-evaluator-type", true, "Policy-Evaluator-Type (Cached/Other");
    DefaultParser commandLineParser = new DefaultParser();
    try {
        CommandLine commandLine = commandLineParser.parse(options, args);
        if (commandLine.hasOption("h")) {
            showUsage();
            return false;
        }
        serviceType = commandLine.getOptionValue("s");
        serviceName = commandLine.getOptionValue("n");
        appId = commandLine.getOptionValue("a");
        rangerHostName = commandLine.getOptionValue("r");
        policyCacheDir = commandLine.getOptionValue("c");
        try {
            String pollingIntervalStr = commandLine.getOptionValue("p");
            pollingInterval = Integer.parseInt(pollingIntervalStr);
        } catch (NumberFormatException exception) {
        // Ignore
        }
        String useCachedPolicyEvaluatorStr = commandLine.getOptionValue("e");
        if (StringUtils.equalsIgnoreCase(useCachedPolicyEvaluatorStr, "cache")) {
            useCachedPolicyEvaluator = true;
        }
        try {
            String socketReadTimeoutStr = commandLine.getOptionValue("t");
            socketReadTimeout = Integer.parseInt(socketReadTimeoutStr);
        } catch (NumberFormatException exception) {
        // Ignore
        }
        ret = true;
    } catch (ParseException exception) {
        System.err.println("Failed to parse arguments:" + exception);
    }
    return ret;
}
Also used : CommandLine(org.apache.commons.cli.CommandLine) ParseException(org.apache.commons.cli.ParseException) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 73 with DefaultParser

use of org.apache.commons.cli.DefaultParser in project iobserve-analysis by research-iobserve.

the class PlanningMain method main.

public static void main(final String[] args) throws IOException, InitializationException, ModelHandlingErrorException {
    final CommandLineParser parser = new DefaultParser();
    final String workingDir;
    final String perOpteryxDir;
    final CommandLine commandLine;
    try {
        for (final String arg : args) {
            if (PlanningMain.LOGGER.isInfoEnabled()) {
                PlanningMain.LOGGER.info("arg: " + arg);
            }
        }
        commandLine = parser.parse(PlanningMain.createOptions(), args);
        workingDir = commandLine.getOptionValue(PlanningMain.INPUT_WORKING_DIR_OPTION);
        perOpteryxDir = commandLine.getOptionValue(PlanningMain.PEROPTERYX_DIR_OPTION);
        if (PlanningMain.LOGGER.isInfoEnabled()) {
            PlanningMain.LOGGER.info("Working dir: " + workingDir + ", PerOpteryx dir: " + perOpteryxDir);
        }
    } catch (final ParseException exp) {
        // LOG.error("CLI error: " + exp.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("planning", PlanningMain.createOptions());
        return;
    }
    final URI modelURI = URI.createFileURI(workingDir);
    if (PlanningMain.LOGGER.isInfoEnabled()) {
        PlanningMain.LOGGER.info("modelURI: " + modelURI);
    }
    final URI perOpteryxURI = URI.createFileURI(perOpteryxDir);
    if (PlanningMain.LOGGER.isInfoEnabled()) {
        PlanningMain.LOGGER.info("perOpteryxURI: " + perOpteryxURI);
        PlanningMain.LOGGER.info("lqnsURI: " + perOpteryxURI);
    }
    PalladioEclipseEnvironment.INSTANCE.setup();
    if (!commandLine.hasOption(PlanningMain.CREATE_RESOURCEENVIRONMENT_OPTION)) {
        if (PlanningMain.LOGGER.isInfoEnabled()) {
            PlanningMain.LOGGER.info("Executing optimization...");
        }
        final AdaptationData adaptationData = new AdaptationData();
        adaptationData.setRuntimeModelURI(modelURI);
        final PlanningData planningData = new PlanningData();
        planningData.setAdaptationData(adaptationData);
        planningData.setOriginalModelDir(modelURI);
        planningData.setPerOpteryxDir(perOpteryxURI);
        // Process model
        final ModelTransformer transformer = new ModelTransformer(planningData);
        transformer.transformModel();
        // Execute PerOpteryx
        final int result = 0;
        if (result == 0) {
            if (PlanningMain.LOGGER.isInfoEnabled()) {
                PlanningMain.LOGGER.info("Optimization was successful.");
            }
        } else {
            if (PlanningMain.LOGGER.isInfoEnabled()) {
                PlanningMain.LOGGER.info("Optimization failed.");
            }
        }
    } else {
        if (PlanningMain.LOGGER.isInfoEnabled()) {
            PlanningMain.LOGGER.info("Creating ResourceEnvironment...");
        }
        final PCMModelHandler modelHandler = new PCMModelHandler(new File(workingDir));
        ModelHelper.fillResourceEnvironmentFromCloudProfile(org.eclipse.emf.common.util.URI.createFileURI(workingDir), modelHandler);
        if (PlanningMain.LOGGER.isInfoEnabled()) {
            PlanningMain.LOGGER.info("ResourceEnvironment successfully created.");
        }
    }
}
Also used : PCMModelHandler(org.iobserve.model.PCMModelHandler) PlanningData(org.iobserve.planning.data.PlanningData) URI(org.eclipse.emf.common.util.URI) HelpFormatter(org.apache.commons.cli.HelpFormatter) CommandLine(org.apache.commons.cli.CommandLine) ModelTransformer(org.iobserve.planning.ModelTransformer) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) AdaptationData(org.iobserve.adaptation.data.AdaptationData) File(java.io.File) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 74 with DefaultParser

use of org.apache.commons.cli.DefaultParser in project herddb by diennea.

the class HerdDBCLI method main.

public static void main(String... args) throws IOException {
    try {
        DefaultParser parser = new DefaultParser();
        Options options = new Options();
        options.addOption("x", "url", true, "JDBC URL");
        options.addOption("u", "username", true, "JDBC Username");
        options.addOption("pwd", "password", true, "JDBC Password");
        options.addOption("q", "query", true, "Execute inline query");
        options.addOption("v", "verbose", false, "Verbose output");
        options.addOption("a", "async", false, "Use (experimental) executeBatchAsync for sending DML");
        options.addOption("s", "schema", true, "Default tablespace (SQL schema)");
        options.addOption("fi", "filter", true, "SQL filter mode: all|ddl|dml");
        options.addOption("f", "file", true, "SQL Script to execute (statement separated by 'GO' lines)");
        options.addOption("at", "autotransaction", false, "Execute scripts in autocommit=false mode and commit automatically");
        options.addOption("atbs", "autotransactionbatchsize", true, "Batch size for 'autotransaction' mode");
        options.addOption("g", "script", true, "Groovy Script to execute");
        options.addOption("i", "ignoreerrors", false, "Ignore SQL Errors during file execution");
        options.addOption("sc", "sqlconsole", false, "Execute SQL console in interactive mode");
        options.addOption("nsch", "nosqlconsolehistory", false, "Disable SQL console history");
        options.addOption("fmd", "mysql", false, "Intruct the parser that the script is coming from a MySQL Dump");
        options.addOption("rwst", "rewritestatements", false, "Rewrite all statements to use JDBC parameters");
        options.addOption("b", "backup", false, "Backup one or more tablespaces (selected with --schema)");
        options.addOption("r", "restore", false, "Restore tablespace");
        options.addOption("nl", "newleader", true, "Leader for new restored tablespace");
        options.addOption("ns", "newschema", true, "Name for new restored tablespace");
        options.addOption("tsm", "tablespacemapper", true, "Path to groovy script with a custom functin to map table names to tablespaces");
        options.addOption("dfs", "dumpfetchsize", true, "Fetch size for dump operations. Defaults to chunks of 100000 records");
        options.addOption("n", "nodeid", true, "Node id");
        options.addOption("t", "table", true, "Table name");
        options.addOption("p", "param", true, "Parameter name");
        options.addOption("val", "values", true, "Parameter values");
        options.addOption("lts", "list-tablespaces", false, "List available tablespaces");
        options.addOption("ln", "list-nodes", false, "List available nodes");
        options.addOption("sts", "show-tablespace", false, "Show full informations about a tablespace (needs -s option)");
        options.addOption("lt", "list-tables", false, "List tablespace tables (needs -s option)");
        options.addOption("st", "show-table", false, "Show full informations about a table (needs -s and -t options)");
        options.addOption("sl", "set-leader", false, "Set the leader for a tablespace (needs -s and -nl options)");
        options.addOption("ar", "add-replica", false, "Add a replica to the tablespace (needs -s and -r options)");
        options.addOption("rr", "remove-replica", false, "Remove a replica from the tablespace (needs -s and -r options)");
        options.addOption("adt", "create-tablespace", false, "Create a tablespace (needs -ns and -nl options)");
        options.addOption("at", "alter-tablespace", false, "Alter a tablespace (needs -s, -param and --values options)");
        options.addOption("d", "describe", false, "Checks and describes a raw file");
        options.addOption("ft", "filetype", true, "Checks and describes a raw file (valid options are txlog, datapage, tablecheckpoint, indexcheckpoint, tablesmetadata, bkledger");
        options.addOption("mdf", "metadatafile", true, "Tables metadata file, required for 'datapage' filetype");
        options.addOption("tsui", "tablespaceuuid", true, "Tablespace UUID, used for describing raw files");
        options.addOption("lid", "ledgerid", true, "Ledger ID on BookKeeper");
        options.addOption("fromid", "fromid", true, "Starting entry Id for filetype=bkledger, default to 0");
        options.addOption("toid", "toid", true, "Starting entry Id for filetype=bkledger, default to LastAddConfirmed");
        org.apache.commons.cli.CommandLine commandLine;
        try {
            commandLine = parser.parse(options, args);
        } catch (ParseException error) {
            println("Syntax error: " + error);
            failAndPrintHelp(options);
            return;
        }
        if (args.length == 0) {
            failAndPrintHelp(options);
            return;
        }
        String schema = commandLine.getOptionValue("schema", TableSpace.DEFAULT);
        String tablespaceuuid = commandLine.getOptionValue("tablespaceuuid", "");
        final boolean verbose = commandLine.hasOption("verbose");
        final boolean async = commandLine.hasOption("async");
        final String filter = commandLine.getOptionValue("filter", "all");
        if (!verbose) {
            LogManager.getLogManager().reset();
        }
        String file = commandLine.getOptionValue("file", "");
        String tablesmetadatafile = commandLine.getOptionValue("metadatafile", "");
        String table = commandLine.getOptionValue("table", "");
        boolean describe = commandLine.hasOption("describe");
        String filetype = commandLine.getOptionValue("filetype", "");
        long ledgerId = Long.parseLong(commandLine.getOptionValue("ledgerid", "0"));
        long fromId = Long.parseLong(commandLine.getOptionValue("fromid", "0"));
        // -1 = LAC
        long toId = Long.parseLong(commandLine.getOptionValue("toid", "-1"));
        String url = commandLine.getOptionValue("url", "jdbc:herddb:server:localhost:7000");
        String username = commandLine.getOptionValue("username", ClientConfiguration.PROPERTY_CLIENT_USERNAME_DEFAULT);
        String password = commandLine.getOptionValue("password", ClientConfiguration.PROPERTY_CLIENT_PASSWORD_DEFAULT);
        if (describe) {
            try {
                if (filetype.equals("bkledger")) {
                    try (HerdDBDataSource datasource = new HerdDBDataSource()) {
                        datasource.setUrl(url);
                        describeRawLedger(ledgerId, fromId, toId, datasource);
                    }
                } else {
                    if (file.isEmpty()) {
                        throw new IllegalArgumentException("file option is required");
                    }
                    describeRawFile(tablespaceuuid, table, tablesmetadatafile, file, filetype);
                }
            } catch (Exception error) {
                prettyPrintException(verbose, error);
                exitCode = 1;
            }
            return;
        }
        String query = commandLine.getOptionValue("query", "");
        boolean backup = commandLine.hasOption("backup");
        boolean restore = commandLine.hasOption("restore");
        String newschema = commandLine.getOptionValue("newschema", "");
        String leader = commandLine.getOptionValue("newleader", "");
        String script = commandLine.getOptionValue("script", "");
        String tablespacemapperfile = commandLine.getOptionValue("tablespacemapper", "");
        int dumpfetchsize = Integer.parseInt(commandLine.getOptionValue("dumpfetchsize", 100000 + ""));
        final boolean ignoreerrors = commandLine.hasOption("ignoreerrors");
        final boolean sqlconsole = commandLine.hasOption("sqlconsole");
        final boolean persistSqlConsoleHistory = !commandLine.hasOption("nosqlconsolehistory");
        final boolean frommysqldump = commandLine.hasOption("mysql");
        final boolean rewritestatements = commandLine.hasOption("rewritestatements") || !tablespacemapperfile.isEmpty() || frommysqldump;
        boolean autotransaction = commandLine.hasOption("autotransaction") || frommysqldump;
        int autotransactionbatchsize = Integer.parseInt(commandLine.getOptionValue("autotransactionbatchsize", 100000 + ""));
        if (!autotransaction) {
            autotransactionbatchsize = 0;
        }
        String nodeId = commandLine.getOptionValue("nodeid", "");
        String param = commandLine.getOptionValue("param", "");
        String values = commandLine.getOptionValue("values", "");
        boolean listTablespaces = commandLine.hasOption("list-tablespaces");
        boolean listNodes = commandLine.hasOption("list-nodes");
        boolean showTablespace = commandLine.hasOption("show-tablespace");
        boolean listTables = commandLine.hasOption("list-tables");
        boolean showTable = commandLine.hasOption("show-table");
        if (showTable) {
            if (table.equals("")) {
                println("Specify the table (-t <table>)");
                exitCode = 1;
                System.exit(exitCode);
            }
        }
        boolean createTablespace = commandLine.hasOption("create-tablespace");
        if (createTablespace) {
            if (newschema.equals("")) {
                println("Specify the tablespace name (--newschema <schema>)");
                exitCode = 1;
                System.exit(exitCode);
            }
            if (leader.equals("")) {
                println("Specify the leader node (--newleader <nodeid>)");
                exitCode = 1;
                System.exit(exitCode);
            }
        }
        boolean alterTablespace = commandLine.hasOption("alter-tablespace");
        if (alterTablespace) {
            if (commandLine.getOptionValue("schema", null) == null) {
                println("Cowardly refusing to assume the default schema in an alter command. Explicitly use \"-s " + TableSpace.DEFAULT + "\" instead");
                exitCode = 1;
                System.exit(exitCode);
            }
            if (param.equals("")) {
                println("Specify the parameter (--param <par>)");
                exitCode = 1;
                System.exit(exitCode);
            }
            if (values.equals("")) {
                println("Specify values (--values <vals>)");
                exitCode = 1;
                System.exit(exitCode);
            }
        }
        boolean setLeader = commandLine.hasOption("set-leader");
        if (setLeader) {
            if (leader.isEmpty()) {
                println("Specify the node (-nl <nodeid>)");
                exitCode = 1;
                System.exit(exitCode);
            }
            if (commandLine.getOptionValue("schema", null) == null) {
                println("Cowardly refusing to assume the default schema in an alter command. Explicitly use \"-s " + TableSpace.DEFAULT + "\" instead");
                exitCode = 1;
                System.exit(exitCode);
            }
        }
        boolean addReplica = commandLine.hasOption("add-replica");
        if (addReplica) {
            if (commandLine.getOptionValue("schema", null) == null) {
                println("Cowardly refusing to assume the default schema in an alter command. Explicitly use \"-s " + TableSpace.DEFAULT + "\" instead");
                exitCode = 1;
                System.exit(exitCode);
            }
            if (nodeId.equals("")) {
                println("Specify the node (-n <nodeid>)");
                exitCode = 1;
                System.exit(exitCode);
            }
        }
        boolean removeReplica = commandLine.hasOption("remove-replica");
        if (removeReplica) {
            if (commandLine.getOptionValue("schema", null) == null) {
                println("Cowardly refusing to assume the default schema in an alter command. Explicitly use \"-s " + TableSpace.DEFAULT + "\" instead");
                exitCode = 1;
                System.exit(exitCode);
            }
            if (nodeId.equals("")) {
                println("Specify the node (-n <nodeid>)");
                exitCode = 1;
                System.exit(exitCode);
            }
        }
        TableSpaceMapper tableSpaceMapper = buildTableSpaceMapper(tablespacemapperfile);
        ZookeeperMetadataStorageManager metadataStorageManager = null;
        try (HerdDBDataSource datasource = new HerdDBDataSource()) {
            datasource.setUrl(url);
            datasource.setUsername(username);
            datasource.setPassword(password);
            try (Connection connection = datasource.getConnection();
                Statement statement = connection.createStatement()) {
                metadataStorageManager = buildMetadataStorageManager(datasource);
                connection.setSchema(schema);
                if (sqlconsole) {
                    runSqlConsole(statement, PRETTY_PRINT, verbose, persistSqlConsoleHistory);
                } else if (backup) {
                    performBackup(statement, schema, file, options, connection, dumpfetchsize);
                } else if (restore) {
                    performRestore(file, leader, newschema, options, statement, connection);
                } else if (!query.isEmpty()) {
                    executeStatement(verbose, ignoreerrors, false, false, query, statement, tableSpaceMapper, false, PRETTY_PRINT);
                } else if (!file.isEmpty()) {
                    executeSqlFile(autotransactionbatchsize, connection, file, verbose, async, ignoreerrors, frommysqldump, rewritestatements, statement, tableSpaceMapper, PRETTY_PRINT, filter, datasource);
                } else if (!script.isEmpty()) {
                    executeScript(connection, datasource, statement, script);
                } else if (listTablespaces) {
                    printTableSpaces(verbose, ignoreerrors, statement, tableSpaceMapper, metadataStorageManager);
                } else if (listNodes) {
                    printNodes(verbose, ignoreerrors, statement, tableSpaceMapper, metadataStorageManager);
                } else if (showTablespace) {
                    printTableSpaceInfos(verbose, ignoreerrors, statement, tableSpaceMapper, schema, metadataStorageManager);
                } else if (listTables) {
                    listTables(verbose, ignoreerrors, statement, tableSpaceMapper, schema);
                } else if (showTable) {
                    printTableInfos(verbose, ignoreerrors, statement, tableSpaceMapper, schema, table);
                } else if (setLeader) {
                    setLeader(metadataStorageManager, schema, leader);
                } else if (addReplica) {
                    changeReplica(metadataStorageManager, schema, nodeId, ChangeReplicaAction.ADD);
                } else if (removeReplica) {
                    changeReplica(metadataStorageManager, schema, nodeId, ChangeReplicaAction.REMOVE);
                } else if (createTablespace) {
                    createTablespace(verbose, ignoreerrors, statement, tableSpaceMapper, newschema, leader);
                } else if (alterTablespace) {
                    alterTablespace(metadataStorageManager, schema, param, values);
                } else {
                    failAndPrintHelp(options);
                    return;
                }
            }
            exitCode = 0;
        } catch (Exception error) {
            prettyPrintException(verbose, error);
            exitCode = 1;
        } finally {
            if (metadataStorageManager != null) {
                try {
                    metadataStorageManager.close();
                } catch (MetadataStorageManagerException ex) {
                }
            }
        }
    } finally {
        System.exit(exitCode);
    }
}
Also used : Options(org.apache.commons.cli.Options) ZookeeperMetadataStorageManager(herddb.cluster.ZookeeperMetadataStorageManager) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) HDBConnection(herddb.client.HDBConnection) HerdDBConnection(herddb.jdbc.HerdDBConnection) HerdDBDataSource(herddb.jdbc.HerdDBDataSource) ScriptException(javax.script.ScriptException) EndOfFileException(org.jline.reader.EndOfFileException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) SQLException(java.sql.SQLException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) UserInterruptException(org.jline.reader.UserInterruptException) ParseException(org.apache.commons.cli.ParseException) MetadataStorageManagerException(herddb.metadata.MetadataStorageManagerException) MetadataStorageManagerException(herddb.metadata.MetadataStorageManagerException) ParseException(org.apache.commons.cli.ParseException) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 75 with DefaultParser

use of org.apache.commons.cli.DefaultParser in project IPK-BrAPI-Validator by plantbreeding.

the class HeadlessMain method parseArgs.

private static CommandLine parseArgs(String[] args) {
    Options options = new Options();
    Option url = new Option("u", "url", true, "The base URL to test. Should end with '/brapi/v1' or similar.");
    url.setRequired(true);
    options.addOption(url);
    Option token = new Option("t", "token", true, "(Default None) Authorization token to be sent with every request.");
    token.setRequired(false);
    options.addOption(token);
    Option version = new Option("v", "version", true, "(Default 'v2.0') The BrAPI Version to test.");
    version.setRequired(false);
    options.addOption(version);
    Option strict = new Option("s", "strict", false, "If used, the validator will not allow extra fields in response objects.");
    strict.setRequired(false);
    options.addOption(strict);
    Option csv = new Option("c", "csv", false, "Generate a CSV test report");
    csv.setRequired(false);
    options.addOption(csv);
    Option json = new Option("j", "json", false, "Generate a JSON test report");
    json.setRequired(false);
    options.addOption(json);
    Option output = new Option("o", "output", true, "Output directory to dump test report files");
    output.setRequired(false);
    options.addOption(output);
    Option help = new Option("h", "help", false, "Print this help menu");
    help.setRequired(false);
    options.addOption(help);
    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("BRAVA CLI", options);
        System.exit(1);
    }
    if (cmd.hasOption("help")) {
        formatter.printHelp("BRAVA CLI", options);
        System.exit(0);
    }
    if (cmd.hasOption("output")) {
        File outputDir = new File(cmd.getOptionValue("output"));
        if (!outputDir.exists() || !outputDir.isDirectory()) {
            LOGGER.error("Error: output directory not found " + outputDir.getAbsolutePath());
            System.exit(1);
        } else if (!outputDir.canWrite()) {
            LOGGER.error("Error: output directory access denied " + outputDir.getAbsolutePath());
            System.exit(1);
        }
    }
    return cmd;
}
Also used : HelpFormatter(org.apache.commons.cli.HelpFormatter) Options(org.apache.commons.cli.Options) CommandLine(org.apache.commons.cli.CommandLine) Option(org.apache.commons.cli.Option) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) File(java.io.File) DefaultParser(org.apache.commons.cli.DefaultParser)

Aggregations

DefaultParser (org.apache.commons.cli.DefaultParser)344 CommandLine (org.apache.commons.cli.CommandLine)290 Options (org.apache.commons.cli.Options)241 CommandLineParser (org.apache.commons.cli.CommandLineParser)234 ParseException (org.apache.commons.cli.ParseException)224 HelpFormatter (org.apache.commons.cli.HelpFormatter)116 Option (org.apache.commons.cli.Option)67 File (java.io.File)34 IOException (java.io.IOException)32 HashMap (java.util.HashMap)30 JobConfig (edu.iu.dsc.tws.api.JobConfig)26 ArrayList (java.util.ArrayList)26 Config (edu.iu.dsc.tws.api.config.Config)25 Twister2Job (edu.iu.dsc.tws.api.Twister2Job)21 Properties (java.util.Properties)19 Test (org.junit.jupiter.api.Test)19 Field (core.field.Field)17 Level (java.util.logging.Level)13 ToolOptions (com.google.api.tools.framework.tools.ToolOptions)12 OptionGroup (org.apache.commons.cli.OptionGroup)11