List of usage examples for org.apache.commons.cli CommandLine getOptionValues
public String[] getOptionValues(char opt)
From source file:de.huberlin.wbi.hiway.common.Worker.java
public void init(String[] args) throws ParseException { conf = new HiWayConfiguration(); try {/* ww w .ja v a 2 s . co m*/ hdfs = FileSystem.get(conf); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } Options opts = new Options(); opts.addOption("appId", true, "Id of this Container's Application Master."); opts.addOption("containerId", true, "Id of this Container."); opts.addOption("workflowId", true, ""); opts.addOption("taskId", true, ""); opts.addOption("taskName", true, ""); opts.addOption("langLabel", true, ""); opts.addOption("id", true, ""); opts.addOption("input", true, ""); opts.addOption("output", true, ""); opts.addOption("size", false, ""); opts.addOption("invocScript", true, "if set, this parameter provides the Worker with the path to the script that is to be stored in invoc-script"); CommandLine cliParser = new GnuParser().parse(opts, args); containerId = cliParser.getOptionValue("containerId"); appId = cliParser.getOptionValue("appId"); String hdfsBaseDirectoryName = conf.get(HiWayConfiguration.HIWAY_AM_DIRECTORY_BASE, HiWayConfiguration.HIWAY_AM_DIRECTORY_BASE_DEFAULT); String hdfsSandboxDirectoryName = conf.get(HiWayConfiguration.HIWAY_AM_DIRECTORY_CACHE, HiWayConfiguration.HIWAY_AM_DIRECTORY_CACHE_DEFAULT); Path hdfsBaseDirectory = new Path(new Path(hdfs.getUri()), hdfsBaseDirectoryName); Data.setHdfsBaseDirectory(hdfsBaseDirectory); Path hdfsSandboxDirectory = new Path(hdfsBaseDirectory, hdfsSandboxDirectoryName); Path hdfsApplicationDirectory = new Path(hdfsSandboxDirectory, appId); Data.setHdfsApplicationDirectory(hdfsApplicationDirectory); Data.setHdfs(hdfs); workflowId = UUID.fromString(cliParser.getOptionValue("workflowId")); taskId = Long.parseLong(cliParser.getOptionValue("taskId")); taskName = cliParser.getOptionValue("taskName"); langLabel = cliParser.getOptionValue("langLabel"); id = Long.parseLong(cliParser.getOptionValue("id")); if (cliParser.hasOption("input")) { for (String inputList : cliParser.getOptionValues("input")) { String[] inputElements = inputList.split(","); String otherContainerId = inputElements[2].equals("null") ? null : inputElements[2]; Data input = new Data(inputElements[0], otherContainerId); input.setInput(Boolean.parseBoolean(inputElements[1])); inputFiles.add(input); } } if (cliParser.hasOption("size")) { determineFileSizes = true; } if (cliParser.hasOption("output")) { for (String output : cliParser.getOptionValues("output")) { outputFiles.add(new Data(output, containerId)); } } if (cliParser.hasOption("invocScript")) { invocScript = cliParser.getOptionValue("invocScript"); } }
From source file:fr.inrialpes.exmo.align.cli.GroupEval.java
public void run(String[] args) throws Exception { try {//from w w w . jav a 2 s . c o m CommandLine line = parseCommandLine(args); if (line == null) return; // --help // Here deal with command specific arguments if (line.hasOption('e')) classname = line.getOptionValue('e'); if (line.hasOption('f')) format = line.getOptionValue('f'); if (line.hasOption('r')) reference = line.getOptionValue('r'); if (line.hasOption('s')) dominant = line.getOptionValue('s'); if (line.hasOption('t')) type = line.getOptionValue('t'); if (line.hasOption('c')) color = line.getOptionValue('c', "lightblue"); if (line.hasOption('l')) { listAlgo = line.getOptionValues('l'); size = listAlgo.length; } if (line.hasOption('w')) ontoDir = line.getOptionValue('w'); } catch (ParseException exp) { logger.error(exp.getMessage()); usage(); System.exit(-1); } Class<?> evalClass = Class.forName(classname); Class<?>[] cparams = { Alignment.class, Alignment.class }; evalConstructor = evalClass.getConstructor(cparams); print(iterateDirectories()); }
From source file:com.redhat.rhn.taskomatic.core.TaskomaticDaemon.java
private Map parseOverrides(CommandLine commandLine) { Map configOverrides = new HashMap(); // Loop thru all possible options and let's see what we get for (Iterator iter = this.masterOptionsMap.keySet().iterator(); iter.hasNext();) { String optionName = (String) iter.next(); if (commandLine.hasOption(optionName)) { // All of these options are single-value options so they're // grouped together here if (optionName.equals(TaskomaticConstants.CLI_PIDFILE) || optionName.equals(TaskomaticConstants.CLI_DBURL) || optionName.equals(TaskomaticConstants.CLI_DBUSER) || optionName.equals(TaskomaticConstants.CLI_DBPASSWORD)) { configOverrides.put(optionName, commandLine.getOptionValue(optionName)); }/*ww w.ja v a 2s. co m*/ // The presence of these options toggle them on, hence the use of // Boolean.TRUE else if (optionName.equals(TaskomaticConstants.CLI_DEBUG) || optionName.equals(TaskomaticConstants.CLI_DAEMON) || optionName.equals(TaskomaticConstants.CLI_SINGLE)) { configOverrides.put(optionName, Boolean.TRUE); } // Possibly multi-value list of task implementations to schedule else if (optionName.equals(TaskomaticConstants.CLI_TASK)) { String[] taskImpls = commandLine.getOptionValues(optionName); if (taskImpls != null && taskImpls.length > 0) { configOverrides.put(optionName, Arrays.asList(taskImpls)); } } } } return configOverrides; }
From source file:com.j2biz.pencil.Starter.java
Starter(final CommandLine line) { assert line != null; final CLIOptionParser cliParser = CLIOptionParser.getInstance(); if (line.hasOption("h")) executeHelp(cliParser);//w w w. j ava 2s .c om this.line = line; this.sourceOptionEntered = line.hasOption(cliParser.getSourceOptionString()); this.configOptionEntered = line.hasOption(cliParser.getConfigOptionString()); if (configOptionEntered && sourceOptionEntered) exitCauseScrAndConfigAreEntered(); if (configOptionEntered) { executeWithConfig(line); } else { final File srcPathFile; if (sourceOptionEntered) { final String fileName = line.getOptionValue(cliParser.getSourceOptionString()); final File file = new File(fileName); if (file.exists()) { srcPathFile = file; } else { srcPathFile = new File(new File("").getAbsoluteFile(), fileName); } } else { srcPathFile = new File(""); } if (!srcPathFile.exists()) { exitCauseSrcPathNotExist(srcPathFile); } else { final ErrorStatusLogger logger = new ConsoleErrorStatusLogger(); final Enhancer enhancer; if (line.hasOption(cliParser.getPackagesOption())) { final String[] packageNames = line.getOptionValues(cliParser.getPackagesOption()); final Source source = new Source(srcPathFile, packageNames); final ClassManager manager = new ClassManager(new File(""), srcPathFile, new Source[] { source }, null, logger); enhancer = new Enhancer(manager, logger); } else { enhancer = new Enhancer(srcPathFile, logger); } enhancer.enhance(); } } }
From source file:cytoscape.CyMain.java
License:asdf
protected void parseCommandLine(String[] args) { // create the options options.addOption("h", "help", false, "Print this message."); options.addOption("v", "version", false, "Print the version number."); // commented out until we actually support doing anything in headless // mode/*from ww w . ja v a2 s. co m*/ // options.addOption("H", "headless", false, "Run in headless (no gui) // mode."); options.addOption( OptionBuilder.withLongOpt("session").withDescription("Load a cytoscape session (.cys) file.") .withValueSeparator('\0').withArgName("file").hasArg() // only allow one session!!! .create("s")); options.addOption(OptionBuilder.withLongOpt("network").withDescription("Load a network file (any format).") .withValueSeparator('\0').withArgName("file").hasArgs().create("N")); options.addOption(OptionBuilder.withLongOpt("edge-attrs") .withDescription("Load an edge attributes file (edge attribute format).").withValueSeparator('\0') .withArgName("file").hasArgs().create("e")); options.addOption(OptionBuilder.withLongOpt("node-attrs") .withDescription("Load a node attributes file (node attribute format).").withValueSeparator('\0') .withArgName("file").hasArgs().create("n")); options.addOption( OptionBuilder.withLongOpt("matrix").withDescription("Load a node attribute matrix file (table).") .withValueSeparator('\0').withArgName("file").hasArgs().create("m")); options.addOption(OptionBuilder.withLongOpt("plugin") .withDescription( "Load a plugin jar file, directory of jar files, plugin class name, or plugin jar URL.") .withValueSeparator('\0').withArgName("file").hasArgs().create("p")); options.addOption(OptionBuilder.withLongOpt("props").withDescription( "Load cytoscape properties file (Java properties format) or individual property: -P name=value.") .withValueSeparator('\0').withArgName("file").hasArgs().create("P")); options.addOption(OptionBuilder.withLongOpt("vizmap") .withDescription("Load vizmap properties file (Java properties format).").withValueSeparator('\0') .withArgName("file").hasArgs().create("V")); // try to parse the cmd line CommandLineParser parser = new PosixParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException e) { System.err.println("Parsing command line failed: " + e.getMessage()); printHelp(); System.exit(1); } // Read any argument containing ".cys" as session file. // Allows session files to be passed in via MIME type settings. // This imprecise method is overwritten by -s option, if specified. for (String freeArg : args) { if (freeArg.contains(".cys")) { sessionFile = freeArg; } } // use what is found on the command line to set values if (line.hasOption("h")) { printHelp(); System.exit(0); } if (line.hasOption("v")) { CytoscapeVersion version = new CytoscapeVersion(); logger.info(version.getVersion()); System.exit(0); } if (line.hasOption("H")) { mode = CyInitParams.TEXT; } else { mode = CyInitParams.GUI; setupLookAndFeel(); } if (line.hasOption("P")) props = createProperties(line.getOptionValues("P")); else props = createProperties(new String[0]); if (line.hasOption("N")) graphFiles = line.getOptionValues("N"); if (line.hasOption("p")) plugins = line.getOptionValues("p"); if (line.hasOption("V")) vizmapProps = createProperties(line.getOptionValues("V")); else vizmapProps = createProperties(new String[0]); if (line.hasOption("s")) sessionFile = line.getOptionValue("s"); if (line.hasOption("n")) nodeAttrFiles = line.getOptionValues("n"); if (line.hasOption("e")) edgeAttrFiles = line.getOptionValues("e"); if (line.hasOption("m")) expressionFiles = line.getOptionValues("m"); }
From source file:com.marklogic.shell.command.load.java
public void execute(Environment env, String[] args) { if (args != null && args.length > 0) { CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try {//from w w w .java2s.c o m cmd = parser.parse(options, args); } catch (ParseException e) { env.outputException(e); return; } ContentCreateOptions contentOptions = new ContentCreateOptions(); String quality = cmd.getOptionValue("q"); if (quality != null) { try { Integer q = Integer.valueOf(quality); contentOptions.setQuality(q.intValue()); } catch (NumberFormatException e) { env.outputError("Invalid document quality (must be an int): " + quality); return; } } String docType = cmd.getOptionValue("t"); if (docType != null) { if ("binary".equals(docType)) { contentOptions.setFormat(DocumentFormat.BINARY); } else if ("text".equals(docType)) { contentOptions.setFormat(DocumentFormat.TEXT); } else if ("xml".equals(docType)) { contentOptions.setFormat(DocumentFormat.XML); } else { env.outputError("Invalid document format. Must be: binary,text,xml"); return; } } String[] cols = cmd.getOptionValues("c"); if (cols != null && cols.length > 0) { contentOptions.setCollections(cols); } String[] perms = cmd.getOptionValues("x"); if (perms != null && perms.length > 0) { List contentPermissions = new ArrayList(); for (int i = 0; i < perms.length; i++) { ContentCapability ccap = null; String p = perms[i]; if (p == null) { env.outputError("Invalid permission option. Must be of the form: 'capability:role'"); return; } String[] parts = p.split(":"); if (parts == null || parts.length != 2) { env.outputError("Invalid permission option. Must be of the form: 'capability:role'"); return; } String capability = parts[0]; String role = parts[1]; if ("execute".equals(capability)) { ccap = ContentCapability.EXECUTE; } else if ("insert".equals(capability)) { ccap = ContentCapability.INSERT; } else if ("read".equals(capability)) { ccap = ContentCapability.READ; } else if ("update".equals(capability)) { ccap = ContentCapability.UPDATE; } else { env.outputError("Invalid permission '" + p + "'. Capability must be one of: execute,insert,read,update"); return; } if (role == null || role.length() == 0) { env.outputError("Invalid permission. Please provide a role"); return; } contentPermissions.add(new ContentPermission(ccap, role)); } ContentPermission[] cperms = new ContentPermission[contentPermissions.size()]; contentPermissions.toArray(cperms); contentOptions.setPermissions(cperms); } env.outputLine("Loading files..."); int total = 0; for (Iterator i = cmd.getArgList().iterator(); i.hasNext();) { String path = i.next().toString(); List files = FileScanner.findFiles(path); if (files != null && files.size() > 0) { List list = new ArrayList(); for (Iterator it = files.iterator(); it.hasNext();) { File f = (File) it.next(); String uri = cmd.getOptionValue("n"); if (uri == null || uri.length() == 0) { uri = getUri(cmd.getOptionValue("i"), f.getName()); } list.add(ContentFactory.newContent(uri, f, contentOptions)); } Content[] contentList = new Content[list.size()]; list.toArray(contentList); Session session = env.getContentSource().newSession(); try { session.insertContent(contentList); total += contentList.length; } catch (RequestException e) { env.outputException(e); } } else { env.outputLine("No file(s) found at location " + path + "."); } } if (total > 0) { env.outputLine("Done. Loaded " + total + " file(s)."); } } else { env.outputLine("You must specify a file path to load."); } }
From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java
/** * Parses the command line options.// w w w . j a v a 2s. c o m * * @param args the command line argument array * * @return true, if all arguments were successfully parsed */ protected boolean parseOptions(String[] args) { try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("?")) { showHelp(); System.exit(0); } if (cmd.hasOption("c")) { configFilename = cmd.getOptionValue("c"); } if (cmd.hasOption("6p")) { String p = cmd.getOptionValue("6p"); try { v6PortNumber = Integer.parseInt(p); } catch (NumberFormatException ex) { v6PortNumber = DhcpConstants.V6_SERVER_PORT; System.err.println( "Invalid port number: '" + p + "' using default: " + v6PortNumber + " Exception=" + ex); } } if (cmd.hasOption("6m")) { String[] ifnames = cmd.getOptionValues("6m"); if ((ifnames == null) || (ifnames.length < 1)) { ifnames = new String[] { "*" }; } v6McastNetIfs = getIPv6NetIfs(ifnames); if ((v6McastNetIfs == null) || v6McastNetIfs.isEmpty()) { return false; } } if (cmd.hasOption("6u")) { String[] addrs = cmd.getOptionValues("6u"); if ((addrs == null) || (addrs.length < 1)) { addrs = new String[] { "*" }; } v6UcastAddrs = getIpAddrs(addrs); if ((v6UcastAddrs == null) || v6UcastAddrs.isEmpty()) { return false; } } if (cmd.hasOption("4b")) { String v4if = cmd.getOptionValue("4b"); v4BcastNetIf = getIPv4NetIf(v4if); if (v4BcastNetIf == null) { return false; } } if (cmd.hasOption("4u")) { String[] addrs = cmd.getOptionValues("4u"); if ((addrs == null) || (addrs.length < 1)) { addrs = new String[] { "*" }; } v4UcastAddrs = getV4IpAddrs(addrs); if ((v4UcastAddrs == null) || v4UcastAddrs.isEmpty()) { return false; } } if (cmd.hasOption("4p")) { String p = cmd.getOptionValue("4p"); try { v4PortNumber = Integer.parseInt(p); } catch (NumberFormatException ex) { v4PortNumber = DhcpConstants.V4_SERVER_PORT; System.err.println( "Invalid port number: '" + p + "' using default: " + v4PortNumber + " Exception=" + ex); } } if (cmd.hasOption("v")) { System.err.println(Version.getVersion()); System.exit(0); } if (cmd.hasOption("tc")) { try { String filename = cmd.getOptionValue("tc"); System.err.println("Parsing server configuration file: " + filename); DhcpServerConfig config = DhcpServerConfiguration.parseConfig(filename); if (config != null) { System.err.println("OK: " + filename + " is a valid DHCPv6 server configuration file."); } } catch (Exception ex) { System.err.println("ERROR: " + ex); } System.exit(0); } if (cmd.hasOption("li")) { Enumeration<NetworkInterface> netIfs = NetworkInterface.getNetworkInterfaces(); if (netIfs != null) { while (netIfs.hasMoreElements()) { NetworkInterface ni = netIfs.nextElement(); System.err.println(ni); } } System.exit(0); } } catch (ParseException pe) { System.err.println("Command line option parsing failure: " + pe); return false; } catch (SocketException se) { System.err.println("Network interface socket failure: " + se); return false; } catch (UnknownHostException he) { System.err.println("IP Address failure: " + he); } return true; }
From source file:fr.ujm.tse.lt2c.satin.main.Main.java
/** * @param args//from w w w. j a v a 2s. c o m * @return a ReasoningArguements object containing all the parsed arguments */ private static ReasoningArguments getArguments(final String[] args) { /* Reasoner fields */ int threadsNB = DEFAULT_THREADS_NB; int bufferSize = DEFAULT_BUFFER_SIZE; long timeout = DEFAULT_TIMEOUT; int iteration = 1; ReasonerProfile profile = DEFAULT_PROFILE; /* Extra fields */ boolean verboseMode = DEFAULT_VERBOSE_MODE; boolean warmupMode = DEFAULT_WARMUP_MODE; boolean dumpMode = DEFAULT_DUMP_MODE; boolean batchMode = DEFAULT_BATCH_MODE; /* * Options */ final Options options = new Options(); final Option bufferSizeO = new Option("b", "buffer-size", true, "set the buffer size"); bufferSizeO.setArgName("size"); bufferSizeO.setArgs(1); bufferSizeO.setType(Number.class); options.addOption(bufferSizeO); final Option timeoutO = new Option("t", "timeout", true, "set the buffer timeout in ms (0 means timeout will be disabled)"); bufferSizeO.setArgName("time"); bufferSizeO.setArgs(1); bufferSizeO.setType(Number.class); options.addOption(timeoutO); final Option iterationO = new Option("i", "iteration", true, "how many times each file "); iterationO.setArgName("number"); iterationO.setArgs(1); iterationO.setType(Number.class); options.addOption(iterationO); final Option directoryO = new Option("d", "directory", true, "infers on all ontologies in the directory"); directoryO.setArgName("directory"); directoryO.setArgs(1); directoryO.setType(File.class); options.addOption(directoryO); options.addOption("o", "output", false, "save output into file"); options.addOption("h", "help", false, "print this message"); options.addOption("v", "verbose", false, "enable verbose mode"); options.addOption("r", "batch-reasoning", false, "enable batch reasoning"); options.addOption("w", "warm-up", false, "insert a warm-up lap before the inference"); final Option profileO = new Option("p", "profile", true, "set the fragment " + java.util.Arrays.asList(ReasonerProfile.values())); profileO.setArgName("profile"); profileO.setArgs(1); options.addOption(profileO); final Option threadsO = new Option("n", "threads", true, "set the number of threads by available core (0 means the jvm manage)"); threadsO.setArgName("number"); threadsO.setArgs(1); threadsO.setType(Number.class); options.addOption(threadsO); /* * Arguments parsing */ final CommandLineParser parser = new GnuParser(); final CommandLine cmd; try { cmd = parser.parse(options, args); } catch (final ParseException e) { LOGGER.error("", e); return null; } /* help */ if (cmd.hasOption("help")) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("main", options); return null; } /* buffer */ if (cmd.hasOption("buffer-size")) { final String arg = cmd.getOptionValue("buffer-size"); try { bufferSize = Integer.parseInt(arg); } catch (final NumberFormatException e) { LOGGER.error("Buffer size must be a number. Default value used", e); } } /* timeout */ if (cmd.hasOption("timeout")) { final String arg = cmd.getOptionValue("timeout"); try { timeout = Integer.parseInt(arg); } catch (final NumberFormatException e) { LOGGER.error("Timeout must be a number. Default value used", e); } } /* verbose */ if (cmd.hasOption("verbose")) { verboseMode = true; if (LOGGER.isInfoEnabled()) { LOGGER.info("Verbose mode enabled"); } } /* warm-up */ if (cmd.hasOption("warm-up")) { warmupMode = true; if (LOGGER.isInfoEnabled()) { LOGGER.info("Warm-up mode enabled"); } } /* dump */ if (cmd.hasOption("output")) { dumpMode = true; if (LOGGER.isInfoEnabled()) { LOGGER.info("Dump mode enabled"); } } /* dump */ if (cmd.hasOption("batch-reasoning")) { batchMode = true; if (LOGGER.isInfoEnabled()) { LOGGER.info("Batch mode enabled"); } } /* directory */ String dir = null; if (cmd.hasOption("directory")) { for (final Object o : cmd.getOptionValues("directory")) { String arg = o.toString(); if (arg.startsWith("~" + File.separator)) { arg = System.getProperty("user.home") + arg.substring(1); } final File directory = new File(arg); if (!directory.exists()) { LOGGER.warn("**Cant not find " + directory); } else if (!directory.isDirectory()) { LOGGER.warn("**" + directory + " is not a directory"); } else { dir = directory.getAbsolutePath(); } } } /* profile */ if (cmd.hasOption("profile")) { final String string = cmd.getOptionValue("profile"); switch (string) { case "RhoDF": profile = ReasonerProfile.RHODF; break; case "BRhoDF": profile = ReasonerProfile.BRHODF; break; case "RDFS": profile = ReasonerProfile.RDFS; break; case "BRDFS": profile = ReasonerProfile.BRDFS; break; default: LOGGER.warn("Profile unknown, default profile used: " + DEFAULT_PROFILE); profile = DEFAULT_PROFILE; break; } } /* threads */ if (cmd.hasOption("threads")) { final String arg = cmd.getOptionValue("threads"); try { threadsNB = Integer.parseInt(arg); } catch (final NumberFormatException e) { LOGGER.error("Threads number must be a number. Default value used", e); } } /* iteration */ if (cmd.hasOption("iteration")) { final String arg = cmd.getOptionValue("iteration"); try { iteration = Integer.parseInt(arg); } catch (final NumberFormatException e) { LOGGER.error("Iteration must be a number. Default value used", e); } } final List<File> files = new ArrayList<>(); if (dir != null) { final File directory = new File(dir); final File[] listOfFiles = directory.listFiles(); for (final File file : listOfFiles) { // Maybe other extensions ? if (file.isFile() && file.getName().endsWith(".nt")) { files.add(file); } } } for (final Object o : cmd.getArgList()) { String arg = o.toString(); if (arg.startsWith("~" + File.separator)) { arg = System.getProperty("user.home") + arg.substring(1); } final File file = new File(arg); if (!file.exists()) { LOGGER.warn("**Cant not find " + file); } else if (file.isDirectory()) { LOGGER.warn("**" + file + " is a directory"); } else { files.add(file); } } Collections.sort(files, new Comparator<File>() { @Override public int compare(final File f1, final File f2) { if (f1.length() > f2.length()) { return 1; } if (f2.length() > f1.length()) { return -1; } return 0; } }); if (LOGGER.isInfoEnabled()) { LOGGER.info("********* OPTIONS *********"); LOGGER.info("Buffer size: " + bufferSize); LOGGER.info("Profile: " + profile); if (threadsNB > 0) { LOGGER.info("Threads: " + threadsNB); } else { LOGGER.info("Threads: Automatic"); } LOGGER.info("Iterations: " + iteration); LOGGER.info("Timeout: " + timeout); LOGGER.info("***************************"); } return new ReasoningArguments(threadsNB, bufferSize, timeout, iteration, profile, verboseMode, warmupMode, dumpMode, batchMode, files); }
From source file:com.gele.tools.wow.wdbearmanager.WDBearManager.java
public void parseCommandLine(String[] parArgs) { // parse the command line this.options = new Options(); // flags//from w w w. j ava 2 s . c om Option optTmp = new Option(this.PARAM_GUI, false, "use GUI"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(this.PARAM_PATCH_UTF8, false, "write UTF-8 text when patching SCP files (not recommended for WadEmu)"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(this.PARAM_UPDATE, false, "update existing database entries"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(this.PARAM_WRITE_SQL, false, "write to SQL database, needs '" + this.PARAM_WDBFILE + "'"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(this.PARAM_VERBOSE, false, "verbose mode, print info"); optTmp.setRequired(false); this.options.addOption(optTmp); // key-value optTmp = new Option(this.PARAM_DBCONFIG, true, "specify alternative database properties; default: 'wdbearmanager_sql.properties'"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(this.PARAM_WDBFILE, true, "name of wdb file to import"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(this.PARAM_LOCALE, true, "locale to be used(eg: enUS, deDE, etc) " + "This is needed if you want to patch SCP files or export WDBTEXT"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(this.PARAM_CSVFOLDER, true, "output CSV to this folder, needs '" + this.PARAM_WDBFILE + "'"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(this.PARAM_TXTFOLDER, true, "output TXT to this folder, needs '" + this.PARAM_WDBFILE + "'"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(this.SCP_NAME, true, "name of the SCP file to patch, use this in conjunction with '" + WDBearManager.PATCH_SCP + "'"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(WDBearManager.PATCH_SCP, true, "type of the SCP file to patch, eg 'quests', 'items', 'creatures', or 'pages'"); optTmp.setRequired(false); this.options.addOption(optTmp); optTmp = new Option(this.PARAM_SCRIPT, true, "specify a Jython script, receives 'wdbmgrapi' variable which contains WDBearManager_API instance"); optTmp.setRequired(false); this.options.addOption(optTmp); Option property = OptionBuilder.withArgName("parameter=value").hasArg().withValueSeparator('^') .withDescription("set value for Jython script").create(this.PARAM_JYTHON); property.setRequired(false); this.options.addOption(property); // // Parse CommandLineParser parser = new GnuParser(); CommandLine cmdLine = null; try { cmdLine = parser.parse(this.options, parArgs); } catch (ParseException ex) { //ex.printStackTrace(); usage(this.options); System.exit(0); } if (cmdLine.hasOption(this.PARAM_JYTHON)) { // initialise the member variable String[] params = cmdLine.getOptionValues(this.PARAM_JYTHON); for (int i = 0; i < params.length; i++) { String[] result = params[i].split("="); if (result.length != 2) { this.myLogger.error("Error in specifying -J parameter '" + params[i] + "': Use param=value"); System.exit(0); } this.paramJython.put(result[0], result[1]); } } // no options if (cmdLine.hasOption(this.PARAM_GUI)) { this.useGUI = true; } if (cmdLine.hasOption(this.PARAM_PATCH_UTF8)) { this.patchUTF8 = true; } if (cmdLine.hasOption(this.PARAM_WRITE_SQL)) { this.writeSQL = true; } if (cmdLine.hasOption(this.PARAM_VERBOSE)) { this.useVerbose = true; } if (cmdLine.hasOption(this.PARAM_UPDATE)) { this.doUpdate = true; } this.paramTXTFolder = cmdLine.getOptionValue(this.PARAM_TXTFOLDER, this.paramTXTFolder); this.paramCSVFolder = cmdLine.getOptionValue(this.PARAM_CSVFOLDER, this.paramCSVFolder); this.paramWdbfile = cmdLine.getOptionValue(this.PARAM_WDBFILE, this.paramWdbfile); this.paramLocale = cmdLine.getOptionValue(this.PARAM_WDBFILE, this.paramLocale); this.paramSCPname = cmdLine.getOptionValue(this.SCP_NAME, this.paramSCPname); this.paramPatchSCP = cmdLine.getOptionValue(WDBearManager.PATCH_SCP, this.paramPatchSCP); this.paramScript = cmdLine.getOptionValue(this.PARAM_SCRIPT, this.paramScript); this.paramDBconfig = cmdLine.getOptionValue(this.PARAM_DBCONFIG, this.paramDBconfig); }
From source file:com.hablutzel.cmdline.CommandLineApplication.java
/** * Method for running the command line application. * * @param args The arguments passed into main() * @throws CommandLineException//from w ww . j a va 2 s . c o m */ public void parseAndRun(String args[]) throws CommandLineException { // Configure our environment configure(); // Make sure there is a main helper if (mainHelper == null) { throw new CommandLineException("You must specify the main method with @CommandLineMain"); } CommandLine line = null; CommandLineParser parser = null; try { // Parse the command line parser = new DefaultParser(); line = parser.parse(options, args); } catch (ParseException e) { throw new CommandLineException("Unable to parse command line", e); } finally { parser = null; } // Assume we're continuing boolean runMain = true; // Loop through all our known options for (Map.Entry<Option, CommandLineMethodHelper> entry : optionHelperMap.entrySet()) { // See if this option was specified Option option = entry.getKey(); CommandLineMethodHelper helper = entry.getValue(); boolean present = option.getOpt() == null || option.getOpt().equals("") ? line.hasOption(option.getLongOpt()) : line.hasOption(option.getOpt()); if (present) { // The user specified this option. Now we have to handle the // values, if it has any if (option.hasArg()) { String[] arguments = option.getOpt() == null || option.getOpt().equals("") ? line.getOptionValues(option.getLongOpt()) : line.getOptionValues(option.getOpt()); runMain = helper.invokeMethod(this, arguments) && runMain; } else { runMain = helper.invokeMethod(this, new String[] {}) && runMain; } } } // Now handle all the extra arguments. In order to clean up memory, // we get rid of the structures that we needed in order to parse if (runMain) { // Get a reference to the arguments String[] arguments = line.getArgs(); // Clean up the parsing variables line = null; optionHelperMap = null; // Now call the main method. This means we have to keep // the main helper around, but that's small mainHelper.invokeMethod(this, arguments); } }