List of usage examples for org.apache.commons.cli Option getOpt
public String getOpt()
From source file:com.evolveum.midpoint.tools.gui.Main.java
public static void main(String[] args) throws Exception { Options options = new Options(); Option propertiesLocaleDelimiter = new Option("d", "delimiter", true, "Delimiter for locale name in properties file. Default is '_' (underscore)."); options.addOption(propertiesLocaleDelimiter); Option targetFolder = new Option("t", "targetFolder", true, "Target folder where properties file is generated."); targetFolder.setRequired(true);//from w ww .j a v a2 s . com options.addOption(targetFolder); Option baseFolder = new Option("b", "baseFolder", true, "Base folder used for properties files searching."); baseFolder.setRequired(true); options.addOption(baseFolder); Option localesToCheck = new Option("l", "locale", true, "Locales to check."); localesToCheck.setRequired(true); options.addOption(localesToCheck); Option recursiveFolderToCheck = new Option("r", "folderRecursive", true, "Folder used for recursive search for properties files."); options.addOption(recursiveFolderToCheck); Option nonRecursiveFolderToCheck = new Option("n", "folderNonRecursive", true, "Folder used for non recursive search for properties files."); options.addOption(nonRecursiveFolderToCheck); Option help = new Option("h", "help", false, "Print this help."); options.addOption(help); Option disableBackup = new Option("db", "disableBackup", false, "Disable backuping property files."); options.addOption(disableBackup); try { CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (line.hasOption(help.getOpt())) { printHelp(options); return; } if (!line.hasOption(recursiveFolderToCheck.getOpt()) && !line.hasOption(nonRecursiveFolderToCheck.getOpt())) { printHelp(options); return; } GeneratorConfiguration config = new GeneratorConfiguration(); if (line.hasOption(baseFolder.getOpt())) { config.setBaseFolder(new File(line.getOptionValue(baseFolder.getOpt()))); } if (line.hasOption(targetFolder.getOpt())) { config.setTargetFolder(new File(line.getOptionValue(targetFolder.getOpt()))); } if (line.hasOption(propertiesLocaleDelimiter.getOpt())) { config.setPropertiesLocaleDelimiter(line.getOptionValue(propertiesLocaleDelimiter.getOpt())); } if (line.hasOption(recursiveFolderToCheck.getOpt())) { String[] recursives = line.getOptionValues(recursiveFolderToCheck.getOpt()); if (recursives != null && recursives.length > 0) { for (String recursive : recursives) { config.getRecursiveFolderToCheck().add(recursive); } } } if (line.hasOption(nonRecursiveFolderToCheck.getOpt())) { String[] nonRecursives = line.getOptionValues(nonRecursiveFolderToCheck.getOpt()); if (nonRecursives != null && nonRecursives.length > 0) { for (String nonRecursive : nonRecursives) { config.getNonRecursiveFolderToCheck().add(nonRecursive); } } } if (line.hasOption(localesToCheck.getOpt())) { String[] locales = line.getOptionValues(localesToCheck.getOpt()); for (String locale : locales) { config.getLocalesToCheck().add(getLocaleFromString(locale)); } } if (line.hasOption(disableBackup.getOpt())) { config.setDisableBackup(true); } PropertiesGenerator generator = new PropertiesGenerator(config); generator.generate(); } catch (ParseException ex) { System.out.println("Error: " + ex.getMessage()); printHelp(options); } catch (Exception ex) { System.out.println("Something is broken."); ex.printStackTrace(); } }
From source file:com.ibm.crail.namenode.NameNode.java
public static void main(String args[]) throws Exception { LOG.info("initalizing namenode "); CrailConfiguration conf = new CrailConfiguration(); CrailConstants.updateConstants(conf); URI uri = CrailUtils.getPrimaryNameNode(); String address = uri.getHost(); int port = uri.getPort(); if (args != null) { Option addressOption = Option.builder("a").desc("ip address namenode is started on").hasArg().build(); Option portOption = Option.builder("p").desc("port namenode is started on").hasArg().build(); Options options = new Options(); options.addOption(portOption);/*from w w w . j av a 2 s . c om*/ options.addOption(addressOption); CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length)); if (line.hasOption(addressOption.getOpt())) { address = line.getOptionValue(addressOption.getOpt()); } if (line.hasOption(portOption.getOpt())) { port = Integer.parseInt(line.getOptionValue(portOption.getOpt())); } } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Namenode", options); System.exit(-1); } } String namenode = "crail://" + address + ":" + port; long serviceId = CrailUtils.getServiceId(namenode); long serviceSize = CrailUtils.getServiceSize(); if (!CrailUtils.verifyNamenode(namenode)) { throw new Exception("Namenode address/port [" + namenode + "] has to be listed in crail.namenode.address " + CrailConstants.NAMENODE_ADDRESS); } CrailConstants.NAMENODE_ADDRESS = namenode + "?id=" + serviceId + "&size=" + serviceSize; CrailConstants.printConf(); CrailConstants.verify(); RpcNameNodeService service = RpcNameNodeService.createInstance(CrailConstants.NAMENODE_RPC_SERVICE); RpcBinding rpcBinding = RpcBinding.createInstance(CrailConstants.NAMENODE_RPC_TYPE); rpcBinding.init(conf, null); rpcBinding.printConf(LOG); rpcBinding.run(service); System.exit(0); ; }
From source file:eu.stratosphere.sopremo.server.SopremoServer.java
/** * Entry point for the program// w ww . j a va2 s. c om * * @param args * arguments from the command line */ @SuppressWarnings("static-access") public static void main(final String[] args) { final Option configDirOpt = OptionBuilder.withArgName("config directory").hasArg() .withDescription("Specify configuration directory.").create("configDir"); final Options options = new Options(); options.addOption(configDirOpt); CommandLineParser parser = new GnuParser(); CommandLine line = null; try { line = parser.parse(options, args); final String configDir = line.getOptionValue(configDirOpt.getOpt(), null); GlobalConfiguration.loadConfiguration(configDir); } catch (ParseException e) { LOG.error("CLI Parsing failed. Reason: " + e.getMessage()); System.exit(1); } // start server SopremoServer sopremoServer = new SopremoServer(); try { sopremoServer.start(); } catch (IOException e) { LOG.error("Cannot start Sopremo server: " + StringUtils.stringifyException(e)); sopremoServer.close(); return; } // and wait for any shutdown signal while (!Thread.interrupted()) { // Sleep try { Thread.sleep(SLEEPINTERVAL); } catch (InterruptedException e) { break; } // Do nothing here } }
From source file:com.cc.apptroy.baksmali.main.java
/** * Run!// ww w .j ava 2s . co m */ public static void main(String[] args) throws IOException { Locale locale = new Locale("en", "US"); Locale.setDefault(locale); CommandLineParser parser = new PosixParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); } catch (ParseException ex) { usage(); return; } baksmaliOptions options = new baksmaliOptions(); boolean disassemble = true; boolean doDump = false; String dumpFileName = null; boolean setBootClassPath = false; String[] remainingArgs = commandLine.getArgs(); Option[] clOptions = commandLine.getOptions(); for (int i = 0; i < clOptions.length; i++) { Option option = clOptions[i]; String opt = option.getOpt(); switch (opt.charAt(0)) { case 'v': version(); return; case '?': while (++i < clOptions.length) { if (clOptions[i].getOpt().charAt(0) == '?') { usage(true); return; } } usage(false); return; case 'o': options.outputDirectory = commandLine.getOptionValue("o"); break; case 'p': options.noParameterRegisters = true; break; case 'l': options.useLocalsDirective = true; break; case 's': options.useSequentialLabels = true; break; case 'b': options.outputDebugInfo = false; break; case 'd': options.bootClassPathDirs.add(option.getValue()); break; case 'f': options.addCodeOffsets = true; break; case 'r': String[] values = commandLine.getOptionValues('r'); int registerInfo = 0; if (values == null || values.length == 0) { registerInfo = baksmaliOptions.ARGS | baksmaliOptions.DEST; } else { for (String value : values) { if (value.equalsIgnoreCase("ALL")) { registerInfo |= baksmaliOptions.ALL; } else if (value.equalsIgnoreCase("ALLPRE")) { registerInfo |= baksmaliOptions.ALLPRE; } else if (value.equalsIgnoreCase("ALLPOST")) { registerInfo |= baksmaliOptions.ALLPOST; } else if (value.equalsIgnoreCase("ARGS")) { registerInfo |= baksmaliOptions.ARGS; } else if (value.equalsIgnoreCase("DEST")) { registerInfo |= baksmaliOptions.DEST; } else if (value.equalsIgnoreCase("MERGE")) { registerInfo |= baksmaliOptions.MERGE; } else if (value.equalsIgnoreCase("FULLMERGE")) { registerInfo |= baksmaliOptions.FULLMERGE; } else { usage(); return; } } if ((registerInfo & baksmaliOptions.FULLMERGE) != 0) { registerInfo &= ~baksmaliOptions.MERGE; } } options.registerInfo = registerInfo; break; case 'c': String bcp = commandLine.getOptionValue("c"); if (bcp != null && bcp.charAt(0) == ':') { options.addExtraClassPath(bcp); } else { setBootClassPath = true; options.setBootClassPath(bcp); } break; case 'x': options.deodex = true; break; case 'X': options.experimental = true; break; case 'm': options.noAccessorComments = true; break; case 'a': options.apiLevel = Integer.parseInt(commandLine.getOptionValue("a")); break; case 'j': options.jobs = Integer.parseInt(commandLine.getOptionValue("j")); break; case 'i': String rif = commandLine.getOptionValue("i"); options.setResourceIdFiles(rif); break; case 't': options.useImplicitReferences = true; break; case 'e': options.dexEntry = commandLine.getOptionValue("e"); break; case 'k': options.checkPackagePrivateAccess = true; break; case 'N': disassemble = false; break; case 'D': doDump = true; dumpFileName = commandLine.getOptionValue("D"); break; case 'I': options.ignoreErrors = true; break; case 'T': options.customInlineDefinitions = new File(commandLine.getOptionValue("T")); break; default: assert false; } } if (remainingArgs.length != 1) { usage(); return; } if (options.jobs <= 0) { options.jobs = Runtime.getRuntime().availableProcessors(); if (options.jobs > 6) { options.jobs = 6; } } String inputDexFileName = remainingArgs[0]; File dexFileFile = new File(inputDexFileName); if (!dexFileFile.exists()) { System.err.println("Can't find the file " + inputDexFileName); System.exit(1); } //Read in and parse the dex file DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexFileFile, options.dexEntry, options.apiLevel, options.experimental); if (dexFile.isOdexFile()) { if (!options.deodex) { System.err.println("Warning: You are disassembling an odex file without deodexing it. You"); System.err.println("won't be able to re-assemble the results unless you deodex it with the -x"); System.err.println("option"); options.allowOdex = true; } } else { options.deodex = false; } if (!setBootClassPath && (options.deodex || options.registerInfo != 0)) { if (dexFile instanceof DexBackedOdexFile) { options.bootClassPathEntries = ((DexBackedOdexFile) dexFile).getDependencies(); } else { options.bootClassPathEntries = getDefaultBootClassPathForApi(options.apiLevel, options.experimental); } } if (options.customInlineDefinitions == null && dexFile instanceof DexBackedOdexFile) { options.inlineResolver = InlineMethodResolver .createInlineMethodResolver(((DexBackedOdexFile) dexFile).getOdexVersion()); } boolean errorOccurred = false; if (disassemble) { errorOccurred = !baksmali.disassembleDexFile(dexFile, options); } if (doDump) { if (dumpFileName == null) { dumpFileName = commandLine.getOptionValue(inputDexFileName + ".dump"); } dump.dump(dexFile, dumpFileName, options.apiLevel, options.experimental); } if (errorOccurred) { System.exit(1); } }
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 ww . j a v a2 s . c o m // ==== 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:client.MultiplexingClient.java
public static void main(String[] args) throws Exception { // Prepare to parse the command line Options options = new Options(); Option sslOpt = new Option("s", "ssl", false, "Use SSL"); Option debugOpt = new Option("d", true, "Debug level (NONE, FINER, FINE, CONFIG, INFO, WARNING, SEVERE. Default INFO."); Option numConnectionsOpt = new Option("n", true, "Number of connections to establish. [Default: 1]"); Option numPcktOpt = new Option("p", true, "Number of packets to send in each connection. [Default: 20]"); Option pcktMaxSizeOpt = new Option("m", true, "Maximum size of packets. [Default: 4096]"); Option help = new Option("h", "print this message"); options.addOption(help);/*from w ww . j a v a2s .c om*/ options.addOption(debugOpt); options.addOption(numConnectionsOpt); options.addOption(numPcktOpt); options.addOption(pcktMaxSizeOpt); options.addOption(sslOpt); CommandLineParser parser = new PosixParser(); // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption(help.getOpt()) || line.getArgs().length < 1) { showUsage(options); return; } if (line.hasOption(sslOpt.getOpt())) { channelFactory = new SSLChannelFactory(true, TRUSTSTORE, TRUSTSTORE_PASSWORD); } else { channelFactory = new PlainChannelFactory(); } if (line.hasOption(numConnectionsOpt.getOpt())) { connectionCount = Integer.parseInt(line.getOptionValue(numConnectionsOpt.getOpt())); } else { connectionCount = 1; } if (line.hasOption(numPcktOpt.getOpt())) { packetsToSend = Integer.parseInt(line.getOptionValue(numPcktOpt.getOpt())); } else { packetsToSend = 20; } if (line.hasOption(pcktMaxSizeOpt.getOpt())) { maxPcktSize = Integer.parseInt(line.getOptionValue(pcktMaxSizeOpt.getOpt())); } else { maxPcktSize = 4096; } InetSocketAddress remotePoint; try { String host = line.getArgs()[0]; int colonIndex = host.indexOf(':'); remotePoint = new InetSocketAddress(host.substring(0, colonIndex), Integer.parseInt(host.substring(colonIndex + 1))); } catch (Exception e) { showUsage(options); return; } // Setups the logging context for Log4j // NDC.push(Thread.currentThread().getName()); st = new SelectorThread(); for (int i = 0; i < connectionCount; i++) { new MultiplexingClient(remotePoint); // Must sleep for a while between opening connections in order // to give the remote host enough time to handle them. Otherwise, // the remote host backlog will get full and the connection // attemps will start to be refused. Thread.sleep(100); } }
From source file:com.ibm.crail.storage.StorageServer.java
public static void main(String[] args) throws Exception { Logger LOG = CrailUtils.getLogger(); CrailConfiguration conf = new CrailConfiguration(); CrailConstants.updateConstants(conf); CrailConstants.printConf();/*from ww w . ja v a 2 s . c o m*/ CrailConstants.verify(); int splitIndex = 0; for (String param : args) { if (param.equalsIgnoreCase("--")) { break; } splitIndex++; } //default values StringTokenizer tokenizer = new StringTokenizer(CrailConstants.STORAGE_TYPES, ","); if (!tokenizer.hasMoreTokens()) { throw new Exception("No storage types defined!"); } String storageName = tokenizer.nextToken(); int storageType = 0; HashMap<String, Integer> storageTypes = new HashMap<String, Integer>(); storageTypes.put(storageName, storageType); for (int type = 1; tokenizer.hasMoreElements(); type++) { String name = tokenizer.nextToken(); storageTypes.put(name, type); } int storageClass = -1; //custom values if (args != null) { Option typeOption = Option.builder("t").desc("storage type to start").hasArg().build(); Option classOption = Option.builder("c").desc("storage class the server will attach to").hasArg() .build(); Options options = new Options(); options.addOption(typeOption); options.addOption(classOption); CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, splitIndex)); if (line.hasOption(typeOption.getOpt())) { storageName = line.getOptionValue(typeOption.getOpt()); storageType = storageTypes.get(storageName).intValue(); } if (line.hasOption(classOption.getOpt())) { storageClass = Integer.parseInt(line.getOptionValue(classOption.getOpt())); } } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Storage tier", options); System.exit(-1); } } if (storageClass < 0) { storageClass = storageType; } StorageTier storageTier = StorageTier.createInstance(storageName); if (storageTier == null) { throw new Exception("Cannot instantiate datanode of type " + storageName); } String extraParams[] = null; splitIndex++; if (args.length > splitIndex) { extraParams = new String[args.length - splitIndex]; for (int i = splitIndex; i < args.length; i++) { extraParams[i - splitIndex] = args[i]; } } storageTier.init(conf, extraParams); storageTier.printConf(LOG); RpcClient rpcClient = RpcClient.createInstance(CrailConstants.NAMENODE_RPC_TYPE); rpcClient.init(conf, args); rpcClient.printConf(LOG); ConcurrentLinkedQueue<InetSocketAddress> namenodeList = CrailUtils.getNameNodeList(); ConcurrentLinkedQueue<RpcConnection> connectionList = new ConcurrentLinkedQueue<RpcConnection>(); while (!namenodeList.isEmpty()) { InetSocketAddress address = namenodeList.poll(); RpcConnection connection = rpcClient.connect(address); connectionList.add(connection); } RpcConnection rpcConnection = connectionList.peek(); if (connectionList.size() > 1) { rpcConnection = new RpcDispatcher(connectionList); } LOG.info("connected to namenode(s) " + rpcConnection.toString()); StorageServer server = storageTier.launchServer(); StorageRpcClient storageRpc = new StorageRpcClient(storageType, CrailStorageClass.get(storageClass), server.getAddress(), rpcConnection); HashMap<Long, Long> blockCount = new HashMap<Long, Long>(); long sumCount = 0; while (server.isAlive()) { StorageResource resource = server.allocateResource(); if (resource == null) { break; } else { storageRpc.setBlock(resource.getAddress(), resource.getLength(), resource.getKey()); DataNodeStatistics stats = storageRpc.getDataNode(); long newCount = stats.getFreeBlockCount(); long serviceId = stats.getServiceId(); long oldCount = 0; if (blockCount.containsKey(serviceId)) { oldCount = blockCount.get(serviceId); } long diffCount = newCount - oldCount; blockCount.put(serviceId, newCount); sumCount += diffCount; LOG.info("datanode statistics, freeBlocks " + sumCount); } } while (server.isAlive()) { DataNodeStatistics stats = storageRpc.getDataNode(); long newCount = stats.getFreeBlockCount(); long serviceId = stats.getServiceId(); long oldCount = 0; if (blockCount.containsKey(serviceId)) { oldCount = blockCount.get(serviceId); } long diffCount = newCount - oldCount; blockCount.put(serviceId, newCount); sumCount += diffCount; LOG.info("datanode statistics, freeBlocks " + sumCount); Thread.sleep(2000); } }
From source file:com.example.dlp.Metadata.java
/** Retrieve infoTypes. */ public static void main(String[] args) throws Exception { Options options = new Options(); Option languageCodeOption = new Option("language", null, true, "BCP-47 language code"); languageCodeOption.setRequired(false); options.addOption(languageCodeOption); Option categoryOption = new Option("category", null, true, "Category of info types to list."); categoryOption.setRequired(false);/*from w w w .j a v a 2 s .c o m*/ options.addOption(categoryOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(Metadata.class.getName(), options); System.exit(1); return; } String languageCode = cmd.getOptionValue(languageCodeOption.getOpt(), "en-US"); if (cmd.hasOption(categoryOption.getOpt())) { String category = cmd.getOptionValue(categoryOption.getOpt()); listInfoTypes(category, languageCode); } else { listRootCategories(languageCode); } }
From source file:com.dasasian.chok.tool.ZkTool.java
public static void main(String[] args) { final Options options = new Options(); Option lsOption = new Option("ls", true, "list zp path contents"); lsOption.setArgName("path"); Option readOption = new Option("read", true, "read and print zp path contents"); readOption.setArgName("path"); Option rmOption = new Option("rm", true, "remove zk files"); rmOption.setArgName("path"); Option rmrOption = new Option("rmr", true, "remove zk directories"); rmrOption.setArgName("path"); OptionGroup actionGroup = new OptionGroup(); actionGroup.setRequired(true);/*from ww w . ja va 2 s . c om*/ actionGroup.addOption(lsOption); actionGroup.addOption(readOption); actionGroup.addOption(rmOption); actionGroup.addOption(rmrOption); options.addOptionGroup(actionGroup); final CommandLineParser parser = new GnuParser(); HelpFormatter formatter = new HelpFormatter(); try { final CommandLine line = parser.parse(options, args); ZkTool zkTool = new ZkTool(); if (line.hasOption(lsOption.getOpt())) { String path = line.getOptionValue(lsOption.getOpt()); zkTool.ls(path); } else if (line.hasOption(readOption.getOpt())) { String path = line.getOptionValue(readOption.getOpt()); zkTool.read(path); } else if (line.hasOption(rmOption.getOpt())) { String path = line.getOptionValue(rmOption.getOpt()); zkTool.rm(path, false); } else if (line.hasOption(rmrOption.getOpt())) { String path = line.getOptionValue(rmrOption.getOpt()); zkTool.rm(path, true); } zkTool.close(); } catch (ParseException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); formatter.printHelp(ZkTool.class.getSimpleName(), options); } }
From source file:com.example.dlp.Redact.java
/** Command line application to redact strings, images using the Data Loss Prevention API. */ public static void main(String[] args) throws Exception { OptionGroup optionsGroup = new OptionGroup(); optionsGroup.setRequired(true);//from w ww . j a v a2 s. c o m Option stringOption = new Option("s", "string", true, "redact string"); optionsGroup.addOption(stringOption); Option fileOption = new Option("f", "file path", true, "redact input file path"); optionsGroup.addOption(fileOption); Options commandLineOptions = new Options(); commandLineOptions.addOptionGroup(optionsGroup); Option minLikelihoodOption = Option.builder("minLikelihood").hasArg(true).required(false).build(); commandLineOptions.addOption(minLikelihoodOption); Option replaceOption = Option.builder("r").longOpt("replace string").hasArg(true).required(false).build(); commandLineOptions.addOption(replaceOption); Option infoTypesOption = Option.builder("infoTypes").hasArg(true).required(false).build(); infoTypesOption.setArgs(Option.UNLIMITED_VALUES); commandLineOptions.addOption(infoTypesOption); Option outputFilePathOption = Option.builder("o").hasArg(true).longOpt("outputFilePath").required(false) .build(); commandLineOptions.addOption(outputFilePathOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(commandLineOptions, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(Redact.class.getName(), commandLineOptions); System.exit(1); return; } String replacement = cmd.getOptionValue(replaceOption.getOpt(), "_REDACTED_"); List<InfoType> infoTypesList = new ArrayList<>(); String[] infoTypes = cmd.getOptionValues(infoTypesOption.getOpt()); if (infoTypes != null) { for (String infoType : infoTypes) { infoTypesList.add(InfoType.newBuilder().setName(infoType).build()); } } Likelihood minLikelihood = Likelihood.valueOf( cmd.getOptionValue(minLikelihoodOption.getOpt(), Likelihood.LIKELIHOOD_UNSPECIFIED.name())); // string inspection if (cmd.hasOption("s")) { String source = cmd.getOptionValue(stringOption.getOpt()); redactString(source, replacement, minLikelihood, infoTypesList); } else if (cmd.hasOption("f")) { String filePath = cmd.getOptionValue(fileOption.getOpt()); String outputFilePath = cmd.getOptionValue(outputFilePathOption.getOpt()); redactImage(filePath, minLikelihood, infoTypesList, outputFilePath); } }