List of usage examples for org.apache.commons.cli Options addOption
public Options addOption(String opt, boolean hasArg, String description)
From source file:com.adobe.aem.demomachine.Json2Csv.java
public static void main(String[] args) throws IOException { String inputFile1 = null;/*from w ww .j a v a2 s . c om*/ String inputFile2 = null; String outputFile = null; HashMap<String, String> hmReportSuites = new HashMap<String, String>(); // Command line options for this tool Options options = new Options(); options.addOption("c", true, "Filename 1"); options.addOption("r", true, "Filename 2"); options.addOption("o", true, "Filename 3"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("c")) { inputFile1 = cmd.getOptionValue("c"); } if (cmd.hasOption("r")) { inputFile2 = cmd.getOptionValue("r"); } if (cmd.hasOption("o")) { outputFile = cmd.getOptionValue("o"); } if (inputFile1 == null || inputFile1 == null || outputFile == null) { System.exit(-1); } } catch (ParseException ex) { logger.error(ex.getMessage()); } // List of customers and report suites for these customers String sInputFile1 = readFile(inputFile1, Charset.defaultCharset()); sInputFile1 = sInputFile1.replaceAll("ObjectId\\(\"([0-9a-z]*)\"\\)", "\"$1\""); // Processing the list of report suites for each customer try { JSONArray jCustomers = new JSONArray(sInputFile1.trim()); for (int i = 0, size = jCustomers.length(); i < size; i++) { JSONObject jCustomer = jCustomers.getJSONObject(i); Iterator<?> keys = jCustomer.keys(); String companyName = null; while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("company")) { companyName = jCustomer.getString(key); } } keys = jCustomer.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("report_suites")) { JSONArray jReportSuites = jCustomer.getJSONArray(key); for (int j = 0, rSize = jReportSuites.length(); j < rSize; j++) { hmReportSuites.put(jReportSuites.getString(j), companyName); System.out.println(jReportSuites.get(j) + " for company " + companyName); } } } } // Creating the out put file PrintWriter writer = new PrintWriter(outputFile, "UTF-8"); writer.println("\"" + "Customer" + "\",\"" + "ReportSuite ID" + "\",\"" + "Number of Documents" + "\",\"" + "Last Updated" + "\""); // Processing the list of SOLR collections String sInputFile2 = readFile(inputFile2, Charset.defaultCharset()); sInputFile2 = sInputFile2.replaceAll("NumberLong\\(\"([0-9a-z]*)\"\\)", "\"$1\""); JSONObject jResults = new JSONObject(sInputFile2.trim()); JSONArray jCollections = jResults.getJSONArray("result"); for (int i = 0, size = jCollections.length(); i < size; i++) { JSONObject jCollection = jCollections.getJSONObject(i); String id = null; String number = null; String lastupdate = null; Iterator<?> keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("_id")) { id = jCollection.getString(key); } } keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("noOfDocs")) { number = jCollection.getString(key); } } keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("latestUpdateDate")) { lastupdate = jCollection.getString(key); } } Date d = new Date(Long.parseLong(lastupdate)); System.out.println(hmReportSuites.get(id) + "," + id + "," + number + "," + lastupdate + "," + new SimpleDateFormat("MM-dd-yyyy").format(d)); writer.println("\"" + hmReportSuites.get(id) + "\",\"" + id + "\",\"" + number + "\",\"" + new SimpleDateFormat("MM-dd-yyyy").format(d) + "\""); } writer.close(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.yahoo.storm.yarn.MasterServer.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { LOG.info("Starting the AM!!!!"); Options opts = new Options(); opts.addOption("app_attempt_id", true, "App Attempt ID. Not to be used " + "unless for testing purposes"); CommandLine cl = new GnuParser().parse(opts, args); ApplicationAttemptId appAttemptID;//from ww w . jav a 2s . c o m Map<String, String> envs = System.getenv(); if (cl.hasOption("app_attempt_id")) { String appIdStr = cl.getOptionValue("app_attempt_id", ""); appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr); } else if (envs.containsKey(ApplicationConstants.Environment.CONTAINER_ID.name())) { ContainerId containerId = ConverterUtils .toContainerId(envs.get(ApplicationConstants.Environment.CONTAINER_ID.name())); appAttemptID = containerId.getApplicationAttemptId(); LOG.info("appAttemptID from env:" + appAttemptID.toString()); } else { LOG.error("appAttemptID is not specified for storm master"); throw new Exception("appAttemptID is not specified for storm master"); } @SuppressWarnings("rawtypes") Map storm_conf = Config.readStormConfig(null); Util.rmNulls(storm_conf); YarnConfiguration hadoopConf = new YarnConfiguration(); final String host = InetAddress.getLocalHost().getHostName(); storm_conf.put("nimbus.host", host); StormAMRMClient rmClient = new StormAMRMClient(appAttemptID, storm_conf, hadoopConf); rmClient.init(hadoopConf); rmClient.start(); BlockingQueue<Container> launcherQueue = new LinkedBlockingQueue<Container>(); MasterServer server = new MasterServer(storm_conf, rmClient); try { final int port = Utils.getInt(storm_conf.get(Config.MASTER_THRIFT_PORT)); final String target = host + ":" + port; InetSocketAddress addr = NetUtils.createSocketAddr(target); RegisterApplicationMasterResponse resp = rmClient.registerApplicationMaster(addr.getHostName(), port, null); LOG.info("Got a registration response " + resp); LOG.info("Max Capability " + resp.getMaximumResourceCapability()); rmClient.setMaxResource(resp.getMaximumResourceCapability()); LOG.info("Starting HB thread"); server.initAndStartHeartbeat(rmClient, launcherQueue, (Integer) storm_conf.get(Config.MASTER_HEARTBEAT_INTERVAL_MILLIS)); LOG.info("Starting launcher"); initAndStartLauncher(rmClient, launcherQueue); rmClient.startAllSupervisors(); LOG.info("Starting Master Thrift Server"); server.serve(); LOG.info("StormAMRMClient::unregisterApplicationMaster"); rmClient.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, "AllDone", null); } finally { if (server.isServing()) { LOG.info("Stop Master Thrift Server"); server.stop(); } LOG.info("Stop RM client"); rmClient.stop(); } System.exit(0); }
From source file:edu.illinois.cs.cogcomp.temporal.normalizer.main.TemporalNormalizerBenchmark.java
/** * * @param args 1. -verbose, this is optional * 2. -useGoldChunk, optional, if not set, temporal chunker will be used * 3. -inputFolder <filepath>, mandatory * 4. -outputFolder <filepath>, mandatory * @throws ParserConfigurationException/*from ww w . ja va 2s. co m*/ * @throws SAXException * @throws IOException */ public static void main(String[] args) throws Exception { CommandLine commandLine; Options options = new Options(); options.addOption("useHeidelTime", false, "If user wants to use HeidelTime to normalize"); options.addOption("useGoldChunk", false, "If user wants to use gold timex extraction"); options.addOption("verbose", false, "If user wants to print execution details"); Option input_opt = Option.builder("inputFolder").required(true).hasArg().desc("The folder of input data") .build(); Option output_opt = Option.builder("outputFolder").required(true).hasArg() .desc("The folder where user wants to write data").build(); options.addOption(input_opt); options.addOption(output_opt); CommandLineParser parser = new DefaultParser(); commandLine = parser.parse(options, args); boolean useHeidelTime = commandLine.hasOption("useHeidelTime"); boolean useGoldChunk = commandLine.hasOption("useGoldChunk"); boolean verbose = commandLine.hasOption("verbose"); String inputFolder = commandLine.getOptionValue("inputFolder"); String outputFolder = commandLine.getOptionValue("outputFolder"); TemporalNormalizerBenchmark benchmark = new TemporalNormalizerBenchmark(); benchmark.setUp(inputFolder, useHeidelTime); if (useGoldChunk) { benchmark.testNormalizationWithTrueExtraction(outputFolder, verbose); } else { benchmark.testTemporalChunker(outputFolder, verbose); } }
From source file:ktdiedrich.imagek.SegmentationCMD.java
/** * @author ktdiedrich@gmail.com// w w w . j a va 2 s . co m * @param ags: [file path] [Median filter size] [imageId] * Command line segmentation * @throws org.apache.commons.cli.ParseException */ public static void main(String[] args) throws org.apache.commons.cli.ParseException { int imageIds[] = null; int medianFilterSize = 0; float seed = Extractor3D.SEED_HIST_THRES; String paths[] = null; Options options = new Options(); options.addOption("p", true, "path name to file including filename"); options.addOption("m", true, "median filter size, m*2+1"); options.addOption("i", true, "image ID"); options.addOption("f", true, "Image ID from"); options.addOption("t", true, "Image ID to, (inclusive)"); options.addOption("s", true, "Seed threshold default " + seed); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("s")) { seed = Float.parseFloat(cmd.getOptionValue("s")); } if (cmd.hasOption("i")) { imageIds = new int[1]; imageIds[0] = Integer.parseInt(cmd.getOptionValue("i")); paths = new String[1]; paths[0] = getImageIdPath(imageIds[0]); // TODO get path to image ID from database and properties file. } if (cmd.hasOption("f") && cmd.hasOption("t")) { int from = Integer.parseInt(cmd.getOptionValue("f")); int to = Integer.parseInt(cmd.getOptionValue("t")); int range = to - from + 1; paths = new String[range]; imageIds = new int[range]; for (int i = 0, imId = from; i < range; i++, imId++) { imageIds[i] = imId; paths[i] = getImageIdPath(imId); } } if (paths == null && cmd.hasOption("p")) { paths = new String[1]; paths[0] = cmd.getOptionValue("p"); } if (cmd.hasOption("m")) { medianFilterSize = Integer.parseInt(cmd.getOptionValue("m")); } // System.out.println("ImageID: "+imageId+" Path: "+paths+" Median filter: "+medianFilterSize); if (paths != null) { int i = 0; for (String path : paths) { String p[] = parseDirectoryFileName(path); String dirPath = p[0]; ImagePlus segImage = segment(path, medianFilterSize, imageIds[i], seed); String title = segImage.getShortTitle(); if (title.contains(File.separator)) ; { title = parseDirectoryFileName(title)[1]; } String outputPath = null; if (!dirPath.endsWith(File.separator)) dirPath = dirPath + File.separator; outputPath = dirPath + title + ".zip"; FileSaver fs = new FileSaver(segImage); fs.saveAsZip(outputPath); System.out.println("Saved: " + outputPath); ImagePlus mipYim = MIP.createShortMIP(segImage, MIP.Y_AXIS); fs = new FileSaver(mipYim); title = mipYim.getShortTitle(); if (title.contains(File.separator)) ; { title = parseDirectoryFileName(title)[1]; } outputPath = dirPath + title + ".png"; fs.saveAsPng(outputPath); System.out.println("Saved: " + outputPath + "\n"); i++; } } }
From source file:com.maxpowered.amazon.advertising.api.app.App.java
public static void main(final String... args) throws FileNotFoundException, IOException, JAXBException, XMLStreamException, InterruptedException { try (ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml")) { /*/* w w w . j av a 2 s . co m*/ * Get default options based on spring configs */ final String inputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_INPUT, STD_IN_STR); final String processedDefault = inputDefault.equals(STD_IN_STR) ? DEFAULT_PROCESSED_FILE_BASE : inputDefault + PROCESSED_EXT; final String outputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_OUTPUT, STD_OUT_STR); int throttleDefault = Integer.valueOf(getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_THROTTLE, String.valueOf(DEFAULT_APP_THROTTLE))); // Maximum of 25000 requests per hour throttleDefault = Math.min(throttleDefault, MAX_APP_THROTTLE); /* * Get options from the CLI args */ final Options options = new Options(); options.addOption("h", false, "Display this help."); options.addOption("i", true, "Set the file to read ASINs from. " + DEFAULT_STR + inputDefault); options.addOption("p", true, "Set the file to store processed ASINs in. " + DEFAULT_STR + processedDefault + " or '" + PROCESSED_EXT + "' appended to the input file name."); // Add a note that the output depends on the configured processors. If none are configured, it defaults to a // std.out processor options.addOption("o", true, "Set the file to write fetched info xml to via FileProcessor. " + DEFAULT_STR + outputDefault); options.addOption("1", false, "Override output file and always output fetched info xml to std.out."); options.addOption("t", true, "Set the requests per hour throttle (max of " + MAX_APP_THROTTLE + "). " + DEFAULT_STR + throttleDefault); final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; boolean needsHelp = false; try { cmd = parser.parse(options, args); } catch (final ParseException e) { needsHelp = true; } if (cmd.hasOption("h") || needsHelp) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("App", options); return; } // Get throttle rate final int throttle = Math.min( cmd.hasOption("t") ? Integer.valueOf(cmd.getOptionValue("t")) : throttleDefault, MAX_APP_THROTTLE); LOG.debug("Throttle (default {}) is {} requests per hour", throttleDefault, throttle); // We don't want to hit our limit, just under an hour worth of milliseconds final int requestWait = 3540000 / throttle; // Get input stream String input; if (cmd.hasOption("i")) { input = cmd.getOptionValue("i"); } else { input = inputDefault; } LOG.debug("Input name (default {}) is {}", inputDefault, input); // Get processed file String processed; if (cmd.hasOption("p")) { processed = cmd.getOptionValue("p"); } else { processed = input + PROCESSED_EXT; } LOG.debug("Processed file name (default {}) is {}", processedDefault, processed); final File processedFile = new File(processed); processedFile.createNewFile(); try (final InputStream inputStream = getInputStream(input)) { // Get output stream String output; if (cmd.hasOption("o")) { output = cmd.getOptionValue("o"); } else { output = outputDefault; } if (cmd.hasOption("1")) { output = STD_OUT_STR; } LOG.debug("Output (default {}) name is {}", outputDefault, output); // Special logic to set the FileProcessor output if (output.equals(STD_OUT_STR)) { final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class); fileProcessor.setOutputStream(System.out); } else if (!output.equals(outputDefault)) { final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class); fileProcessor.setOutputFile(output); } // This could be easily configured through CLI or properties final List<String> responseGroups = Lists.newArrayList(); for (final ResponseGroup responseGroup : new ResponseGroup[] { ResponseGroup.IMAGES, ResponseGroup.ITEM_ATTRIBUTES }) { responseGroups.add(responseGroup.getResponseGroupName()); } final String responseGroupString = Joiner.on(",").join(responseGroups); // Search the list of remaining ASINs final ProductFetcher fetcher = ctx.getBeanFactory().getBean(ProductFetcher.class); fetcher.setProcessedFile(processedFile); fetcher.setRequestWait(requestWait); fetcher.setInputStream(inputStream); fetcher.setResponseGroups(responseGroupString); // This ensures that statistics of processed asins should almost always get printed at the end Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { fetcher.logStatistics(); } }); fetcher.fetchProductInformation(); } } }
From source file:kafka.benchmark.AdvertisingTopology.java
public static void main(final String[] args) throws Exception { Options opts = new Options(); opts.addOption("conf", true, "Path to the config file."); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(opts, args); String configPath = cmd.getOptionValue("conf"); Map<?, ?> conf = Utils.findAndReadConfigFile(configPath, true); Map<String, ?> benchmarkParams = getKafkaConfs(conf); LOG.info("conf: {}", conf); LOG.info("Parameters used: {}", benchmarkParams); KStreamBuilder builder = new KStreamBuilder(); // builder.addStateStore( // Stores.create("config-params") // .withStringKeys().withStringValues() // .inMemory().maxEntries(10).build(), "redis"); String topicsArr[] = { (String) benchmarkParams.get("topic") }; KStream<String, ?> source1 = builder.stream(topicsArr); Properties props = new Properties(); props.putAll(benchmarkParams);//from ww w .j av a 2 s. co m // props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafka-benchmarks"); // props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); //// props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181"); props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data // props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); source1 // Parse the String as JSON .mapValues(input -> { JSONObject obj = new JSONObject(input.toString()); //System.out.println(obj.toString()); String[] tuple = { obj.getString("user_id"), obj.getString("page_id"), obj.getString("ad_id"), obj.getString("ad_type"), obj.getString("event_type"), obj.getString("event_time"), obj.getString("ip_address") }; return tuple; }) // Filter the records if event type is "view" .filter(new Predicate<String, String[]>() { @Override public boolean test(String key, String[] value) { return value[4].equals("view"); // "event_type" } }) // project the event .mapValues(input -> { String[] arr = (String[]) input; return new String[] { arr[2], arr[5] }; // "ad_id" and "event_time" }) // perform join with redis data .transformValues(new RedisJoinBolt(benchmarkParams)).filter((key, value) -> value != null) // create key from value .map((key, value) -> { String[] arr = (String[]) value; return new KeyValue<String, String[]>(arr[0], arr); }) // process campaign .aggregateByKey(new Initializer<List<String[]>>() { @Override public List<String[]> apply() { return new ArrayList<String[]>(); } }, new Aggregator<String, String[], List<String[]>>() { @Override public List<String[]> apply(String aggKey, String[] value, List<String[]> aggregate) { aggregate.add(value); return aggregate; } }, // UnlimitedWindows.of("kafka-test-unlim"), // HoppingWindows.of("kafka-test-hopping").with(12L).every(5L), TumblingWindows.of("kafka-test-tumbling").with(WINDOW_SIZE), strSerde, arrSerde) .toStream().process(new CampaignProcessor(benchmarkParams)); KafkaStreams streams = new KafkaStreams(builder, props); streams.start(); }
From source file:ch.psi.zmq.receiver.FileReceiver.java
public static void main(String[] args) { int port = 8888; String source = "localhost"; Options options = new Options(); options.addOption("h", false, "Help"); @SuppressWarnings("static-access") Option optionP = OptionBuilder.withArgName("port").hasArg() .withDescription("Source port (default: " + port + ")").create("p"); options.addOption(optionP);/*w w w . j av a2s . co m*/ @SuppressWarnings("static-access") Option optionS = OptionBuilder.withArgName("source").hasArg().isRequired().withDescription( "Source address of the ZMQ stream (default port " + port + " : use -p to set the port if needed)") .create("s"); options.addOption(optionS); @SuppressWarnings("static-access") Option optionD = OptionBuilder.withArgName("path").hasArg().isRequired() .withDescription("tpath for storing files with relative destination paths").create("d"); options.addOption(optionD); GnuParser parser = new GnuParser(); CommandLine line; String path = "."; try { line = parser.parse(options, args); if (line.hasOption(optionP.getOpt())) { port = Integer.parseInt(line.getOptionValue(optionP.getOpt())); } if (line.hasOption("h")) { HelpFormatter f = new HelpFormatter(); f.printHelp("receiver", options); return; } source = line.getOptionValue(optionS.getOpt()); path = line.getOptionValue(optionD.getOpt()); } catch (ParseException e) { System.err.println(e.getMessage()); HelpFormatter f = new HelpFormatter(); f.printHelp("receiver", options); System.exit(-1); } final FileReceiver r = new FileReceiver(source, port, path); r.receive(); // Control+C Signal.handle(new Signal("INT"), new SignalHandler() { int count = 0; public void handle(Signal sig) { if (count < 1) { count++; r.terminate(); } else { System.exit(-1); } } }); }
From source file:com.linkedin.databus2.client.util.DbusClientClusterUtil.java
/** * @param args/*from www. j a v a 2 s . c o m*/ * DbusClientClusterUtil -s <serverList> -n <namespace> -g <group> -d <dir> members * leader * keys * readSCN <key> * writeSCN <key> SCN [OFFSET] * remove <key> * readLastTS * writeLastTS TIMESTAMP */ public static void main(String[] args) { try { GnuParser cmdLineParser = new GnuParser(); Options options = new Options(); options.addOption("n", true, "Zookeeper namespace [/DatabusClient") .addOption("g", true, "Groupname [default-group-name] ") .addOption("d", true, "Shared directory name [shareddata] ") .addOption("s", true, "Zookeeper server list [localhost:2181] ").addOption("h", false, "help"); CommandLine cmdLineArgs = cmdLineParser.parse(options, args, false); if (cmdLineArgs.hasOption('h')) { usage(); System.exit(0); } String namespace = cmdLineArgs.getOptionValue('n'); if (namespace == null || namespace.isEmpty()) { namespace = "/DatabusClient"; } String groupname = cmdLineArgs.getOptionValue('g'); if (groupname == null || groupname.isEmpty()) { groupname = "default-group-name"; } String sharedDir = cmdLineArgs.getOptionValue('d'); if (sharedDir == null || sharedDir.isEmpty()) { sharedDir = "shareddata"; } String serverList = cmdLineArgs.getOptionValue('s'); if (serverList == null || serverList.isEmpty()) { serverList = "localhost:2181"; } String[] fns = cmdLineArgs.getArgs(); if (fns.length < 1) { usage(); System.exit(1); } String function = fns[0]; String arg1 = (fns.length > 1) ? fns[1] : null; String arg2 = (fns.length > 2) ? fns[2] : null; try { String memberName = "cmd-line-tool"; DatabusClientNode clusterNode = new DatabusClientNode(new DatabusClientNode.StaticConfig(true, serverList, 2000, 5000, namespace, groupname, memberName, false, sharedDir)); DatabusClientGroupMember member = clusterNode.getMember(namespace, groupname, memberName); if (member == null || !member.joinWithoutLeadershipDuties()) { System.err.println("Initialization failed for: " + member); System.exit(1); } if (function.equals("members")) { List<String> mlist = member.getMembers(); for (String m : mlist) { System.out.println(m); } } else if (function.equals("leader")) { String leader = member.getLeader(); System.out.println(leader); } else if (function.equals("keys")) { List<String> keyList = member.getSharedKeys(); if (keyList != null) { for (String m : keyList) { System.out.println(m); } } } else if (function.equals("readSCN")) { List<String> keyList; if (arg1 == null) { keyList = member.getSharedKeys(); } else { keyList = new ArrayList<String>(); keyList.add(arg1); } if (keyList != null) { for (String k : keyList) { if (!k.equals(DatabusClientDSCUpdater.DSCKEY)) { Checkpoint cp = (Checkpoint) member.readSharedData(k); if (cp != null) { System.out.println(k + " " + cp.getWindowScn() + " " + cp.getWindowOffset()); } else { System.err.println(k + " null null"); } } } } } else if (function.equals("writeSCN")) { if (arg1 != null && arg2 != null) { Checkpoint cp = new Checkpoint(); cp.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION); cp.setWindowScn(Long.parseLong(arg2)); if (fns.length > 3) { cp.setWindowOffset(Integer.parseInt(fns[3])); } else { cp.setWindowOffset(-1); } if (member.writeSharedData(arg1, cp)) { System.out.println(arg1 + " " + cp.getWindowScn() + " " + cp.getWindowOffset()); } else { System.err.println("Write failed! " + member + " couldn't write key=" + arg1); System.exit(1); } } else { usage(); System.exit(1); } } else if (function.equals("readLastTs")) { Long timeInMs = (Long) member.readSharedData(DatabusClientDSCUpdater.DSCKEY); if (timeInMs != null) { System.out.println(DatabusClientDSCUpdater.DSCKEY + " " + timeInMs.longValue()); } else { System.err.println(DatabusClientDSCUpdater.DSCKEY + " null"); } } else if (function.equals("writeLastTs")) { if (arg1 != null) { Long ts = Long.parseLong(arg1); if (member.writeSharedData(DatabusClientDSCUpdater.DSCKEY, ts)) { System.out.println(DatabusClientDSCUpdater.DSCKEY + " " + ts); } else { System.err.println("Write failed! " + member + " couldn't write key=" + DatabusClientDSCUpdater.DSCKEY); System.exit(1); } } else { usage(); System.exit(1); } } else if (function.equals("remove")) { if (!member.removeSharedData(arg1)) { System.err.println("Remove failed! " + arg1); System.exit(1); } } else if (function.equals("create")) { if (!member.createPaths()) { System.err.println("Create path failed!"); System.exit(1); } } else { usage(); System.exit(1); } } catch (InvalidConfigException e) { e.printStackTrace(); usage(); System.exit(1); } } catch (ParseException e) { usage(); System.exit(1); } }
From source file:de.flashpixx.rrd_antlr4.CMain.java
/** * main// www .j a va2s.c o m * * @param p_args command-line arguments * @throws IOException on any io error */ public static void main(final String[] p_args) throws IOException { // --- define CLI options --- final Options l_clioptions = new Options(); l_clioptions.addOption("help", false, CCommon.languagestring(CMain.class, "help")); l_clioptions.addOption("output", true, CCommon.languagestring(CMain.class, "output", DEFAULTOUTPUT)); l_clioptions.addOption("imports", true, CCommon.languagestring(CMain.class, "import")); l_clioptions.addOption("excludes", true, CCommon.languagestring(CMain.class, "exclude")); l_clioptions.addOption("grammar", true, CCommon.languagestring(CMain.class, "grammar")); l_clioptions.addOption("language", true, CCommon.languagestring(CMain.class, "language")); l_clioptions.addOption("docclean", true, CCommon.languagestring(CMain.class, "documentationclean")); l_clioptions.addOption("templates", true, CCommon.languagestring(CMain.class, "template", Arrays.asList(ETemplate.values()), DEFAULTTEMPLATE)); final CommandLine l_cli; try { l_cli = new DefaultParser().parse(l_clioptions, p_args); } catch (final Exception l_exception) { System.err .println(CCommon.languagestring(CMain.class, "parseerror", l_exception.getLocalizedMessage())); System.exit(-1); return; } // --- process CLI arguments and push configuration --- if (l_cli.hasOption("help")) { final HelpFormatter l_formatter = new HelpFormatter(); l_formatter.printHelp( new java.io.File(CMain.class.getProtectionDomain().getCodeSource().getLocation().getPath()) .getName(), l_clioptions); System.exit(0); } if (!l_cli.hasOption("grammar")) { System.err.println(CCommon.languagestring(CMain.class, "grammarnotset")); System.exit(-1); } final Tuple5<File, Set<ETemplate>, Set<File>, Set<String>, Set<String>> l_initdata = CMain.initialize( l_cli.getOptionValue("language"), l_cli.hasOption("output") ? l_cli.getOptionValue("output") : DEFAULTOUTPUT, l_cli.hasOption("templates") ? l_cli.getOptionValue("templates").split(",") : new String[] { DEFAULTTEMPLATE }, l_cli.getOptionValue("imports", "").split(","), l_cli.getOptionValue("excludes", "").split(","), l_cli.getOptionValue("docclean", "").split(",")); // --- run generator --- final IGenerator l_generator = new CStandalone(l_initdata.v1(), l_initdata.v3(), l_initdata.v5(), l_initdata.v2()); if (Arrays.stream(l_cli.getOptionValue("grammar").split(",")) .flatMap(i -> CMain.filelist(new File(i.trim()), l_initdata.v3(), l_initdata.v4())) .map(i -> l_generator.generate(i).hasError()).findFirst().isPresent()) System.exit(-1); l_generator.finish(); }