List of usage examples for org.apache.commons.cli DefaultParser DefaultParser
DefaultParser
From source file:gobblin.aws.GobblinAWSClusterManager.java
public static void main(String[] args) throws Exception { final Options options = buildOptions(); try {//from w ww. j a va 2 s . com final CommandLine cmd = new DefaultParser().parse(options, args); if (!cmd.hasOption(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME) || !cmd.hasOption(GobblinAWSConfigurationKeys.APP_WORK_DIR)) { printUsage(options); System.exit(1); } Log4jConfigHelper.updateLog4jConfiguration(GobblinAWSClusterManager.class, GobblinAWSConfigurationKeys.GOBBLIN_AWS_LOG4J_CONFIGURATION_FILE); LOGGER.info(JvmUtils.getJvmInputArguments()); // Note: Application id is required param for {@link GobblinClusterManager} super class // .. but has not meaning in AWS cluster context, so defaulting to a fixed value final String applicationId = "1"; final String appWorkDir = cmd.getOptionValue(GobblinAWSConfigurationKeys.APP_WORK_DIR); try (GobblinAWSClusterManager clusterMaster = new GobblinAWSClusterManager( cmd.getOptionValue(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME), applicationId, ConfigFactory.load(), Optional.of(new Path(appWorkDir)))) { clusterMaster.start(); } } catch (ParseException pe) { printUsage(options); System.exit(1); } }
From source file:com.act.reachables.CladeTraversal.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from w w w . jav a2 s . c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(CladeTraversal.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(CladeTraversal.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } String targetInchi = cl.getOptionValue(OPTION_TARGET_INCHI, PABA_INCHI); String inchiFileName = cl.getOptionValue(OPTION_OUTPUT_INCHI_FILE_NAME, DEFAULT_INCHI_FILE); String reactionsFileName = cl.getOptionValue(OPTION_OUTPUT_REACTION_FILE_NAME, DEFAULT_REACTIONS_FILE); String reactionDirectory = cl.getOptionValue(OPTION_OUTPUT_FAILED_REACTIONS_DIR_NAME, "/"); String actDataFile = cl.getOptionValue(OPTION_ACT_DATA_FILE, DEFAULT_ACTDATA_FILE); runCladeExpansion(actDataFile, targetInchi, inchiFileName, reactionsFileName, reactionDirectory); }
From source file:de.flashpixx.rrd_antlr4.CMain.java
/** * main/*from w w w . j ava 2s. c om*/ * * @param p_args command-line arguments * @throws IOException on any io error */ public static void main(final String[] p_args) throws IOException { // --- define CLI options --- final Options l_clioptions = new Options(); l_clioptions.addOption("help", false, CCommon.languagestring(CMain.class, "help")); l_clioptions.addOption("output", true, CCommon.languagestring(CMain.class, "output", DEFAULTOUTPUT)); l_clioptions.addOption("imports", true, CCommon.languagestring(CMain.class, "import")); l_clioptions.addOption("excludes", true, CCommon.languagestring(CMain.class, "exclude")); l_clioptions.addOption("grammar", true, CCommon.languagestring(CMain.class, "grammar")); l_clioptions.addOption("language", true, CCommon.languagestring(CMain.class, "language")); l_clioptions.addOption("docclean", true, CCommon.languagestring(CMain.class, "documentationclean")); l_clioptions.addOption("templates", true, CCommon.languagestring(CMain.class, "template", Arrays.asList(ETemplate.values()), DEFAULTTEMPLATE)); final CommandLine l_cli; try { l_cli = new DefaultParser().parse(l_clioptions, p_args); } catch (final Exception l_exception) { System.err .println(CCommon.languagestring(CMain.class, "parseerror", l_exception.getLocalizedMessage())); System.exit(-1); return; } // --- process CLI arguments and push configuration --- if (l_cli.hasOption("help")) { final HelpFormatter l_formatter = new HelpFormatter(); l_formatter.printHelp( new java.io.File(CMain.class.getProtectionDomain().getCodeSource().getLocation().getPath()) .getName(), l_clioptions); System.exit(0); } if (!l_cli.hasOption("grammar")) { System.err.println(CCommon.languagestring(CMain.class, "grammarnotset")); System.exit(-1); } final Tuple5<File, Set<ETemplate>, Set<File>, Set<String>, Set<String>> l_initdata = CMain.initialize( l_cli.getOptionValue("language"), l_cli.hasOption("output") ? l_cli.getOptionValue("output") : DEFAULTOUTPUT, l_cli.hasOption("templates") ? l_cli.getOptionValue("templates").split(",") : new String[] { DEFAULTTEMPLATE }, l_cli.getOptionValue("imports", "").split(","), l_cli.getOptionValue("excludes", "").split(","), l_cli.getOptionValue("docclean", "").split(",")); // --- run generator --- final IGenerator l_generator = new CStandalone(l_initdata.v1(), l_initdata.v3(), l_initdata.v5(), l_initdata.v2()); if (Arrays.stream(l_cli.getOptionValue("grammar").split(",")) .flatMap(i -> CMain.filelist(new File(i.trim()), l_initdata.v3(), l_initdata.v4())) .map(i -> l_generator.generate(i).hasError()).findFirst().isPresent()) System.exit(-1); l_generator.finish(); }
From source file:herddb.cli.HerdDBCLI.java
public static void main(String... args) throws IOException { try {//from w w w . j a v a 2 s .c om 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("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("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"); options.addOption("mdf", "metadatafile", true, "Tables metadata file, required for 'datapage' filetype"); options.addOption("tsui", "tablespaceuuid", true, "Tablespace UUID, used for describing raw files"); 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", ""); if (describe) { try { if (file.isEmpty()) { throw new IllegalArgumentException("file option is required"); } describeRawFile(tablespaceuuid, table, tablesmetadatafile, file, filetype); } catch (Exception error) { if (verbose) { error.printStackTrace(); } else { println("error:" + error); } exitCode = 1; } return; } 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); 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"); boolean sqlconsole = commandLine.hasOption("sqlconsole"); 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 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); try (HerdDBDataSource datasource = new HerdDBDataSource()) { datasource.setUrl(url); datasource.setUsername(username); datasource.setPassword(password); try (Connection connection = datasource.getConnection(); Statement statement = connection.createStatement()) { connection.setSchema(schema); if (sqlconsole) { runSqlConsole(connection, statement, PRETTY_PRINT); } 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); } else if (listNodes) { printNodes(verbose, ignoreerrors, statement, tableSpaceMapper); } else if (showTablespace) { printTableSpaceInfos(verbose, ignoreerrors, statement, tableSpaceMapper, schema); } else if (listTables) { listTables(verbose, ignoreerrors, statement, tableSpaceMapper, schema); } else if (showTable) { printTableInfos(verbose, ignoreerrors, statement, tableSpaceMapper, schema, table); } else if (addReplica) { changeReplica(verbose, ignoreerrors, statement, tableSpaceMapper, schema, nodeId, ChangeReplicaAction.ADD); } else if (removeReplica) { changeReplica(verbose, ignoreerrors, statement, tableSpaceMapper, schema, nodeId, ChangeReplicaAction.REMOVE); } else if (createTablespace) { createTablespace(verbose, ignoreerrors, statement, tableSpaceMapper, newschema, leader); } else if (alterTablespace) { alterTablespace(verbose, ignoreerrors, statement, tableSpaceMapper, schema, param, values); } else { failAndPrintHelp(options); return; } } exitCode = 0; } catch (Exception error) { if (verbose) { error.printStackTrace(); } else { println("error:" + error); } exitCode = 1; } } finally { System.exit(exitCode); } }
From source file:com.twentyn.patentSearch.DocumentSearch.java
public static void main(String[] args) throws Exception { System.out.println("Starting up..."); System.out.flush();//from ww w .j a v a 2s . co m Options opts = new Options(); opts.addOption(Option.builder("x").longOpt("index").hasArg().required().desc("Path to index file to read") .build()); opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build()); opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build()); opts.addOption(Option.builder("f").longOpt("field").hasArg().desc("The indexed field to search").build()); opts.addOption( Option.builder("q").longOpt("query").hasArg().desc("The query to use when searching").build()); opts.addOption(Option.builder("l").longOpt("list-file").hasArg() .desc("A file containing a list of queries to run in sequence").build()); opts.addOption( Option.builder("e").longOpt("enumerate").desc("Enumerate the documents in the index").build()); opts.addOption(Option.builder("d").longOpt("dump").hasArg() .desc("Dump terms in the document index for a specified field").build()); opts.addOption( Option.builder("o").longOpt("output").hasArg().desc("Write results JSON to this file.").build()); opts.addOption(Option.builder("n").longOpt("inchi-field").hasArg() .desc("The index of the InChI field if an input TSV is specified.").build()); opts.addOption(Option.builder("s").longOpt("synonym-field").hasArg() .desc("The index of the chemical synonym field if an input TSV is specified.").build()); HelpFormatter helpFormatter = new HelpFormatter(); CommandLineParser cmdLineParser = new DefaultParser(); CommandLine cmdLine = null; try { cmdLine = cmdLineParser.parse(opts, args); } catch (ParseException e) { System.out.println("Caught exception when parsing command line: " + e.getMessage()); helpFormatter.printHelp("DocumentIndexer", opts); System.exit(1); } if (cmdLine.hasOption("help")) { helpFormatter.printHelp("DocumentIndexer", opts); System.exit(0); } if (!(cmdLine.hasOption("enumerate") || cmdLine.hasOption("dump") || (cmdLine.hasOption("field") && (cmdLine.hasOption("query") || cmdLine.hasOption("list-file"))))) { System.out.println("Must specify one of 'enumerate', 'dump', or 'field' + {'query', 'list-file'}"); helpFormatter.printHelp("DocumentIndexer", opts); System.exit(1); } if (cmdLine.hasOption("verbose")) { // With help from http://stackoverflow.com/questions/23434252/programmatically-change-log-level-in-log4j2 LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration ctxConfig = ctx.getConfiguration(); LoggerConfig logConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); logConfig.setLevel(Level.DEBUG); ctx.updateLoggers(); LOGGER.debug("Verbose logging enabled"); } ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); LOGGER.info("Opening index at " + cmdLine.getOptionValue("index")); try (Directory indexDir = FSDirectory.open(new File(cmdLine.getOptionValue("index")).toPath()); IndexReader indexReader = DirectoryReader.open(indexDir);) { if (cmdLine.hasOption("enumerate")) { /* Enumerate all documents in the index. * With help from * http://stackoverflow.com/questions/2311845/is-it-possible-to-iterate-through-documents-stored-in-lucene-index */ for (int i = 0; i < indexReader.maxDoc(); i++) { Document doc = indexReader.document(i); LOGGER.info("Doc " + i + ":"); LOGGER.info(doc); } } else if (cmdLine.hasOption("dump")) { /* Dump indexed terms for a specific field. * With help from http://stackoverflow.com/questions/11148036/find-list-of-terms-indexed-by-lucene */ Terms terms = SlowCompositeReaderWrapper.wrap(indexReader).terms(cmdLine.getOptionValue("dump")); LOGGER.info("Has positions: " + terms.hasPositions()); LOGGER.info("Has offsets: " + terms.hasOffsets()); LOGGER.info("Has freqs: " + terms.hasFreqs()); LOGGER.info("Stats: " + terms.getStats()); LOGGER.info(terms); TermsEnum termsEnum = terms.iterator(); BytesRef br = null; while ((br = termsEnum.next()) != null) { LOGGER.info(" " + br.utf8ToString()); } } else { IndexSearcher searcher = new IndexSearcher(indexReader); String field = cmdLine.getOptionValue("field"); List<Pair<String, String>> queries = null; if (cmdLine.hasOption("query")) { queries = Collections.singletonList(Pair.of("", cmdLine.getOptionValue("query"))); } else if (cmdLine.hasOption("list-file")) { if (!(cmdLine.hasOption("inchi-field") && cmdLine.hasOption("synonym-field"))) { LOGGER.error("Must specify both inchi-field and synonym-field when using list-file."); System.exit(1); } Integer inchiField = Integer.parseInt(cmdLine.getOptionValue("inchi-field")); Integer synonymField = Integer.parseInt(cmdLine.getOptionValue("synonym-field")); queries = new LinkedList<>(); BufferedReader r = new BufferedReader(new FileReader(cmdLine.getOptionValue("list-file"))); String line; while ((line = r.readLine()) != null) { line = line.trim(); if (!line.isEmpty()) { // TODO: use a proper TSV reader; this is intentionally terrible as is. String[] fields = line.split("\t"); queries.add(Pair.of(fields[inchiField].replace("\"", ""), fields[synonymField])); } } r.close(); } if (queries == null || queries.size() == 0) { LOGGER.error("Found no queries to run."); return; } List<SearchResult> searchResults = new ArrayList<>(queries.size()); for (Pair<String, String> queryPair : queries) { String inchi = queryPair.getLeft(); String rawQueryString = queryPair.getRight(); /* The Lucene query parser interprets the kind of structural annotations we see in chemical entities * as query directives, which is not what we want at all. Phrase queries seem to work adequately * with the analyzer we're currently using. */ String queryString = rawQueryString.trim().toLowerCase(); String[] parts = queryString.split("\\s+"); PhraseQuery query = new PhraseQuery(); for (String p : parts) { query.add(new Term(field, p)); } LOGGER.info("Running query: " + query.toString()); BooleanQuery bq = new BooleanQuery(); bq.add(query, BooleanClause.Occur.MUST); bq.add(new TermQuery(new Term(field, "yeast")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "ferment")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "fermentation")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "fermentive")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "saccharomyces")), BooleanClause.Occur.SHOULD); LOGGER.info(" Full query: " + bq.toString()); TopDocs topDocs = searcher.search(bq, 100); ScoreDoc[] scoreDocs = topDocs.scoreDocs; if (scoreDocs.length == 0) { LOGGER.info("Search returned no results."); } List<ResultDocument> results = new ArrayList<>(scoreDocs.length); for (int i = 0; i < scoreDocs.length; i++) { ScoreDoc scoreDoc = scoreDocs[i]; Document doc = indexReader.document(scoreDoc.doc); LOGGER.info("Doc " + i + ": " + scoreDoc.doc + ", score " + scoreDoc.score + ": " + doc.get("id") + ", " + doc.get("title")); results.add(new ResultDocument(scoreDoc.doc, scoreDoc.score, doc.get("title"), doc.get("id"), null)); } LOGGER.info("----- Done with query " + query.toString()); // TODO: reduce memory usage when not writing results to an output file. searchResults.add(new SearchResult(inchi, rawQueryString, bq, results)); } if (cmdLine.hasOption("output")) { try (FileWriter writer = new FileWriter(cmdLine.getOptionValue("output"));) { writer.write(objectMapper.writeValueAsString(searchResults)); } } } } }
From source file:com.hpe.nv.samples.basic.BasicComparisonWithoutNV.java
public static void main(String[] args) throws Exception { try {//from ww w .j a v a 2s . c o m // program arguments Options options = new Options(); options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP"); options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port"); options.addOption("u", "username", true, "[mandatory] NV username"); options.addOption("w", "password", true, "[mandatory] NV password"); options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false"); options.addOption("y", "proxy", true, "[optional] Proxy server host:port"); options.addOption("a", "active-adapter-ip", true, "[optional] Active adapter IP. Default: --server-ip argument"); options.addOption("t", "site-url", true, "[optional] Site under test URL. Default: HPE Network Virtualization site URL. If you change this value, make sure to change the --xpath argument too"); options.addOption("x", "xpath", true, "[optional] Parameter for ExpectedConditions.visibilityOfElementLocated(By.xpath(...)) method. Use an xpath expression of some element in the site. Default: //div[@id='content']"); options.addOption("k", "analysis-ports", true, "[optional] A comma-separated list of ports for test analysis"); options.addOption("b", "browser", true, "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome, Firefox. Default: Firefox"); options.addOption("d", "debug", true, "[optional] Pass true to view console debug messages during execution. Default: false"); options.addOption("h", "help", false, "[optional] Generates and prints help information"); // parse and validate the command line arguments CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { // print help if help argument is passed HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("BasicComparisonWithoutNV.java", options); return; } if (line.hasOption("server-ip")) { serverIp = line.getOptionValue("server-ip"); if (serverIp.equals("0.0.0.0")) { throw new Exception( "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP"); } } else { throw new Exception("Missing argument -i/--server-ip <serverIp>"); } if (line.hasOption("server-port")) { serverPort = Integer.parseInt(line.getOptionValue("server-port")); } else { throw new Exception("Missing argument -o/--server-port <serverPort>"); } if (line.hasOption("username")) { username = line.getOptionValue("username"); } else { throw new Exception("Missing argument -u/--username <username>"); } if (line.hasOption("password")) { password = line.getOptionValue("password"); } else { throw new Exception("Missing argument -w/--password <password>"); } if (line.hasOption("ssl")) { ssl = Boolean.parseBoolean(line.getOptionValue("ssl")); } if (line.hasOption("site-url")) { siteUrl = line.getOptionValue("site-url"); } else { siteUrl = "http://www8.hp.com/us/en/software-solutions/network-virtualization/index.html"; } if (line.hasOption("xpath")) { xpath = line.getOptionValue("xpath"); } else { xpath = "//div[@id='content']"; } if (line.hasOption("proxy")) { proxySetting = line.getOptionValue("proxy"); } if (line.hasOption("active-adapter-ip")) { activeAdapterIp = line.getOptionValue("active-adapter-ip"); } else { activeAdapterIp = serverIp; } if (line.hasOption("analysis-ports")) { String analysisPortsStr = line.getOptionValue("analysis-ports"); analysisPorts = analysisPortsStr.split(","); } else { analysisPorts = new String[] { "80", "8080" }; } if (line.hasOption("browser")) { browser = line.getOptionValue("browser"); } else { browser = "Firefox"; } if (line.hasOption("debug")) { debug = Boolean.parseBoolean(line.getOptionValue("debug")); } String newLine = System.getProperty("line.separator"); String testDescription = "*** This sample demonstrates how NV helps you test your application under various network conditions. ***" + newLine + "*** This test starts by navigating to the home page in the HPE Network Virtualization website using the Selenium WebDriver. ***" + newLine + "*** This initial step runs without NV emulation and provides a basis for comparison. ***" + newLine + "*** ***" + newLine + "*** Next, the sample starts an NV test configured with a \"3G Busy\" network scenario. ***" + newLine + "*** The same step runs as before - navigating to the home page in the HPE Network Virtualization website - but this time, ***" + newLine + "*** it does so over an emulated \"3G Busy\" network as part of an NV transaction. ***" + newLine + "*** ***" + newLine + "*** When the sample finishes running, it prints a summary to the console. This summary displays a comparison of the time ***" + newLine + "*** it took to navigate to the site both with and without NV's network emulation. The results show that the slow \"3G Busy\" ***" + newLine + "*** network increases the time it takes to navigate to the site, as you would expect. ***" + newLine + "*** ***" + newLine + "*** You can view the actual steps of this sample in the BasicComparisonWithoutNV.java file. ***" + newLine; // print the sample's description System.out.println(testDescription); // start console spinner if (!debug) { spinner = new Thread(new Spinner()); spinner.start(); } // sample execution steps /***** Part 1 - Navigate to the site without using NV emulation *****/ printPartDescription("\b------ Part 1 - Navigate to the site without using NV emulation"); buildSeleniumWebDriver(); startNoNV = System.currentTimeMillis(); seleniumNavigateToPage(); stopNoNV = System.currentTimeMillis(); driverCloseAndQuit(); printPartSeparator(); /***** Part 2 - Navigate to the site using NV "3G Busy" network scenario emulation *****/ printPartDescription( "------ Part 2 - Navigate to the site using NV \"3G Busy\" network scenario emulation"); initTestManager(); setActiveAdapter(); startBusyTest(); testRunning = true; connectToTransactionManager(); startTransaction(); transactionInProgress = true; buildSeleniumWebDriver(); seleniumNavigateToPage(); stopTransaction(); transactionInProgress = false; driverCloseAndQuit(); stopTest(); testRunning = false; printPartSeparator(); /***** Part 3 - Analyze the NV test and print the results to the console *****/ printPartDescription("------ Part 3 - Analyze the NV test and print the results to the console"); analyzeTestJson(); printPartSeparator(); doneCallback(); } catch (Exception e) { try { handleError(e.getMessage()); } catch (Exception e2) { System.out.println("Error occurred: " + e2.getMessage()); } } }
From source file:com.khubla.antlr4formatter.Antlr4Formatter.java
public static void main(String[] args) { try {/*from w ww. ja v a 2 s .c o m*/ System.out.println("khubla.com Antlr4 Formatter"); /* * options */ final Options options = new Options(); final Option o1 = Option.builder().argName(INPUT_OPTION).longOpt(INPUT_OPTION).type(String.class) .hasArg().required(false).desc("input file").build(); options.addOption(o1); final Option o2 = Option.builder().argName(OUTPUT_OPTION).longOpt(OUTPUT_OPTION).type(String.class) .hasArg().required(false).desc("output file").build(); options.addOption(o2); final Option o3 = Option.builder().argName(DIR_OPTION).longOpt(DIR_OPTION).type(String.class).hasArg() .required(false).desc("input dir").build(); options.addOption(o3); /* * parse */ final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (final Exception e) { e.printStackTrace(); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("posix", options); System.exit(0); } /* * get the file */ final String inputFilename = cmd.getOptionValue(INPUT_OPTION); final String outputFilename = cmd.getOptionValue(OUTPUT_OPTION); final String inputDirOption = cmd.getOptionValue(DIR_OPTION); if (null == inputDirOption) { formatSingleFile(inputFilename, outputFilename); } else { formatDirectory(inputDirOption); } } catch (final Exception e) { e.printStackTrace(); } }
From source file:gobblin.aws.GobblinAWSTaskRunner.java
public static void main(String[] args) throws Exception { final Options options = buildOptions(); try {// w ww.j a va2s . c om 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); } 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); } }
From source file:com.twitter.heron.ckptmgr.CheckpointManager.java
public static void main(String[] args) throws IOException, ParseException, CheckpointManagerException { Options options = constructOptions(); Options helpOptions = constructHelpOptions(); CommandLineParser parser = new DefaultParser(); // parse the help options first. CommandLine cmd = parser.parse(helpOptions, args, true); if (cmd.hasOption("h")) { usage(options);//from w w w. j av a 2 s . com return; } try { // Now parse the required options cmd = parser.parse(options, args); } catch (ParseException e) { usage(options); throw new RuntimeException("Error parsing command line options ", e); } String topologyName = cmd.getOptionValue("topologyname"); String topologyId = cmd.getOptionValue("topologyid"); String ckptmgrId = cmd.getOptionValue("ckptmgrid"); int port = Integer.parseInt(cmd.getOptionValue("ckptmgrport")); String stateConfigFilename = cmd.getOptionValue("ckptmgrconfig"); String heronInternalConfig = cmd.getOptionValue("heroninternalconfig"); SystemConfig systemConfig = SystemConfig.newBuilder(true).putAll(heronInternalConfig, true).build(); CheckpointManagerConfig ckptmgrConfig = CheckpointManagerConfig.newBuilder(true) .putAll(stateConfigFilename, true).build(); // Add the SystemConfig into SingletonRegistry SingletonRegistry.INSTANCE.registerSingleton(SystemConfig.HERON_SYSTEM_CONFIG, systemConfig); // Init the logging setting and redirect the stdout and stderr to logging // For now we just set the logging level as INFO; later we may accept an argument to set it. Level loggingLevel = Level.INFO; String loggingDir = systemConfig.getHeronLoggingDirectory(); // Log to file and TMaster LoggingHelper.loggerInit(loggingLevel, true); LoggingHelper.addLoggingHandler(LoggingHelper.getFileHandler(ckptmgrId, loggingDir, true, systemConfig.getHeronLoggingMaximumSize(), systemConfig.getHeronLoggingMaximumFiles())); LoggingHelper.addLoggingHandler(new ErrorReportLoggingHandler()); // Start the actual things LOG.info(String.format( "Starting topology %s with topologyId %s with " + "Checkpoint Manager Id %s, Port: %d.", topologyName, topologyId, ckptmgrId, port)); LOG.info("System Config: " + systemConfig); CheckpointManager checkpointManager = new CheckpointManager(topologyName, topologyId, ckptmgrId, CHECKPOINT_MANAGER_HOST, port, systemConfig, ckptmgrConfig); checkpointManager.startAndLoop(); LOG.info("Loops terminated. Exiting."); }
From source file:com.hpe.nv.samples.advanced.AdvMultipleTestsSequential.java
public static void main(String[] args) throws Exception { try {/*from www . j ava 2 s. co m*/ // program arguments Options options = new Options(); options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP"); options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port"); options.addOption("u", "username", true, "[mandatory] NV username"); options.addOption("w", "password", true, "[mandatory] NV password"); options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false"); options.addOption("y", "proxy", true, "[optional] Proxy server host:port"); options.addOption("t", "site-url", true, "[optional] Site under test URL. Default: HPE Network Virtualization site URL. If you change this value, make sure to change the --xpath argument too"); options.addOption("x", "xpath", true, "[optional] Parameter for ExpectedConditions.visibilityOfElementLocated(By.xpath(...)) method. Use an xpath expression of some element in the site. Default: //div[@id='content']"); options.addOption("a", "active-adapter-ip", true, "[optional] Active adapter IP. Default: --server-ip argument"); options.addOption("f", "first-zip-result-file-path", true, "[optional] File path to store the first test analysis results as a .zip file"); options.addOption("s", "second-zip-result-file-path", true, "[optional] File path to store the second test analysis results as a .zip file"); options.addOption("k", "analysis-ports", true, "[optional] A comma-separated list of ports for test analysis"); options.addOption("b", "browser", true, "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox"); options.addOption("d", "debug", true, "[optional] Pass true to view console debug messages during execution. Default: false"); options.addOption("h", "help", false, "[optional] Generates and prints help information"); // parse and validate the command line arguments CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { // print help if help argument is passed HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("AdvMultipleTestsSequential.java", options); return; } if (line.hasOption("server-ip")) { serverIp = line.getOptionValue("server-ip"); if (serverIp.equals("0.0.0.0")) { throw new Exception( "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP"); } } else { throw new Exception("Missing argument -i/--server-ip <serverIp>"); } if (line.hasOption("server-port")) { serverPort = Integer.parseInt(line.getOptionValue("server-port")); } else { throw new Exception("Missing argument -o/--server-port <serverPort>"); } if (line.hasOption("username")) { username = line.getOptionValue("username"); } else { throw new Exception("Missing argument -u/--username <username>"); } if (line.hasOption("password")) { password = line.getOptionValue("password"); } else { throw new Exception("Missing argument -w/--password <password>"); } if (line.hasOption("ssl")) { ssl = Boolean.parseBoolean(line.getOptionValue("ssl")); } if (line.hasOption("site-url")) { siteUrl = line.getOptionValue("site-url"); } else { siteUrl = "http://www8.hp.com/us/en/software-solutions/network-virtualization/index.html"; } if (line.hasOption("xpath")) { xpath = line.getOptionValue("xpath"); } else { xpath = "//div[@id='content']"; } if (line.hasOption("first-zip-result-file-path")) { firstZipResultFilePath = line.getOptionValue("first-zip-result-file-path"); } if (line.hasOption("second-zip-result-file-path")) { secondZipResultFilePath = line.getOptionValue("second-zip-result-file-path"); } if (line.hasOption("proxy")) { proxySetting = line.getOptionValue("proxy"); } if (line.hasOption("active-adapter-ip")) { activeAdapterIp = line.getOptionValue("active-adapter-ip"); } else { activeAdapterIp = serverIp; } if (line.hasOption("analysis-ports")) { String analysisPortsStr = line.getOptionValue("analysis-ports"); analysisPorts = analysisPortsStr.split(","); } else { analysisPorts = new String[] { "80", "8080" }; } if (line.hasOption("browser")) { browser = line.getOptionValue("browser"); } else { browser = "Firefox"; } if (line.hasOption("debug")) { debug = Boolean.parseBoolean(line.getOptionValue("debug")); } String newLine = System.getProperty("line.separator"); String testDescription = "*** This sample shows how to run several tests sequentially with different network scenarios. ***" + newLine + "*** ***" + newLine + "*** You can view the actual steps of this sample in the AdvMultipleTestsSequential.java file. ***" + newLine; // print the sample's description System.out.println(testDescription); // start console spinner if (!debug) { spinner = new Thread(new Spinner()); spinner.start(); } // sample execution steps /***** Part 1 - Initialize the TestManager object and set the active adapter *****/ printPartDescription( "\b------ Part 1 - Initialize the TestManager object and set the active adapter"); initTestManager(); setActiveAdapter(); printPartSeparator(); /***** Part 2 - Start the first NV test with the "3G Busy" network scenario and run the "Home Page" transaction *****/ printPartDescription( "------ Part 2 - Start the first NV test with the \"3G Busy\" network scenario and run the \"Home Page\" transaction"); startTest("3G Busy"); testRunning = true; connectToTransactionManager(); startTransaction(); transactionInProgress = true; buildSeleniumWebDriver(); seleniumNavigateToPage(); stopTransaction(); transactionInProgress = false; driverCloseAndQuit(); printPartSeparator(); /***** Part 3 - Stop the first NV test, analyze it and print the results to the console *****/ printPartDescription( "------ Part 3 - Stop the first NV test, analyze it and print the results to the console"); stopTest(); testRunning = false; analyzeTest(); printPartSeparator(); /***** Part 4 - Start the second NV test with the "3G Good" network scenario and run the "Home Page" transaction *****/ printPartDescription( "------ Part 4 - Start the second NV test with the \"3G Good\" network scenario and run the \"Home Page\" transaction"); startTest("3G Good"); testRunning = true; connectToTransactionManager(); startTransaction(); transactionInProgress = true; buildSeleniumWebDriver(); seleniumNavigateToPage(); stopTransaction(); transactionInProgress = false; driverCloseAndQuit(); printPartSeparator(); /***** Part 5 - Stop the second NV test, analyze it and print the results to the console *****/ printPartDescription( "------ Part 3 - Stop the second NV test, analyze it and print the results to the console"); stopTest(); testRunning = false; analyzeTest(); printPartSeparator(); doneCallback(); } catch (Exception e) { try { handleError(e.getMessage()); } catch (Exception e2) { System.out.println("Error occurred: " + e2.getMessage()); } } }