List of usage examples for org.apache.commons.cli OptionGroup OptionGroup
OptionGroup
From source file:asl.seedscan.SeedScan.java
public static void main(String args[]) { // Default locations of config and schema files File configFile = new File("config.xml"); File schemaFile = new File("schemas/SeedScanConfig.xsd"); boolean parseConfig = true; ArrayList<File> schemaFiles = new ArrayList<File>(); schemaFiles.add(schemaFile);/*from w w w. jav a2s . c om*/ // ==== Command Line Parsing ==== Options options = new Options(); Option opConfigFile = new Option("c", "config-file", true, "The config file to use for seedscan. XML format according to SeedScanConfig.xsd."); Option opSchemaFile = new Option("s", "schema-file", true, "The xsd schema file which should be used to verify the config file format. "); OptionGroup ogConfig = new OptionGroup(); ogConfig.addOption(opConfigFile); OptionGroup ogSchema = new OptionGroup(); ogConfig.addOption(opSchemaFile); options.addOptionGroup(ogConfig); options.addOptionGroup(ogSchema); PosixParser optParser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = optParser.parse(options, args, true); } catch (org.apache.commons.cli.ParseException e) { logger.error("Error while parsing command-line arguments."); System.exit(1); } Option opt; Iterator<?> iter = cmdLine.iterator(); while (iter.hasNext()) { opt = (Option) iter.next(); if (opt.getOpt().equals("c")) { configFile = new File(opt.getValue()); } else if (opt.getOpt().equals("s")) { schemaFile = new File(opt.getValue()); } } // ==== Configuration Read and Parse Actions ==== ConfigParser parser = new ConfigParser(schemaFiles); ConfigT config = parser.parseConfig(configFile); // Print out configuration file contents Formatter formatter = new Formatter(new StringBuilder(), Locale.US); // ===== CONFIG: LOCK FILE ===== File lockFile = new File(config.getLockfile()); logger.info("SeedScan lock file is '" + lockFile + "'"); LockFile lock = new LockFile(lockFile); if (!lock.acquire()) { logger.error("Could not acquire lock."); System.exit(1); } // ===== CONFIG: LOGGING ===== // MTH: This is now done in log4j.properties file // ===== CONFIG: DATABASE ===== MetricDatabase readDB = new MetricDatabase(config.getDatabase()); MetricDatabase writeDB = new MetricDatabase(config.getDatabase()); MetricReader reader = new MetricReader(readDB); MetricInjector injector = new MetricInjector(writeDB); // ===== CONFIG: SCANS ===== Hashtable<String, Scan> scans = new Hashtable<String, Scan>(); if (config.getScans().getScan() == null) { logger.error("No scans in configuration."); System.exit(1); } else { for (ScanT scanCfg : config.getScans().getScan()) { String name = scanCfg.getName(); if (scans.containsKey(name)) { logger.error("Duplicate scan name '" + name + "' encountered."); System.exit(1); } // This should really be handled by jaxb by setting it up in schemas/SeedScanConfig.xsd if (scanCfg.getStartDay() == null && scanCfg.getStartDate() == null) { logger.error( "== SeedScan Error: Must set EITHER cfg:start_day -OR- cfg:start_date in config.xml to start Scan!"); System.exit(1); } // Configure this Scan Scan scan = new Scan(scanCfg.getName()); scan.setPathPattern(scanCfg.getPath()); scan.setDatalessDir(scanCfg.getDatalessDir()); scan.setEventsDir(scanCfg.getEventsDir()); scan.setPlotsDir(scanCfg.getPlotsDir()); scan.setDaysToScan(scanCfg.getDaysToScan().intValue()); if (scanCfg.getStartDay() != null) { scan.setStartDay(scanCfg.getStartDay().intValue()); } if (scanCfg.getStartDate() != null) { scan.setStartDate(scanCfg.getStartDate().intValue()); } if (scanCfg.getNetworkSubset() != null) { logger.debug("Filter on Network Subset=[{}]", scanCfg.getNetworkSubset()); Filter filter = new Filter(false); for (String network : scanCfg.getNetworkSubset().split(",")) { logger.debug("Network =[{}]", network); filter.addFilter(network); } scan.setNetworks(filter); } if (scanCfg.getStationSubset() != null) { logger.debug("Filter on Station Subset=[{}]", scanCfg.getStationSubset()); Filter filter = new Filter(false); for (String station : scanCfg.getStationSubset().split(",")) { logger.debug("Station =[{}]", station); filter.addFilter(station); } scan.setStations(filter); } if (scanCfg.getLocationSubset() != null) { logger.debug("Filter on Location Subset=[{}]", scanCfg.getLocationSubset()); Filter filter = new Filter(false); for (String location : scanCfg.getLocationSubset().split(",")) { logger.debug("Location =[{}]", location); filter.addFilter(location); } scan.setLocations(filter); } if (scanCfg.getChannelSubset() != null) { logger.debug("Filter on Channel Subset=[{}]", scanCfg.getChannelSubset()); Filter filter = new Filter(false); for (String channel : scanCfg.getChannelSubset().split(",")) { logger.debug("Channel =[{}]", channel); filter.addFilter(channel); } scan.setChannels(filter); } for (MetricT met : scanCfg.getMetrics().getMetric()) { try { Class<?> metricClass = Class.forName(met.getClassName()); MetricWrapper wrapper = new MetricWrapper(metricClass); for (ArgumentT arg : met.getArgument()) { wrapper.add(arg.getName(), arg.getValue()); } scan.addMetric(wrapper); } catch (ClassNotFoundException ex) { logger.error("No such metric class '" + met.getClassName() + "'"); System.exit(1); } catch (InstantiationException ex) { logger.error("Could not dynamically instantiate class '" + met.getClassName() + "'"); System.exit(1); } catch (IllegalAccessException ex) { logger.error("Illegal access while loading class '" + met.getClassName() + "'"); System.exit(1); } catch (NoSuchFieldException ex) { logger.error("Invalid dynamic argument to Metric subclass '" + met.getClassName() + "'"); System.exit(1); } } scans.put(name, scan); } } // ==== Establish Database Connection ==== // TODO: State Tracking in the Database // - Record scan started in database. // - Track our progress as we go so a new process can pick up where // we left off if our process dies. // - Mark when each date-station-channel-operation is complete //LogDatabaseHandler logDB = new LogDatabaseHandler(configuration.get // For each day ((yesterday - scanDepth) to yesterday) // scan for these channel files, only process them if // they have not yet been scanned, or if changes have // occurred to the file since its last scan. Do this for // each scan type. Do not re-scan data for each type, // launch processes for each scan and use the same data set // for each. If we can pipe the data as it is read, do so. // If we need to push all of it at once, do these in sequence // in order to preserve overall system memory resources. Scan scan = null; // ==== Perform Scans ==== scan = scans.get("daily"); //MTH: This part could/should be moved up higher except that we need to know datalessDir, which, // at this point, is configured on a per scan basis ... so we need to know what scan we're doing MetaServer metaServer = null; if (config.getMetaserver() != null) { if (config.getMetaserver().getUseRemote().equals("yes") || config.getMetaserver().getUseRemote().equals("true")) { String remoteServer = config.getMetaserver().getRemoteUri(); try { metaServer = new MetaServer(new URI(remoteServer)); } catch (Exception e) { logger.error("caught URI exception:" + e.getMessage()); } } else { metaServer = new MetaServer(scan.getDatalessDir()); } } else { // Use local MetaServer metaServer = new MetaServer(scan.getDatalessDir()); } List<Station> stations = null; if (config.getStationList() == null) { // get StationList from MetaServer logger.info("Get StationList from MetaServer"); stations = metaServer.getStationList(); } else { // read StationList from config.xml logger.info("Read StationList from config.xml"); List<String> stationList = config.getStationList().getStation(); if (stationList.size() > 0) { stations = new ArrayList<Station>(); for (String station : stationList) { String[] words = station.split("_"); if (words.length != 2) { logger.warn(String.format("stationList: station=[%s] is NOT a valid station --> Skip", station)); } else { stations.add(new Station(words[0], words[1])); logger.info("config.xml: Read station:" + station); } } } else { logger.error("Error: No valid stations read from config.xml"); } } if (stations == null) { logger.error("Found NO stations to scan --> EXITTING SeedScan"); System.exit(1); } Thread readerThread = new Thread(reader); readerThread.start(); logger.info("Reader thread started."); Thread injectorThread = new Thread(injector); injectorThread.start(); logger.info("Injector thread started."); // Loop over scans and hand each one to a ScanManager logger.info("Hand scan to ScanManager"); for (String key : scans.keySet()) { scan = scans.get(key); logger.info(String.format("Scan=[%s] startDay=%d startDate=%d daysToScan=%d\n", key, scan.getStartDay(), scan.getStartDate(), scan.getDaysToScan())); ScanManager scanManager = new ScanManager(reader, injector, stations, scan, metaServer); } logger.info("ScanManager is [ FINISHED ] --> stop the injector and reader threads"); try { injector.halt(); logger.info("All stations processed. Waiting for injector thread to finish..."); synchronized (injectorThread) { //injectorThread.wait(); injectorThread.interrupt(); } logger.info("Injector thread halted."); } catch (InterruptedException ex) { logger.warn("The injector thread was interrupted while attempting to complete requests."); } try { reader.halt(); logger.info("All stations processed. Waiting for reader thread to finish..."); synchronized (readerThread) { //readerThread.wait(); readerThread.interrupt(); } logger.info("Reader thread halted."); } catch (InterruptedException ex) { logger.warn("The reader thread was interrupted while attempting to complete requests."); } try { lock.release(); } catch (IOException e) { ; } finally { logger.info("Release seedscan lock and quit metaServer"); lock = null; metaServer.quit(); } }
From source file:de.burlov.amazon.s3.dirsync.CLI.java
/** * @param args//from w ww.ja va 2 s . com */ @SuppressWarnings("static-access") public static void main(String[] args) { Logger.getLogger("").setLevel(Level.OFF); Logger deLogger = Logger.getLogger("de"); deLogger.setLevel(Level.INFO); Handler handler = new ConsoleHandler(); handler.setFormatter(new VerySimpleFormatter()); deLogger.addHandler(handler); deLogger.setUseParentHandlers(false); // if (true) // { // LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception")); // return; // } Options opts = new Options(); OptionGroup gr = new OptionGroup(); /* * Befehlsgruppe initialisieren */ gr = new OptionGroup(); gr.setRequired(true); gr.addOption(OptionBuilder.withArgName("up|down").hasArg() .withDescription("Upload/Download changed or new files").create(CMD_UPDATE)); gr.addOption(OptionBuilder.withArgName("up|down").hasArg() .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT)); gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR)); gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET)); gr.addOption(OptionBuilder.create(CMD_HELP)); gr.addOption(OptionBuilder.create(CMD_VERSION)); gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY)); gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP)); gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password") .hasArg().create(CMD_CHANGE_PASSWORD)); gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS)); gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET)); gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR)); opts.addOptionGroup(gr); /* * Parametergruppe initialisieren */ opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key") .create(OPT_S3S_KEY)); opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg() .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET)); opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription( "Optional bucket name for storage. If not specified then an unique bucket name will be generated") .create(OPT_BUCKET)); // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg(). // withDescription( // "Where the new bucket should be created. Default US").create( // OPT_LOCATION)); opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg() .withDescription("Local directory path").create(OPT_LOCAL_DIR)); opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg() .withDescription("Remote directory name").create(OPT_REMOTE_DIR)); opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg() .withDescription("Encryption password").create(OPT_ENC_PASSWORD)); opts.addOption(OptionBuilder.withArgName("patterns").hasArgs() .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'") .create(OPT_EXCLUDE_PATTERNS)); opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription( "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included") .create(OPT_INCLUDE_PATTERNS)); if (args.length == 0) { printUsage(opts); return; } CommandLine cmd = null; try { cmd = new GnuParser().parse(opts, args); if (cmd.hasOption(CMD_HELP)) { printUsage(opts); return; } if (cmd.hasOption(CMD_VERSION)) { System.out.println("s3dirsync version " + Version.CURRENT_VERSION); return; } String awsKey = cmd.getOptionValue(OPT_S3S_KEY); String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET); String bucket = cmd.getOptionValue(OPT_BUCKET); String bucketLocation = cmd.getOptionValue(OPT_LOCATION); String localDir = cmd.getOptionValue(OPT_LOCAL_DIR); String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR); String password = cmd.getOptionValue(OPT_ENC_PASSWORD); String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS); String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS); if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) { System.out.println("S3 account data required"); return; } if (StringUtils.isBlank(bucket)) { bucket = awsKey + ".dirsync"; } if (cmd.hasOption(CMD_DELETE_BUCKET)) { if (StringUtils.isBlank(bucket)) { System.out.println("Bucket name required"); return; } int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket); System.out.println("Deleted objects: " + deleted); return; } if (cmd.hasOption(CMD_LIST_BUCKETS)) { for (String str : S3Utils.listBuckets(awsKey, awsSecret)) { System.out.println(str); } return; } if (cmd.hasOption(CMD_LIST_BUCKET)) { if (StringUtils.isBlank(bucket)) { System.out.println("Bucket name required"); return; } for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) { System.out.println(str); } return; } if (StringUtils.isBlank(password)) { System.out.println("Encryption password required"); return; } char[] psw = password.toCharArray(); DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw); ds.setExcludePatterns(parseSubargumenths(exclude)); ds.setIncludePatterns(parseSubargumenths(include)); if (cmd.hasOption(CMD_SUMMARY)) { ds.printStorageSummary(); return; } if (StringUtils.isBlank(remoteDir)) { System.out.println("Remote directory name required"); return; } if (cmd.hasOption(CMD_DELETE_DIR)) { ds.deleteFolder(remoteDir); return; } if (cmd.hasOption(CMD_LIST_DIR)) { Folder folder = ds.getFolder(remoteDir); if (folder == null) { System.out.println("No such folder found: " + remoteDir); return; } for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) { System.out.println(entry.getKey() + " (" + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")"); } return; } if (cmd.hasOption(CMD_CLEANUP)) { ds.cleanUp(); return; } if (cmd.hasOption(CMD_CHANGE_PASSWORD)) { String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD); if (StringUtils.isBlank(newPassword)) { System.out.println("new password required"); return; } char[] chars = newPassword.toCharArray(); ds.changePassword(chars); newPassword = null; Arrays.fill(chars, ' '); return; } if (StringUtils.isBlank(localDir)) { System.out.println(OPT_LOCAL_DIR + " argument required"); return; } String direction = ""; boolean up = false; boolean snapshot = false; if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) { direction = cmd.getOptionValue(CMD_UPDATE); } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) { direction = cmd.getOptionValue(CMD_SNAPSHOT); snapshot = true; } if (StringUtils.isBlank(direction)) { System.out.println("Operation direction required"); return; } up = StringUtils.equalsIgnoreCase(OPT_UP, direction); File baseDir = new File(localDir); if (!baseDir.exists() && !baseDir.mkdirs()) { System.out.println("Invalid local directory: " + baseDir.getAbsolutePath()); return; } ds.syncFolder(baseDir, remoteDir, up, snapshot); } catch (DirSyncException e) { System.out.println(e.getMessage()); e.printStackTrace(); } catch (ParseException e) { System.out.println(e.getMessage()); printUsage(opts); } catch (Exception e) { e.printStackTrace(System.err); } }
From source file:it.unipd.dei.ims.falcon.CmdLine.java
public static void main(String[] args) { // last argument is always index path Options options = new Options(); // one of these actions has to be specified OptionGroup actionGroup = new OptionGroup(); actionGroup.addOption(new Option("i", true, "perform indexing")); // if dir, all files, else only one file actionGroup.addOption(new Option("q", true, "perform a single query")); actionGroup.addOption(new Option("b", false, "perform a query batch (read from stdin)")); actionGroup.setRequired(true);//from w w w .j a v a 2 s . c om options.addOptionGroup(actionGroup); // other options options.addOption(new Option("l", "segment-length", true, "length of a segment (# of chroma vectors)")); options.addOption( new Option("o", "segment-overlap", true, "overlap portion of a segment (# of chroma vectors)")); options.addOption(new Option("Q", "quantization-level", true, "quantization level for chroma vectors")); options.addOption(new Option("k", "min-kurtosis", true, "minimum kurtosis for indexing chroma vectors")); options.addOption(new Option("s", "sub-sampling", true, "sub-sampling of chroma features")); options.addOption(new Option("v", "verbose", false, "verbose output (including timing info)")); options.addOption(new Option("T", "transposition-estimator-strategy", true, "parametrization for the transposition estimator strategy")); options.addOption(new Option("t", "n-transp", true, "number of transposition; if not specified, no transposition is performed")); options.addOption(new Option("f", "force-transp", true, "force transposition by an amount of semitones")); options.addOption(new Option("p", "pruning", false, "enable query pruning; if -P is unspecified, use default strategy")); options.addOption(new Option("P", "pruning-custom", true, "custom query pruning strategy")); // parse HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.getArgs().length != 1) throw new ParseException("no index path was specified"); } catch (ParseException ex) { System.err.println("ERROR - parsing command line:"); System.err.println(ex.getMessage()); formatter.printHelp("falcon -{i,q,b} [options] index_path", options); return; } // default values final float[] DEFAULT_TRANSPOSITION_ESTIMATOR_STRATEGY = new float[] { 0.65192807f, 0.0f, 0.0f, 0.0f, 0.3532628f, 0.4997167f, 0.0f, 0.41703504f, 0.0f, 0.16297342f, 0.0f, 0.0f }; final String DEFAULT_QUERY_PRUNING_STRATEGY = "ntf:0.340765*[0.001694,0.995720];ndf:0.344143*[0.007224,0.997113];" + "ncf:0.338766*[0.001601,0.995038];nmf:0.331577*[0.002352,0.997884];"; // TODO not the final one int hashes_per_segment = Integer.parseInt(cmd.getOptionValue("l", "150")); int overlap_per_segment = Integer.parseInt(cmd.getOptionValue("o", "50")); int nranks = Integer.parseInt(cmd.getOptionValue("Q", "3")); int subsampling = Integer.parseInt(cmd.getOptionValue("s", "1")); double minkurtosis = Float.parseFloat(cmd.getOptionValue("k", "-100.")); boolean verbose = cmd.hasOption("v"); int ntransp = Integer.parseInt(cmd.getOptionValue("t", "1")); TranspositionEstimator tpe = null; if (cmd.hasOption("t")) { if (cmd.hasOption("T")) { // TODO this if branch is yet to test Pattern p = Pattern.compile("\\d\\.\\d*"); LinkedList<Double> tokens = new LinkedList<Double>(); Matcher m = p.matcher(cmd.getOptionValue("T")); while (m.find()) tokens.addLast(new Double(cmd.getOptionValue("T").substring(m.start(), m.end()))); float[] strategy = new float[tokens.size()]; if (strategy.length != 12) { System.err.println("invalid transposition estimator strategy"); System.exit(1); } for (int i = 0; i < strategy.length; i++) strategy[i] = new Float(tokens.pollFirst()); } else { tpe = new TranspositionEstimator(DEFAULT_TRANSPOSITION_ESTIMATOR_STRATEGY); } } else if (cmd.hasOption("f")) { int[] transps = parseIntArray(cmd.getOptionValue("f")); tpe = new ForcedTranspositionEstimator(transps); ntransp = transps.length; } QueryPruningStrategy qpe = null; if (cmd.hasOption("p")) { if (cmd.hasOption("P")) { qpe = new StaticQueryPruningStrategy(cmd.getOptionValue("P")); } else { qpe = new StaticQueryPruningStrategy(DEFAULT_QUERY_PRUNING_STRATEGY); } } // action if (cmd.hasOption("i")) { try { Indexing.index(new File(cmd.getOptionValue("i")), new File(cmd.getArgs()[0]), hashes_per_segment, overlap_per_segment, subsampling, nranks, minkurtosis, tpe, verbose); } catch (IndexingException ex) { Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex); } } if (cmd.hasOption("q")) { String queryfilepath = cmd.getOptionValue("q"); doQuery(cmd, queryfilepath, hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp, minkurtosis, qpe, verbose); } if (cmd.hasOption("b")) { try { long starttime = System.currentTimeMillis(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = null; while ((line = in.readLine()) != null && !line.trim().isEmpty()) doQuery(cmd, line, hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp, minkurtosis, qpe, verbose); in.close(); long endtime = System.currentTimeMillis(); System.out.println(String.format("total time: %ds", (endtime - starttime) / 1000)); } catch (IOException ex) { Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.hurence.logisland.plugin.PluginManager.java
public static void main(String... args) throws Exception { System.out.println(BannerLoader.loadBanner()); String logislandHome = new File( new File(PluginManager.class.getProtectionDomain().getCodeSource().getLocation().getPath()) .getParent()).getParent(); System.out.println("Using Logisland home: " + logislandHome); Options options = new Options(); OptionGroup mainGroup = new OptionGroup() .addOption(OptionBuilder.withDescription( "Install a component. It can be either a logisland plugin or a kafka connect module.") .withArgName("artifact").hasArgs(1).withLongOpt("install").create("i")) .addOption(OptionBuilder.withDescription( "Removes a component. It can be either a logisland plugin or a kafka connect module.") .withArgName("artifact").hasArgs(1).withLongOpt("remove").create("r")) .addOption(OptionBuilder.withDescription("List installed components.").withLongOpt("list") .create("l")); mainGroup.setRequired(true);//from w ww. j a va 2 s. c o m options.addOptionGroup(mainGroup); options.addOption(OptionBuilder.withDescription("Print this help.").withLongOpt("help").create("h")); try { CommandLine commandLine = new PosixParser().parse(options, args); System.out.println(commandLine.getArgList()); if (commandLine.hasOption("l")) { listPlugins(); } else if (commandLine.hasOption("i")) { installPlugin(commandLine.getOptionValue("i"), logislandHome); } else if (commandLine.hasOption("r")) { removePlugin(commandLine.getOptionValue("r")); } else { printUsage(options); } } catch (ParseException e) { if (!options.hasOption("h")) { System.err.println(e.getMessage()); System.out.println(); } printUsage(options); } }
From source file:Executable.LinkImputeR.java
/** * Main function//from ww w . j av a 2 s . co m * @param args Command line arguments * @throws Exception If an uncaught error occurs */ public static void main(String[] args) throws Exception { try { Options options = new Options(); OptionGroup all = new OptionGroup(); all.addOption(Option.builder("c").build()); all.addOption(Option.builder("s").build()); all.addOption(Option.builder("v").build()); all.addOption(Option.builder("h").build()); options.addOptionGroup(all); CommandLineParser parser = new DefaultParser(); CommandLine commands = parser.parse(options, args); String[] fileNames = commands.getArgs(); XMLConfiguration c; boolean done = false; if (commands.hasOption("c")) { if (fileNames.length == 2) { c = convert(new File(fileNames[0])); writeXML(c, new File(fileNames[1])); } else { System.out.println("An input and output file must be provided"); System.out.println(); help(); } done = true; } if (commands.hasOption("s")) { if (fileNames.length == 1) { c = convert(new File(fileNames[0])); accuracy(c); } else { System.out.println("An input file must be provided"); System.out.println(); help(); } done = true; } if (commands.hasOption("v")) { System.out.println("LinkImputeR version 1.1.3"); done = true; } if (commands.hasOption("h")) { help(); done = true; } if (!done) { if (fileNames.length == 3) { File xml = new File(fileNames[0]); FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>( XMLConfiguration.class).configure(new Parameters().xml().setFile(xml)); XMLConfiguration config = builder.getConfiguration(); switch (config.getString("mode")) { case "accuracy": accuracy(config); break; case "impute": if (args.length == 3) { impute(config, args[1], new File(args[2])); } else { impute(config, null, null); } break; } } else { System.out.println("An input file, case name and output file must be provided (in that order)"); System.out.println(); help(); } } } catch (UnrecognizedOptionException ex) { System.err.println("Unrecognised command line option (" + ex.getOption() + ")"); System.err.println(); help(); } catch (AlreadySelectedException ex) { System.err.println("Only one option can be selected at a time"); System.err.println(); help(); } catch (VCFException ex) { System.err.println("====="); System.err.println("ERROR"); System.err.println("====="); System.err.println("There's a problem with the VCF file"); System.err.println(ex.getMessage()); System.err.println(); System.err.println("Technical details follow:"); throw ex; } catch (INIException ex) { System.err.println("====="); System.err.println("ERROR"); System.err.println("====="); System.err.println("There's a problem with the ini file"); System.err.println(ex.getMessage()); System.err.println(); System.err.println("Technical details follow:"); throw ex; } catch (OutputException ex) { System.err.println("====="); System.err.println("ERROR"); System.err.println("====="); System.err.println("There's a problem writing an output file"); System.err.println(ex.getMessage()); System.err.println(); System.err.println("Technical details follow:"); throw ex; } catch (AlgorithmException ex) { System.err.println("====="); System.err.println("ERROR"); System.err.println("====="); System.err.println("There's a problem with the algorithms"); System.err.println(ex.getMessage()); System.err.println(); System.err.println("Technical details follow:"); throw ex; } catch (ProgrammerException ex) { System.err.println("====="); System.err.println("ERROR"); System.err.println("====="); System.err.println("Well this is embarrassing. This shouldn't have happened. " + "Please contact the maintainer if you can not solve the error" + "from the technical details."); System.err.println(); System.err.println("Technical details follow:"); throw ex; } catch (Exception ex) { System.err.println("====="); System.err.println("ERROR"); System.err.println("====="); System.err.println("Well this is embarrassing. This was not expected to have happened. " + "Please contact the maintainer if you can not solve the error" + "from the technical details."); System.err.println(); System.err.println("Note: The maintainer would be interested in knowing " + "about any XML related messages so he can write nicer error " + "messages for these problems."); System.err.println(); System.err.println("Technical details follow:"); throw ex; } }
From source file:ca.uhn.hunit.run.TestRunner.java
/** * @param args/*from ww w. j av a 2s .c om*/ * @throws URISyntaxException * @throws JAXBException * @throws ConfigurationException * @throws InterfaceWontStartException * @throws FileNotFoundException * @throws ParseException */ public static void main(String[] theArgs) throws URISyntaxException, JAXBException, InterfaceWontStartException, ConfigurationException, FileNotFoundException, ParseException { Options options = new Options(); OptionGroup fileOptionGroup = new OptionGroup(); fileOptionGroup.setRequired(false); Option option = new Option("f", "file", true, "The path to the file to load the test battery from"); option.setValueSeparator('='); fileOptionGroup.addOption(option); option = new Option("c", "classpath", true, "The classpath path to the file to load the test battery from"); option.setValueSeparator('='); fileOptionGroup.addOption(option); options.addOptionGroup(fileOptionGroup); OptionGroup uiOptionGroup = new OptionGroup(); option = new Option("g", "gui", false, "Start hUnit in GUI mode (default)"); uiOptionGroup.addOption(option); option = new Option("x", "text", false, "Start hUnit in Text mode"); uiOptionGroup.addOption(option); options.addOptionGroup(uiOptionGroup); option = new Option("t", "tests", true, "A comma separated list of tests to execute (default is all)"); option.setValueSeparator('='); option.setRequired(false); options.addOption(option); Resource defFile = null; CommandLine parser; boolean textMode = false; try { parser = new PosixParser().parse(options, theArgs); if (parser.hasOption("f")) { defFile = new FileSystemResource(parser.getOptionValue("f")); } else if (parser.hasOption("c")) { defFile = new ClassPathResource(parser.getOptionValue("c")); } if (parser.hasOption("x")) { textMode = true; } } catch (Exception e) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar hunit-[version]-jar-with-dependencies.jar [-c FILE|-f FILE] [options]", options); return; } String[] testsToExecute = null; if (parser.hasOption("t")) { testsToExecute = parser.getOptionValue("t").split(","); } if (textMode) { executeInTextMode(defFile, testsToExecute); } else { executeInGuiMode(defFile, testsToExecute); } }
From source file:name.wagners.bpp.Bpp.java
public static void main(final String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("generations") .withDescription("Number of generations [default: 50]").create("g")); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("mutrate") .withDescription("Mutation rate [default: 1]").create()); options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("mutprop") .withDescription("Mutation propability [default: 0.5]").create()); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("populationsize") .withDescription("Size of population [default: 20]").create()); options.addOption(OptionBuilder.hasArg().withArgName("a|b").withLongOpt("recombalg") .withDescription("Recombination algorithm [default: a]").create()); // options.addOption(OptionBuilder // .hasArg()//from w ww . j av a 2 s .c o m // .withArgName("int") // .withLongOpt("recombrate") // .withDescription("Recombination rate [default: 1]") // .create()); options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("recombprop") .withDescription("Recombination propability [default: 0.8]").create()); options.addOption(OptionBuilder.hasArg().withArgName("a").withLongOpt("selalg") .withDescription("Selection algorithm [default: a]").create()); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("selectionpressure") .withDescription("Selection pressure [default: 4]").create()); options.addOption(OptionBuilder.hasArg().withArgName("bool").withLongOpt("elitism") .withDescription("Enable Elitism [default: 1]").create("e")); options.addOption(OptionBuilder.hasArg().withArgName("filename") // .isRequired() .withLongOpt("datafile").withDescription("Problem data file [default: \"binpack.txt\"]") .create("f")); options.addOptionGroup(new OptionGroup() .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v")) .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q"))); options.addOption(OptionBuilder.withLongOpt("version") .withDescription("print the version information and exit").create("V")); options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h")); try { // parse the command line arguments CommandLine line = parser.parse(options, args); // validate that block-size has been set if (line.hasOption("help")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Bpp", options); System.exit(0); } if (line.hasOption("version")) { log.info("Bpp 0.1 (c) 2007 by Daniel Wagner"); } if (line.hasOption("datafile")) { fname = line.getOptionValue("datafile"); } if (line.hasOption("elitism")) { elitism = Boolean.parseBoolean(line.getOptionValue("elitism")); } if (line.hasOption("generations")) { gen = Integer.parseInt(line.getOptionValue("generations")); } if (line.hasOption("mutprop")) { mp = Double.parseDouble(line.getOptionValue("mutprop")); } if (line.hasOption("mutrate")) { mr = Integer.parseInt(line.getOptionValue("mutrate")); } if (line.hasOption("populationsize")) { ps = Integer.parseInt(line.getOptionValue("populationsize")); } if (line.hasOption("recombalg")) { sel = line.getOptionValue("recombalg").charAt(0); } if (line.hasOption("recombprop")) { rp = Double.parseDouble(line.getOptionValue("recombprop")); } if (line.hasOption("selalg")) { selalg = line.getOptionValue("selalg").charAt(0); } if (line.hasOption("selectionpressure")) { sp = Integer.parseInt(line.getOptionValue("selectionpressure")); } } catch (ParseException exp) { log.info("Unexpected exception:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Bpp", options); System.exit(1); } // Ausgabe der eingestellten Optionen log.info("Configuration"); log.info(" Datafile: " + fname); log.info(" Generations: " + gen); log.info(" Population size: " + ps); log.info(" Elitism: " + elitism); log.info(" Mutation propapility: " + mp); log.info(" Mutation rate: " + mr); log.info(" Recombination algorithm " + (char) sel); log.info(" Recombination propapility: " + rp); log.info(" Selection pressure: " + sp); // Daten laden instance = new Instance(); instance.load(fname); Evolutionizer e = new Evolutionizer(instance); e.run(); }
From source file:LNISmokeTest.java
/** * Execute command line. See Usage string for options and arguments. * // w ww . j ava2 s . c o m * @param argv the argv * * @throws Exception the exception */ public static void main(String[] argv) throws Exception { Options options = new Options(); OptionGroup func = new OptionGroup(); func.addOption(new Option("c", "copy", true, "copy <Item> to -C <Collection>")); func.addOption(new Option("s", "submit", true, "submit <collection> -P <packager> -i <file>")); func.addOption(new Option("d", "disseminate", true, "disseminate <item> -P <packager> -o <file>")); func.addOption(new Option("f", "propfind", true, "propfind of all properties or -N <propname>")); func.addOption(new Option("r", "rpropfind", true, "recursive propfind, only collections")); func.addOption(new Option("n", "names", true, "list all property names on resource")); func.addOption(new Option("p", "proppatch", true, "set property: <handle> -N <property> -V <newvalue>")); func.setRequired(true); options.addOptionGroup(func); options.addOption("h", "help", false, "show help message"); options.addOption("e", "endpoint", true, "SOAP endpoint URL (REQUIRED)"); options.addOption("P", "packager", true, "Packager to use to import/export a package."); options.addOption("C", "collection", true, "Target collection of -c copy"); options.addOption("o", "output", true, "file to create for new package"); options.addOption("i", "input", true, "file containing package to submit"); options.addOption("N", "name", true, "name of property to query/set"); options.addOption("V", "value", true, "new value for property being set"); try { CommandLine line = (new PosixParser()).parse(options, argv); if (line.hasOption("h")) { usage(options, 0, null); } // get SOAP client connection, using the endpoint URL String endpoint = line.getOptionValue("e"); if (endpoint == null) { usage(options, 2, "Missing the required -e endpoint argument"); } LNISoapServletServiceLocator loc = new LNISoapServletServiceLocator(); LNISoapServlet lni = loc.getDSpaceLNI(new URL(endpoint)); // propfind - with optional single-property Name if (line.hasOption("f")) { String pfXml = (line.hasOption("N")) ? specificPropPrefix + line.getOptionValue("N") + specificPropSuffix : allProp; doPropfind(lni, line.getOptionValue("f"), pfXml, 0, null); } // recursive propfind limited to collection, community objects else if (line.hasOption("r")) { doPropfind(lni, line.getOptionValue("r"), someProp, -1, "collection,community"); } else if (line.hasOption("n")) { doPropfind(lni, line.getOptionValue("n"), nameProp, 0, null); } else if (line.hasOption("p")) { if (line.hasOption("N") && line.hasOption("V")) { doProppatch(lni, line.getOptionValue("p"), line.getOptionValue("N"), line.getOptionValue("V")); } else { usage(options, 13, "Missing required args: -N <name> -V <value>n"); } } // submit a package else if (line.hasOption("s")) { if (line.hasOption("P") && line.hasOption("i")) { doPut(lni, line.getOptionValue("s"), line.getOptionValue("P"), line.getOptionValue("i"), endpoint); } else { usage(options, 13, "Missing required args after -s: -P <packager> -i <file>"); } } // Disseminate (GET) item as package else if (line.hasOption("d")) { if (line.hasOption("P") && line.hasOption("o")) { doGet(lni, line.getOptionValue("d"), line.getOptionValue("P"), line.getOptionValue("o"), endpoint); } else { usage(options, 13, "Missing required args after -d: -P <packager> -o <file>"); } } // copy from src to dst else if (line.hasOption("c")) { if (line.hasOption("C")) { doCopy(lni, line.getOptionValue("c"), line.getOptionValue("C")); } else { usage(options, 13, "Missing required args after -c: -C <collection>\n"); } } else { usage(options, 14, "Missing command option.\n"); } } catch (ParseException pe) { usage(options, 1, "Error in arguments: " + pe.toString()); } catch (java.rmi.RemoteException de) { System.out.println("ERROR, got RemoteException, message=" + de.getMessage()); de.printStackTrace(); die(1, " Exception class=" + de.getClass().getName()); } }
From source file:bogdanrechi.xmlo.Xmlo.java
/** * Main method./*from w w w .j ava2s . c om*/ * * @param args * Program arguments. */ @SuppressWarnings("static-access") public static void main(String[] args) { long timeStart = System.currentTimeMillis(); _log = Logger.getLogger(Xmlo.class); Options argOptions = new Options(); OptionGroup operationTypes = new OptionGroup(); operationTypes.addOption( OptionBuilder.withDescription("XPath query").hasArg().withArgName("file").create("xpath")); operationTypes.addOption( OptionBuilder.withDescription("XSLT transformation").hasArg().withArgName("file").create("xslt")); operationTypes.addOption( OptionBuilder.withDescription("XQuery (with $sourceFilePath, see XmlOperations for details)") .hasArg().withArgName("file").create("xquery")); operationTypes .addOption(OptionBuilder.withDescription("XSD verify").hasArgs().withArgName("file").create("xsd")); operationTypes .addOption(OptionBuilder.withDescription("DTD verify").hasArgs().withArgName("file").create("dtd")); argOptions.addOptionGroup(operationTypes); argOptions.addOption(OptionBuilder.withDescription("on screen information while performing") .withLongOpt("verbose").create("v")); argOptions.addOption(OptionBuilder.withDescription("output non-void or invalid-type results only") .withLongOpt("results-only").create("o")); argOptions.addOption(OptionBuilder.withDescription("replicate input structure on the destination side") .withLongOpt("keep-structure").create("k")); argOptions.addOption(OptionBuilder.withDescription("recursive browsing of the target structure") .withLongOpt("resursive").create("r")); argOptions.addOption(OptionBuilder.withDescription("XPath and XQuery results not numbered") .withLongOpt("not-numbered").create("nn")); argOptions.addOption(OptionBuilder.withDescription("destination files extension").hasArg() .withArgName("ext").withLongOpt("extension").create("x")); argOptions.addOption(OptionBuilder.withDescription("target files mask").hasArg().withArgName("files mask") .withLongOpt("target").create("t")); OptionGroup destinationGroup = new OptionGroup(); destinationGroup.addOption(OptionBuilder.withDescription("destination file").hasArg().withArgName("file") .withLongOpt("destination-file").create("df")); destinationGroup.addOption(OptionBuilder.withDescription("destination folder").hasArg() .withArgName("folder").withLongOpt("destination-directory").create("dd")); destinationGroup.addOption(OptionBuilder.withDescription("destination terminal (and verbose)") .withLongOpt("destination-terminal").create("dt")); argOptions.addOptionGroup(destinationGroup); argOptions.addOption(OptionBuilder.withDescription("file containing namespaces aliases").hasArg() .withArgName("file").withLongOpt("namespaces").create("n")); argOptions.addOption(OptionBuilder.withDescription("usage information").withLongOpt("help").create("h")); argOptions.addOption(OptionBuilder.withDescription("show examples").withLongOpt("examples").create("e")); argOptions.addOption(OptionBuilder.withDescription("keep blank nodes while printing") .withLongOpt("keep-blanks").create("b")); argOptions.addOption( OptionBuilder.withDescription("show duration for each file when the verbose option is activated") .withLongOpt("show-duration").create("d")); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(argOptions, args); if (cmd.hasOption('h') || cmd.hasOption('e') || cmd.getOptions().length == 0) { Format.println("\n" + General.getAboutInformation("resources/xmlo/metadata.properties")); if (cmd.hasOption('h') || cmd.getOptions().length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("xmlo", "where:", argOptions, null, true); Format.println(); } if (cmd.hasOption("e")) { String examples = Files.readTextFileFromResources("resources/xmlo/examples.txt", _errorMessage); if (examples != null) Format.println(examples); else { Format.println("Internal error! Please see the log file for detalis."); _log.error(_errorMessage.get()); System.exit(1); } } System.exit(0); return; } Format.println(); // options if (cmd.hasOption('r')) _recursive = true; if (cmd.hasOption('k')) _keepStructure = true; if (cmd.hasOption('o')) _resultsOnly = true; if (cmd.hasOption('v')) _verbose = true; if (cmd.hasOption('b')) _keepBlanks = true; if (cmd.hasOption('d')) _showDuration = true; if (cmd.hasOption('x')) _extension = "." + cmd.getOptionValue('x'); if (cmd.hasOption("nn")) _notNumbered = true; if (cmd.hasOption("df")) { _destination = cmd.getOptionValue("df"); if (Files.isFolder(_destination)) printErrorAndExit("The destination is a folder!"); _destinationIsFile = true; } if (cmd.hasOption("dd")) { _destination = cmd.getOptionValue("dd"); if (!Files.exists(_destination)) printErrorAndExit("The destination folder does not exist!"); if (!Files.isFolder(_destination)) printErrorAndExit("The destination is not a folder!"); } if (cmd.hasOption("dt")) _destinationIsTerminal = _verbose = true; if (cmd.hasOption('t')) _target = cmd.getOptionValue('t'); if (cmd.hasOption('n')) { _namespaces = cmd.getOptionValue('n'); extractNamespacesAliases(); } // operations if (cmd.hasOption("xpath")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XPATH; doXPath(cmd.getOptionValue("xpath")); } if (cmd.hasOption("xslt")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XSLT; doXslt(cmd.getOptionValue("xslt")); } if (cmd.hasOption("xquery")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XQUERY; doXQuery(cmd.getOptionValue("xquery")); } if (cmd.hasOption("xsd")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XSD; doXsd(cmd.getOptionValues("xsd")); } if (cmd.hasOption("dtd")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_DTD; doDtd(cmd.getOptionValues("dtd")); } } catch (ParseException e) { printErrorAndExit(e.getMessage()); } Format.println("Finished%s.", _showDuration ? " in " + TimeMeasure.printDuration(timeStart) : ""); if (Platform.SYSTEM_IS_LINUX) Format.println(); System.exit(0); }
From source file:asl.seedscan.DQAWeb.java
public static void main(String args[]) { db = new MetricDatabase("", "", ""); findConsoleHandler();/*from w w w .j av a 2 s . c o m*/ consoleHandler.setLevel(Level.ALL); Logger.getLogger("").setLevel(Level.CONFIG); // Default locations of config and schema files File configFile = new File("dqaweb-config.xml"); File schemaFile = new File("schemas/DQAWebConfig.xsd"); boolean parseConfig = true; boolean testMode = false; ArrayList<File> schemaFiles = new ArrayList<File>(); schemaFiles.add(schemaFile); // ==== Command Line Parsing ==== Options options = new Options(); Option opConfigFile = new Option("c", "config-file", true, "The config file to use for seedscan. XML format according to SeedScanConfig.xsd."); Option opSchemaFile = new Option("s", "schema-file", true, "The schame file which should be used to verify the config file format. "); Option opTest = new Option("t", "test", false, "Run in test console mode rather than as a servlet."); OptionGroup ogConfig = new OptionGroup(); ogConfig.addOption(opConfigFile); OptionGroup ogSchema = new OptionGroup(); ogConfig.addOption(opSchemaFile); OptionGroup ogTest = new OptionGroup(); ogTest.addOption(opTest); options.addOptionGroup(ogConfig); options.addOptionGroup(ogSchema); options.addOptionGroup(ogTest); PosixParser optParser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = optParser.parse(options, args, true); } catch (org.apache.commons.cli.ParseException e) { logger.severe("Error while parsing command-line arguments."); System.exit(1); } Option opt; Iterator iter = cmdLine.iterator(); while (iter.hasNext()) { opt = (Option) iter.next(); if (opt.getOpt().equals("c")) { configFile = new File(opt.getValue()); } else if (opt.getOpt().equals("s")) { schemaFile = new File(opt.getValue()); } else if (opt.getOpt().equals("t")) { testMode = true; } } String query = ""; System.out.println("Entering Test Mode"); System.out.println("Enter a query string to view results or type \"help\" for example query strings"); InputStreamReader input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(input); String result = ""; while (testMode == true) { try { System.out.printf("Query: "); query = reader.readLine(); if (query.equals("exit")) { testMode = false; } else if (query.equals("help")) { System.out.println("Need to add some help for people"); //TODO } else { result = processCommand(query); } System.out.println(result); } catch (IOException err) { System.err.println("Error reading line, in DQAWeb.java"); } } System.err.printf("DONE.\n"); }