List of usage examples for java.util Map containsKey
boolean containsKey(Object key);
From source file:com.qcloud.project.macaovehicle.util.MessageGetter.java
public static void main(String[] args) throws Exception { // StringBuilder stringBuilder = new StringBuilder(); // stringBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><auditData><url>vehicle</url><success>0</success><vehicle><ric>1000001</ric><reason></reason><state>1</state></vehicle></auditData>"); // System.out.println(stringBuilder.toString()); // String dataPostURL = "http://120.25.12.206:8888/DeclMsg/Ciq"; // MessageGetter.sendXml(stringBuilder.toString(), dataPostURL); Map<String, Object> param = new LinkedHashMap<String, Object>(); param.put("driverIc", "C09000000002a6d32701"); param.put("driverName", ""); param.put("sex", "1"); param.put("birthday", "1991-09-01T00:00:00"); param.put("nationality", ""); param.put("corpName", "??"); param.put("registerNo", "C0900000000347736701"); param.put("drivingValidityDate", "2017-04-17T09:00:00"); param.put("commonFlag", "1"); param.put("residentcardValidityDate", "2014-04-27T09:00:00"); param.put("leftHandFingerprint", "1"); param.put("rightHandFingerprint", "2"); param.put("imageEignvalues", "3"); param.put("certificateNo", "4"); param.put("validityEndDate", "2020-04-17T09:00:00"); param.put("creator", ""); param.put("createDate", "2014-04-17T09:00:00"); param.put("modifier", ""); param.put("modifyDate", "2014-04-17T09:00:00"); param.put("cityCode", ""); param.put("nation", "?"); param.put("tel", "13568877897"); param.put("visaCode", "21212121"); param.put("subscriberCode", "7937"); param.put("visaValidityDate", "2017-04-17T09:00:00"); param.put("icCode", "TDriver000018950"); param.put("toCountry", ""); param.put("fromCountry", ""); param.put("licenseCode", "168819"); param.put("idCard", "440882199110254657"); param.put("secondName", ""); param.put("secondBirthday", "1991-04-17T09:00:00"); param.put("secondCertificateNo", "123456789"); param.put("secondCertificateType", "03"); param.put("visaNo", "123456789"); param.put("stayPeriod", "180"); param.put("residentcardValidityDate", "2017-04-27T09:00:00"); param.put("returnCardNo", "123456789"); param.put("pass", "123456789"); param.put("drivingLicense", "422801197507232815"); param.put("customCode", "12345"); param.put("visaCity", "?"); param.put("certificateType", "01"); param.put("certificateCode", "12345678"); param.put("subscribeDate", "2010-04-17T09:00:00"); param.put("passportNo", "G20961897"); param.put("transactType", "01"); param.put("isAvoidInspect", "N"); param.put("isPriorityInspect", "N"); param.put("remark", ""); String picSourcePath1 = "H://images/?.jpg"; // String picSourcePath1="H://images/1/1.jpg"; String picSourcePath2 = "H://images/1/2.jpeg"; String picSourcePath3 = "H://images/1/3.jpeg"; String picSourcePath4 = "H://images/1/4.jpeg"; String picSourcePath5 = "H://images/1/5.jpeg"; String picSourcePath6 = "H://images/1/6.jpeg"; param.put("driverPhoto", Base64PicUtil.GetImageStr(picSourcePath1)); // param.put("imageA", Base64PicUtil.GetImageStr(picSourcePath2)); // param.put("imageB", Base64PicUtil.GetImageStr(picSourcePath3)); // param.put("imageC", Base64PicUtil.GetImageStr(picSourcePath4)); // param.put("imageD", Base64PicUtil.GetImageStr(picSourcePath5)); String dataStr = MessageGetter.sendMessage(param, "driver", dataPostURL); Map<String, Object> map = XmlParseUtils.XmlToMap(dataStr); System.out.println(dataStr);//from w ww.j a v a2s. co m if (map.containsKey("message")) { String message = (String) map.get("message"); if (message.equals("true")) { System.out.println("==================================================="); System.out.println(map); } } System.out.println(dataStr); }
From source file:org.jetbrains.webdemo.executors.JunitExecutor.java
public static void main(String[] args) { try {/* w ww . j ava2 s . co m*/ JUnitCore jUnitCore = new JUnitCore(); jUnitCore.addListener(new MyRunListener()); List<Class> classes = getAllClassesFromTheDir(new File(args[0])); for (Class cl : classes) { boolean hasTestMethods = false; for (Method method : cl.getMethods()) { if (method.isAnnotationPresent(Test.class)) { hasTestMethods = true; break; } } if (!hasTestMethods) continue; Request request = Request.aClass(cl); jUnitCore.run(request); } try { ObjectMapper objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(Throwable.class, new ThrowableSerializer()); module.addSerializer(junit.framework.ComparisonFailure.class, new JunitFrameworkComparisonFailureSerializer()); module.addSerializer(org.junit.ComparisonFailure.class, new OrgJunitComparisonFailureSerializer()); objectMapper.registerModule(module); System.setOut(standardOutput); Map<String, List<TestRunInfo>> groupedTestResults = new HashMap<>(); for (TestRunInfo testRunInfo : output) { if (!groupedTestResults.containsKey(testRunInfo.className)) { groupedTestResults.put(testRunInfo.className, new ArrayList<TestRunInfo>()); } groupedTestResults.get(testRunInfo.className).add(testRunInfo); } System.out.print(objectMapper.writeValueAsString(groupedTestResults)); } catch (IOException e) { e.printStackTrace(); } } catch (Throwable e) { System.setOut(standardOutput); System.out.print("[\""); e.printStackTrace(); System.out.print("\"]"); } }
From source file:Main.java
public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.putIfAbsent(i, "val" + i); }/*ww w . j a va 2 s .c o m*/ map.forEach((id, val) -> System.out.println(val)); map.computeIfPresent(3, (num, val) -> val + num); System.out.println(map.get(3)); // val33 map.computeIfPresent(9, (num, val) -> null); System.out.println(map.containsKey(9)); // false map.computeIfAbsent(23, num -> "val" + num); System.out.println(map.containsKey(23)); // true map.computeIfAbsent(3, num -> "bam"); System.out.println(map.get(3)); // val33 }
From source file:de.ingrid.iplug.PlugServer.java
/** * To start the plug server from the commandline. * @param args Arguments for the plug server e.g. --descriptor . * @throws Exception If something goes wrong. *///from w w w. java 2 s. c o m public static void main(String[] args) throws Exception { Map arguments = readParameters(args); PlugDescription plugDescription = null; File plugDescriptionFile = new File(PLUG_DESCRIPTION); if (arguments.containsKey("--plugdescription")) { plugDescriptionFile = new File((String) arguments.get("--plugdescription")); } plugDescription = loadPlugDescriptionFromFile(plugDescriptionFile); PlugServer server = null; if (arguments.containsKey("--resetPassword")) { String pw = (String) arguments.get("--resetPassword"); fLogger.info("Resetting password to '" + pw + "' ..."); plugDescription.setIplugAdminPassword(BCrypt.hashpw(pw, BCrypt.gensalt())); XMLSerializer serializer = new XMLSerializer(); serializer.serialize(plugDescription, plugDescriptionFile); fLogger.info("Done ... please restart iPlug."); return; } else if (arguments.containsKey("--migratePassword")) { fLogger.info("Migrating plain text password from PlugDescription to encrypted one ..."); plugDescription.setIplugAdminPassword( BCrypt.hashpw(plugDescription.getIplugAdminPassword(), BCrypt.gensalt())); XMLSerializer serializer = new XMLSerializer(); serializer.serialize(plugDescription, plugDescriptionFile); fLogger.info("Done ... please restart iPlug."); return; } else if (arguments.containsKey("--descriptor")) { File commConf = new File((String) arguments.get("--descriptor")); server = new PlugServer(plugDescription, commConf, plugDescriptionFile, 60 * 1000); } if (server != null) { server.initPlugServer(); } }
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 w w w. j a v a 2 s .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:hk.idv.kenson.jrconsole.Console.java
/** * @param args// w w w . j a v a2 s .co m */ public static void main(String[] args) { try { Map<String, Object> params = Console.parseArgs(args); if (params.containsKey("help")) { printUsage(); return; } if (params.containsKey("version")) { System.err.println("Version: " + VERSION); return; } if (params.containsKey("debug")) { for (String key : params.keySet()) log.info("\"" + key + "\" => \"" + params.get(key) + "\""); return; } checkParam(params); stepCompile(params); JasperReport jasper = stepLoadReport(params); JasperPrint print = stepFill(jasper, params); InputStream stream = stepExport(print, params); File output = new File(params.get("output").toString()); FileOutputStream fos = new FileOutputStream(output); copy(stream, fos); fos.close(); stream.close(); System.out.println(output.getAbsolutePath()); //Output the report path for pipe } catch (IllegalArgumentException ex) { printUsage(); System.err.println("Error: " + ex.getMessage()); ex.printStackTrace(); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException("Unexpected exception", ex); } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5GoldLabelEstimator.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String inputDir = args[0];/*ww w. java 2 s . c o m*/ File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } // we will process only a subset first List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>(); Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); for (File file : files) { allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file)); } // collect turkers and csv List<String> turkerIDs = extractAndSortTurkerIDs(allArgumentPairs); String preparedCSV = prepareCSV(allArgumentPairs, turkerIDs); // save CSV and run MACE Path tmpDir = Files.createTempDirectory("mace"); File maceInputFile = new File(tmpDir.toFile(), "input.csv"); FileUtils.writeStringToFile(maceInputFile, preparedCSV, "utf-8"); File outputPredictions = new File(tmpDir.toFile(), "predictions.txt"); File outputCompetence = new File(tmpDir.toFile(), "competence.txt"); // run MACE MACE.main(new String[] { "--iterations", "500", "--threshold", String.valueOf(MACE_THRESHOLD), "--restarts", "50", "--outputPredictions", outputPredictions.getAbsolutePath(), "--outputCompetence", outputCompetence.getAbsolutePath(), maceInputFile.getAbsolutePath() }); // read back the predictions and competence List<String> predictions = FileUtils.readLines(outputPredictions, "utf-8"); // check the output if (predictions.size() != allArgumentPairs.size()) { throw new IllegalStateException("Wrong size of the predicted file; expected " + allArgumentPairs.size() + " lines but was " + predictions.size()); } String competenceRaw = FileUtils.readFileToString(outputCompetence, "utf-8"); String[] competence = competenceRaw.split("\t"); if (competence.length != turkerIDs.size()) { throw new IllegalStateException( "Expected " + turkerIDs.size() + " competence number, got " + competence.length); } // rank turkers by competence Map<String, Double> turkerIDCompetenceMap = new TreeMap<>(); for (int i = 0; i < turkerIDs.size(); i++) { turkerIDCompetenceMap.put(turkerIDs.get(i), Double.valueOf(competence[i])); } // sort by value descending Map<String, Double> sortedCompetences = IOHelper.sortByValue(turkerIDCompetenceMap, false); System.out.println("Sorted turker competences: " + sortedCompetences); // assign the gold label and competence for (int i = 0; i < allArgumentPairs.size(); i++) { AnnotatedArgumentPair annotatedArgumentPair = allArgumentPairs.get(i); String goldLabel = predictions.get(i).trim(); // might be empty if (!goldLabel.isEmpty()) { // so far the gold label has format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal // strip now only the gold label annotatedArgumentPair.setGoldLabel(goldLabel); } // update turker competence for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) { String turkID = assignment.getTurkID(); int turkRank = getTurkerRank(turkID, sortedCompetences); assignment.setTurkRank(turkRank); double turkCompetence = turkerIDCompetenceMap.get(turkID); assignment.setTurkCompetence(turkCompetence); } } // now sort the data back according to their original file name Map<String, List<AnnotatedArgumentPair>> fileNameAnnotatedPairsMap = new HashMap<>(); for (AnnotatedArgumentPair argumentPair : allArgumentPairs) { String fileName = IOHelper.createFileName(argumentPair.getDebateMetaData(), argumentPair.getArg1().getStance()); if (!fileNameAnnotatedPairsMap.containsKey(fileName)) { fileNameAnnotatedPairsMap.put(fileName, new ArrayList<AnnotatedArgumentPair>()); } fileNameAnnotatedPairsMap.get(fileName).add(argumentPair); } // and save them to the output file for (Map.Entry<String, List<AnnotatedArgumentPair>> entry : fileNameAnnotatedPairsMap.entrySet()) { String fileName = entry.getKey(); List<AnnotatedArgumentPair> argumentPairs = entry.getValue(); File outputFile = new File(outputDir, fileName); // and save all sampled pairs into a XML file XStreamTools.toXML(argumentPairs, outputFile); System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile); } }
From source file:com.msopentech.odatajclient.engine.performance.PerfTestReporter.java
public static void main(final String[] args) throws Exception { // 1. check input directory final File reportdir = new File(args[0] + File.separator + "target" + File.separator + "surefire-reports"); if (!reportdir.isDirectory()) { throw new IllegalArgumentException("Expected directory, got " + args[0]); }/* w w w . ja va2 s . com*/ // 2. read test data from surefire output final File[] xmlReports = reportdir.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { return name.endsWith("-output.txt"); } }); final Map<String, Map<String, Double>> testData = new TreeMap<String, Map<String, Double>>(); for (File xmlReport : xmlReports) { final BufferedReader reportReader = new BufferedReader(new FileReader(xmlReport)); try { while (reportReader.ready()) { String line = reportReader.readLine(); final String[] parts = line.substring(0, line.indexOf(':')).split("\\."); final String testClass = parts[0]; if (!testData.containsKey(testClass)) { testData.put(testClass, new TreeMap<String, Double>()); } line = reportReader.readLine(); testData.get(testClass).put(parts[1], Double.valueOf(line.substring(line.indexOf(':') + 2, line.indexOf('[')))); } } finally { IOUtils.closeQuietly(reportReader); } } // 3. build XSLX output (from template) final HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(args[0] + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + XLS)); for (Map.Entry<String, Map<String, Double>> entry : testData.entrySet()) { final Sheet sheet = workbook.getSheet(entry.getKey()); int rows = 0; for (Map.Entry<String, Double> subentry : entry.getValue().entrySet()) { final Row row = sheet.createRow(rows++); Cell cell = row.createCell(0); cell.setCellValue(subentry.getKey()); cell = row.createCell(1); cell.setCellValue(subentry.getValue()); } } final FileOutputStream out = new FileOutputStream( args[0] + File.separator + "target" + File.separator + XLS); try { workbook.write(out); } finally { IOUtils.closeQuietly(out); } }
From source file:com.joliciel.talismane.fr.TalismaneFrench.java
/** * @param args/*w w w .j a v a2 s. c o m*/ * @throws Exception */ public static void main(String[] args) throws Exception { Map<String, String> argsMap = TalismaneConfig.convertArgs(args); CorpusFormat corpusReaderType = null; String treebankDirPath = null; boolean keepCompoundPosTags = true; if (argsMap.containsKey("corpusReader")) { corpusReaderType = CorpusFormat.valueOf(argsMap.get("corpusReader")); argsMap.remove("corpusReader"); } if (argsMap.containsKey("treebankDir")) { treebankDirPath = argsMap.get("treebankDir"); argsMap.remove("treebankDir"); } if (argsMap.containsKey("keepCompoundPosTags")) { keepCompoundPosTags = argsMap.get("keepCompoundPosTags").equalsIgnoreCase("true"); argsMap.remove("keepCompoundPosTags"); } Extensions extensions = new Extensions(); extensions.pluckParameters(argsMap); TalismaneFrench talismaneFrench = new TalismaneFrench(); TalismaneConfig config = new TalismaneConfig(argsMap, talismaneFrench); if (config.getCommand() == null) return; if (corpusReaderType != null) { if (corpusReaderType == CorpusFormat.ftbDep) { File inputFile = new File(config.getInFilePath()); FtbDepReader ftbDepReader = new FtbDepReader(inputFile, config.getInputCharset()); ftbDepReader.setKeepCompoundPosTags(keepCompoundPosTags); ftbDepReader.setPredictTransitions(config.isPredictTransitions()); config.setParserCorpusReader(ftbDepReader); config.setPosTagCorpusReader(ftbDepReader); config.setTokenCorpusReader(ftbDepReader); if (config.getCommand().equals(Command.compare)) { File evaluationFile = new File(config.getEvaluationFilePath()); FtbDepReader ftbDepEvaluationReader = new FtbDepReader(evaluationFile, config.getInputCharset()); ftbDepEvaluationReader.setKeepCompoundPosTags(keepCompoundPosTags); config.setParserEvaluationCorpusReader(ftbDepEvaluationReader); config.setPosTagEvaluationCorpusReader(ftbDepEvaluationReader); } } else if (corpusReaderType == CorpusFormat.ftb) { TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance(); TreebankServiceLocator treebankServiceLocator = TreebankServiceLocator .getInstance(talismaneServiceLocator); TreebankUploadService treebankUploadService = treebankServiceLocator .getTreebankUploadServiceLocator().getTreebankUploadService(); TreebankExportService treebankExportService = treebankServiceLocator .getTreebankExportServiceLocator().getTreebankExportService(); File treebankFile = new File(treebankDirPath); TreebankReader treebankReader = treebankUploadService.getXmlReader(treebankFile); // we prepare both the tokeniser and pos-tag readers, just in case they are needed InputStream posTagMapStream = talismaneFrench.getDefaultPosTagMapFromStream(); Scanner scanner = new Scanner(posTagMapStream, "UTF-8"); List<String> descriptors = new ArrayList<String>(); while (scanner.hasNextLine()) descriptors.add(scanner.nextLine()); FtbPosTagMapper ftbPosTagMapper = treebankExportService.getFtbPosTagMapper(descriptors, talismaneFrench.getDefaultPosTagSet()); PosTagAnnotatedCorpusReader posTagAnnotatedCorpusReader = treebankExportService .getPosTagAnnotatedCorpusReader(treebankReader, ftbPosTagMapper, keepCompoundPosTags); config.setPosTagCorpusReader(posTagAnnotatedCorpusReader); TokeniserAnnotatedCorpusReader tokenCorpusReader = treebankExportService .getTokeniserAnnotatedCorpusReader(treebankReader, ftbPosTagMapper, keepCompoundPosTags); config.setTokenCorpusReader(tokenCorpusReader); SentenceDetectorAnnotatedCorpusReader sentenceCorpusReader = treebankExportService .getSentenceDetectorAnnotatedCorpusReader(treebankReader); config.setSentenceCorpusReader(sentenceCorpusReader); } else if (corpusReaderType == CorpusFormat.conll || corpusReaderType == CorpusFormat.spmrl) { File inputFile = new File(config.getInFilePath()); ParserRegexBasedCorpusReader corpusReader = config.getParserService() .getRegexBasedCorpusReader(inputFile, config.getInputCharset()); corpusReader.setPredictTransitions(config.isPredictTransitions()); config.setParserCorpusReader(corpusReader); config.setPosTagCorpusReader(corpusReader); config.setTokenCorpusReader(corpusReader); if (corpusReaderType == CorpusFormat.spmrl) { corpusReader.setRegex( "%INDEX%\\t%TOKEN%\\t.*\\t.*\\t%POSTAG%\\t.*\\t.*\\t.*\\t%GOVERNOR%\\t%LABEL%"); } if (config.getCommand().equals(Command.compare)) { File evaluationFile = new File(config.getEvaluationFilePath()); ParserRegexBasedCorpusReader evaluationReader = config.getParserService() .getRegexBasedCorpusReader(evaluationFile, config.getInputCharset()); config.setParserEvaluationCorpusReader(evaluationReader); config.setPosTagEvaluationCorpusReader(evaluationReader); } } else { throw new TalismaneException("Unknown corpusReader: " + corpusReaderType); } } Talismane talismane = config.getTalismane(); extensions.prepareCommand(config, talismane); talismane.process(); }
From source file:com.jwm123.loggly.reporter.AppLauncher.java
public static void main(String args[]) throws Exception { try {//w w w . ja va 2s. co m CommandLine cl = parseCLI(args); try { config = new Configuration(); } catch (Exception e) { e.printStackTrace(); System.err.println("ERROR: Failed to read in persisted configuration."); } if (cl.hasOption("h")) { HelpFormatter help = new HelpFormatter(); String jarName = AppLauncher.class.getProtectionDomain().getCodeSource().getLocation().getFile(); if (jarName.contains("/")) { jarName = jarName.substring(jarName.lastIndexOf("/") + 1); } help.printHelp("java -jar " + jarName + " [options]", opts); } if (cl.hasOption("c")) { config.update(); } if (cl.hasOption("q")) { Client client = new Client(config); client.setQuery(cl.getOptionValue("q")); if (cl.hasOption("from")) { client.setFrom(cl.getOptionValue("from")); } if (cl.hasOption("to")) { client.setTo(cl.getOptionValue("to")); } List<Map<String, Object>> report = client.getReport(); if (report != null) { List<Map<String, String>> reportContent = new ArrayList<Map<String, String>>(); ReportGenerator generator = null; if (cl.hasOption("file")) { generator = new ReportGenerator(new File(cl.getOptionValue("file"))); } byte reportFile[] = null; if (cl.hasOption("g")) { System.out.println("Search results: " + report.size()); Set<Object> values = new TreeSet<Object>(); Map<Object, Integer> counts = new HashMap<Object, Integer>(); for (String groupBy : cl.getOptionValues("g")) { for (Map<String, Object> result : report) { if (mapContains(result, groupBy)) { Object value = mapGet(result, groupBy); values.add(value); if (counts.containsKey(value)) { counts.put(value, counts.get(value) + 1); } else { counts.put(value, 1); } } } System.out.println("For key: " + groupBy); for (Object value : values) { System.out.println(" " + value + ": " + counts.get(value)); } } if (cl.hasOption("file")) { Map<String, String> reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Month", MONTH_FORMAT.format(new Date())); reportContent.add(reportAddition); for (Object value : values) { reportAddition = new LinkedHashMap<String, String>(); reportAddition.put(value.toString(), "" + counts.get(value)); reportContent.add(reportAddition); } reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Total", "" + report.size()); reportContent.add(reportAddition); } } else { System.out.println("The Search [" + cl.getOptionValue("q") + "] yielded " + report.size() + " results."); if (cl.hasOption("file")) { Map<String, String> reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Month", MONTH_FORMAT.format(new Date())); reportContent.add(reportAddition); reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Count", "" + report.size()); reportContent.add(reportAddition); } } if (cl.hasOption("file")) { reportFile = generator.build(reportContent); File reportFileObj = new File(cl.getOptionValue("file")); FileUtils.writeByteArrayToFile(reportFileObj, reportFile); if (cl.hasOption("e")) { ReportMailer mailer = new ReportMailer(config, cl.getOptionValues("e"), cl.getOptionValue("s"), reportFileObj.getName(), reportFile); mailer.send(); } } } } } catch (IllegalArgumentException e) { System.err.println(e.getMessage()); System.exit(1); } }