Java Code Examples for org.apache.commons.cli.DefaultParser#parse()

The following examples show how to use org.apache.commons.cli.DefaultParser#parse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CliOptionsParser.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public static CliOptions parseEmbeddedModeClient(String[] args) {
	try {
		DefaultParser parser = new DefaultParser();
		CommandLine line = parser.parse(EMBEDDED_MODE_CLIENT_OPTIONS, args, true);
		return new CliOptions(
			line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
			checkSessionId(line),
			checkUrl(line, CliOptionsParser.OPTION_ENVIRONMENT),
			checkUrl(line, CliOptionsParser.OPTION_DEFAULTS),
			checkUrls(line, CliOptionsParser.OPTION_JAR),
			checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
			line.getOptionValue(CliOptionsParser.OPTION_UPDATE.getOpt())
		);
	}
	catch (ParseException e) {
		throw new SqlClientException(e.getMessage());
	}
}
 
Example 2
Source File: CliOptionsParser.java    From flink-sql-submit with Apache License 2.0 6 votes vote down vote up
public static CliOptions parseClient(String[] args) {
    if (args.length < 1) {
        throw new RuntimeException("./sql-submit -w <work_space_dir> -f <sql-file>");
    }
    try {
        DefaultParser parser = new DefaultParser();
        CommandLine line = parser.parse(CLIENT_OPTIONS, args, true);
        return new CliOptions(
                line.getOptionValue(CliOptionsParser.OPTION_SQL_FILE.getOpt()),
                line.getOptionValue(CliOptionsParser.OPTION_WORKING_SPACE.getOpt())
        );
    }
    catch (ParseException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 3
Source File: CliOptionsParser.java    From flink with Apache License 2.0 6 votes vote down vote up
public static CliOptions parseGatewayModeGateway(String[] args) {
	try {
		DefaultParser parser = new DefaultParser();
		CommandLine line = parser.parse(GATEWAY_MODE_GATEWAY_OPTIONS, args, true);
		return new CliOptions(
			line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
			null,
			null,
			checkUrl(line, CliOptionsParser.OPTION_DEFAULTS),
			checkUrls(line, CliOptionsParser.OPTION_JAR),
			checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
			null
		);
	}
	catch (ParseException e) {
		throw new SqlClientException(e.getMessage());
	}
}
 
Example 4
Source File: CliOptionsParser.java    From flink with Apache License 2.0 6 votes vote down vote up
public static CliOptions parseGatewayModeClient(String[] args) {
	try {
		DefaultParser parser = new DefaultParser();
		CommandLine line = parser.parse(GATEWAY_MODE_CLIENT_OPTIONS, args, true);
		return new CliOptions(
			line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
			checkSessionId(line),
			checkUrl(line, CliOptionsParser.OPTION_ENVIRONMENT),
			null,
			checkUrls(line, CliOptionsParser.OPTION_JAR),
			checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
			line.getOptionValue(CliOptionsParser.OPTION_UPDATE.getOpt())
		);
	}
	catch (ParseException e) {
		throw new SqlClientException(e.getMessage());
	}
}
 
Example 5
Source File: CliOptionsParser.java    From flink with Apache License 2.0 6 votes vote down vote up
public static CliOptions parseEmbeddedModeClient(String[] args) {
	try {
		DefaultParser parser = new DefaultParser();
		CommandLine line = parser.parse(EMBEDDED_MODE_CLIENT_OPTIONS, args, true);
		return new CliOptions(
			line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
			checkSessionId(line),
			checkUrl(line, CliOptionsParser.OPTION_ENVIRONMENT),
			checkUrl(line, CliOptionsParser.OPTION_DEFAULTS),
			checkUrls(line, CliOptionsParser.OPTION_JAR),
			checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
			line.getOptionValue(CliOptionsParser.OPTION_UPDATE.getOpt())
		);
	}
	catch (ParseException e) {
		throw new SqlClientException(e.getMessage());
	}
}
 
Example 6
Source File: LoadModel.java    From djl with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, ModelException, TranslateException {
    Options options = Arguments.getOptions();
    try {
        DefaultParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args, null, false);
        Arguments arguments = new Arguments(cmd);

        Classifications classifications = predict(arguments);
        logger.info("{}", classifications);
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setLeftPadding(1);
        formatter.setWidth(120);
        formatter.printHelp(e.getMessage(), options);
    }
}
 
Example 7
Source File: CliOptionsParser.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public static CliOptions parseGatewayModeGateway(String[] args) {
	try {
		DefaultParser parser = new DefaultParser();
		CommandLine line = parser.parse(GATEWAY_MODE_GATEWAY_OPTIONS, args, true);
		return new CliOptions(
			line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
			null,
			null,
			checkUrl(line, CliOptionsParser.OPTION_DEFAULTS),
			checkUrls(line, CliOptionsParser.OPTION_JAR),
			checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
			null
		);
	}
	catch (ParseException e) {
		throw new SqlClientException(e.getMessage());
	}
}
 
Example 8
Source File: CliFrontendParser.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public static CommandLine parse(Options options, String[] args, boolean stopAtNonOptions) throws CliArgsException {
	final DefaultParser parser = new DefaultParser();

	try {
		return parser.parse(options, args, stopAtNonOptions);
	} catch (ParseException e) {
		throw new CliArgsException(e.getMessage());
	}
}
 
Example 9
Source File: IntegrationTest.java    From djl with Apache License 2.0 5 votes vote down vote up
public boolean runTests(String[] args) {
    Options options = Arguments.getOptions();
    try {
        DefaultParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args, null, false);
        Arguments arguments = new Arguments(cmd);

        Duration duration = Duration.ofMinutes(arguments.getDuration());
        List<TestClass> tests = listTests(arguments, source);

        boolean testsPassed = true;
        while (!duration.isNegative()) {
            long begin = System.currentTimeMillis();

            testsPassed = testsPassed && runTests(tests);

            long delta = System.currentTimeMillis() - begin;
            duration = duration.minus(Duration.ofMillis(delta));
        }
        return testsPassed;
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setLeftPadding(1);
        formatter.setWidth(120);
        formatter.printHelp(e.getMessage(), options);
        return false;
    } catch (Throwable t) {
        logger.error("Unexpected error", t);
        return false;
    }
}
 
Example 10
Source File: CliFrontendParser.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public static RunOptions parseRunCommand(String[] args) throws CliArgsException {
	try {
		DefaultParser parser = new DefaultParser();
		CommandLine line = parser.parse(RUN_OPTIONS, args, true);
		return new RunOptions(line);
	}
	catch (ParseException e) {
		throw new CliArgsException(e.getMessage());
	}
}
 
Example 11
Source File: TrainWithOptimizers.java    From djl with Apache License 2.0 5 votes vote down vote up
public static TrainingResult runExample(String[] args)
        throws IOException, ParseException, ModelNotFoundException, MalformedModelException {
    Options options = OptimizerArguments.getOptions();
    DefaultParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, null, false);
    OptimizerArguments arguments = new OptimizerArguments(cmd);

    try (Model model = getModel(arguments)) {
        // get training dataset
        RandomAccessDataset trainDataset = getDataset(Dataset.Usage.TRAIN, arguments);
        RandomAccessDataset validationDataset = getDataset(Dataset.Usage.TEST, arguments);

        // setup training configuration
        DefaultTrainingConfig config = setupTrainingConfig(arguments);

        try (Trainer trainer = model.newTrainer(config)) {
            trainer.setMetrics(new Metrics());

            /*
             * CIFAR10 is 32x32 image and pre processed into NCHW NDArray.
             * 1st axis is batch axis, we can use 1 for initialization.
             */
            Shape inputShape = new Shape(1, 3, Cifar10.IMAGE_HEIGHT, Cifar10.IMAGE_WIDTH);

            // initialize trainer with proper input shape
            trainer.initialize(inputShape);
            EasyTrain.fit(trainer, arguments.getEpoch(), trainDataset, validationDataset);

            return trainer.getTrainingResult();
        }
    }
}
 
Example 12
Source File: PythonShellParser.java    From flink with Apache License 2.0 5 votes vote down vote up
private static CommandLine parse(Options options, String[] args) {
	final DefaultParser parser = new DefaultParser();
	try {
		return parser.parse(options, args, true);
	} catch (ParseException e) {
		throw new RuntimeException("Parser parses options failed.", e);
	}
}
 
Example 13
Source File: CommandLineParser.java    From flink with Apache License 2.0 5 votes vote down vote up
public T parse(@Nonnull String[] args) throws FlinkParseException {
	final DefaultParser parser = new DefaultParser();
	final Options options = parserResultFactory.getOptions();

	final CommandLine commandLine;
	try {
		commandLine = parser.parse(options, args, true);
	} catch (ParseException e) {
		throw new FlinkParseException("Failed to parse the command line arguments.", e);
	}

	return parserResultFactory.createResult(commandLine);
}
 
Example 14
Source File: CliFrontendParser.java    From flink with Apache License 2.0 5 votes vote down vote up
public static RunOptions parseRunCommand(String[] args) throws CliArgsException {
	try {
		DefaultParser parser = new DefaultParser();
		CommandLine line = parser.parse(RUN_OPTIONS, args, true);
		return new RunOptions(line);
	}
	catch (ParseException e) {
		throw new CliArgsException(e.getMessage());
	}
}
 
Example 15
Source File: CliFrontendParser.java    From flink with Apache License 2.0 5 votes vote down vote up
public static CommandLine parse(Options options, String[] args, boolean stopAtNonOptions) throws CliArgsException {
	final DefaultParser parser = new DefaultParser();

	try {
		return parser.parse(options, args, stopAtNonOptions);
	} catch (ParseException e) {
		throw new CliArgsException(e.getMessage());
	}
}
 
Example 16
Source File: Arguments.java    From djl with Apache License 2.0 4 votes vote down vote up
public static Arguments parseArgs(String[] args) throws ParseException {
    Options options = Arguments.getOptions();
    DefaultParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, null, false);
    return new Arguments(cmd);
}
 
Example 17
Source File: Main.java    From djl with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    Options options = Config.getOptions();
    try {
        DefaultParser cmdParser = new DefaultParser();
        CommandLine cmd = cmdParser.parse(options, args, null, false);
        Config config = new Config(cmd);

        String output = config.getOutput();
        String packageName = config.getPackageName();
        String library = config.getLibrary();
        String[] headerFiles = config.getHeaderFiles();
        String mappingFile = config.getMappingFile();

        Path dir = Paths.get(output);
        Files.createDirectories(dir);

        Properties mapping = new Properties();
        if (mappingFile != null) {
            Path file = Paths.get(mappingFile);
            if (Files.notExists(file)) {
                logger.error("mapping file does not exists: {}", mappingFile);
                System.exit(-1); // NOPMD
            }
            try (InputStream in = Files.newInputStream(file)) {
                mapping.load(in);
            }
        }

        JnaParser jnaParser = new JnaParser();
        Map<String, TypeDefine> typedefMap = jnaParser.getTypedefMap();
        Map<String, List<TypeDefine>> structMap = jnaParser.getStructMap();
        JnaGenerator generator =
                new JnaGenerator(library, packageName, typedefMap, structMap.keySet(), mapping);
        generator.init(output);

        for (String headerFile : headerFiles) {
            jnaParser.parse(headerFile);
        }

        generator.writeNativeSize();
        generator.writeStructure(structMap);
        generator.writeLibrary(jnaParser.getFunctions(), jnaParser.getEnumMap());
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setLeftPadding(1);
        formatter.setWidth(120);
        formatter.printHelp(e.getMessage(), options);
        System.exit(-1); // NOPMD
    } catch (Throwable t) {
        logger.error("", t);
        System.exit(-1); // NOPMD
    }
}
 
Example 18
Source File: Injector.java    From conga with Apache License 2.0 4 votes vote down vote up
private static void buildFromArgs(Builder builder, String[] args) {
  Options options = new Options();
  options.addOption("i", "input", true, "path of input file");
  options.addOption("o", "output", true, "path of output file");
  options.addOption("e", "encoding", true, "message encoding");
  options.addOption("a", "apipath", true, "API path");
  options.addOption("h", "host", true, "remote host");
  options.addOption(Option.builder("p").longOpt("port").hasArg(true).desc("remote port")
      .type(Number.class).build());
  options.addOption(Option.builder("u").longOpt("uri").hasArg(true)
      .desc("API URI as wss://host.apipath:port").type(URI.class).build());
  options.addOption(Option.builder("t").longOpt("timeout").hasArg(true).desc("timeout seconds")
      .type(Number.class).build());
  options.addOption(Option.builder("k").longOpt("keepalive").hasArg(true)
      .desc("keepalive interval millis").type(Number.class).build());
  options.addOption(Option.builder("b").longOpt("batches").hasArg(true)
      .desc("number of injection batches").type(Number.class).build());
  options.addOption(Option.builder("w").longOpt("wait").hasArg(true)
      .desc("wait between injection batches in seconds").type(Number.class).build());
  options.addOption("?", "help", false, "disply usage");

  DefaultParser parser = new DefaultParser();
  CommandLine cmd;
  try {
    cmd = parser.parse(options, args);

    if (cmd.hasOption("?")) {
      usage(options);
      System.exit(0);
    }
    if (cmd.hasOption("i")) {
      String input = cmd.getOptionValue("i");
      builder.inputPath(input);
    }
    // String output = cmd.getOptionValue("o");
    // builder.outputPath(output);
    if (cmd.hasOption("e")) {
      String encoding = cmd.getOptionValue("e");
      builder.encoding(encoding);
    }
    if (cmd.hasOption("a")) {
      String apiPath = cmd.getOptionValue("a");
      builder.apiPath(apiPath);
    }
    if (cmd.hasOption("h")) {
      String host = cmd.getOptionValue("h");
      builder.remoteHost(host);
    }
    if (cmd.hasOption("p")) {
      Number port = (Number) cmd.getParsedOptionValue("p");
      builder.remotePort(port.intValue());
    }
    if (cmd.hasOption("u")) {
      URI uri = (URI) cmd.getParsedOptionValue("u");
      builder.uri(uri);
    }
    if (cmd.hasOption("t")) {
      Number timeoutSeconds = (Number) cmd.getParsedOptionValue("t");
      builder.timeoutSeconds(timeoutSeconds.intValue());
    }
    if (cmd.hasOption("k")) {
      Number keepalive = (Number) cmd.getParsedOptionValue("l");
      builder.heartbeatInterval(keepalive.longValue());
    }
    if (cmd.hasOption("b")) {
      Number batches = (Number) cmd.getParsedOptionValue("b");
      builder.batches(batches.intValue());
    }
    if (cmd.hasOption("w")) {
      Number waitSeconds = (Number) cmd.getParsedOptionValue("w");
      builder.waitSeconds(waitSeconds.intValue());
    }
  } catch (ParseException e) {
    System.err.println(e.getMessage());
    usage(options);
    System.exit(1);
  }
}
 
Example 19
Source File: Exchange.java    From conga with Apache License 2.0 4 votes vote down vote up
private static void buildFromArgs(Builder builder, String[] args) {
  Options options = new Options();
  options.addOption("i", "input", true, "path of input file");
  options.addOption("o", "output", true, "path of output file");
  options.addOption("e", "encoding", true, "message encoding");
  options.addOption("c", "contextpath", true, "context path");
  options.addOption("h", "host", true, "local host");
  options.addOption(Option.builder("p").longOpt("port").hasArg(true).desc("listen port")
      .type(Number.class).build());
  options.addOption(Option.builder("k").longOpt("keepalive").hasArg(true)
      .desc("keepalive interval millis").type(Number.class).build());
  options.addOption("s", "keystorepath", true, "key store path");
  options.addOption("w", "keystorepassword", true, "key store password");
  options.addOption("?", "help", false, "disply usage");

  DefaultParser parser = new DefaultParser();
  CommandLine cmd;
  try {
    cmd = parser.parse(options, args);

    if (cmd.hasOption("?")) {
      usage(options);
      System.exit(0);
    }
    // String output = cmd.getOptionValue("o");
    // builder.outputPath(output);
    if (cmd.hasOption("e")) {
      String encoding = cmd.getOptionValue("e");
      builder.encoding(encoding);
    }
    if (cmd.hasOption("a")) {
      String apiPath = cmd.getOptionValue("a");
      builder.contextPath(apiPath);
    }
    if (cmd.hasOption("h")) {
      String host = cmd.getOptionValue("h");
      builder.host(host);
    }
    if (cmd.hasOption("s")) {
      String keyStorePath = cmd.getOptionValue("s");
      builder.keyStorePath(keyStorePath);
    }
    if (cmd.hasOption("w")) {
      String keyStorePassword = cmd.getOptionValue("w");
      builder.keyStorePassword(keyStorePassword);
    }
    if (cmd.hasOption("p")) {
      Number port = (Number) cmd.getParsedOptionValue("p");
      builder.port(port.intValue());
    }
    if (cmd.hasOption("k")) {
      Number keepalive = (Number) cmd.getParsedOptionValue("l");
      builder.heartbeatInterval(keepalive.longValue());
    }
  } catch (ParseException e) {
    System.err.println(e.getMessage());
    usage(options);
    System.exit(1);
  }
}
 
Example 20
Source File: ConnectorValidator.java    From aws-athena-query-federation with Apache License 2.0 4 votes vote down vote up
static TestConfig fromArgs(String[] args) throws ParseException
{
  log.info("Received arguments: {}", args);

  requireNonNull(args);

  Options options = new Options();
  options.addOption("f", LAMBDA_METADATA_FUNCTION_ARG, true,
                            "The name of the Lambda function to be validated. "
                                    + "Uses your configured default AWS region.");
  options.addOption("r", LAMBDA_RECORD_FUNCTION_ARG, true,
                    "The name of the Lambda function to be used to read data records. "
                            + "If not provided, this defaults to the value provided for lambda-func. "
                            + "Uses your configured default AWS region.");
  options.addOption("c", CATALOG_ID_ARG, true,
                    "The catalog name to pass to the Lambda function to be validated.");
  options.addOption("s", SCHEMA_ID_ARG, true,
                    "The schema name to be used when validating the Lambda function. "
                            + "If not provided, a random existing schema will be chosen.");
  options.addOption("t", TABLE_ID_ARG, true,
                    "The table name to be used when validating the Lambda function. "
                            + "If not provided, a random existing table will be chosen.");
  options.addOption("c", CONSTRAINTS_ARG, true,
                    "A comma-separated list of field/value pair constraints to be applied "
                            + "when reading metadata and records from the Lambda function to be validated");
  options.addOption("p", PLANNING_ONLY_ARG, false,
                    "If this option is set, then the validator will not attempt to read"
                            + " any records after calling GetSplits.");
  options.addOption("h", HELP_ARG, false, "Prints usage information.");
  DefaultParser argParser = new DefaultParser();
  CommandLine parsedArgs = argParser.parse(options, args);

  if (parsedArgs.hasOption(HELP_ARG)) {
    new HelpFormatter().printHelp(150, "./validate_connector.sh --" + LAMBDA_METADATA_FUNCTION_ARG
                                               + " lambda_func [--" + LAMBDA_RECORD_FUNCTION_ARG
                                               + " record_func] [--" + CATALOG_ID_ARG
                                               + " catalog] [--" + SCHEMA_ID_ARG
                                               + " schema [--" + TABLE_ID_ARG
                                               + " table [--" + CONSTRAINTS_ARG
                                               + " constraints]]] [--" + PLANNING_ONLY_ARG + "] [--" + HELP_ARG + "]",
                                  null,
                                  options,
                                  null);
    System.exit(0);
  }

  checkArgument(parsedArgs.hasOption(LAMBDA_METADATA_FUNCTION_ARG),
                "Lambda function must be provided via the --lambda-func or -l args!");
  String metadataFunction = parsedArgs.getOptionValue(LAMBDA_METADATA_FUNCTION_ARG);
  checkArgument(metadataFunction.equals(metadataFunction.toLowerCase()),
                "Lambda function name must be lowercase.");

  if (parsedArgs.hasOption(TABLE_ID_ARG)) {
    checkArgument(parsedArgs.hasOption(SCHEMA_ID_ARG),
                  "The --schema argument must be provided if the --table argument is provided.");
  }

  if (parsedArgs.hasOption(CONSTRAINTS_ARG)) {
    checkArgument(parsedArgs.hasOption(TABLE_ID_ARG),
                  "The --table argument must be provided if the --constraints argument is provided.");
  }

  String catalog = metadataFunction;
  if (parsedArgs.hasOption(CATALOG_ID_ARG)) {
    catalog = parsedArgs.getOptionValue(CATALOG_ID_ARG);
    checkArgument(catalog.equals(catalog.toLowerCase()),
                  "Catalog name must be lowercase.");
  }

  return new TestConfig(metadataFunction,
                        parsedArgs.hasOption(LAMBDA_RECORD_FUNCTION_ARG)
                                ? parsedArgs.getOptionValue(LAMBDA_RECORD_FUNCTION_ARG)
                                : metadataFunction,
                        catalog,
                        Optional.ofNullable(parsedArgs.getOptionValue(SCHEMA_ID_ARG)),
                        Optional.ofNullable(parsedArgs.getOptionValue(TABLE_ID_ARG)),
                        Optional.ofNullable(parsedArgs.getOptionValue(CONSTRAINTS_ARG)),
                        parsedArgs.hasOption(PLANNING_ONLY_ARG));
}