List of usage examples for org.apache.commons.cli CommandLineParser parse
CommandLine parse(Options options, String[] arguments) throws ParseException;
From source file:eu.itesla_project.online.mpi.Master.java
public static void main(String[] args) throws Exception { try {// w ww .j ava 2 s.c om CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(OPTIONS, args); String mode = line.getOptionValue("m"); Path tmpDir = Paths.get(line.getOptionValue("t")); Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("f")); Path statisticsDbDir = Paths.get(line.getOptionValue("s")); String statisticsDbName = line.getOptionValue("d"); int coresPerRank = Integer.parseInt(line.getOptionValue("n")); Path stdOutArchive = line.hasOption("o") ? Paths.get(line.getOptionValue("o")) : null; MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext(); ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); ExecutorService executorService = MultiStateNetworkAwareExecutors.newCachedThreadPool(); try { MpiStatisticsFactory statisticsFactory = statisticsFactoryClass .asSubclass(MpiStatisticsFactory.class).newInstance(); MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName); try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics, mpiExecutorContext, coresPerRank, false, stdOutArchive)) { OnlineConfig config = OnlineConfig.load(); try (LocalOnlineApplication application = new LocalOnlineApplication(config, computationManager, scheduledExecutorService, executorService, true)) { switch (mode) { case "ui": System.out.println("LocalOnlineApplication created"); System.out.println("Waiting till shutdown"); // indefinitely wait for JMX commands //TimeUnit.DAYS.sleep(Integer.MAX_VALUE); synchronized (application) { try { application.wait(); } catch (InterruptedException ex) { } } break; default: throw new IllegalArgumentException("Invalid mode " + mode); } } } } finally { mpiExecutorContext.shutdown(); executorService.shutdown(); scheduledExecutorService.shutdown(); executorService.awaitTermination(15, TimeUnit.MINUTES); scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES); } } catch (ParseException e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("master", OPTIONS, true); System.exit(-1); } catch (Throwable t) { LOGGER.error(t.toString(), t); System.exit(-1); } }
From source file:de.peran.DependencyReadingStarter.java
public static void main(final String[] args) throws ParseException, FileNotFoundException { final Options options = OptionConstants.createOptions(OptionConstants.FOLDER, OptionConstants.STARTVERSION, OptionConstants.ENDVERSION, OptionConstants.OUT); final CommandLineParser parser = new DefaultParser(); final CommandLine line = parser.parse(options, args); final File projectFolder = new File(line.getOptionValue(OptionConstants.FOLDER.getName())); final File dependencyFile; if (line.hasOption(OptionConstants.OUT.getName())) { dependencyFile = new File(line.getOptionValue(OptionConstants.OUT.getName())); } else {//from www .ja va 2 s . co m dependencyFile = new File("dependencies.xml"); } File outputFile = projectFolder.getParentFile(); if (outputFile.isDirectory()) { outputFile = new File(projectFolder.getParentFile(), "ausgabe.txt"); } LOG.debug("Lese {}", projectFolder.getAbsolutePath()); final VersionControlSystem vcs = VersionControlSystem.getVersionControlSystem(projectFolder); System.setOut(new PrintStream(outputFile)); // System.setErr(new PrintStream(outputFile)); final DependencyReader reader; if (vcs.equals(VersionControlSystem.SVN)) { final String url = SVNUtils.getInstance().getWCURL(projectFolder); final List<SVNLogEntry> entries = getSVNCommits(line, url); LOG.debug("SVN commits: " + entries.stream().map(entry -> entry.getRevision()).collect(Collectors.toList())); reader = new DependencyReader(projectFolder, url, dependencyFile, entries); } else if (vcs.equals(VersionControlSystem.GIT)) { final List<GitCommit> commits = getGitCommits(line, projectFolder); reader = new DependencyReader(projectFolder, dependencyFile, commits); LOG.debug("Reader initalized"); } else { throw new RuntimeException("Unknown version control system"); } reader.readDependencies(); }
From source file:fr.inria.atlanmod.kyanos.benchmarks.XmiTraverser.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input model"); inputOpt.setArgs(1);/*from www . j av a 2 s . c o m*/ inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); options.addOption(inputOpt); options.addOption(inClassOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); URI uri = URI.createFileURI(commandLine.getOptionValue(IN)); Class<?> inClazz = XmiTraverser.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi", new XMIResourceFactoryImpl()); Resource resource = resourceSet.createResource(uri); Map<String, Object> loadOpts = new HashMap<String, Object>(); resource.load(loadOpts); LOG.log(Level.INFO, "Start counting"); int count = 0; long begin = System.currentTimeMillis(); for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator .next(), count++) ; long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End counting"); LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count)); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); resource.unload(); } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:com.artistech.tuio.dispatch.TuioPublish.java
public static void main(String[] args) throws InterruptedException { //read off the TUIO port from the command line int tuio_port = 3333; int zeromq_port = 5565; TuioSink.SerializeType serialize_method = TuioSink.SerializeType.PROTOBUF; Options options = new Options(); options.addOption("t", "tuio-port", true, "TUIO Port to listen on. (Default = 3333)"); options.addOption("z", "zeromq-port", true, "ZeroMQ Port to publish on. (Default = 5565)"); options.addOption("s", "serialize-method", true, "Serialization Method (JSON, OBJECT, Default = PROTOBUF)."); options.addOption("h", "help", false, "Show this message."); HelpFormatter formatter = new HelpFormatter(); try {/* w ww. ja v a 2 s .c om*/ CommandLineParser parser = new org.apache.commons.cli.BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { formatter.printHelp("tuio-zeromq-publish", options); return; } else { if (cmd.hasOption("t") || cmd.hasOption("tuio-port")) { tuio_port = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("z") || cmd.hasOption("zeromq-port")) { zeromq_port = Integer.parseInt(cmd.getOptionValue("z")); } if (cmd.hasOption("s") || cmd.hasOption("serialize-method")) { serialize_method = (TuioSink.SerializeType) Enum.valueOf(TuioSink.SerializeType.class, cmd.getOptionValue("s")); } } } catch (ParseException | IllegalArgumentException ex) { System.err.println("Error Processing Command Options:"); formatter.printHelp("tuio-zeromq-publish", options); return; } //start up the zmq publisher ZMQ.Context context = ZMQ.context(1); // We send updates via this socket try (ZMQ.Socket publisher = context.socket(ZMQ.PUB)) { // We send updates via this socket publisher.bind("tcp://*:" + Integer.toString(zeromq_port)); //create a new TUIO sink connected at the specified port TuioSink sink = new TuioSink(); sink.setSerializationType(serialize_method); TuioClient client = new TuioClient(tuio_port); System.out.println( MessageFormat.format("Listening to TUIO message at port: {0}", Integer.toString(tuio_port))); System.out.println( MessageFormat.format("Publishing to ZeroMQ at port: {0}", Integer.toString(zeromq_port))); System.out.println(MessageFormat.format("Serializing as: {0}", serialize_method)); client.addTuioListener(sink); client.connect(); //while not halted (infinite loop...) //read any available messages and publish while (!sink.mailbox.isHalted()) { ImmutablePair<String, byte[]> msg = sink.mailbox.getMessage(); publisher.sendMore(msg.left + "." + serialize_method.toString()); publisher.send(msg.right, 0); } //cleanup } context.term(); }
From source file:com.github.brosander.java.performance.sampler.analysis.PerformanceSampleAnalyzer.java
public static void main(String[] args) { Options options = new Options(); options.addOption("i", FILE_OPT, true, "The file to analyze."); options.addOption("o", OUTPUT_FILE_OPT, true, "The output file (default json to stdout)."); options.addOption("p", RELEVANT_PATTERN_OPT, true, "Pattern(s) to include as roots in the output (default: " + DEFAULT_PATTERN + ")"); CommandLineParser parser = new DefaultParser(); try {/*from ww w. j a v a2s. c om*/ CommandLine commandLine = parser.parse(options, args); String file = commandLine.getOptionValue(FILE_OPT); if (StringUtils.isEmpty(file)) { printUsageAndExit("Must specify file", options, 1); } Pattern relevantPattern = Pattern .compile(commandLine.getOptionValue(RELEVANT_PATTERN_OPT, DEFAULT_PATTERN)); PerformanceSampleElement performanceSampleElement = relevantElements(relevantPattern, new ObjectMapper().readValue(new File(file), PerformanceSampleElement.class)); updateCounts(performanceSampleElement); String outputFile = commandLine.getOptionValue(OUTPUT_FILE_OPT); if (StringUtils.isEmpty(outputFile)) { new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(System.out, new OutputPerformanceSampleElement(performanceSampleElement)); } else { new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(new File(outputFile), new OutputPerformanceSampleElement(performanceSampleElement)); } } catch (Exception e) { e.printStackTrace(); printUsageAndExit(e.getMessage(), options, 2); } }
From source file:com.threew.validacion.tarjetas.credito.App.java
/** * Apliacion principal o main de la librera. * @param args the command line arguments *///from w w w . java 2 s. c o m public static void main(String[] args) { /// Preguntar por los argumentos // Probar con nmeros de tarjeta Options opciones = new Options(); /// Agregar opciones opciones.addOption("n", true, "el nmero de tarjeta a validar"); opciones.addOption("c", "el cdigo CVV/CVV2 de la tarjeta a validar"); /// Analizar la linea de comandos CommandLineParser parser = new DefaultParser(); try { /// Linea de comandos CommandLine cmd = parser.parse(opciones, args); /// Preguntar si a linea de comandos se usa if (cmd.hasOption("n") == true) { String numero = cmd.getOptionValue("n"); /// Validar validar(numero); } else { validar(args[1]); } } catch (ParseException ex) { Log.error(ex.toString()); } }
From source file:StompMessagePublisher.java
public static void main(String[] args) throws ParseException { Options options = new Options(); options.addOption("h", true, "Host to connect to"); options.addOption("p", true, "Port to connect to"); options.addOption("u", true, "User name"); options.addOption("P", true, "Password"); options.addOption("d", true, "JMS Destination"); options.addOption("j", true, "JSON to send"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); // String host = "loyjbsms11-public.lolacloud.com"; // String host = "pink.cloudtroopers.ro"; String host = "localhost"; // String host = "pink.cloudtroopers.ro"; String port = "61613"; String user = "guest"; String pass = "P@ssword1"; // String destination = REWARD_POINTS_JMS_DESTINATION; // String json = REWARD_POINTS_JSON_MERGE; String destination = MEMBER_REGISTRATION_JMS_DESTINATION; String json = MEMBER_REGISTRATION_JSON; if (cmd.hasOption("h")) { host = cmd.getOptionValue("h"); }/*from w w w. j a va2 s .co m*/ if (cmd.hasOption("p")) { port = cmd.getOptionValue("p"); } if (cmd.hasOption("u")) { user = cmd.getOptionValue("u"); } if (cmd.hasOption("P")) { pass = cmd.getOptionValue("P"); } if (cmd.hasOption("d")) { destination = cmd.getOptionValue("d"); } if (cmd.hasOption("j")) { json = cmd.getOptionValue("j"); } try { StompConnection connection = new StompConnection(); connection.open(host, Integer.parseInt(port)); connection.connect(user, pass); for (int i = 0; i < 1; i++) { System.out.println(" msg " + i); String newJson = json.replaceAll("" + EXTERNAL_PROVIDER_ID, "" + (EXTERNAL_PROVIDER_ID + i)); newJson = newJson.replaceAll("" + CUSTOMER_ACCT_ID, "" + (CUSTOMER_ACCT_ID + i)); newJson = newJson.replaceAll("" + LOYALTY_ACCT_ID, "" + (LOYALTY_ACCT_ID + i)); send(host, port, user, pass, destination, newJson, connection); } connection.disconnect(); connection.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
From source file:br.usp.poli.lta.cereda.spa2run.Main.java
public static void main(String[] args) { Utils.printBanner();// w w w . jav a 2 s . c o m CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(Utils.getOptions(), args); List<Spec> specs = Utils.fromFilesToSpecs(line.getArgs()); List<Metric> metrics = Utils.fromFilesToMetrics(line); Utils.setMetrics(metrics); Utils.resetCalculations(); AdaptiveAutomaton automaton = Utils.getAutomatonFromSpecs(specs); System.out.println("SPA generated successfully:"); System.out.println("- " + specs.size() + " submachine(s) found."); if (!Utils.detectEpsilon(automaton)) { System.out.println("- No empty transitions."); } if (!metrics.isEmpty()) { System.out.println("- " + metrics.size() + " metric(s) found."); } System.out.println("\nStarting shell, please wait...\n" + "(press CTRL+C or type `:quit'\n" + "to exit the application)\n"); String query = ""; Scanner scanner = new Scanner(System.in); String prompt = "[%d] query> "; String result = "[%d] result> "; int counter = 1; do { try { String term = String.format(prompt, counter); System.out.print(term); query = scanner.nextLine().trim(); if (!query.equals(":quit")) { boolean accept = automaton.recognize(Utils.toSymbols(query)); String type = automaton.getRecognitionPaths().size() == 1 ? " (deterministic)" : " (nondeterministic)"; System.out.println(String.format(result, counter) + accept + type); if (!metrics.isEmpty()) { System.out.println(StringUtils.repeat(" ", String.format("[%d] ", counter).length()) + Utils.prettyPrintMetrics()); } System.out.println(); } } catch (Exception exception) { System.out.println(); Utils.printException(exception); System.out.println(); } counter++; Utils.resetCalculations(); } while (!query.equals(":quit")); System.out.println("That's all folks!"); } catch (ParseException nothandled) { Utils.printHelp(); } catch (Exception exception) { Utils.printException(exception); } }
From source file:com.cloudera.csd.tools.MetricTools.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new DefaultParser(); try {//from w w w .j av a 2s . co m CommandLine cmdLine = parser.parse(OPTIONS, args); if (!cmdLine.getArgList().isEmpty()) { throw new ParseException("Unexpected extra arguments: " + cmdLine.getArgList()); } Main main = new Main(cmdLine); main.run(); } catch (ParseException ex) { IOUtils.write("Error: " + ex.getMessage() + "\n", System.err); printUsageMessage(System.err); System.exit(1); } }
From source file:com.incapture.rapgen.persistence.GenPersistence.java
public static void main(String[] args) { Options options = new Options(); options.addOption("o", true, "Output root folder for kernel files"); options.addOption("g", true, "The type of grammar to generate, current options are 'SDK' or 'API'"); options.addOption("mainApiFile", true, "FileName specifying the api"); CommandLineParser cparser = new PosixParser(); try {//w w w. java 2s .com CommandLine cmd = cparser.parse(options, args); String mainApiFile = cmd.getOptionValue("mainApiFile"); String outputFolder = cmd.getOptionValue('o'); GenType genType = GenType.valueOf(cmd.getOptionValue('g')); StringTemplateGroup templateLib = loadTemplates(genType); List<StorableAttributes> storableAttributes = parseApiFiles(cmd, mainApiFile, templateLib, genType); StorableSerDeserRepo mappersRepo = StorableMappersLoader.loadSerDeserHelpers(); log.info(String.format("Got %s storable mapper(s)", mappersRepo.getAll().size())); Generator generator = new Generator(templateLib); Map<String, StringTemplate> pathToTemplate = generator.generatePersistenceFiles(storableAttributes, mappersRepo); log.info(String.format("Writing persistence files in [%s]", outputFolder)); OutputWriter.writeTemplates(outputFolder, pathToTemplate); } catch (ParseException e) { System.err.println("Error parsing command line - " + e.getMessage()); System.out.println("Usage: " + options.toString()); } catch (IOException | RecognitionException e) { System.err.println("Error running GenApi: " + ExceptionToString.format(e)); } }