@Override protected void startApplication(final CmdLineParser parser) throws Exception { final List<String> lines = FileUtils.readLines(input, Charset.defaultCharset()); final List<List<Double>> tradesPerStrategy = new ArrayList<List<Double>>(lines.size()); for (final String line : lines) { final String[] tradeStrs = Strings.split(line, ","); final List<Double> trades = new ArrayList<Double>(tradeStrs.length); for (final String tradeStr : tradeStrs) { trades.add(Double.parseDouble(tradeStr)); } tradesPerStrategy.add(trades); } final List<Double> optimalFs = new OptimalfScriptTask(tradesPerStrategy).run(); final StringBuilder optimalFsStr = new StringBuilder(); for (final Double optimalF : optimalFs) { optimalFsStr.append(optimalF); optimalFsStr.append("\n"); } FileUtils.writeStringToFile(output, optimalFsStr.toString(), Charset.defaultCharset()); }
/** * Parse the CLI arguments and return the populated parameters structure. * * @param args the CLI arguments * @return the parsed parameters, or null if failed * @throws org.kohsuke.args4j.CmdLineException if cmd line is malformed */ public static CLI create (final String... args) throws CmdLineException { logger.info("CLI args: {}", Arrays.toString(args)); CLI cli = new CLI(); final CmdLineParser parser = new CmdLineParser(cli); parser.parseArgument(args); if (args.length == 0) { cli.help = true; } if (cli.help) { printUsage(parser); } return cli; }
public static void main(final String[] args) { try { final MainArgs mainArgs = new MainArgs(); new CmdLineParser(mainArgs).parseArgument(args); if (mainArgs.isHelp()) { printUsage(); } else if (mainArgs.isVersion()) { printVersion(); } else { Guice.createInjector(new EndPointHealthModule()) .getInstance(Main.class).run(mainArgs); } } catch (final CmdLineException e) { System.err.println(e.getMessage()); printUsage(); } }
public static void main(String[] args) throws IOException { Consumer consumer = new Consumer(); CmdLineParser parser = new CmdLineParser(consumer); try { parser.parseArgument(args); } catch (CmdLineException ce) { System.err.println(ce.getMessage()); System.err.println(); System.err.println(" Options are:"); parser.printUsage(System.err); // print the list of available options System.err.println(); System.exit(0); } consumer.run(); }
public static void main(String[] args) throws IOException { Producer producer = new Producer(); CmdLineParser parser = new CmdLineParser(producer); try { parser.parseArgument(args); } catch (CmdLineException ce) { System.err.println(ce.getMessage()); System.err.println(); System.err.println(" Options are:"); parser.printUsage(System.err); // print the list of available options System.err.println(); System.exit(0); } producer.run(); }
private void doMain(final String[] arguments) throws IOException { final CmdLineParser parser = new CmdLineParser(this); if (arguments.length < 1) { parser.printUsage(out); System.exit(-1); } try { parser.parseArgument(arguments); } catch (CmdLineException clEx) { out.println("ERROR: Unable to parse command-line options: " + clEx); } out.println("The file '" + fileName + "' was provided and verbosity is set to '" + verbose + "'."); }
private void printUsage(PrintWriter writer) { // fix defaults for options like help and other 0-arg booleans OptionHandlerRegistry.getRegistry().registerHandler(Boolean.class, BooleanNoDefOptionHandler.class); OptionHandlerRegistry.getRegistry().registerHandler(boolean.class, BooleanNoDefOptionHandler.class); ParserProperties prop = ParserProperties.defaults() .withUsageWidth(80) .withOptionSorter(null); ByteArrayOutputStream buf = new ByteArrayOutputStream(); // new args instance to get correct defaults new CmdLineParser(new CliArgs(), prop) .printUsage(new OutputStreamWriter(buf, StandardCharsets.UTF_8), null); writer.println(MessageFormat.format(Messages.UsageHelp.replace("${tab}", "\t"), new String(buf.toByteArray(), StandardCharsets.UTF_8), DangerStatementOptionHandler.getMetaVariable() + '\n' + DbObjTypeOptionHandler.getMetaVariable())); }
/** Parse the command line options. * @param args the command line args as passed to the main method of the * program. * @return the parsed command line options or {@code null} if * the program needs to exit. {@code null} will be returned * if the command lines are wrong or the command line help * was displayed. */ public static Params parse(String[] args) { Params result = new Params(); CmdLineParser cmdLineParser = new CmdLineParser(result); try { if (log.isDebugEnabled()) { log.debug("Args: {}", Arrays.toString(args)); } cmdLineParser.parseArgument(args); if (result.help) { cmdLineParser.printUsage(System.err); return null; } return result; } catch (CmdLineException ex) { log.warn("Error in parsing", ex); System.err.println(ex.getMessage()); cmdLineParser.printUsage(System.err); } return null; }
private void doMain( String[] args) { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); ensureResultXmlDirectory(); generateDonutJsonFiles(); }catch (CmdLineException c){ System.err.println(c.getMessage()); System.err.println("usage: Main [options ...]"); parser.printUsage(System.err); System.exit(1); }catch (Exception e) { System.err.println(e.getMessage()); System.exit(1); } }
@Override protected void startApplication(final CmdLineParser parser) throws Exception { final List<String> lines = FileUtils.readLines(input, Charset.defaultCharset()); final List<List<Double>> tradesPerStrategy = new ArrayList<List<Double>>(lines.size()); for (final String line : lines) { final String[] tradeStrs = Strings.split(line, ","); final List<Double> trades = new ArrayList<Double>(tradeStrs.length); for (final String tradeStr : tradeStrs) { trades.add(Double.parseDouble(tradeStr)); } tradesPerStrategy.add(trades); } final List<Double> optimalFs = new OrnsteinUhlenbeckScriptTask(tradesPerStrategy).run(); final StringBuilder optimalFsStr = new StringBuilder(); for (final Double optimalF : optimalFs) { optimalFsStr.append(optimalF); optimalFsStr.append("\n"); } FileUtils.writeStringToFile(output, optimalFsStr.toString(), Charset.defaultCharset()); }
@Test public void testCreatePipelineBuilder_Sql() throws Exception { // Given Main main = new Main(); CmdLineParser cmdLineParser = new CmdLineParser(main); cmdLineParser.parseArgument( "--type", "sql", "--url", "jdbc:h2:mem:test", "--username", "sa", "--files", "target/test-classes/com/github/gquintana/beepbeep/**/*.sql"); // When PipelineBuilder pipelineBuilder = main.createPipelineBuilder(); // Then assertThat(main.url).isEqualTo("jdbc:h2:mem:test"); assertThat(pipelineBuilder).isInstanceOf(SqlPipelineBuilder.class); }
@Test public void testCreatePipelineBuilder_SqlConfiguration() throws Exception { // Given File configFile = new File(temporaryFolder.getRoot(), "sql.yml"); TestFiles.writeResource("config/sql1.yml", configFile); Main main = new Main(); CmdLineParser cmdLineParser = new CmdLineParser(main); cmdLineParser.parseArgument( "--config", configFile.getPath()); // When PipelineBuilder pipelineBuilder = main.createPipelineBuilder(); // Then assertThat(pipelineBuilder).isInstanceOf(SqlPipelineBuilder.class); assertThat(getField(pipelineBuilder, "url")).isEqualTo("jdbc:h2:mem:test"); }
public static void main(String[] args) throws ClassNotFoundException { // https://martin-thoma.com/how-to-parse-command-line-arguments-in-java/ EBoardRender.Config config = new EBoardRender.Config(); CmdLineParser parser = new CmdLineParser( config ); try { parser.parseArgument(args); } catch (CmdLineException e) { e.printStackTrace(); } Configuration conf = Configuration.getInstance(config.getConfig()); String command = conf.getCommand().trim().toUpperCase(); CommandHandler commandHandler = conf.getCommandHandlerFactory().getCommandHandler(command); commandHandler.execute(conf); }
private void parseArguments(String[] args) { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); } catch (CmdLineException e) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("java -jar reddit-history.jar [options...] arguments..."); // print the list of available options parser.printUsage(System.err); System.err.println(); System.exit(0); return; } }
@Override public void performAction(CmdLineParser parser) throws CommandException { LOGGER.debug("Creating {}", this::getModelName); final Api api = new Api( name, description, initialVersion); final ApiConfig config = new ApiConfig( endpoint, endpointType, publicApi, Lists.newArrayList(new ApiGateway(gateway))); // create final VersionAgnosticApi apiClient = buildServerApiClient(VersionAgnosticApi.class, serverVersion); ManagementApiUtil.invokeAndCheckResponse(() -> apiClient.create(orgName, api)); // configure ManagementApiUtil.invokeAndCheckResponse(() -> apiClient.configure(orgName, name, initialVersion, config)); }
@Override public void performAction(CmdLineParser parser) throws CommandException { if (!definitionStdIn && null == definitionFile) { throw new ExitWithCodeException(1, "API definition must be provided", true); } // read definition from STDIN or file String definition; try (InputStream is = (definitionStdIn ? System.in : Files.newInputStream(definitionFile))) { definition = CharStreams.toString(new InputStreamReader(is)); } catch (IOException e) { throw new CommandException(e); } LOGGER.debug("Adding definition to API '{}' with contents: {}", this::getModelName, () -> definition); ManagementApiUtil.invokeAndCheckResponse(() -> buildServerApiClient(VersionAgnosticApi.class, serverVersion).setDefinition(orgName, name, version, definitionType, new TypedString(definition))); }
@Override public void performAction(CmdLineParser parser) throws CommandException { if (!configStdIn && null == configFile) { throw new ExitWithCodeException(1, "Policy configuration must be provided", true); } // read configuration from STDIN or file String policyConfig; try (InputStream is = (configStdIn ? System.in : Files.newInputStream(configFile))) { policyConfig = CharStreams.toString(new InputStreamReader(is)); } catch (IOException e) { throw new CommandException(e); } LOGGER.debug("Adding policy '{}' to API '{}' with configuration: {}", () -> policyName, this::getModelName, () -> policyConfig); final ApiPolicy apiPolicy = new ApiPolicy(policyName); apiPolicy.setDefinitionId(policyName); ManagementApiUtil.invokeAndCheckResponse(() -> buildServerApiClient(VersionAgnosticApi.class, serverVersion).addPolicy(orgName, name, version, apiPolicy)); }
@Override public void performAction(CmdLineParser parser) throws CommandException { LOGGER.debug("Showing {}", this::getModelName); try { final A apiClient = this.buildServerApiClient(getApiClass()); final Method fetchMethod = apiClient.getClass().getMethod("fetch", String.class); @SuppressWarnings("unchecked") final M model = (M) fetchMethod.invoke(apiClient, getModelId()); LOGGER.debug("{} received: {}", this::getModelName, () -> MappingUtil.safeWriteValueAsJson(model)); processModel(model); } catch (Exception e) { throw new CommandException(e); } }
/** * @param args the arguments * @param parser the command line parser containing usage information * @return a child Command for the given args, or <code>null</code> if not found */ protected Command getChildAction(List<String> args, CmdLineParser parser) { final String commandName = args.get(0); // find implementation final Class<? extends Command> commandClass = commandMap.get(commandName); if (null != commandClass) { try { final Command command = InjectionUtil.getInjector().getInstance(commandClass); command.setParent(this); command.setCommandName(commandName); return command; } catch (ProvisionException | ConfigurationException e) { throw new CommandException(String.format("Error getting child command for args: %s", args), e); } } return null; }
/** * Parse the command line into the specified configuration. * * @param args The command line. * @param config The configuration class. * @return true if successful, false on errors such as missing arguments. */ private boolean parseCommandLine(String[] args, Configuration config) { CmdLineParser parser = new CmdLineParser(config); try { parser.parseArgument(args); if (config.getRemainingArguments() == null || config.getRemainingArguments().isEmpty()) { printUsage(parser); return false; } else { return true; } } catch (CmdLineException e) { printUsage(parser); System.out.println("Error: " + e.getMessage()); return false; } }
private void parseArguments(String[] args) { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); } catch (CmdLineException e) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("java -jar torfiles.jar [options...] arguments..."); // print the list of available options parser.printUsage(System.err); System.err.println(); System.exit(0); return; } }
public static void main(String[] args) throws IOException { final MultiEntitySinkConfig config = new MultiEntitySinkConfig(); final CmdLineParser cmdLineParser = new CmdLineParser(config); try { cmdLineParser.parseArgument(args); final OsmosisReader reader = new OsmosisReader(newInputStream(config.getSource())); final MultiEntitySink sink = new MultiEntitySink(config); sink.addObserver(new MultiEntitySinkObserver()); reader.setSink(sink); reader.run(); } catch (CmdLineException e) { System.out.println(e.getMessage()); System.out.print("Usage: java -jar osm-parquetizer.jar"); System.out.println(); cmdLineParser.printSingleLineUsage(System.out); } }
private void processArgs(String[] args) throws CmdLineException { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); if (arguments.isEmpty() && (outDir == null || imagecatUrl == null || hostPart == null || pagePrefix == null)){ throw new CmdLineException("Usage Error!"); } // make outputDir if (!outDir.exists() && outDir.isDirectory()){ LOG.info("Creating ["+outDir.getAbsolutePath()+"]"); outDir.mkdirs(); } } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println(USAGE); parser.printUsage(System.err); throw e; } }
private void processArgs(String[] args) throws CmdLineException { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); if (arguments.isEmpty() && (pageDir == null || configFile == null || solrUrl == null)) { throw new CmdLineException("Usage Error!"); } } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println(USAGE); parser.printUsage(System.err); throw e; } }
public Exporter(String[] args) { final CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(80)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); print_usage_and_exit_(parser); /* UNREACHABLE */ } // If help is requested, simply print that. if (help) { print_usage_and_exit_(parser); /* UNREACHABLE */ } // If there are no files, comlain with a non-zero exit code. if (dir == null) System.exit(EX_USAGE); dirPath = FileSystems.getDefault().getPath(dir); }
public ApiBin(String[] args) { final CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(80)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); print_usage_and_exit_(parser); /* UNREACHABLE */ } // If help is requested, simply print that. if (help) { print_usage_and_exit_(parser); /* UNREACHABLE */ } }
private void doMain(final String[] args) throws Exception { final ParserProperties properties = ParserProperties.defaults().withUsageWidth(80); final CmdLineParser parser = new CmdLineParser(this, properties); try { parser.parseArgument(args); if (_url == null) { throw new CmdLineException(parser, "URL to camera stream required.", null); } // http://1.0.0.6:8085/axis-cgi/jpg/image.cgi?resolution=640x480 Camera axis = new Camera("Axis 2100 Network Camera", _url, "", "", Constants.REFRESH_RATE ); CameraFrame frame = new CameraFrame( axis ); frame.setVisible(true); frame.run(); } catch (Exception e) { System.err.println("Usage:"); parser.printUsage(System.err); } }
/** * Initialize the verifier, using command-line arguments. * * @param args The command-line arguments passed to the program. */ public RhistMain(String[] args) { final CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(80)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); print_usage_and_exit_(parser); /* UNREACHABLE */ } // If help is requested, simply print that. if (help) { print_usage_and_exit_(parser); /* UNREACHABLE */ } // If there are no files, comlain with a non-zero exit code. if (dir == null) System.exit(EX_USAGE); path_ = FileSystems.getDefault().getPath(dir); }
/** * Initialize the verifier, using command-line arguments. * @param args The command-line arguments passed to the program. */ public Verify(String[] args) { final CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(80)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); print_usage_and_exit_(parser); /* UNREACHABLE */ } // If help is requested, simply print that. if (help) { print_usage_and_exit_(parser); /* UNREACHABLE */ } // If there are no files, comlain with a non-zero exit code. if (files.isEmpty()) System.exit(EX_USAGE); }
public void setup(String[] args) { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); if (showUsage) { System.err.println(versionString); System.err.println("Usage:"); parser.printUsage(System.err); System.exit(0); } } catch (CmdLineException e) { System.err.println("ERROR: " + e.getMessage()); System.err.println("Usage:"); parser.printUsage(System.err); System.exit(1); } tools.INDEX_DIRECTORY_NAME = index_location; }
public FreebaseToolsRunner(String[] initArgs) { // Use this to construct a tools instance with a set of command-line `initArgs', // for example, `new FreebaseTools(new String[]{"--version"})'. CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(initArgs); if (showUsage) { System.err.println(versionString); System.err.println("Usage:"); parser.printUsage(System.err); System.exit(0); } } catch (CmdLineException e) { System.err.println("ERROR: " + e.getMessage()); System.err.println("Usage:"); parser.printUsage(System.err); System.exit(1); } }
public void doMain(String... args) throws Exception { CmdLineParser cmdLineParser = new CmdLineParser(this); try { cmdLineParser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); cmdLineParser.printUsage(System.err); return; } connectToMqttBroker(); try { wait4ever(); } finally { close(); } }
public static void main(String[] args) throws Exception { // Hack, make jvm init the static fields. RealtimeConfig.loadSubtypes(); MyOptions options = new MyOptions(); CmdLineParser parser = RuntimeUtil.parseArgs(args, options); if (options.help) { parser.printUsage(System.out); return; } Plugins.loadPlugins(); IndexRConfig config = new IndexRConfig(); boolean ok = false; try { ok = runTool(options, config); } catch (Exception e) { logger.error("", e); } finally { IOUtils.closeQuietly(config); } if (ok) { System.exit(0); } else { System.exit(1); } }
public static void main(String[] args) throws Exception { RealtimeConfig.loadSubtypes(); MyOptions options = new MyOptions(); CmdLineParser parser = RuntimeUtil.parseArgs(args, options); if (options.help) { parser.printUsage(System.out); return; } Plugins.loadPlugins(); if (!hiveMode(options)) { logger.info("Failed. options: {}", options.toString()); System.exit(1); } else { logger.info("Succeed. options: {}", options.toString()); } }
/** * Parses arguments and initializes the parser. * * @param args the arguments * @param silent if <code>true</code>, no error messages will be written */ public static boolean parse(String[] args, boolean silent) throws Exception { CommandLineParser p = new CommandLineParser(); commandLineParser.set(p); p.cmdLineParser = null; try { p.cmdLineParser = new CmdLineParser(p); p.cmdLineParser.parseArgument(args); if (p.arguments.isEmpty()) { if (!silent) { printUsage(); return false; } } if (p.tabuFileName != null) { p.loadTabuTables(p.tabuFileName); } return true; } catch (CmdLineException e) { System.out.println(e.getMessage()); printUsage(); throw e; } }
private static Pattern compilePattern(CmdLineParser cmdLineParser, String patternString) { try { return Pattern.compile(patternString); } catch (IllegalArgumentException e) { explainUsageErrorAndExit(cmdLineParser, String.format("Invalid regex: %s", e.getMessage())); return null; } }
private LaunchOptions parseArguments(String[] args) { LaunchOptions res = new LaunchOptions(); CmdLineParser parser = new CmdLineParser(res); try { parser.parseArgument(args); } catch (final CmdLineException e) { printUsage(res); throw new JBakeException("Invalid commandline arguments: " + e.getMessage(), e); } return res; }
private void printUsage(Object options) { CmdLineParser parser = new CmdLineParser(options); StringWriter sw = new StringWriter(); sw.append(USAGE_PREFIX + "\n"); sw.append(ALT_USAGE_PREFIX + " <source> <destination>\n"); sw.append(ALT_USAGE_PREFIX + " [OPTION]... [<value>...]\n\n"); sw.append("Options:"); System.out.println(sw.toString()); parser.setUsageWidth(100); parser.printUsage(System.out); }