List of usage examples for org.apache.commons.cli HelpFormatter printHelp
public void printHelp(String cmdLineSyntax, Options options)
options
with the specified command line syntax. From source file:net.k3rnel.arena.server.GameServer.java
/** * If you don't know what this method does, you clearly don't know enough Java to be working on this. * @param args// ww w . java2 s .c om */ public static void main(String[] args) { /* * Pipe errors to a file */ try { PrintStream p = new PrintStream(new File("./errors.txt")); System.setErr(p); } catch (Exception e) { e.printStackTrace(); } /* * Server settings */ Options options = new Options(); options.addOption("s", "settings", true, "Can be low, medium, or high."); options.addOption("p", "players", true, "Sets the max number of players."); options.addOption("ng", "nogui", false, "Starts server in headless mode."); options.addOption("ar", "autorun", false, "Runs without asking a single question."); options.addOption("h", "help", false, "Shows this menu."); if (args.length > 0) { CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); /* * The following sets the server's settings based on the * computing ability of the server specified by the server owner. */ if (line.hasOption("settings")) { String settings = line.getOptionValue("settings"); if (settings.equalsIgnoreCase("low")) { m_movementThreads = 4; } else if (settings.equalsIgnoreCase("medium")) { m_movementThreads = 8; } else if (settings.equalsIgnoreCase("high")) { m_movementThreads = 12; } else { System.err.println("Server requires a settings parameter"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java GameServer [param] <args>", options); System.exit(0); } } else { System.err.println("Server requires a settings parameter"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java GameServer [param] <args>", options); System.exit(0); } if (line.hasOption("players")) { m_maxPlayers = Integer.parseInt(line.getOptionValue("players")); if (m_maxPlayers == 0 || m_maxPlayers == -1) m_maxPlayers = 99999; } else { System.err.println("WARNING: No maximum player count provided. Will default to 500 players."); m_maxPlayers = 500; } if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); System.err.println("Server requires a settings parameter"); formatter.printHelp("java GameServer [param] <args>", options); } /* * Create the server gui */ @SuppressWarnings("unused") GameServer gs; if (line.hasOption("nogui")) { if (line.hasOption("autorun")) gs = new GameServer(true); else gs = new GameServer(false); } else { if (line.hasOption("autorun")) System.out.println("autorun doesn't work with GUI"); gs = new GameServer(false); } } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java GameServer [param] <args>", options); } } else { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); System.err.println("Server requires a settings parameter"); formatter.printHelp("java GameServer [param] <args>", options); } }
From source file:com.artistech.tuio.mouse.MouseDriver.java
/** * Main: can take a port value as an argument. * * @param args/* w w w .j ava 2s . c om*/ */ public static void main(String args[]) { int tuio_port = 3333; Options options = new Options(); options.addOption("t", "tuio-port", true, "TUIO Port to listen on. (Default = 3333)"); options.addOption("h", "help", false, "Show this message."); HelpFormatter formatter = new HelpFormatter(); try { CommandLineParser parser = new org.apache.commons.cli.BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { formatter.printHelp("tuio-mouse-driver", options); return; } else { if (cmd.hasOption("t") || cmd.hasOption("tuio-port")) { tuio_port = Integer.parseInt(cmd.getOptionValue("t")); } } } catch (ParseException | NumberFormatException ex) { System.err.println("Error Processing Command Options:"); formatter.printHelp("tuio-mouse-driver", options); return; } try { MouseDriver mouse = new MouseDriver(); TuioClient client = new TuioClient(tuio_port); logger.info( MessageFormat.format("Listening to TUIO message at port: {0}", Integer.toString(tuio_port))); client.addTuioListener(mouse); client.connect(); } catch (AWTException e) { logger.fatal(null, e); } }
From source file:com.seanmadden.fast.ldap.main.Main.java
/** * The Main Event.//from w w w . j a v a 2 s.co m * * @param args */ @SuppressWarnings("static-access") public static void main(String[] args) { BasicConfigurator.configure(); log.debug("System initializing"); try { Logger.getRootLogger().addAppender( new FileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "log.log")); } catch (IOException e1) { log.error("Unable to open the log file..?"); } /* * Initialize the configuration engine. */ XMLConfiguration config = new XMLConfiguration(); config.setListDelimiter('|'); /* * Initialize the Command-Line parsing engine. */ CommandLineParser parser = new PosixParser(); Options opts = new Options(); opts.addOption(OptionBuilder.withLongOpt("config-file").hasArg() .withDescription("The configuration file to load").withArgName("config.xml").create("c")); opts.addOption(OptionBuilder.withLongOpt("profile").hasArg().withDescription("The profile to use") .withArgName("Default").create("p")); opts.addOption(OptionBuilder.withLongOpt("password").hasArg().withDescription("Password to connect with") .withArgName("password").create("P")); opts.addOption(OptionBuilder.withLongOpt("debug").hasArg(false).create('d')); opts.addOption(OptionBuilder.withLongOpt("verbose").hasArg(false).create('v')); File configurationFile = new File("config.xml"); try { // Parse the command-line options CommandLine cmds = parser.parse(opts, args); if (!cmds.hasOption('p')) { Logger.getRootLogger().addAppender(new GuiErrorAlerter(Level.ERROR)); } Logger.getRootLogger().setLevel(Level.ERROR); if (cmds.hasOption('v')) { Logger.getRootLogger().setLevel(Level.INFO); } if (cmds.hasOption('d')) { Logger.getRootLogger().setLevel(Level.DEBUG); } log.debug("Enabling configuration file parsing"); // The user has given us a file to parse. if (cmds.hasOption("c")) { configurationFile = new File(cmds.getOptionValue("c")); } log.debug("Config file: " + configurationFile); // Load the configuration file if (configurationFile.exists()) { config.load(configurationFile); } else { log.error("Cannot find config file"); } /* * Convert the profiles into memory */ Vector<ConnectionProfile> profs = new Vector<ConnectionProfile>(); List<?> profList = config.configurationAt("Profiles").configurationsAt("Profile"); for (Object p : profList) { SubnodeConfiguration profile = (SubnodeConfiguration) p; String name = profile.getString("[@name]"); String auth = profile.getString("LdapAuthString"); String server = profile.getString("LdapServerString"); String group = profile.getString("LdapGroupsLocation"); ConnectionProfile prof = new ConnectionProfile(name, server, auth, group); profs.add(prof); } ConnectionProfile prof = null; if (!cmds.hasOption('p')) { /* * Deploy the profile selector, to select a profile */ ProfileSelector profSel = new ProfileSelector(profs); prof = profSel.getSelection(); if (prof == null) { return; } /* * Empty the profiles and load a clean copy - then save it back * to the file */ config.clearTree("Profiles"); for (ConnectionProfile p : profSel.getProfiles()) { config.addProperty("Profiles.Profile(-1)[@name]", p.getName()); config.addProperty("Profiles.Profile.LdapAuthString", p.getLdapAuthString()); config.addProperty("Profiles.Profile.LdapServerString", p.getLdapServerString()); config.addProperty("Profiles.Profile.LdapGroupsLocation", p.getLdapGroupsString()); } config.save(configurationFile); } else { for (ConnectionProfile p : profs) { if (p.getName().equals(cmds.getOptionValue('p'))) { prof = p; break; } } } log.info("User selected " + prof); String password = ""; if (cmds.hasOption('P')) { password = cmds.getOptionValue('P'); } else { password = PasswordPrompter.promptForPassword("Password?"); } if (password.equals("")) { return; } LdapInterface ldap = new LdapInterface(prof.getLdapServerString(), prof.getLdapAuthString(), prof.getLdapGroupsString(), password); /* * Gather options information from the configuration engine for the * specified report. */ Hashtable<String, Hashtable<String, ReportOption>> reportDataStructure = new Hashtable<String, Hashtable<String, ReportOption>>(); List<?> repConfig = config.configurationAt("Reports").configurationsAt("Report"); for (Object p : repConfig) { SubnodeConfiguration repNode = (SubnodeConfiguration) p; // TODO Do something with the report profile. // Allowing the user to deploy "profiles" is a nice feature // String profile = repNode.getString("[@profile]"); String reportName = repNode.getString("[@report]"); Hashtable<String, ReportOption> reportOptions = new Hashtable<String, ReportOption>(); reportDataStructure.put(reportName, reportOptions); // Loop through the options and add each to the table. for (Object o : repNode.configurationsAt("option")) { SubnodeConfiguration option = (SubnodeConfiguration) o; String name = option.getString("[@name]"); String type = option.getString("[@type]"); String value = option.getString("[@value]"); ReportOption ro = new ReportOption(); ro.setName(name); if (type.toLowerCase().equals("boolean")) { ro.setBoolValue(Boolean.parseBoolean(value)); } else if (type.toLowerCase().equals("integer")) { ro.setIntValue(Integer.valueOf(value)); } else { // Assume a string type here then. ro.setStrValue(value); } reportOptions.put(name, ro); log.debug(ro); } } System.out.println(reportDataStructure); /* * At this point, we now need to deploy the reports window to have * the user pick a report and select some happy options to allow * that report to work. Let's go. */ /* * Deploy the Reports selector, to select a report */ Reports.getInstance().setLdapConnection(ldap); ReportsWindow reports = new ReportsWindow(Reports.getInstance().getAllReports(), reportDataStructure); Report report = reports.getSelection(); if (report == null) { return; } /* * Empty the profiles and load a clean copy - then save it back to * the file */ config.clearTree("Reports"); for (Report r : Reports.getInstance().getAllReports()) { config.addProperty("Reports.Report(-1)[@report]", r.getClass().getCanonicalName()); config.addProperty("Reports.Report[@name]", "Standard"); for (ReportOption ro : r.getOptions().values()) { config.addProperty("Reports.Report.option(-1)[@name]", ro.getName()); config.addProperty("Reports.Report.option[@type]", ro.getType()); config.addProperty("Reports.Report.option[@value]", ro.getStrValue()); } } config.save(configurationFile); ProgressBar bar = new ProgressBar(); bar.start(); report.execute(); ASCIIFormatter format = new ASCIIFormatter(); ReportResult res = report.getResult(); format.format(res, new File(res.getForName() + "_" + res.getReportName() + ".txt")); bar.stop(); JOptionPane.showMessageDialog(null, "The report is at " + res.getForName() + "_" + res.getReportName() + ".txt", "Success", JOptionPane.INFORMATION_MESSAGE); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("FAST Ldap Searcher", opts); } catch (ConfigurationException e) { e.printStackTrace(); log.fatal("OH EM GEES! Configuration errors."); } catch (Exception e) { e.printStackTrace(); } }
From source file:imageviewer.system.ImageViewerClient.java
public static void main(String[] args) { // Use Apache command-line interface (CLI) to set up the argument // handling, etc. Option help = new Option("help", "Print this message"); Option fullScreen = new Option("fullscreen", "Run imageViewer in full screen mode"); Option noNetwork = new Option("nonet", "No network connectivity"); Option client = OptionBuilder.withArgName("prefix").hasArg() .withDescription("Specify client node (prefix) for imageServer").create("client"); Option imageType = OptionBuilder.withArgName("image type").hasArg().withDescription("Open as image type") .create("type"); Option imageDir = OptionBuilder.withArgName("image directory").hasArg() .withDescription("Open images in directory").create("dir"); Option property = OptionBuilder.withArgName("property=value").hasArg().withValueSeparator() .withDescription("use value for given property").create("D"); Options o = new Options(); o.addOption(help);/*from w ww .j a v a2 s .c om*/ o.addOption(client); o.addOption(imageDir); o.addOption(fullScreen); o.addOption(noNetwork); o.addOption(property); try { CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(o, args); String jaasConfig = System.getProperty("java.security.auth.login.config"); if (jaasConfig == null) System.setProperty("java.security.auth.login.config", "config/jaas.config"); String antialising = new String("swing.aatext"); if (System.getProperty(antialising) == null) System.setProperty(antialising, "true"); @SuppressWarnings("unused") ImageViewerClient ivc = new ImageViewerClient(line); } catch (UnrecognizedOptionException uoe) { System.err.println("Unknown argument: " + uoe.getMessage()); HelpFormatter hf = new HelpFormatter(); hf.printHelp("ImageViewerClient", o); System.exit(1); } catch (Exception exc) { exc.printStackTrace(); } }
From source file:edu.ntnu.EASY.Main.java
public static void main(String[] args) { CommandLine cl = null;/* w ww. java 2s. co m*/ CommandLineParser clp = new BasicParser(); HelpFormatter hf = new HelpFormatter(); try { cl = clp.parse(options, args); } catch (ParseException e) { e.printStackTrace(); hf.printHelp(USAGE, options); System.exit(1); } if (cl.hasOption('h') || cl.hasOption('?')) { hf.printHelp(USAGE, options); System.exit(0); } Environment env = new Environment(); env.populationSize = Integer.parseInt(cl.getOptionValue('p', "200")); env.maxGenerations = Integer.parseInt(cl.getOptionValue('g', "1000")); env.fitnessThreshold = 2.0; env.mutationRate = Double.parseDouble(cl.getOptionValue('m', "0.01")); env.crossoverRate = Double.parseDouble(cl.getOptionValue('c', "0.01")); env.numChildren = Integer.parseInt(cl.getOptionValue('b', "200")); env.numParents = Integer.parseInt(cl.getOptionValue('f', "20")); env.rank = Integer.parseInt(cl.getOptionValue('r', "10")); env.elitism = Integer.parseInt(cl.getOptionValue('e', "3")); ParentSelector<double[]> parentSelector = null; int parent = Integer.parseInt(cl.getOptionValue('P', "1")); switch (parent) { case 1: parentSelector = new FitnessProportionateSelector<double[]>(env.numParents); break; case 2: parentSelector = new RankSelector<double[]>(env.rank); break; case 3: parentSelector = new SigmaScaledSelector<double[]>(env.numParents); break; case 4: parentSelector = new TournamentSelector<double[]>(env.rank, env.numParents); break; case 5: parentSelector = new StochasticTournamentSelector<double[]>(env.rank, env.numParents, 0.3); break; case 6: parentSelector = new BoltzmanSelector<double[]>(env.numParents); break; default: System.out.printf("No such parent selector: %d%n", parent); hf.printHelp(USAGE, options); System.exit(1); } AdultSelector<double[]> adultSelector = null; int adult = Integer.parseInt(cl.getOptionValue('A', "1")); switch (adult) { case 1: adultSelector = new FullGenerationalReplacement<double[]>(); break; case 2: adultSelector = new GenerationalMixing<double[]>(env.numAdults); break; case 3: adultSelector = new Overproduction<double[]>(env.numAdults); break; default: System.out.printf("No such adult selector: %d%n", adult); hf.printHelp(USAGE, options); System.exit(1); } String targetFile = cl.getOptionValue('t', "target.dat"); double[] target = null; try { target = Util.readTargetSpikeTrain(targetFile); } catch (IOException e) { System.out.printf("Couldn't read target file: %s%n", targetFile); hf.printHelp(USAGE, options); System.exit(1); } FitnessCalculator<double[]> fitCalc = null; int calc = Integer.parseInt(cl.getOptionValue('C', "1")); switch (calc) { case 1: fitCalc = new SpikeTimeFitnessCalculator(target); break; case 2: fitCalc = new SpikeIntervalFitnessCalculator(target); break; case 3: fitCalc = new WaveformFitnessCalculator(target); break; default: System.out.printf("No such fitness calculator: %d%n", calc); hf.printHelp(USAGE, options); System.exit(1); } String output = cl.getOptionValue('o', "neuron"); Incubator<double[], double[]> incubator = new NeuronIncubator( new NeuronReplicator(env.mutationRate, env.crossoverRate), env.numChildren); Evolution<double[], double[]> evo = new Evolution<double[], double[]>(fitCalc, adultSelector, parentSelector, incubator); NeuronReport report = new NeuronReport(env.maxGenerations); evo.runEvolution(env, report); try { PrintStream ps = new PrintStream(new FileOutputStream(output + ".log")); report.writeToStream(ps); } catch (FileNotFoundException e) { System.out.printf("Could not write to %s.log%n", output); } double[] bestPhenome = report.getBestPhenome(); Plot train = Plot.newPlot("Neuron").setAxis("x", "ms").setAxis("y", "activation") .with("bestPhenome", bestPhenome).with("target", target).make(); double[] averageFitness = report.getAverageFitness(); double[] bestFitness = report.getBestFitness(); Plot fitness = Plot.newPlot("Fitness").setAxis("x", "generation").setAxis("y", "fitness") .with("average", averageFitness).with("best", bestFitness).make(); train.plot(); fitness.plot(); train.writeToFile(output + "-train"); fitness.writeToFile(output + "-fitness"); }
From source file:com.consol.citrus.util.TestCaseCreator.java
/** * Main CLI method.// ww w . j a v a 2s . c om * @param args */ public static void main(String[] args) { Options options = new TestCaseCreatorCliOptions(); CommandLineParser cliParser = new GnuParser(); CommandLine cmd = null; try { cmd = cliParser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("CITRUS test creation", options); return; } TestCaseCreator creator = TestCaseCreator.build().withName(cmd.getOptionValue("name")) .withAuthor(cmd.getOptionValue("author", "Unknown")) .withDescription(cmd.getOptionValue("description", "TODO: Description")) .usePackage(cmd.getOptionValue("package", "com.consol.citrus")) .withFramework(UnitFramework.fromString(cmd.getOptionValue("framework", "testng"))); creator.createTestCase(); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("\n **** CITRUS TESTCREATOR ****", "\n CLI options:", options, ""); } }
From source file:de.dfki.dmas.owls2wsdl.core.OWLS2WSDL.java
public static void main(String[] args) { // http://jakarta.apache.org/commons/cli/usage.html System.out.println("ARG COUNT: " + args.length); OWLS2WSDLSettings.getInstance();//from w w w .j av a 2s .c om Options options = new Options(); Option help = new Option("help", "print help message"); options.addOption(help); // create the parser CommandLineParser parser = new GnuParser(); CommandLine cmdLine = null; for (int i = 0; i < args.length; i++) { System.out.println("ARG: " + args[i].toString()); } if (args.length > 0) { if (args[args.length - 1].toString().endsWith(".owl")) { // -kbdir d:\tmp\KB http://127.0.0.1/ontology/ActorDefault.owl Option test = new Option("test", "parse only, don't save"); @SuppressWarnings("static-access") Option kbdir = OptionBuilder.withArgName("dir").hasArg() .withDescription("knowledgebase directory; necessary").create("kbdir"); options.addOption(test); options.addOption(kbdir); try { cmdLine = parser.parse(options, args); if (cmdLine.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("owls2wsdl [options] FILE.owl", options); System.exit(0); } } catch (ParseException exp) { // oops, something went wrong System.out.println("Error: Parsing failed, reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("owls2wsdl", options, true); } if (args.length == 1) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("owls2wsdl [options] FILE.owl", options); System.out.println("Error: Option -kbdir is missing."); System.exit(0); } else { String ontURI = args[args.length - 1].toString(); String persistentName = "KB_" + ontURI.substring(ontURI.lastIndexOf("/") + 1, ontURI.lastIndexOf(".")) + "-MAP.xml"; try { if (cmdLine.hasOption("kbdir")) { String kbdirValue = cmdLine.getOptionValue("kbdir"); if (new File(kbdirValue).isDirectory()) { DatatypeParser p = new DatatypeParser(); p.parse(args[args.length - 1].toString()); p.getAbstractDatatypeKBData(); if (!cmdLine.hasOption("test")) { System.out.println("AUSGABE: " + kbdirValue + File.separator + persistentName); FileOutputStream ausgabeStream = new FileOutputStream( kbdirValue + File.separator + persistentName); AbstractDatatypeKB.getInstance().marshallAsXML(ausgabeStream, true); // System.out); } } } } catch (java.net.MalformedURLException murle) { System.err.println("MalformedURLException: " + murle.getMessage()); System.err.println("Try something like: http://127.0.0.1/ontology/my_ontology.owl"); } catch (Exception e) { System.err.println("Exception: " + e.toString()); } } } else if (args[args.length - 1].toString().endsWith(".xml")) { // -owlclass http://127.0.0.1/ontology/Student.owl#HTWStudent // -xsd -d 1 -h D:\tmp\KB\KB_Student-MAP.xml Option xsd = new Option("xsd", "generate XML Schema"); Option info = new Option("info", "print datatype information"); @SuppressWarnings("static-access") Option owlclass = OptionBuilder.withArgName("class").hasArg() .withDescription("owl class to translate; necessary").create("owlclass"); Option keys = new Option("keys", "list all owlclass keys"); options.addOption(keys); options.addOption(owlclass); options.addOption(info); options.addOption(xsd); options.addOption("h", "hierarchy", false, "use hierarchy pattern"); options.addOption("d", "depth", true, "set recursion depth"); options.addOption("b", "behavior", true, "set inheritance bevavior"); options.addOption("p", "primitive", true, "set default primitive type"); try { cmdLine = parser.parse(options, args); if (cmdLine.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("owls2wsdl [options] FILE.xml", options); System.exit(0); } } catch (ParseException exp) { // oops, something went wrong System.out.println("Error: Parsing failed, reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("owls2wsdl", options, true); } if (args.length == 1) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("owls2wsdl [options] FILE.xml", options); System.exit(0); } else if (cmdLine.hasOption("keys")) { File f = new File(args[args.length - 1].toString()); try { AbstractDatatypeMapper.getInstance().loadAbstractDatatypeKB(f); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } AbstractDatatypeKB.getInstance().getAbstractDatatypeKBData().printRegisteredDatatypes(); System.exit(0); } else if (!cmdLine.hasOption("owlclass")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("owls2wsdl [options] FILE.xml", "", options, "Info: owl class not set.\n e.g. -owlclass http://127.0.0.1/ontology/Student.owl#Student"); System.exit(0); } else { File f = new File(args[args.length - 1].toString()); try { AbstractDatatypeMapper.getInstance().loadAbstractDatatypeKB(f); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } String owlclassString = cmdLine.getOptionValue("owlclass"); if (!AbstractDatatypeKB.getInstance().getAbstractDatatypeKBData().containsKey(owlclassString)) { System.err.println("Error: Key " + owlclassString + " not in knowledgebase."); System.exit(1); } if (cmdLine.hasOption("info")) { AbstractDatatypeKB.getInstance().getAbstractDatatypeKBData().get(owlclassString) .printDatatype(); } if (cmdLine.hasOption("xsd")) { boolean hierachy = false; int depth = 0; String inheritanceBehavior = AbstractDatatype.InheritanceByNone; String defaultPrimitiveType = "http://www.w3.org/2001/XMLSchema#string"; if (cmdLine.hasOption("h")) { hierachy = true; } if (cmdLine.hasOption("d")) { depth = Integer.parseInt(cmdLine.getOptionValue("d")); } if (cmdLine.hasOption("b")) { System.out.print("Set inheritance behaviour to: "); if (cmdLine.getOptionValue("b") .equals(AbstractDatatype.InheritanceByParentsFirstRDFTypeSecond)) { System.out.println(AbstractDatatype.InheritanceByParentsFirstRDFTypeSecond); inheritanceBehavior = AbstractDatatype.InheritanceByNone; } else if (cmdLine.getOptionValue("b") .equals(AbstractDatatype.InheritanceByRDFTypeFirstParentsSecond)) { System.out.println(AbstractDatatype.InheritanceByRDFTypeFirstParentsSecond); inheritanceBehavior = AbstractDatatype.InheritanceByRDFTypeFirstParentsSecond; } else if (cmdLine.getOptionValue("b") .equals(AbstractDatatype.InheritanceByRDFTypeOnly)) { System.out.println(AbstractDatatype.InheritanceByRDFTypeOnly); inheritanceBehavior = AbstractDatatype.InheritanceByRDFTypeOnly; } else if (cmdLine.getOptionValue("b") .equals(AbstractDatatype.InheritanceBySuperClassOnly)) { System.out.println(AbstractDatatype.InheritanceBySuperClassOnly); inheritanceBehavior = AbstractDatatype.InheritanceBySuperClassOnly; } else { System.out.println(AbstractDatatype.InheritanceByNone); inheritanceBehavior = AbstractDatatype.InheritanceByNone; } } if (cmdLine.hasOption("p")) { defaultPrimitiveType = cmdLine.getOptionValue("p"); if (defaultPrimitiveType.split("#")[0].equals("http://www.w3.org/2001/XMLSchema")) { System.err.println("Error: Primitive Type not valid: " + defaultPrimitiveType); System.exit(1); } } XsdSchemaGenerator xsdgen = new XsdSchemaGenerator("SCHEMATYPE", hierachy, depth, inheritanceBehavior, defaultPrimitiveType); try { AbstractDatatypeKB.getInstance().toXSD(owlclassString, xsdgen, System.out); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } } } else { try { cmdLine = parser.parse(options, args); if (cmdLine.hasOption("help")) { printDefaultHelpMessage(); } } catch (ParseException exp) { // oops, something went wrong System.out.println("Error: Parsing failed, reason: " + exp.getMessage()); printDefaultHelpMessage(); } } } else { OWLS2WSDLGui.createAndShowGUI(); } // for(Iterator it=options.getOptions().iterator(); it.hasNext(); ) { // String optString = ((Option)it.next()).getOpt(); // if(cmdLine.hasOption(optString)) { // System.out.println("Option set: "+optString); // } // } }
From source file:de.prozesskraft.pkraft.Perlcode.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try//from ww w.ja v a2 s . com // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/" + "../etc/pkraft-perlcode.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option ostep = OptionBuilder.withArgName("STEPNAME").hasArg().withDescription( "[optional] stepname of step to generate a script for. if this parameter is omitted, a script for the process will be generated.") // .isRequired() .create("step"); Option ooutput = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[mandatory] directory for generated files. must not exist when calling.") // .isRequired() .create("output"); Option odefinition = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] process definition file.") // .isRequired() .create("definition"); Option onolist = OptionBuilder.withArgName("") // .hasArg() .withDescription( "[optional] with this parameter the multiple use of multi-optionis is forced. otherwise it is possible to use an integrated comma-separeated list.") // .isRequired() .create("nolist"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(ostep); options.addOption(ooutput); options.addOption(odefinition); options.addOption(onolist); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("perlcode", options); System.exit(0); } else if (commandline.hasOption("v")) { System.out.println("web: www.prozesskraft.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("definition"))) { System.err.println("option -definition is mandatory."); exiter(); } if (!(commandline.hasOption("output"))) { System.err.println("option -output is mandatory."); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ Process p1 = new Process(); java.io.File outputDir = new java.io.File(commandline.getOptionValue("output")); java.io.File outputDirProcessScript = new java.io.File(commandline.getOptionValue("output")); java.io.File outputDirBin = new java.io.File(commandline.getOptionValue("output") + "/bin"); java.io.File outputDirLib = new java.io.File(commandline.getOptionValue("output") + "/lib"); boolean nolist = false; if (commandline.hasOption("nolist")) { nolist = true; } if (outputDir.exists()) { System.err.println("fatal: directory already exists: " + outputDir.getCanonicalPath()); exiter(); } else { outputDir.mkdir(); } p1.setInfilexml(commandline.getOptionValue("definition")); System.err.println("info: reading process definition " + commandline.getOptionValue("definition")); Process p2 = null; try { p2 = p1.readXml(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("error"); exiter(); } // perlcode generieren fuer einen bestimmten step if (commandline.hasOption("step")) { outputDirBin.mkdir(); String stepname = commandline.getOptionValue("step"); writeStepAsPerlcode(p2, stepname, outputDirBin, nolist); } // perlcode generieren fuer den gesamten process else { outputDirBin.mkdir(); writeProcessAsPerlcode(p2, outputDirProcessScript, outputDirBin, nolist); // copy all perllibs from the lib directory outputDirLib.mkdir(); final Path source = Paths.get(WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/../perllib"); final Path target = Paths.get(outputDirLib.toURI()); copyDirectoryTree.copyDirectoryTree(source, target); } }
From source file:com.github.andreax79.meca.Main.java
@SuppressWarnings("static-access") public static void main(String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption("X", "suppress-output", false, "don't create the output file"); OptionGroup boundariesOptions = new OptionGroup(); boundariesOptions.addOption(new Option("P", "periodic", false, "periodic boundaries (default)")); boundariesOptions.addOption(new Option("F", "fixed", false, "fixed-value boundaries")); boundariesOptions.addOption(new Option("A", "adiabatic", false, "adiabatic boundaries")); boundariesOptions.addOption(new Option("R", "reflective", false, "reflective boundaries")); options.addOptionGroup(boundariesOptions); OptionGroup colorOptions = new OptionGroup(); colorOptions.addOption(new Option("bn", "black-white", false, "black and white color scheme (default)")); colorOptions.addOption(new Option("ca", "activation-color", false, "activation color scheme")); colorOptions.addOption(new Option("co", "omega-color", false, "omega color scheme")); options.addOptionGroup(colorOptions); options.addOption(OptionBuilder.withLongOpt("rule").withDescription("rule number (required)").hasArg() .withArgName("rule").create()); options.addOption(OptionBuilder.withLongOpt("width").withDescription("space width (required)").hasArg() .withArgName("width").create()); options.addOption(OptionBuilder.withLongOpt("steps").withDescription("number of steps (required)").hasArg() .withArgName("steps").create()); options.addOption(OptionBuilder.withLongOpt("alpha").withDescription("memory factor (default 0)").hasArg() .withArgName("alpha").create()); options.addOption(OptionBuilder.withLongOpt("pattern").withDescription("inititial pattern").hasArg() .withArgName("pattern").create()); options.addOption("s", "single-seed", false, "single cell seed"); options.addOption("si", "single-seed-inverse", false, "all 1 except one cell"); options.addOption(OptionBuilder.withLongOpt("update-patter") .withDescription("update patter (valid values are " + UpdatePattern.validValues() + ")").hasArg() .withArgName("updatepatter").create()); // test//from w ww. j av a 2 s. co m // args = new String[]{ "--rule=10", "--steps=500" , "--width=60", "-P" , "-s" }; try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (!line.hasOption("rule")) throw new ParseException("no rule number (use --rule=XX)"); int rule; try { rule = Integer.parseInt(line.getOptionValue("rule")); if (rule < 0 || rule > 15) throw new ParseException("invalid rule number"); } catch (NumberFormatException ex) { throw new ParseException("invalid rule number"); } if (!line.hasOption("width")) throw new ParseException("no space width (use --width=XX)"); int width; try { width = Integer.parseInt(line.getOptionValue("width")); if (width < 1) throw new ParseException("invalid width"); } catch (NumberFormatException ex) { throw new ParseException("invalid width"); } if (!line.hasOption("steps")) throw new ParseException("no number of steps (use --steps=XX)"); int steps; try { steps = Integer.parseInt(line.getOptionValue("steps")); if (width < 1) throw new ParseException("invalid number of steps"); } catch (NumberFormatException ex) { throw new ParseException("invalid number of steps"); } double alpha = 0; if (line.hasOption("alpha")) { try { alpha = Double.parseDouble(line.getOptionValue("alpha")); if (alpha < 0 || alpha > 1) throw new ParseException("invalid alpha"); } catch (NumberFormatException ex) { throw new ParseException("invalid alpha"); } } String pattern = null; if (line.hasOption("pattern")) { pattern = line.getOptionValue("pattern"); if (pattern != null) pattern = pattern.trim(); } if (line.hasOption("single-seed")) pattern = "S"; else if (line.hasOption("single-seed-inverse")) pattern = "SI"; UpdatePattern updatePatter = UpdatePattern.synchronous; if (line.hasOption("update-patter")) { try { updatePatter = UpdatePattern.getUpdatePattern(line.getOptionValue("update-patter")); } catch (IllegalArgumentException ex) { throw new ParseException(ex.getMessage()); } } Boundaries boundaries = Boundaries.periodic; if (line.hasOption("periodic")) boundaries = Boundaries.periodic; else if (line.hasOption("fixed")) boundaries = Boundaries.fixed; else if (line.hasOption("adiabatic")) boundaries = Boundaries.adiabatic; else if (line.hasOption("reflective")) boundaries = Boundaries.reflective; ColorScheme colorScheme = ColorScheme.noColor; if (line.hasOption("black-white")) colorScheme = ColorScheme.noColor; else if (line.hasOption("activation-color")) colorScheme = ColorScheme.activationColor; else if (line.hasOption("omega-color")) colorScheme = ColorScheme.omegaColor; Output output = Output.all; if (line.hasOption("suppress-output")) output = Output.noOutput; Main.drawRule(rule, width, boundaries, updatePatter, steps, alpha, pattern, output, colorScheme); } catch (ParseException ex) { System.err.println("Copyright (C) 2009 Andrea Bonomi - <andrea.bonomi@gmail.com>"); System.err.println(); System.err.println("https://github.com/andreax79/one-neighbor-binary-cellular-automata"); System.err.println(); System.err.println("This program is free software; you can redistribute it and/or modify it"); System.err.println("under the terms of the GNU General Public License as published by the"); System.err.println("Free Software Foundation; either version 2 of the License, or (at your"); System.err.println("option) any later version."); System.err.println(); System.err.println("This program is distributed in the hope that it will be useful, but"); System.err.println("WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY"); System.err.println("or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License"); System.err.println("for more details."); System.err.println(); System.err.println("You should have received a copy of the GNU General Public License along"); System.err.println("with this program; if not, write to the Free Software Foundation, Inc.,"); System.err.println("59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.)"); System.err.println(); System.err.println(ex.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("main", options); } catch (IOException ex) { System.err.println("IO exception:" + ex.getMessage()); } }
From source file:edu.mit.lib.tools.Modernize.java
public static void main(String[] args) throws Exception { // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("i", "identifier", true, "root handle to migrate - 'all' for entire repo"); options.addOption("t", "target", true, "URL of mds repository to import into"); options.addOption("s", "scratch", true, "scratch directory for processing"); options.addOption("m", "migrate", false, "export for migration (remove handle and metadata that will be re-created in new system)"); options.addOption("h", "help", false, "help"); CommandLine line = parser.parse(options, args); if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("Modernize\n", options); System.out.println(/*from w w w . ja v a 2 s . c o m*/ "\nentire repository: Modernize -i all -t http://my-mds-repo.org/webapi -s /dspace/export"); System.out.println( "\ncontent subtree: Modernize -i 123456789/1 -t http://my-mds-repo.org/webapi -s /dspace/export"); System.exit(0); } String scratch = null; if (line.hasOption('s')) { scratch = line.getOptionValue('s'); if (scratch == null) { System.out.println("Scratch directory required!"); System.exit(1); } } Modernize mod = new Modernize(Paths.get(scratch)); if (line.hasOption('i')) { String id = line.getOptionValue('i'); if (id != null) { mod.exportIdentifier(id); } else { mod.bail("Must provide an identifer!"); } } if (line.hasOption('t')) { String targetUrl = line.getOptionValue('t'); if (targetUrl != null) { mod.importToMds(targetUrl); } else { mod.bail("Must provide an URL to an mds repository!"); } } mod.finish(); }