List of usage examples for java.util LinkedHashMap LinkedHashMap
public LinkedHashMap()
From source file:AndroidUninstallStock.java
@SuppressWarnings("static-access") public static void main(String[] args) { try {//from w w w . ja v a 2 s . c o m String lang = Locale.getDefault().getLanguage(); GnuParser cmdparser = new GnuParser(); Options cmdopts = new Options(); for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) { // hack for printOptions java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld); fieldopt.setAccessible(true); fieldopt.set(cmdopts, new LinkedHashMap<>()); } cmdopts.addOption("h", "help", false, "Help"); cmdopts.addOption("t", "test", false, "Show only report"); cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg() .withDescription("Path to ADB from Android SDK").create("a")); cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg() .withDescription("Select device (\"adb devices\")").create("d")); cmdopts.addOption(null, "restore", false, "If packages have not yet removed and are disabled, " + "you can activate them again"); cmdopts.addOption(null, "google", false, "Delete packages are in the Google section"); cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex" + System.lineSeparator() + "(It is required to repeat command execution)"); cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]"); //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)"); cmdopts.addOption(null, "scanlibs", false, "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib"); cmdopts.addOptionGroup(new OptionGroup() { { addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired() .withDescription("Create file with list packages").create()); addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create()); } }); cmdopts.getOption("lang").setDescription( "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market"); CommandLine cmd = cmdparser.parse(cmdopts, args); if (args.length == 0 || cmd.hasOption("help")) { PrintWriter console = new PrintWriter(System.out); HelpFormatter cmdhelp = new HelpFormatter(); cmdhelp.setOptionComparator(new Comparator<Option>() { @Override public int compare(Option o1, Option o2) { return 0; } }); console.println("WARNING: Before use make a backup with ClockworkMod Recovery!"); console.println(); console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]"); cmdhelp.printOptions(console, 80, cmdopts, 3, 2); console.flush(); return; } String adb = cmd.getOptionValue("adb", "adb"); try { run(adb, "start-server"); } catch (IOException e) { System.out.println("Error: Not found ADB! Use -a or --adb"); return; } final boolean NotTest = !cmd.hasOption("test"); String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev")); if (!deverror.isEmpty()) { System.out.println(deverror); return; } System.out.println("Getting list packages:"); LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>(); for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) { // "pm list packages" give list sorted by packages ;) String pckg = ln.substring("package:".length()); String pckgname = ln.substring(ln.lastIndexOf('=') + 1); pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1); if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) { apklist.put(pckg, pckgname); } } for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) { String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk"); if (!apklist.containsKey(path)) { apklist.put(path, ""); } } apklist.remove("/system/app/mcRegistry"); for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } String genfile = cmd.getOptionValue("genfile"); if (genfile != null) { Path genpath = Paths.get(genfile); try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8, new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE })) { if (cmd.getOptionValue("lang") != null) { lang = cmd.getOptionValue("lang"); } LinkedHashSet<String> listsystem = new LinkedHashSet<String>() { { add("com.android"); add("com.google.android"); //add("com.sec.android.app"); add("com.monotype.android"); add("eu.chainfire.supersu"); } }; // \r\n for Windows Notepad gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"); gen.write("<!-- & raplace with & or use <![CDATA[ ]]> -->\r\n"); gen.write("<AndroidUninstallStock>\r\n\r\n"); gen.write("<Normal>\r\n"); System.out.println(); System.out.println("\tNormal:"); writeInfo(gen, apklist, lang, listsystem, true); gen.write("\t<apk name=\"Exclude Google and etc\">\r\n"); for (String exc : listsystem) { gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n"); } gen.write("\t</apk>\r\n"); gen.write("</Normal>\r\n\r\n"); gen.write("<Google>\r\n"); System.out.println(); System.out.println("\tGoogle:"); writeInfo(gen, apklist, lang, listsystem, false); gen.write("</Google>\r\n\r\n"); gen.write("</AndroidUninstallStock>\r\n"); System.out.println("File " + genpath.toAbsolutePath() + " created."); } return; } String[] FileName = cmd.getArgs(); if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) { System.out.println("Error: File " + FileName[0] + " not found!"); return; } DocumentBuilderFactory xmlfactory = getXmlDocFactory(); // DocumentBuilder.setErrorHandler() for print errors Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0])); LinkedList<AusInfo> Normal = new LinkedList<AusInfo>(); LinkedList<AusInfo> Google = new LinkedList<AusInfo>(); NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes(); for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) { Node ndnow = ndaus.item(ndausx); NodeList nd = ndnow.getChildNodes(); String ndname = ndnow.getNodeName(); for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) { if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) { continue; } if (ndname.equalsIgnoreCase("Normal")) { Normal.add(getApkInfo(nd.item(ndx))); } else if (ndname.equalsIgnoreCase("Google")) { Google.add(getApkInfo(nd.item(ndx))); } } } // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages. // Now requires a restart. System.out.println(); System.out.println("Include and Exclude packages (Normal):"); LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false); System.out.println(); System.out.println("Global Exclude packages (Normal):"); apkNormal = getApkFromPattern(apkNormal, Normal, true); System.out.println(); System.out.println("Final list packages (Normal):"); for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>(); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Include and Exclude packages (Google):"); apkGoogle = getApkFromPattern(apklist, Google, false); System.out.println(); System.out.println("Global Exclude packages (Google):"); apkGoogle = getApkFromPattern(apkGoogle, Google, true); System.out.println(); System.out.println("Final list packages (Google):"); for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } } if (NotTest) { if (!hasRoot(adb)) { System.out.println("No Root"); System.out.println(); System.out.println("FINISH :)"); return; } } if (cmd.hasOption("restore")) { System.out.println(); System.out.println("Enable (Restore) packages (Normal):"); damage(adb, "pm enable ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Enable (Restore) packages (Google):"); damage(adb, "pm enable ", NotTest, apkGoogle, 2); } System.out.println(); System.out.println("FINISH :)"); return; } else { System.out.println(); System.out.println("Disable packages (Normal):"); damage(adb, "pm disable ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Disable packages (Google):"); damage(adb, "pm disable ", NotTest, apkGoogle, 2); } } if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) { System.out.println(); System.out.println("FINISH :)"); return; } // Reboot now not needed /*if (NotTest) { reboot(adb, "-s", lastdevice, "reboot"); if (!hasRoot(adb)) { System.out.println("No Root"); System.out.println(); System.out.println("FINISH :)"); return; } }*/ if (cmd.hasOption("unlib")) { // "find" not found System.out.println(); System.out.println("Getting list libraries:"); LinkedList<String> liblist = new LinkedList<String>(); liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/")); String dircur = "/system/lib/"; for (int x = 0; x < liblist.size(); x++) { if (liblist.get(x).startsWith("scan:")) { dircur = liblist.get(x).substring("scan:".length()); liblist.remove(x); x--; } else if (liblist.get(x).startsWith("d")) { String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/"; liblist.remove(x); x--; liblist.add("scan:/system/lib/" + dir); liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir)); continue; } liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4)); System.out.println(liblist.get(x)); } final boolean scanlibs = cmd.hasOption("scanlibs"); LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal, "Normal", scanlibs); libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal"); System.out.println(); System.out.println("Final list libraries (Normal):"); for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) { System.out.println(info.getKey() + " = " + info.getValue()); } LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>(); if (cmd.hasOption("google")) { libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs); libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google"); System.out.println(); System.out.println("Final list libraries (Google):"); for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) { System.out.println(info.getKey() + " = " + info.getValue()); } } LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist); for (String key : apkNormal.keySet()) { apkExclude.remove(key); } for (String key : apkGoogle.keySet()) { apkExclude.remove(key); } System.out.println(); System.out.println("Include libraries from Exclude packages:"); LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude); System.out.println(); System.out.println("Enclude libraries from Exclude packages (Normal):"); for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) { if (libExclude.containsKey(info.getKey())) { System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey())); libNormal.remove(info.getKey()); } } System.out.println(); System.out.println("Enclude libraries from Exclude packages (Google):"); for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) { if (libExclude.containsKey(info.getKey())) { System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey())); libGoogle.remove(info.getKey()); } } System.out.println(); System.out.println("Delete libraries (Normal):"); damage(adb, "rm ", NotTest, libNormal, 1); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Delete libraries (Google):"); damage(adb, "rm ", NotTest, libGoogle, 1); } } if (cmd.hasOption("unapk")) { System.out.println(); System.out.println("Cleaning data packages (Normal):"); damage(adb, "pm clear ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Cleaning data packages (Google):"); damage(adb, "pm clear ", NotTest, apkGoogle, 2); } System.out.println(); System.out.println("Uninstall packages (Normal):"); damage(adb, "pm uninstall ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Uninstall packages (Google):"); damage(adb, "pm uninstall ", NotTest, apkGoogle, 2); } } if (cmd.hasOption("unapk")) { System.out.println(); System.out.println("Delete packages (Normal):"); LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>(); for (Map.Entry<String, String> apk : apkNormal.entrySet()) { dexNormal.put(apk.getKey(), apk.getValue()); dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue()); dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue()); } damage(adb, "rm ", NotTest, dexNormal, 1); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Delete packages (Google):"); LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>(); for (Map.Entry<String, String> apk : apkGoogle.entrySet()) { dexGoogle.put(apk.getKey(), apk.getValue()); dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue()); dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue()); } damage(adb, "rm ", NotTest, dexGoogle, 1); } } if (NotTest) { run(adb, "-s", lastdevice, "reboot"); } System.out.println(); System.out.println("FINISH :)"); } catch (SAXException e) { System.out.println("Error parsing list: " + e); } catch (Throwable e) { e.printStackTrace(); } }
From source file:com.jwm123.loggly.reporter.AppLauncher.java
public static void main(String args[]) throws Exception { try {//from w w w. j a v a2s . c om 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); } }
From source file:com.github.jcustenborder.kafka.connect.spooldir.SchemaGenerator.java
public static void main(String... args) throws Exception { ArgumentParser parser = ArgumentParsers.newArgumentParser("CsvSchemaGenerator").defaultHelp(true) .description("Generate a schema based on a file."); parser.addArgument("-t", "--type").required(true).choices("csv", "json") .help("The type of generator to use."); parser.addArgument("-c", "--config").type(File.class); parser.addArgument("-f", "--file").type(File.class).required(true) .help("The data file to generate the schema from."); parser.addArgument("-i", "--id").nargs("*").help("Field(s) to use as an identifier."); parser.addArgument("-o", "--output").type(File.class) .help("Output location to write the configuration to. Stdout is default."); Namespace ns = null;// w w w . ja v a2s . com try { ns = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } File inputFile = ns.get("file"); List<String> ids = ns.getList("id"); if (null == ids) { ids = ImmutableList.of(); } Map<String, Object> settings = new LinkedHashMap<>(); File inputPropertiesFile = ns.get("config"); if (null != inputPropertiesFile) { Properties inputProperties = new Properties(); try (FileInputStream inputStream = new FileInputStream(inputPropertiesFile)) { inputProperties.load(inputStream); } for (String s : inputProperties.stringPropertyNames()) { Object v = inputProperties.getProperty(s); settings.put(s, v); } } final SchemaGenerator generator; final String type = ns.getString("type"); if ("csv".equalsIgnoreCase(type)) { generator = new CsvSchemaGenerator(settings); } else if ("json".equalsIgnoreCase(type)) { generator = new JsonSchemaGenerator(settings); } else { throw new UnsupportedOperationException( String.format("'%s' is not a supported schema generator type", type)); } Map.Entry<Schema, Schema> kvp = generator.generate(inputFile, ids); Properties properties = new Properties(); properties.putAll(settings); properties.setProperty(SpoolDirSourceConnectorConfig.KEY_SCHEMA_CONF, ObjectMapperFactory.INSTANCE.writeValueAsString(kvp.getKey())); properties.setProperty(SpoolDirSourceConnectorConfig.VALUE_SCHEMA_CONF, ObjectMapperFactory.INSTANCE.writeValueAsString(kvp.getValue())); String output = ns.getString("output"); final String comment = "Configuration was dynamically generated. Please verify before submitting."; if (Strings.isNullOrEmpty(output)) { properties.store(System.out, comment); } else { try (FileOutputStream outputStream = new FileOutputStream(output)) { properties.store(outputStream, comment); } } }
From source file:com.game.ui.views.MapPanel.java
public static void main(String[] args) throws IOException { MapInformation map = new MapInformation(); try {/* w ww . jav a 2 s . c o m*/ map = GameUtils.fetchParticularMapData(Configuration.PATH_FOR_MAP, "Test1"); Player player = new Player(); player.setType("Barbarian"); player.setMovement(1); int user = 0; LinkedHashMap<Integer, Integer> userLocation = new LinkedHashMap<>(); TreeMap<Integer, TileInformation> tileInfo = map.getPathMap(); for (Map.Entry<Integer, TileInformation> entry : tileInfo.entrySet()) { if (entry.getValue().isStartTile()) { userLocation.put(user, entry.getValue().getLocation()); entry.getValue().setPlayer(player); user++; } } map.setUserLocation(userLocation); } catch (Exception ex) { Logger.getLogger(MapPanel.class.getName()).log(Level.SEVERE, null, ex); } new MapPanel(map); }
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 w w. j a v a 2s .c o 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:TweetAttributes.java
public static void main(String[] args) throws IOException, ParseException, JSONException { int k = Integer.parseInt(args[0]); String inputFile = args[1];/* w ww .j a v a 2 s . c om*/ String initialSeedsFile = args[2]; String outputFile = args[3]; KMeansJaccard kmj = new KMeansJaccard(k); kmj.makeTweetObjects(inputFile); List<TweetAttributes> centroidPoints = kmj.getInitialCentroids(initialSeedsFile); Map<Long, List<Double>> distanceMap = new LinkedHashMap<>(); List<TweetAttributes> tweets = kmj.getTweetList(); buildDistanceMap(centroidPoints, tweets, kmj, distanceMap); for (Long i : distanceMap.keySet()) { kmj.assignClusterToTweet(i, distanceMap.get(i)); } List<TweetAttributes> tweetCopy = tweets; List<TweetAttributes> centroidCopy = centroidPoints; double cost = calculateCost(tweets, centroidPoints, kmj); Map<Integer, List<TweetAttributes>> tweetClusterMapping = getTweetCLusterMapping(tweets); for (Integer i : tweetClusterMapping.keySet()) { List<TweetAttributes> ta = tweetClusterMapping.get(i); for (TweetAttributes tweet : ta) { centroidPoints.remove(i - 1); centroidPoints.add(i - 1, tweet); distanceMap.clear(); buildDistanceMap(centroidPoints, tweets, kmj, distanceMap); for (Long id : distanceMap.keySet()) { kmj.assignClusterToTweet(id, distanceMap.get(id)); } double newCost = calculateCost(tweets, centroidPoints, kmj); if (newCost < cost) { cost = newCost; tweetCopy = kmj.getTweetList(); centroidCopy = kmj.getCentroidList(); } } } double sse = calculateSSE(tweetCopy, centroidCopy, kmj); System.out.println("COST: " + cost + " " + "SSE:" + sse); writeOutputToFile(tweetCopy, outputFile); }
From source file:TestBufferStreamGenomicsDBImporter.java
/** * Sample driver code for testing Java VariantContext write API for GenomicsDB * The code shows two ways of using the API * (a) Iterator<VariantContext>// w w w. j a va2 s . c o m * (b) Directly adding VariantContext objects * If "-iterators" is passed as the second argument, method (a) is used. */ public static void main(final String[] args) throws IOException, GenomicsDBException, ParseException { if (args.length < 2) { System.err.println("For loading: [-iterators] <loader.json> " + "<stream_name_to_file.json> [bufferCapacity rank lbRowIdx ubRowIdx useMultiChromosomeIterator]"); System.exit(-1); } int argsLoaderFileIdx = 0; if (args[0].equals("-iterators")) argsLoaderFileIdx = 1; //Buffer capacity long bufferCapacity = (args.length >= argsLoaderFileIdx + 3) ? Integer.parseInt(args[argsLoaderFileIdx + 2]) : 1024; //Specify rank (or partition idx) of this process int rank = (args.length >= argsLoaderFileIdx + 4) ? Integer.parseInt(args[argsLoaderFileIdx + 3]) : 0; //Specify smallest row idx from which to start loading. // This is useful for incremental loading into existing array long lbRowIdx = (args.length >= argsLoaderFileIdx + 5) ? Long.parseLong(args[argsLoaderFileIdx + 4]) : 0; //Specify largest row idx up to which loading should be performed - for completeness long ubRowIdx = (args.length >= argsLoaderFileIdx + 6) ? Long.parseLong(args[argsLoaderFileIdx + 5]) : Long.MAX_VALUE - 1; //Boolean to use MultipleChromosomeIterator boolean useMultiChromosomeIterator = (args.length >= argsLoaderFileIdx + 7) ? Boolean.parseBoolean(args[argsLoaderFileIdx + 6]) : false; //<loader.json> first arg String loaderJSONFile = args[argsLoaderFileIdx]; GenomicsDBImporter loader = new GenomicsDBImporter(loaderJSONFile, rank, lbRowIdx, ubRowIdx); //<stream_name_to_file.json> - useful for the driver only //JSON file that contains "stream_name": "vcf_file_path" entries FileReader mappingReader = new FileReader(args[argsLoaderFileIdx + 1]); JSONParser parser = new JSONParser(); LinkedHashMap streamNameToFileName = (LinkedHashMap) parser.parse(mappingReader, new LinkedHashFactory()); ArrayList<VCFFileStreamInfo> streamInfoVec = new ArrayList<VCFFileStreamInfo>(); long rowIdx = 0; for (Object currObj : streamNameToFileName.entrySet()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) currObj; VCFFileStreamInfo currInfo = new VCFFileStreamInfo(entry.getValue(), loaderJSONFile, rank, useMultiChromosomeIterator); /** The following 2 lines are not mandatory - use initializeSampleInfoMapFromHeader() * iff you know for sure that sample names in the VCF header are globally unique * across all streams/files. If not, you have 2 options: * (a) specify your own mapping from sample index in the header to SampleInfo object * (unique_name, rowIdx) OR * (b) specify the mapping in the callset_mapping_file (JSON) and pass null to * addSortedVariantContextIterator() */ LinkedHashMap<Integer, GenomicsDBImporter.SampleInfo> sampleIndexToInfo = new LinkedHashMap<Integer, GenomicsDBImporter.SampleInfo>(); rowIdx = GenomicsDBImporter.initializeSampleInfoMapFromHeader(sampleIndexToInfo, currInfo.mVCFHeader, rowIdx); int streamIdx = -1; if (args[0].equals("-iterators")) streamIdx = loader.addSortedVariantContextIterator(entry.getKey(), currInfo.mVCFHeader, currInfo.mIterator, bufferCapacity, VariantContextWriterBuilder.OutputType.BCF_STREAM, sampleIndexToInfo); //pass sorted VC iterators else //use buffers - VCs will be provided by caller streamIdx = loader.addBufferStream(entry.getKey(), currInfo.mVCFHeader, bufferCapacity, VariantContextWriterBuilder.OutputType.BCF_STREAM, sampleIndexToInfo); currInfo.mStreamIdx = streamIdx; streamInfoVec.add(currInfo); } if (args[0].equals("-iterators")) { //Much simpler interface if using Iterator<VariantContext> loader.importBatch(); assert loader.isDone(); } else { //Must be called after all iterators/streams added - no more iterators/streams // can be added once this function is called loader.setupGenomicsDBImporter(); //Counts and tracks buffer streams for which new data must be supplied //Initialized to all the buffer streams int numExhaustedBufferStreams = streamInfoVec.size(); int[] exhaustedBufferStreamIdxs = new int[numExhaustedBufferStreams]; for (int i = 0; i < numExhaustedBufferStreams; ++i) exhaustedBufferStreamIdxs[i] = i; while (!loader.isDone()) { //Add data for streams that were exhausted in the previous round for (int i = 0; i < numExhaustedBufferStreams; ++i) { VCFFileStreamInfo currInfo = streamInfoVec.get(exhaustedBufferStreamIdxs[i]); boolean added = true; while (added && (currInfo.mIterator.hasNext() || currInfo.mNextVC != null)) { if (currInfo.mNextVC != null) added = loader.add(currInfo.mNextVC, currInfo.mStreamIdx); if (added) if (currInfo.mIterator.hasNext()) currInfo.mNextVC = currInfo.mIterator.next(); else currInfo.mNextVC = null; } } loader.importBatch(); numExhaustedBufferStreams = (int) loader.getNumExhaustedBufferStreams(); for (int i = 0; i < numExhaustedBufferStreams; ++i) exhaustedBufferStreamIdxs[i] = loader.getExhaustedBufferStreamIndex(i); } } }
From source file:com.maxl.java.aips2sqlite.Aips2Sqlite.java
public static void main(String[] args) { Options options = new Options(); addOption(options, "help", "print this message", false, false); addOption(options, "version", "print the version information and exit", false, false); addOption(options, "quiet", "be extra quiet", false, false); addOption(options, "verbose", "be extra verbose", false, false); addOption(options, "nodown", "no download, parse only", false, false); addOption(options, "lang", "use given language", true, false); addOption(options, "alpha", "only include titles which start with option value", true, false); addOption(options, "regnr", "only include medications which start with option value", true, false); addOption(options, "owner", "only include medications owned by option value", true, false); addOption(options, "pseudo", "adds pseudo expert infos to db", false, false); addOption(options, "inter", "adds drug interactions to db", false, false); addOption(options, "pinfo", "generate patient info htmls", false, false); addOption(options, "xml", "generate xml file", false, false); addOption(options, "gln", "generate csv file with Swiss gln codes", false, false); addOption(options, "shop", "generate encrypted files for shopping cart", false, false); addOption(options, "onlyshop", "skip generation of sqlite database", false, false); addOption(options, "zurrose", "generate only zur Rose database", false, false); addOption(options, "desitin", "generate encrypted files for Desitin", false, false); addOption(options, "onlydesitin", "skip generation of sqlite database", false, false); addOption(options, "zip", "generate zipped big files (sqlite or xml)", false, false); addOption(options, "reports", "generates various reports", false, false); addOption(options, "indications", "generates indications section keywords report", false, false); addOption(options, "plain", "does not update the package section", false, false); addOption(options, "stats", "generates statistics for given user", true, false); // Parse command line options commandLineParse(options, args);//from w w w . j a v a 2 s. c o m // Generates statistics if (!CmlOptions.STATS.isEmpty()) { System.out.println("processing " + CmlOptions.STATS + " stats"); String user = CmlOptions.STATS; CalcStats cs = new CalcStats(user); cs.processIbsaData(); } // Download all files and save them in appropriate directories // XML + XSD -> ./xml, XLS -> ./xls if (CmlOptions.DOWNLOAD_ALL) { System.out.println(""); allDown(); } // Generate only zur Rose DB if (CmlOptions.ZUR_ROSE_DB == true) { FileOps.encryptCsvToDir("access.ami", "", Constants.DIR_ZURROSE, "access_rose.ami", Constants.DIR_OUTPUT, 0, 4, null); DispoParse dp = new DispoParse(); dp.process("csv"); } System.out.println(""); // Pointer to product map, extraction order = insertion order Map<String, Product> map_products = new LinkedHashMap<String, Product>(); boolean no_db = false; // Generate encrypted files for shopping cart (ibsa) if (CmlOptions.SHOPPING_CART == true || CmlOptions.ONLY_SHOPPING_CART == true) { ShoppingCartIbsa sc_ibsa = new ShoppingCartIbsa(map_products); sc_ibsa.listFiles(Constants.DIR_IBSA); Map<String, String> map_pharma_groups = sc_ibsa.readPharmacyGroups(); sc_ibsa.processConditionsFiles(Constants.DIR_IBSA); sc_ibsa.encryptConditionsToDir(Constants.DIR_OUTPUT, "ibsa_conditions"); FileOps.encryptCsvToDir("customer_glns", "targeting_glns", Constants.DIR_IBSA, "ibsa_glns", Constants.DIR_OUTPUT, 0, 5, map_pharma_groups); FileOps.encryptCsvToDir("access.ami", "", Constants.DIR_IBSA, "access.ami", Constants.DIR_OUTPUT, 0, 4, null); FileOps.encryptFileToDir("authors.ami", Constants.DIR_CRYPTO); // Same file for all customization if (CmlOptions.ONLY_SHOPPING_CART) no_db = true; } // Generate encrypted files for shopping cart (desitin) if (CmlOptions.DESITIN_DB == true || CmlOptions.ONLY_DESITIN_DB == true) { ShoppingCartDesitin sc_desitin = new ShoppingCartDesitin(map_products); sc_desitin.listFiles(Constants.DIR_DESITIN); sc_desitin.processConditionFile(Constants.DIR_DESITIN); sc_desitin.encryptConditionsToDir(Constants.DIR_OUTPUT, "desitin_conditions"); FileOps.encryptCsvToDir("access.ami", "", Constants.DIR_DESITIN, "desitin_access.ami", Constants.DIR_OUTPUT, 0, 4, null); FileOps.encryptFileToDir("authors.ami", Constants.DIR_CRYPTO); // Same file for all customization if (CmlOptions.ONLY_DESITIN_DB == true) no_db = true; } // Generate a csv file with all the GLN codes pertinent information if (CmlOptions.GLN_CODES == true) { GlnCodes glns = new GlnCodes(); glns.generateCsvFile(); } if (!CmlOptions.DB_LANGUAGE.isEmpty() && CmlOptions.ZUR_ROSE_DB == false && no_db == false) { // Extract drug interactions information if (CmlOptions.ADD_INTERACTIONS == true) { Interactions inter = new Interactions(CmlOptions.DB_LANGUAGE); // Generate in various data exchange files inter.generateDataExchangeFiles(); } if (CmlOptions.ONLY_SHOPPING_CART == false && CmlOptions.ONLY_DESITIN_DB == false) { if (CmlOptions.SHOW_LOGS) { System.out.println(""); System.out.println("- Generating sqlite database... "); } long startTime = System.currentTimeMillis(); // Generates SQLite database - function should return the number of entries generateSQLiteDB(map_products); if (CmlOptions.SHOW_LOGS) { long stopTime = System.currentTimeMillis(); System.out .println("- Generated sqlite database in " + (stopTime - startTime) / 1000.0f + " sec"); } } } System.exit(0); }
From source file:cz.hobrasoft.pdfmu.Main.java
/** * The main entry point of PDFMU// w w w. ja va 2 s . c o m * * @param args the command line arguments */ public static void main(String[] args) { int exitStatus = 0; // Default: 0 (normal termination) // Create a map of operations Map<String, Operation> operations = new LinkedHashMap<>(); operations.put("inspect", OperationInspect.getInstance()); operations.put("update-version", OperationVersionSet.getInstance()); operations.put("update-properties", OperationMetadataSet.getInstance()); operations.put("attach", OperationAttach.getInstance()); operations.put("sign", OperationSignatureAdd.getInstance()); // Create a command line argument parser ArgumentParser parser = createFullParser(operations); // Parse command line arguments Namespace namespace = null; try { // If help is requested, // `parseArgs` prints help message and throws `ArgumentParserException` // (so `namespace` stays null). // If insufficient or invalid `args` are given, // `parseArgs` throws `ArgumentParserException`. namespace = parser.parseArgs(args); } catch (HelpScreenException e) { parser.handleError(e); // Do nothing } catch (UnrecognizedCommandException e) { exitStatus = PARSER_UNRECOGNIZED_COMMAND.getCode(); parser.handleError(e); // Print the error in human-readable format } catch (UnrecognizedArgumentException e) { exitStatus = PARSER_UNRECOGNIZED_ARGUMENT.getCode(); parser.handleError(e); // Print the error in human-readable format } catch (ArgumentParserException ape) { OperationException oe = apeToOe(ape); exitStatus = oe.getCode(); // We could also write `oe` as a JSON document, // but we do not know whether JSON output was requested, // so we use the text output (default). parser.handleError(ape); // Print the error in human-readable format } if (namespace == null) { System.exit(exitStatus); } assert exitStatus == 0; // Handle command line arguments WritingMapper wm = null; // Extract operation name String operationName = namespace.getString("operation"); assert operationName != null; // The argument "operation" is a sub-command, thus it is required // Select the operation from `operations` assert operations.containsKey(operationName); // Only supported operation names are allowed Operation operation = operations.get(operationName); assert operation != null; // Choose the output format String outputFormat = namespace.getString("output_format"); switch (outputFormat) { case "json": // Disable loggers disableLoggers(); // Initialize the JSON serializer wm = new WritingMapper(); operation.setWritingMapper(wm); // Configure the operation break; case "text": // Initialize the text output TextOutput to = new TextOutput(System.err); // Bind to `System.err` operation.setTextOutput(to); // Configure the operation break; default: assert false; // The option has limited choices } // Execute the operation try { operation.execute(namespace); } catch (OperationException ex) { exitStatus = ex.getCode(); // Log the exception logger.severe(ex.getLocalizedMessage()); Throwable cause = ex.getCause(); if (cause != null && cause.getMessage() != null) { logger.severe(cause.getLocalizedMessage()); } if (wm != null) { // JSON output is enabled ex.writeInWritingMapper(wm); } } System.exit(exitStatus); }
From source file:Main.java
public static <K, V> LinkedHashMap<K, V> createLinkedHashMap() { return new LinkedHashMap(); }