List of usage examples for org.apache.commons.cli ParseException printStackTrace
public void printStackTrace()
From source file:edu.cmu.lti.oaqa.knn4qa.apps.FilterVocabulary.java
public static void main(String[] args) { String optKeys[] = { IN_VOC_FILE_PARAM, OUT_VOC_FILE_PARAM, CommonParams.MEM_FWD_INDEX_PARAM, CommonParams.MAX_WORD_QTY_PARAM }; String optDescs[] = { IN_VOC_FILE_DESC, OUT_VOC_FILE_DESC, CommonParams.MEM_FWD_INDEX_DESC, CommonParams.MAX_WORD_QTY_DESC }; boolean hasArg[] = { true, true, true, true }; ParamHelper mParamHelper = null;/*from ww w .j a v a2 s . c o m*/ try { mParamHelper = new ParamHelper(args, optKeys, optDescs, hasArg); CommandLine cmd = mParamHelper.getCommandLine(); String outputFile = cmd.getOptionValue(OUT_VOC_FILE_PARAM); if (null == outputFile) { UsageSpecify(OUT_VOC_FILE_DESC, mParamHelper.getOptions()); } String inputFile = cmd.getOptionValue(IN_VOC_FILE_PARAM); if (null == inputFile) { UsageSpecify(IN_VOC_FILE_DESC, mParamHelper.getOptions()); } int maxWordQty = Integer.MAX_VALUE; String tmpi = cmd.getOptionValue(CommonParams.MAX_WORD_QTY_PARAM); if (null != tmpi) { maxWordQty = Integer.parseInt(tmpi); } String memFwdIndxName = cmd.getOptionValue(CommonParams.MEM_FWD_INDEX_PARAM); if (null == memFwdIndxName) { UsageSpecify(CommonParams.MEM_FWD_INDEX_DESC, mParamHelper.getOptions()); } VocabularyFilterAndRecoder filter = new FrequentIndexWordFilterAndRecoder(memFwdIndxName, maxWordQty); BufferedReader finp = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(inputFile))); BufferedWriter fout = new BufferedWriter( new OutputStreamWriter(CompressUtils.createOutputStream(outputFile))); try { String line; int wordQty = 0; long addedQty = 0; long totalQty = 0; for (totalQty = 0; (line = finp.readLine()) != null;) { ++totalQty; // Skip empty lines line = line.trim(); if (line.isEmpty()) continue; GizaVocRec rec = new GizaVocRec(line); if (filter.checkWord(rec.mWord)) { rec.save(fout); addedQty++; } if (totalQty % REPORT_INTERVAL_QTY == 0) System.out.println(String.format( "Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty, wordQty, inputFile, addedQty)); } } finally { finp.close(); fout.close(); } } catch (ParseException e) { Usage("Cannot parse arguments", mParamHelper != null ? mParamHelper.getOptions() : null); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:dk.statsbiblioteket.netark.dvenabler.Command.java
@SuppressWarnings("CallToPrintStackTrace") public static void main(String[] args) throws IOException { CommandLine cli;//from w ww. j a v a 2s.c o m try { cli = new GnuParser().parse(getOptions(), args); } catch (ParseException e) { System.err.println("Exception parsing arguments"); e.printStackTrace(); usage(); return; } if (cli.hasOption(HELP)) { usage(); return; } if (!cli.hasOption(INPUT)) { System.err.println("input index must be specified"); usage(); return; } final File in = new File(cli.getOptionValue(INPUT)); if (!in.exists() || !in.isDirectory()) { System.err.println("Unable to access index folder '" + in + "'"); usage(); return; } final boolean verbose = cli.hasOption(VERBOSE); if (cli.hasOption(LIST)) { list(in, verbose); return; } if (cli.hasOption(CONVERT)) { if (!cli.hasOption(OUTPUT)) { System.err.println("convert is specified but output is missing"); usage(); return; } final File out = new File(cli.getOptionValue(OUTPUT)); if (!cli.hasOption(FIELDS)) { System.err.println("convert is specified but no fields are defined.\n" + "Use '.' to signal that no fields should be changed"); usage(); return; } final String[] rawFields = cli.getOptionValues(FIELDS); List<DVConfig> dvFields = getTweakedFields(in, rawFields); if (dvFields == null) { System.err.println("Invalid field specification"); usage(); return; } convert(in, out, dvFields, verbose); return; } System.out.println("Nothing to do"); usage(); }
From source file:bbs.monitor.ListNode.java
public static void main(String[] args) throws Exception { boolean printRawForm = false; String transport = null;//from w w w. j a v a 2 s .c o m String selfAddressAndPort = null; // parse command-line arguments Options opts = new Options(); opts.addOption("h", "help", false, "print help"); opts.addOption("r", "raw", false, "print nodes in the raw form (hostname:port)"); opts.addOption("t", "transport", true, "transpoft, UDP or TCP"); opts.addOption("s", "selfipaddress", true, "self IP address (and port)"); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, args); } catch (ParseException e) { System.out.println("There is an invalid option."); e.printStackTrace(); System.exit(1); } String optVal; if (cmd.hasOption('h')) { usage(COMMAND); System.exit(1); } if (cmd.hasOption('r')) { printRawForm = true; } optVal = cmd.getOptionValue('t'); if (optVal != null) { transport = optVal; } optVal = cmd.getOptionValue('s'); if (optVal != null) { selfAddressAndPort = optVal; } args = cmd.getArgs(); // parse initial contact String contactHostAndPort = null; int contactPort = -1; if (args.length < 1) { usage(COMMAND); System.exit(1); } contactHostAndPort = args[0]; if (args.length >= 2) contactPort = Integer.parseInt(args[1]); // // prepare a NodeCollector and invoke it // // prepare StatConfiguration StatConfiguration config = StatFactory.getDefaultConfiguration(); config.setDoUPnPNATTraversal(false); if (transport != null) { config.setMessagingTransport(transport); } if (selfAddressAndPort != null) { MessagingUtility.HostAndPort hostAndPort = MessagingUtility.parseHostnameAndPort(selfAddressAndPort, config.getSelfPort()); config.setSelfAddress(hostAndPort.getHostName()); config.setSelfPort(hostAndPort.getPort()); } // prepare MessageReceiver and initial contact MessagingProvider provider = config.deriveMessagingProvider(); MessageReceiver receiver = config.deriveMessageReceiver(provider); MessagingAddress contact; try { contact = provider.getMessagingAddress(contactHostAndPort, contactPort); } catch (IllegalArgumentException e) { contact = provider.getMessagingAddress(contactHostAndPort, config.getContactPort()); } // prepare a callback NodeCollectorCallback cb; if (printRawForm) { cb = new NodeCollectorCallback() { public void addNode(ID id, MessagingAddress address) { System.out.println(new MessagingUtility.HostAndPort(address.getHostname(), address.getPort())); // <hostname>:<port> } public void removeNode(ID id) { } }; } else { cb = new NodeCollectorCallback() { public void addNode(ID id, MessagingAddress address) { //System.out.println(HTMLUtil.convertMessagingAddressToURL(address)); System.out.println("http://" + address.getHostAddress() + ":" + address.getPort() + "/"); // http://<hostname>:port/ } public void removeNode(ID id) { } }; } // instantiate and invoke a NodeCollector NodeCollector collector = StatFactory.getNodeCollector(config, contact, cb, receiver); collector.investigate(); // stop MessageReceiver to prevent // handling incoming messages and submissions to a thread pool receiver.stop(); }
From source file:edu.internet2.middleware.psp.PspCLI.java
/** * Run this application./* w ww .ja v a2 s .c o m*/ * * @param args the command line arguments */ public static void main(String[] args) { PspOptions options = new PspOptions(args); try { if (args.length == 0) { options.printUsage(); return; } options.parseCommandLineOptions(); PspCLI pspCLI = new PspCLI(options); if (options.getInterval() == 0) { pspCLI.run(); } else { pspCLI.schedule(); } } catch (ParseException e) { options.printUsage(); System.err.println(e.getMessage()); e.printStackTrace(); } catch (ResourceException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } }
From source file:alluxio.cli.LogLevel.java
/** * Sets or gets log level of master and worker through their REST API. * * @param args same arguments as {@link LogLevel} *//* w w w . j av a2 s .c o m*/ public static void main(String[] args) { int exitCode = 1; try { logLevel(args); exitCode = 0; } catch (ParseException e) { printHelp("Unable to parse input args: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); System.err.println(String.format("Failed to set log level: %s", e.getMessage())); } System.exit(exitCode); }
From source file:dhtaccess.benchmark.ThroughputMeasure.java
public static void main(String[] args) { boolean details = false; int repeats = DEFAULT_REPEATS; int queryFreq = DEFAULT_QUERIES_PER_SEC; boolean doPut = true; // parse options Options options = new Options(); options.addOption("h", "help", false, "print help"); options.addOption("d", "details", false, "requests secret hash and TTL"); options.addOption("r", "repeats", true, "number of requests"); options.addOption("f", "freq", true, "number of queries per second"); options.addOption("n", "no-put", false, "does not put"); CommandLineParser parser = new PosixParser(); CommandLine cmd = null;// ww w. ja v a 2 s. c o m try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println("There is an invalid option."); e.printStackTrace(); System.exit(1); } String optVal; if (cmd.hasOption('h')) { usage(COMMAND); System.exit(1); } if (cmd.hasOption('d')) { details = true; } optVal = cmd.getOptionValue('r'); if (optVal != null) { repeats = Integer.parseInt(optVal); } optVal = cmd.getOptionValue('f'); if (optVal != null) { queryFreq = Integer.parseInt(optVal); } if (cmd.hasOption('n')) { doPut = false; } args = cmd.getArgs(); // parse arguments if (args.length < 1) { usage(COMMAND); System.exit(1); } (new ThroughputMeasure()).start(details, repeats, queryFreq, doPut, args); }
From source file:de.moritzrupp.stockreader.Main.java
/** * main/*w w w. j a v a 2 s .c o m*/ * @param args */ public static void main(String[] args) { initOptions(); clParser = new GnuParser(); if (args.length == 0) { // if no arguments formatter.printHelp("stockreader", header, options, footer); System.exit(1); } try { CommandLine line = clParser.parse(options, args); if (line.hasOption("h")) { printHelp(); } if (line.hasOption("v")) { System.out.println("stockreader version " + VERSION + ". Copyright 2013 by Moritz Rupp. All rights reserved.\n" + "This application is licensed under The MIT License (MIT). See https://github.com/moritzrupp/stockreader/blob/master/LICENSE.md"); System.exit(0); } if (line.hasOption("p")) { priceArg = true; } if (line.hasOption("f")) { fileArg = true; theFile = new File(line.getOptionValue("f")); } host = line.getOptionValue("host"); username = line.getOptionValue("user"); passwd = line.getOptionValue("password"); from = line.getOptionValue("from"); to = line.getOptionValue("to"); } catch (ParseException exp) { // TODO Auto-generated catch block exp.printStackTrace(); } try { reader = new StockReader(';', new StockQuote(), "UTF-8", (fileArg) ? theFile.toString() : new File(".").getCanonicalPath() + ((System.getProperty("os.name").toLowerCase().startsWith("win")) ? "\\" : "/") + "stocks.csv"); for (int i = 0; i < args.length; i++) { switch (args[i].charAt(0)) { case '-': if (args[i].length() < 2) { System.err.println("Not a valid argument: " + args[i]); printHelp(); System.exit(1); } if (args[i].charAt(1) == 'f' || (args[i].charAt(1) == '-' && args[i].charAt(2) == 'f')) { // get the path and set it to "nosymbol" args[i + 1] = "nosymbol"; } break; default: if (!args[i].equals("nosymbol")) { reader.addSymbol(args[i]); } break; } } reader.getQuotes(); reader.writeToCSV(priceArg); reader.sendmail(from, to, "Aktienkurse", host, username, passwd); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (java.text.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:net.mmberg.nadia.processor.NadiaProcessor.java
/** * @param args/*from w w w. java 2s . c o m*/ */ @SuppressWarnings("static-access") public static void main(String[] args) { Class<? extends UserInterface> ui_class = ConsoleInterface.class; //default UI String dialog_file = default_dialog; //default dialogue //process command line args Options cli_options = new Options(); cli_options.addOption("h", "help", false, "print this message"); cli_options.addOption(OptionBuilder.withLongOpt("interface").withDescription("select user interface") .hasArg(true).withArgName("console, rest").create("i")); cli_options.addOption("f", "file", true, "specify dialogue path and file, e.g. -f /res/dialogue1.xml"); cli_options.addOption("r", "resource", true, "load dialogue (by name) from resources, e.g. -r dialogue1"); cli_options.addOption("s", "store", true, "load dialogue (by name) from internal store, e.g. -s dialogue1"); CommandLineParser parser = new org.apache.commons.cli.BasicParser(); try { CommandLine cmd = parser.parse(cli_options, args); //Help if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("nadia", cli_options, true); return; } //UI if (cmd.hasOption("i")) { String interf = cmd.getOptionValue("i"); if (interf.equals("console")) ui_class = ConsoleInterface.class; else if (interf.equals("rest")) ui_class = RESTInterface.class; } //load dialogue from path file if (cmd.hasOption("f")) { dialog_file = "file:///" + cmd.getOptionValue("f"); } //load dialogue from resources if (cmd.hasOption("r")) { dialog_file = config.getProperty(NadiaProcessorConfig.DIALOGUEDIR) + "/" + cmd.getOptionValue("r") + ".xml"; } //load dialogue from internal store if (cmd.hasOption("s")) { Dialog store_dialog = DialogStore.getInstance().getDialogFromStore((cmd.getOptionValue("s"))); store_dialog.save(); dialog_file = config.getProperty(NadiaProcessorConfig.DIALOGUEDIR) + "/" + cmd.getOptionValue("s") + ".xml"; } } catch (ParseException e1) { logger.severe("NADIA: loading by main-method failed. " + e1.getMessage()); e1.printStackTrace(); } //start Nadia with selected UI default_dialog = dialog_file; NadiaProcessor nadia = new NadiaProcessor(); try { ui = ui_class.newInstance(); ui.register(nadia); ui.start(); } catch (Exception e) { e.printStackTrace(); } }
From source file:dhtaccess.benchmark.LatencyMeasure.java
public static void main(String[] args) { boolean details = false; int repeats = DEFAULT_REPEATS; boolean doPut = true; // parse options Options options = new Options(); options.addOption("h", "help", false, "print help"); options.addOption("d", "details", false, "requests secret hash and TTL"); options.addOption("r", "repeats", true, "number of requests"); options.addOption("n", "no-put", false, "does not put"); CommandLineParser parser = new PosixParser(); CommandLine cmd = null;//from w ww . ja va 2 s . co m try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println("There is an invalid option."); e.printStackTrace(); System.exit(1); } String optVal; if (cmd.hasOption('h')) { usage(COMMAND); System.exit(1); } if (cmd.hasOption('d')) { details = true; } optVal = cmd.getOptionValue('r'); if (optVal != null) { repeats = Integer.parseInt(optVal); } if (cmd.hasOption('n')) { doPut = false; } args = cmd.getArgs(); // parse arguments if (args.length < 1) { usage(COMMAND); System.exit(1); } // prepare for RPC int numAccessor = args.length; DHTAccessor[] accessorArray = new DHTAccessor[numAccessor]; try { for (int i = 0; i < numAccessor; i++) { accessorArray[i] = new DHTAccessor(args[i]); } } catch (MalformedURLException e) { e.printStackTrace(); System.exit(1); } // generate key prefix Random rnd = new Random(System.currentTimeMillis()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < KEY_PREFIX_LENGTH; i++) { sb.append((char) ('a' + rnd.nextInt(26))); } String keyPrefix = sb.toString(); String valuePrefix = VALUE_PREFIX; // benchmarking System.out.println("Repeats " + repeats + " times."); if (doPut) { System.out.println("Putting: " + keyPrefix + "<number>"); for (int i = 0; i < repeats; i++) { byte[] key = null, value = null; try { key = (keyPrefix + i).getBytes(ENCODE); value = (valuePrefix + i).getBytes(ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.exit(1); } int accIndex = rnd.nextInt(numAccessor); DHTAccessor acc = accessorArray[accIndex]; acc.put(key, value, TTL); } } System.out.println("Benchmarking by getting."); int count = 0; long startTime = System.currentTimeMillis(); if (details) { for (int i = 0; i < repeats; i++) { byte[] key = null; try { key = (keyPrefix + i).getBytes(ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.exit(1); } int accIndex = rnd.nextInt(numAccessor); DHTAccessor acc = accessorArray[accIndex]; Set<DetailedGetResult> valueSet = acc.getDetails(key); if (valueSet != null && !valueSet.isEmpty()) { count++; } } } else { for (int i = 0; i < repeats; i++) { byte[] key = null; try { key = (keyPrefix + i).getBytes(ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.exit(1); } int accIndex = rnd.nextInt(numAccessor); DHTAccessor acc = accessorArray[accIndex]; Set<byte[]> valueSet = acc.get(key); if (valueSet != null && !valueSet.isEmpty()) { count++; } } } System.out.println(System.currentTimeMillis() - startTime + " msec."); System.out.println("Rate of successful gets: " + count + " / " + repeats); }
From source file:microbiosima.Microbiosima.java
/** * @param args/*w w w. ja v a 2 s .c o m*/ * the command line arguments * @throws java.io.FileNotFoundException * @throws java.io.UnsupportedEncodingException */ public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { //Init with default values int populationSize = 500; int microSize = 1000; int numberOfSpecies = 150; int numberOfGeneration = 10000; int numberOfObservation = 100; int numberOfReplication = 1; double pctEnv = 0; double pctPool = 0; Options options = new Options(); Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print the version information and exit"); options.addOption(help); options.addOption(version); options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS") .desc("Number generation for observation [default: 100]").build()); options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP") .desc("Number of replication [default: 1]").build()); Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen") .desc("Four Parameters in the following orders: " + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation" + " [default: 500 1000 150 10000]"); options.addOption(C.build()); HelpFormatter formatter = new HelpFormatter(); String syntax = "microbiosima pctEnv pctPool"; String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n" + "required arguments:\n" + " pctEnv Percentage of environmental acquisition\n" + " pctPool Percentage of pooled environmental component\n" + "\noptional arguments:\n"; String footer = "\n"; formatter.setWidth(80); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); String[] pct_config = cmd.getArgs(); if (cmd.hasOption("h") || args.length == 0) { formatter.printHelp(syntax, header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Microbiosima " + VERSION); System.exit(0); } if (pct_config.length != 2) { System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got " + pct_config.length + ": " + Arrays.toString(pct_config)); formatter.printHelp(syntax, header, options, footer, true); System.exit(3); } else { pctEnv = Double.parseDouble(pct_config[0]); pctPool = Double.parseDouble(pct_config[1]); if (pctEnv < 0 || pctEnv > 1) { System.out.println( "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv=" + pctEnv + ")! EXIT"); System.exit(3); } if (pctPool < 0 || pctPool > 1) { System.out.println( "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool=" + pctPool + ")! EXIT"); System.exit(3); } } if (cmd.hasOption("config")) { String[] configs = cmd.getOptionValues("config"); populationSize = Integer.parseInt(configs[0]); microSize = Integer.parseInt(configs[1]); numberOfSpecies = Integer.parseInt(configs[2]); numberOfGeneration = Integer.parseInt(configs[3]); } if (cmd.hasOption("obs")) { numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs")); } if (cmd.hasOption("rep")) { numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep")); } } catch (ParseException e) { e.printStackTrace(); System.exit(3); } StringBuilder sb = new StringBuilder(); sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize) .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ") .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration) .append("\n\tNumber generation for observation: ").append(numberOfObservation) .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n"); System.out.println(sb.toString()); // System.exit(3); // LogNormalDistribution lgd=new LogNormalDistribution(0,1); // environment=lgd.sample(150); // double environment_sum=0; // for (int i=0;i<No;i++){ // environment_sum+=environment[i]; // } // for (int i=0;i<No;i++){ // environment[i]/=environment_sum; // } double[] environment = new double[numberOfSpecies]; for (int i = 0; i < numberOfSpecies; i++) { environment[i] = 1 / (double) numberOfSpecies; } for (int rep = 0; rep < numberOfReplication; rep++) { String prefix = "" + (rep + 1) + "_"; String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt"; System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix); try { PrintWriter file1 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix))); PrintWriter file2 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix))); PrintWriter file3 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix))); PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix))); PrintWriter file5 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix))); PrintWriter file6 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix))); Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0, 0); while (population.getNumberOfGeneration() < numberOfGeneration) { population.sumSpecies(); if (population.getNumberOfGeneration() % numberOfObservation == 0) { file1.println(population.gammaDiversity(true)); file2.println(population.alphaDiversity(true)); file3.print(population.betaDiversity(true)); file3.print("\t"); file3.println(population.BrayCurtis(true)); file4.println(population.printOut()); file5.println(population.interGenerationDistance()); file6.println(population.environmentPopulationDistance()); } population.getNextGen(); } file1.close(); file2.close(); file3.close(); file4.close(); file5.close(); file6.close(); } catch (IOException e) { e.printStackTrace(); } } }