List of usage examples for org.apache.commons.cli CommandLine getOptionValues
public String[] getOptionValues(char opt)
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 w w . j a v a2s.com*/ 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); } }
From source file:fr.cnrs.sharp.Main.java
public static void main(String args[]) { Options options = new Options(); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); Option helpOpt = new Option("h", "help", false, "print the help"); Option inProvFileOpt = OptionBuilder.withArgName("input_PROV_file_1> ... <input_PROV_file_n") .withLongOpt("input_PROV_files").withDescription("The list of PROV input files, in RDF Turtle.") .hasArgs().create("i"); Option inRawFileOpt = OptionBuilder.withArgName("input_raw_file_1> ... <input_raw_file_n") .withLongOpt("input_raw_files") .withDescription(/*from ww w . jav a2 s . c o m*/ "The list of raw files to be fingerprinted and possibly interlinked with owl:sameAs.") .hasArgs().create("ri"); Option summaryOpt = OptionBuilder.withArgName("summary").withLongOpt("summary") .withDescription("Materialization of wasInfluencedBy relations.").create("s"); options.addOption(inProvFileOpt); options.addOption(inRawFileOpt); options.addOption(versionOpt); options.addOption(helpOpt); options.addOption(summaryOpt); String header = "SharpTB is a tool to maturate provenance based on PROV inferences"; String footer = "\nPlease report any issue to alban.gaignard@univ-nantes.fr"; try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SharpTB", header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { logger.info("SharpTB version 0.1.0"); System.exit(0); } if (cmd.hasOption("ri")) { String[] inFiles = cmd.getOptionValues("ri"); Model model = ModelFactory.createDefaultModel(); for (String inFile : inFiles) { Path p = Paths.get(inFile); if (!p.toFile().isFile()) { logger.error("Cannot find file " + inFile); System.exit(1); } else { //1. fingerprint try { model.add(Interlinking.fingerprint(p)); } catch (IOException e) { logger.error("Cannot fingerprint file " + inFile); } } } //2. genSameAs Model sameAs = Interlinking.generateSameAs(model); sameAs.write(System.out, "TTL"); } if (cmd.hasOption("i")) { String[] inFiles = cmd.getOptionValues("i"); Model data = ModelFactory.createDefaultModel(); for (String inFile : inFiles) { Path p = Paths.get(inFile); if (!p.toFile().isFile()) { logger.error("Cannot find file " + inFile); System.exit(1); } else { RDFDataMgr.read(data, inFile, Lang.TTL); } } Model res = Harmonization.harmonizeProv(data); try { Path pathInfProv = Files.createTempFile("PROV-inf-tgd-egd-", ".ttl"); res.write(new FileWriter(pathInfProv.toFile()), "TTL"); System.out.println("Harmonized PROV written to file " + pathInfProv.toString()); //if the summary option is activated, then save the subgraph and generate a visualization if (cmd.hasOption("s")) { String queryInfluence = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" + "PREFIX prov: <http://www.w3.org/ns/prov#> \n" + "CONSTRUCT { \n" + " ?x ?p ?y .\n" + " ?x rdfs:label ?lx .\n" + " ?y rdfs:label ?ly .\n" + "} WHERE {\n" + " ?x ?p ?y .\n" + " FILTER (?p IN (prov:wasInfluencedBy)) .\n" + " ?x rdfs:label ?lx .\n" + " ?y rdfs:label ?ly .\n" + "}"; Query query = QueryFactory.create(queryInfluence); QueryExecution queryExec = QueryExecutionFactory.create(query, res); Model summary = queryExec.execConstruct(); queryExec.close(); Util.writeHtmlViz(summary); } } catch (IOException ex) { logger.error("Impossible to write the harmonized provenance file."); System.exit(1); } } else { // logger.info("Please fill the -i input parameter."); // HelpFormatter formatter = new HelpFormatter(); // formatter.printHelp("SharpTB", header, options, footer, true); // System.exit(0); } } catch (ParseException ex) { logger.error("Error while parsing command line arguments. Please check the following help:"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SharpToolBox", header, options, footer, true); System.exit(1); } }
From source file:com.eternitywall.ots.OtsCli.java
public static void main(String[] args) { // Create the Options Options options = new Options(); options.addOption("c", "calendar", true, "Create timestamp with the aid of a remote calendar. May be specified multiple times."); options.addOption("k", "key", true, "Signature key file of private remote calendars."); options.addOption("d", "digest", true, "Verify a (hex-encoded) digest rather than a file."); options.addOption("a", "algorithm", true, "Pass the hashing algorithm of the document to timestamp: SHA256(default), SHA1, RIPEMD160."); options.addOption("m", "", true, "Commitments are sent to remote calendars in the event of timeout the timestamp is considered done if at least M calendars replied."); options.addOption("s", "shrink", false, "Shrink upgraded timestamp."); options.addOption("V", "version", false, "Print " + title + " version."); options.addOption("v", "verbose", false, "Be more verbose.."); options.addOption("f", "file", true, "Specify target file explicitly (default: original file present in the same directory without .ots)"); options.addOption("h", "help", false, "print this help."); // Parse the args to retrieve options & command CommandLineParser parser = new BasicParser(); try {/*from ww w . j a va 2 s .c o m*/ CommandLine line = parser.parse(options, args); // args are the arguments passed to the the application via the main method if (line.hasOption("c")) { String[] cals = line.getOptionValues("c"); calendarsUrl.addAll(Arrays.asList(cals)); } if (line.hasOption("m")) { m = Integer.valueOf(line.getOptionValue("m")); } if (line.hasOption("k")) { signatureFile = line.getOptionValue("k"); calendarsUrl.clear(); } if (line.hasOption("s")) { shrink = true; } if (line.hasOption("v")) { verbose = true; } if (line.hasOption("V")) { System.out.println("Version: " + title + " v." + version + '\n'); return; } if (line.hasOption("h")) { showHelp(); return; } if (line.hasOption("d")) { shasum = Utils.hexToBytes(line.getOptionValue("d")); } if (line.hasOption("f")) { verifyFile = line.getOptionValue("f"); } if (line.hasOption("a")) { algorithm = line.getOptionValue("a"); if (!Arrays.asList(algorithms).contains(algorithm.toUpperCase())) { System.out.println("Algorithm: " + algorithm + " not supported\n"); return; } } if (line.getArgList().isEmpty()) { showHelp(); return; } cmd = line.getArgList().get(0); files = line.getArgList().subList(1, line.getArgList().size()); } catch (Exception e) { System.out.println(title + ": invalid parameters "); return; } // Parse the command switch (cmd) { case "info": case "i": if (files.isEmpty()) { System.out.println("Show information on a timestamp given as argument.\n"); System.out.println(title + " info: bad options "); break; } info(files.get(0), verbose); break; case "stamp": case "s": if (!files.isEmpty()) { multistamp(files, calendarsUrl, m, signatureFile, algorithm); } else if (shasum != null) { Hash hash = new Hash(shasum, algorithm); stamp(hash, calendarsUrl, m, signatureFile); } else { System.out.println("Create timestamp with the aid of a remote calendar.\n"); System.out.println(title + ": bad options number "); } break; case "verify": case "v": if (!files.isEmpty()) { Hash hash = null; if (shasum != null) { hash = new Hash(shasum, algorithm); } if (verifyFile == null) { verifyFile = files.get(0).replace(".ots", ""); } verify(files.get(0), hash, verifyFile); } else { System.out.println("Verify the timestamp attestations given as argument.\n"); System.out.println(title + ": bad options number "); } break; case "upgrade": case "u": if (files.isEmpty()) { System.out.println("Upgrade remote calendar timestamps to be locally verifiable.\n"); System.out.println(title + ": bad options number "); break; } upgrade(files.get(0), shrink); break; default: System.out.println(title + ": bad option: " + cmd); } }
From source file:de.uni_koblenz.west.splendid.tools.NXVoidGenerator.java
public static void main(String[] args) { try {// w w w . j a va2 s. c o m // parse the command line arguments CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(OPTIONS, args); // print help message if (cmd.hasOption("h") || cmd.hasOption("help")) { new HelpFormatter().printHelp(USAGE, OPTIONS); System.exit(0); } // get input files (from option -i or all remaining parameters) String[] inputFiles = cmd.getOptionValues("i"); if (inputFiles == null) inputFiles = cmd.getArgs(); if (inputFiles.length == 0) { System.out.println("need at least one input file."); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE); System.exit(1); } String outputFile = cmd.getOptionValue("o"); // process all input files new NXVoidGenerator().process(outputFile, inputFiles); } catch (ParseException exp) { // print parse error and display usage message System.out.println(exp.getMessage()); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE, OPTIONS); } }
From source file:com.hs.mail.deliver.Deliver.java
public static void main(String[] args) { CommandLine cli = null; try {//w w w.j ava2 s . c o m cli = new PosixParser().parse(OPTS, args); } catch (ParseException e) { usage(); System.exit(EX_USAGE); } // Configuration file path String config = cli.getOptionValue("c", DEFAULT_CONFIG_LOCATION); // Message file path File file = new File(cli.getOptionValue("p")); // Envelope sender address String from = cli.getOptionValue("f"); // Destination mailboxes String[] rcpts = cli.getOptionValues("r"); if (!file.exists()) { // Message file must exist logger.error("File not exist: " + file.getAbsolutePath()); System.exit(EX_TEMPFAIL); } if (from == null || rcpts == null) { // If sender or recipients address was not specified, get the // addresses from the message header. InputStream is = null; try { is = new FileInputStream(file); MessageHeader header = new MessageHeader(is); if (from == null && header.getFrom() != null) { from = header.getFrom().getAddress(); } if (rcpts == null) { rcpts = getRecipients(header); } } catch (IOException ex) { logger.error(ex.getMessage(), ex); System.exit(EX_TEMPFAIL); } finally { IOUtils.closeQuietly(is); } } if (from == null || ArrayUtils.isEmpty(rcpts)) { usage(); System.exit(EX_USAGE); } Deliver deliver = new Deliver(); deliver.init(config); // Spool the incoming message deliver.deliver(from, rcpts, file); System.exit(EX_OK); }
From source file:ekb.elastic.ingest.TaxiQuery.java
public static void main(String... args) { Options options = new Options(); HelpFormatter help = new HelpFormatter(); try {//from w w w . ja v a 2s . com Option hostOpt = new Option("h", "host", true, "ElasticSearch URL"); hostOpt.setArgs(1); hostOpt.setRequired(true); Option portOpt = new Option("p", "port", true, "ElasticSearch URL"); portOpt.setArgs(1); portOpt.setRequired(true); Option clusterOpt = new Option("c", "cluster", true, "Cluster"); clusterOpt.setArgs(1); clusterOpt.setRequired(true); Option indexOpt = new Option("i", "index", true, "The index"); indexOpt.setArgs(1); indexOpt.setRequired(true); Option pickupTimeOpt = new Option("u", "pickup", true, "The pickup time"); pickupTimeOpt.setArgs(1); pickupTimeOpt.setRequired(true); Option dropTimeOpt = new Option("d", "dropoff", true, "The dropoff time"); dropTimeOpt.setArgs(1); dropTimeOpt.setRequired(true); options.addOption(hostOpt); options.addOption(portOpt); options.addOption(clusterOpt); options.addOption(indexOpt); options.addOption(pickupTimeOpt); options.addOption(dropTimeOpt); GnuParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", cmd.getOptionValue('c')) .build(); Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress( cmd.getOptionValue('h'), Integer.parseInt(cmd.getOptionValue('p')))); TaxiQuery tq = new TaxiQuery(); TaxiStats stats = tq.getTaxiStats(client, cmd.getOptionValues("i")); log.info("Results:\n" + stats.toDateString()); sdf.parse(cmd.getOptionValue("u")); sdf.parse(cmd.getOptionValue("d")); // 2013-01-01T10:10:00 ArrayList<TaxiBucket> list = tq.getInterval(client, cmd.getOptionValues("index"), cmd.getOptionValue("u"), cmd.getOptionValue("d"), 60); log.info("List size is: " + list.size()); client.close(); } catch (ParseException pe) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); help.printUsage(pw, 80, TaxiQuery.class.getName(), options); log.error(sw.toString()); } catch (TaxiQueryException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); log.error(sw.toString()); } catch (java.text.ParseException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); log.error(sw.toString()); } }
From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java
public static void main(String[] args) throws Exception { Parser parser = new PosixParser(); Options options = new Options(); options.addOption("r", "repo", true, "Repository type to search: local|central"); options.addOption("c", "client-concurrency", true, "Max threads to allow each client tester to run tests, defaults to 10"); options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5"); options.addOption("m", "max-time", true, "Max time (in minutes) to allow tests to complete, defaults to 10"); options.addOption("v", "version", false, "Print version and exit"); options.addOption("h", "help", false, "This help text"); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { System.out.println(options); System.exit(0);/*from w ww. j av a2s. c om*/ } if (commandLine.hasOption("v")) { System.out.println("How the hell should I know?"); System.exit(0); } // 1. Find all testers in given repos List<RepoSearcher> repoSearchers = new ArrayList<>(); for (String repo : commandLine.getOptionValues("r")) { if ("local".equals(repo.toLowerCase())) { repoSearchers.add(new LocalRepoSearcher()); } else if ("central".equals(repo.toLowerCase())) { repoSearchers.add(new CentralRepoSearcher()); } else { System.err.println("Unrecognized repo: " + repo); System.err.println(options); System.exit(1); } } int clientConcurrency = 10; if (commandLine.hasOption("c")) { try { clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c")); } catch (NumberFormatException nfe) { System.err.println( "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'"); System.exit(1); } } int testConcurrency = 5; if (commandLine.hasOption("t")) { try { testConcurrency = Integer.parseInt(commandLine.getOptionValue("t")); } catch (NumberFormatException nfe) { System.err.println( "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'"); System.exit(1); } } int maxMinutes = 10; if (commandLine.hasOption("m")) { try { maxMinutes = Integer.parseInt(commandLine.getOptionValue("m")); } catch (NumberFormatException nfe) { System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'"); System.exit(1); } } Properties clientProps = new Properties(); clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency)); File baseRunDir = new File(System.getProperty("user.dir") + "/run"); baseRunDir.mkdirs(); File tmpDir = new File(baseRunDir, "jars"); tmpDir.mkdirs(); List<ServerRunner> serverRunners = new ArrayList<>(); List<ClientRunner> clientRunners = new ArrayList<>(); for (RepoSearcher searcher : repoSearchers) { List<File> jars = searcher.findAndCache(tmpDir); for (File f : jars) { ServerRunner serverRunner = new ServerRunner(f, baseRunDir); System.out.println("Found tester: " + serverRunner.getVersion()); serverRunners.add(serverRunner); clientRunners.add(new ClientRunner(f, baseRunDir, clientProps)); } } // 2. Start servers and collect ports System.out.println(); System.out.println("Starting " + serverRunners.size() + " servers..."); for (ServerRunner server : serverRunners) { server.startServer(); } System.out.println(); List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size()); for (ServerRunner server : serverRunners) { for (ClientRunner client : clientRunners) { tests.add(new TestCombo(server, client)); } } System.out.println("Enqueued " + tests.size() + " test combos to run..."); long startTime = System.currentTimeMillis(); // 3. Run every client against every server, collecting results BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size()); ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000, TimeUnit.MILLISECONDS, workQueue); service.prestartAllCoreThreads(); workQueue.addAll(tests); while (!workQueue.isEmpty()) { Thread.sleep(1000); } service.shutdown(); service.awaitTermination(maxMinutes, TimeUnit.MINUTES); long endTime = System.currentTimeMillis(); long totalTimeSecs = Math.round((endTime - startTime) / 1000.0); for (ServerRunner server : serverRunners) { server.shutdownServer(); } System.out.println(); System.out.println("======="); System.out.println("Results"); System.out.println("-------"); // print a summary int totalTests = 0; int totalSuccess = 0; for (TestCombo combo : tests) { String clientVer = combo.getClientVersion(); String serverVer = combo.getServerVersion(); String results = combo.getClientResults(); ObjectMapper mapper = new ObjectMapper(new JsonFactory()); JsonNode node = mapper.reader().readTree(results); JsonNode resultsArray = node.get("results"); int numTests = resultsArray.size(); int numSuccess = 0; for (int i = 0; i < numTests; i++) { if ("success".equals(resultsArray.get(i).get("result").asText())) { numSuccess++; } } totalSuccess += numSuccess; totalTests += numTests; System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds"); } System.out.println("-------"); System.out.println( "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds"); FileWriter out = new FileWriter("results.json"); PrintWriter pw = new PrintWriter(out); // 4. Output full results pw.println("{\n \"results\": ["); for (TestCombo combo : tests) { combo.emitResults(pw, " "); } pw.println(" ],"); pw.println(" \"servers\": ["); for (ServerRunner server : serverRunners) { server.emitInfo(pw, " "); } pw.println(" ],"); pw.close(); }
From source file:com.dattack.dbping.cli.PingAnalyzerCli.java
/** * The <code>main</code> method. * * @param args// w w w . ja va2 s . com * the program arguments */ public static void main(final String[] args) { try { // create Options object final Options options = new Options(); // add t option options.addOption(START_DATE_OPTION, true, "the date for an analysis run to begin"); options.addOption(END_DATE_OPTION, true, "the date for an analysis run to finish"); options.addOption(SPAN_OPTION, true, "the period of time between points"); options.addOption(DATA_FILE_OPTION, true, "the data file to analyze"); options.addOption(METRIC_OPTION, true, "the metric to analyze"); options.addOption(MAX_VALUE_OPTION, true, "the maximum value to use"); options.addOption(MIN_VALUE_OPTION, true, "the minimum value to use"); final CommandLineParser parser = new DefaultParser(); final CommandLine cmd = parser.parse(options, args); final ReportContext context = new ReportContext(); context.setStartDate(TimeUtils.parseDate(cmd.getOptionValue(START_DATE_OPTION))); context.setEndDate(TimeUtils.parseDate(cmd.getOptionValue(END_DATE_OPTION))); context.setTimeSpan(TimeUtils.parseTimeSpanMillis(cmd.getOptionValue(SPAN_OPTION))); context.setMaxValue(parseLong(cmd.getOptionValue(MAX_VALUE_OPTION))); context.setMinValue(parseLong(cmd.getOptionValue(MIN_VALUE_OPTION))); if (cmd.hasOption(METRIC_OPTION)) { for (final String metricName : cmd.getOptionValues(METRIC_OPTION)) { context.addMetricNameFilter(MetricName.parse(metricName)); } } final PingAnalyzerCli ping = new PingAnalyzerCli(); for (final String file : cmd.getOptionValues(DATA_FILE_OPTION)) { ping.execute(new File(file), context); } } catch (final ParseException | ConfigurationException e) { System.err.println(e.getMessage()); } }
From source file:com.dattack.dbtools.ping.PingAnalyzer.java
/** * The <code>main</code> method. * * @param args//from w w w . j a va 2 s. c o m * the program arguments */ public static void main(final String[] args) { try { // create Options object final Options options = new Options(); // add t option options.addOption(START_DATE_OPTION, true, "the date for an analysis run to begin"); options.addOption(END_DATE_OPTION, true, "the date for an analysis run to finish"); options.addOption(SPAN_OPTION, true, "the period of time between points"); options.addOption(DATA_FILE_OPTION, true, "the data file to analyze"); options.addOption(METRIC_OPTION, true, "the metric to analyze"); options.addOption(MAX_VALUE_OPTION, true, "the maximum value to use"); options.addOption(MIN_VALUE_OPTION, true, "the minimum value to use"); final CommandLineParser parser = new DefaultParser(); final CommandLine cmd = parser.parse(options, args); final ReportContext context = new ReportContext(); context.setStartDate(TimeUtils.parseDate(cmd.getOptionValue(START_DATE_OPTION))); context.setEndDate(TimeUtils.parseDate(cmd.getOptionValue(END_DATE_OPTION))); context.setTimeSpan(TimeUtils.parseTimeSpanMillis(cmd.getOptionValue(SPAN_OPTION))); context.setMaxValue(parseLong(cmd.getOptionValue(MAX_VALUE_OPTION))); context.setMinValue(parseLong(cmd.getOptionValue(MIN_VALUE_OPTION))); if (cmd.hasOption(METRIC_OPTION)) { for (final String metricName : cmd.getOptionValues(METRIC_OPTION)) { context.addMetricNameFilter(MetricName.parse(metricName)); } } final PingAnalyzer ping = new PingAnalyzer(); for (final String file : cmd.getOptionValues(DATA_FILE_OPTION)) { ping.execute(new File(file), context); } } catch (final ParseException | ConfigurationException e) { System.err.println(e.getMessage()); } }
From source file:com.cws.esolutions.core.main.EmailUtility.java
public static final void main(final String[] args) { final String methodName = EmailUtility.CNAME + "#main(final String[] args)"; if (DEBUG) {/* w w w .j a v a 2s .c om*/ DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", (Object) args); } if (args.length == 0) { HelpFormatter usage = new HelpFormatter(); usage.printHelp(EmailUtility.CNAME, options, true); return; } try { CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); URL xmlURL = null; JAXBContext context = null; Unmarshaller marshaller = null; CoreConfigurationData configData = null; xmlURL = FileUtils.getFile(commandLine.getOptionValue("config")).toURI().toURL(); context = JAXBContext.newInstance(CoreConfigurationData.class); marshaller = context.createUnmarshaller(); configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL); EmailMessage message = new EmailMessage(); message.setMessageTo(new ArrayList<String>(Arrays.asList(commandLine.getOptionValues("to")))); message.setMessageSubject(commandLine.getOptionValue("subject")); message.setMessageBody((String) commandLine.getArgList().get(0)); message.setEmailAddr((StringUtils.isNotEmpty(commandLine.getOptionValue("from"))) ? new ArrayList<String>(Arrays.asList(commandLine.getOptionValue("from"))) : new ArrayList<String>(Arrays.asList(configData.getMailConfig().getMailFrom()))); if (DEBUG) { DEBUGGER.debug("EmailMessage: {}", message); } try { EmailUtils.sendEmailMessage(configData.getMailConfig(), message, false); } catch (MessagingException mx) { System.err.println( "An error occurred while sending the requested message. Exception: " + mx.getMessage()); } } catch (ParseException px) { px.printStackTrace(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(EmailUtility.CNAME, options, true); } catch (MalformedURLException mx) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(EmailUtility.CNAME, options, true); } catch (JAXBException jx) { jx.printStackTrace(); System.err.println("An error occurred while loading the provided configuration file. Cannot continue."); } }