List of usage examples for com.google.common.collect Maps newLinkedHashMap
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap()
From source file:cc.kave.histories.DoSomethingApp.java
public static void main(String[] args) throws SQLException, IOException { try (SqliteHistoryDatabase database = new SqliteHistoryDatabase("histories")) { Set<OUHistory> histories = database.getHistories(); System.out.printf("%d histories found...", histories.size()); int changes = 0; int removals = 0; int additions = 0; Map<ITypeName, Integer> counts = Maps.newLinkedHashMap(); int i = 1; for (OUHistory h : histories) { OUSnapshot start = h.getStart(); // System.out.println(start); Usage u = GsonUtil.deserialize(start.getUsageJson(), Query.class); OUSnapshot end = h.getEnd(); // System.out.println(end); Usage v = GsonUtil.deserialize(end.getUsageJson(), Query.class); int calls1 = u.getReceiverCallsites().hashCode(); int calls2 = v.getReceiverCallsites().hashCode(); if (calls1 != calls2) { int delta = v.getReceiverCallsites().size() - u.getReceiverCallsites().size(); if (delta < 0) { removals++;/* w w w .j a v a 2 s .com*/ System.out.println("## method(s) removed ##############################"); } if (delta == 0) { changes++; System.out.println("## method(s) changed ##############################"); } if (delta > 0) { additions++; Integer count = counts.get(u.getType()); if (count == null) { counts.put(u.getType(), 1); } else { counts.put(u.getType(), count + 1); } System.out.printf("## %d - delta: %d ##############################\n", i++, delta); System.out.println(u); System.out.println("-----------------------"); System.out.println(v); } } } // Map<ITypeName, Integer> sortedCounts = // MapSorter.sortByCount(counts); // for (ITypeName type : sortedCounts.keySet()) { // System.out.printf("%5dx %s\n", sortedCounts.get(type), type); // } System.out.printf("%d removals, %d changes, %d additions (%d total)", removals, changes, additions, (removals + changes + additions)); } }
From source file:com.textocat.textokit.segmentation.GenerateBasicAggregateDescriptor.java
/** * @param args/*from ww w. j a v a 2 s. c o m*/ * @throws ResourceInitializationException */ public static void main(String[] args) throws UIMAException, IOException, SAXException { Map<String, MetaDataObject> aeDescriptions = Maps.newLinkedHashMap(); aeDescriptions.put("tokenizer", TokenizerAPI.getAEImport()); aeDescriptions.put("sentenceSplitter", SentenceSplitterAPI.getAEImport()); String outputPath = "desc/basic-aggregate.xml"; AnalysisEngineDescription desc = PipelineDescriptorUtils.createAggregateDescription(aeDescriptions); FileOutputStream out = FileUtils.openOutputStream(new File(outputPath)); try { desc.toXML(out); } finally { IOUtils.closeQuietly(out); } }
From source file:com.textocat.textokit.postagger.GenerateAggregateDescriptorForMorphAnnotator.java
public static void main(String[] args) throws UIMAException, IOException, SAXException { if (args.length != 1) { System.err.println("Usage: <output-path>"); System.exit(1);/*from w ww . j a v a 2s .c o m*/ } String outputPath = args[0]; // NOTE! A file URL for generated SerializedDictionaryResource description assumes // that the required dictionary file is within one of UIMA datapath folders. // So users of the generated aggregate descriptor should setup 'uima.datapath' properly . ExternalResourceDescription morphDictDesc = getMorphDictionaryAPI() .getResourceDescriptionWithPredictorEnabled(); Map<String, MetaDataObject> aeDescriptions = Maps.newLinkedHashMap(); aeDescriptions.put("tokenizer", TokenizerAPI.getAEImport()); // aeDescriptions.put("sentence-splitter", SentenceSplitterAPI.getAEImport()); // aeDescriptions.put("morph-analyzer", MorphologyAnnotator.createDescription(DefaultAnnotationAdapter.class, PosTaggerAPI.getTypeSystemDescription())); // aeDescriptions.put("tag-assembler", TagAssembler.createDescription()); AnalysisEngineDescription desc = PipelineDescriptorUtils.createAggregateDescription(aeDescriptions); // bind the dictionary resource bindExternalResource(desc, "morph-analyzer/" + MorphologyAnnotator.RESOURCE_KEY_DICTIONARY, morphDictDesc); bindExternalResource(desc, "tag-assembler/" + GramModelBasedTagMapper.RESOURCE_GRAM_MODEL, morphDictDesc); FileOutputStream out = FileUtils.openOutputStream(new File(outputPath)); try { desc.toXML(out); } finally { IOUtils.closeQuietly(out); } }
From source file:org.prebake.client.Main.java
public static void main(String... argv) { long t0 = System.nanoTime(); final Logger logger = Logger.getLogger(Main.class.getName()); CommandLineArgs args = new CommandLineArgs(argv); if (!CommandLineArgs.setUpLogger(args, logger)) { System.out.println(USAGE); System.exit(0);/* ww w.ja va 2s . co m*/ } if (!args.getFlags().isEmpty()) { System.err.println(USAGE); if (!args.getFlags().isEmpty()) { System.err.println("Unused flags : " + Joiner.on(' ').join(args.getFlags())); } System.exit(-1); } Bake bake = new Bake(logger) { @Override protected Connection connect(int port) throws IOException { final Socket socket = new Socket(InetAddress.getLoopbackAddress(), port); return new Connection() { public InputStream getInputStream() throws IOException { return new FilterInputStream(socket.getInputStream()) { @Override public void close() throws IOException { socket.shutdownInput(); } }; } public OutputStream getOutputStream() throws IOException { return new FilterOutputStream(socket.getOutputStream()) { @Override public void close() throws IOException { socket.shutdownOutput(); } }; } public void close() throws IOException { socket.close(); } }; } @Override protected void launch(Path prebakeDir, List<String> argv) throws IOException { Map<String, String> env = Maps.newLinkedHashMap(); boolean doneWithPreJavaFlags = false; List<String> cmd = Lists.newArrayListWithCapacity(argv.size() + 1); cmd.add("java"); for (String arg : argv) { if (!doneWithPreJavaFlags && arg.startsWith("-Denv.")) { // See PATH environment variable channeling in CommandLineArgs int eq = arg.indexOf('='); env.put(arg.substring(6, eq).toUpperCase(Locale.ROOT), arg.substring(eq + 1)); } else { cmd.add(arg); } if (!arg.startsWith("-")) { doneWithPreJavaFlags = true; } } File logFile = new File(prebakeDir.resolve(FileNames.LOGS).resolve("main.log").toUri()); logger.log(Level.INFO, "Execing {0} with env {1} > {2}", new Object[] { cmd, env, logFile }); ProcessBuilder pb = new ProcessBuilder(cmd.toArray(new String[0])); pb.environment().putAll(env); pb.redirectOutput(logFile).redirectErrorStream(true).start(); } @Override protected void sleep(int millis) throws InterruptedException { Thread.sleep(millis); } }; Path cwd = FileSystems.getDefault().getPath(System.getProperty("user.dir")); int result; try { Path prebakeDir = bake.findPrebakeDir(cwd); Collection<String> argVals = args.getValues(); Commands commands = bake.decodeArgv(prebakeDir.getParent(), argVals.toArray(new String[argVals.size()])); result = bake.issueCommands(prebakeDir, commands, System.out); } catch (IOException ex) { ex.printStackTrace(); result = -1; } logger.log(Level.INFO, "Build took {0}.", prettyTime(System.nanoTime() - t0)); System.exit(result); }
From source file:com.metamx.TsvToJson.java
public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); String[] fields = args[0].split(","); File inFile = new File(args[1]); File outFile = new File(args[2]); FieldHandler[] handlers = new FieldHandler[fields.length]; for (int i = 0; i < fields.length; i++) { String field = fields[i]; String[] fieldParts = field.split(":"); String fieldName = fieldParts[0]; if (fieldParts.length < 2 || "string".equalsIgnoreCase(fieldParts[1])) { handlers[i] = new StringField(fieldName); } else if ("number".equalsIgnoreCase(fieldParts[1])) { handlers[i] = new NumberField(fieldName); } else if ("ISO8601".equals(fieldParts[1])) { handlers[i] = new IsoToNumberField(fieldName); } else {/*from w ww . ja v a2s .c o m*/ throw new IAE("Unknown type[%s]", fieldParts[1]); } } BufferedReader in = null; BufferedWriter out = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(inFile), Charsets.UTF_8)); out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), Charsets.UTF_8)); String line = null; int count = 0; long currTime = System.currentTimeMillis(); long startTime = currTime; while ((line = in.readLine()) != null) { if (count % 1000000 == 0) { long nowTime = System.currentTimeMillis(); System.out.printf("Processed [%,d] lines in %,d millis. Incremental time %,d millis.%n", count, nowTime - startTime, nowTime - currTime); currTime = nowTime; } ++count; String[] splits = line.split("\t"); if (splits.length == 30) { continue; } if (splits.length != handlers.length) { throw new IAE("splits.length[%d] != handlers.length[%d]; line[%s]", splits.length, handlers.length, line); } Map<String, Object> jsonMap = Maps.newLinkedHashMap(); for (int i = 0; i < handlers.length; ++i) { jsonMap.put(handlers[i].getFieldName(), handlers[i].process(splits[i])); } final String str = mapper.writeValueAsString(jsonMap); out.write(str); out.write("\n"); } System.out.printf("Completed %,d lines in %,d millis.%n", count, System.currentTimeMillis() - startTime); out.flush(); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } }
From source file:com.lyndir.masterpassword.CLI.java
public static void main(final String[] args) throws IOException { // Read information from the environment. char[] masterPassword; String siteName = null, context = null; String userName = System.getenv(MPConstant.env_userName); String siteTypeName = ifNotNullElse(System.getenv(MPConstant.env_siteType), ""); MPSiteType siteType = siteTypeName.isEmpty() ? MPSiteType.GeneratedLong : MPSiteType.forOption(siteTypeName); MPSiteVariant variant = MPSiteVariant.Password; String siteCounterName = ifNotNullElse(System.getenv(MPConstant.env_siteCounter), ""); UnsignedInteger siteCounter = siteCounterName.isEmpty() ? UnsignedInteger.valueOf(1) : UnsignedInteger.valueOf(siteCounterName); // Parse information from option arguments. boolean userNameArg = false, typeArg = false, counterArg = false, variantArg = false, contextArg = false; for (final String arg : Arrays.asList(args)) // Full Name if ("-u".equals(arg) || "--username".equals(arg)) userNameArg = true;/*from www .j a v a 2s. c o m*/ else if (userNameArg) { userName = arg; userNameArg = false; } // Type else if ("-t".equals(arg) || "--type".equals(arg)) typeArg = true; else if (typeArg) { siteType = MPSiteType.forOption(arg); typeArg = false; } // Counter else if ("-c".equals(arg) || "--counter".equals(arg)) counterArg = true; else if (counterArg) { siteCounter = UnsignedInteger.valueOf(arg); counterArg = false; } // Variant else if ("-v".equals(arg) || "--variant".equals(arg)) variantArg = true; else if (variantArg) { variant = MPSiteVariant.forOption(arg); variantArg = false; } // Context else if ("-C".equals(arg) || "--context".equals(arg)) contextArg = true; else if (contextArg) { context = arg; contextArg = false; } // Help else if ("-h".equals(arg) || "--help".equals(arg)) { System.out.println(); System.out.format("Usage: mpw [-u name] [-t type] [-c counter] site\n\n"); System.out.format(" -u name Specify the full name of the user.\n"); System.out.format(" Defaults to %s in env.\n\n", MPConstant.env_userName); System.out.format(" -t type Specify the password's template.\n"); System.out.format( " Defaults to %s in env or 'long' for password, 'name' for login.\n", MPConstant.env_siteType); int optionsLength = 0; Map<String, MPSiteType> typeMap = Maps.newLinkedHashMap(); for (MPSiteType elementType : MPSiteType.values()) { String options = Joiner.on(", ").join(elementType.getOptions()); typeMap.put(options, elementType); optionsLength = Math.max(optionsLength, options.length()); } for (Map.Entry<String, MPSiteType> entry : typeMap.entrySet()) { String infoString = strf(" -v %" + optionsLength + "s | ", entry.getKey()); String infoNewline = "\n" + StringUtils.repeat(" ", infoString.length() - 3) + " | "; infoString += entry.getValue().getDescription().replaceAll("\n", infoNewline); System.out.println(infoString); } System.out.println(); System.out.format(" -c counter The value of the counter.\n"); System.out.format(" Defaults to %s in env or '1'.\n\n", MPConstant.env_siteCounter); System.out.format(" -v variant The kind of content to generate.\n"); System.out.format(" Defaults to 'password'.\n"); optionsLength = 0; Map<String, MPSiteVariant> variantMap = Maps.newLinkedHashMap(); for (MPSiteVariant elementVariant : MPSiteVariant.values()) { String options = Joiner.on(", ").join(elementVariant.getOptions()); variantMap.put(options, elementVariant); optionsLength = Math.max(optionsLength, options.length()); } for (Map.Entry<String, MPSiteVariant> entry : variantMap.entrySet()) { String infoString = strf(" -v %" + optionsLength + "s | ", entry.getKey()); String infoNewline = "\n" + StringUtils.repeat(" ", infoString.length() - 3) + " | "; infoString += entry.getValue().getDescription().replaceAll("\n", infoNewline); System.out.println(infoString); } System.out.println(); System.out.format(" -C context A variant-specific context.\n"); System.out.format(" Defaults to empty.\n"); for (Map.Entry<String, MPSiteVariant> entry : variantMap.entrySet()) { String infoString = strf(" -v %" + optionsLength + "s | ", entry.getKey()); String infoNewline = "\n" + StringUtils.repeat(" ", infoString.length() - 3) + " | "; infoString += entry.getValue().getContextDescription().replaceAll("\n", infoNewline); System.out.println(infoString); } System.out.println(); System.out.format(" ENVIRONMENT\n\n"); System.out.format(" MP_USERNAME | The full name of the user.\n"); System.out.format(" MP_SITETYPE | The default password template.\n"); System.out.format(" MP_SITECOUNTER | The default counter value.\n\n"); return; } else siteName = arg; // Read missing information from the console. Console console = System.console(); try (InputStreamReader inReader = new InputStreamReader(System.in)) { LineReader lineReader = new LineReader(inReader); if (siteName == null) { System.err.format("Site name: "); siteName = lineReader.readLine(); } if (userName == null) { System.err.format("User's name: "); userName = lineReader.readLine(); } if (console != null) masterPassword = console.readPassword("%s's master password: ", userName); else { System.err.format("%s's master password: ", userName); masterPassword = lineReader.readLine().toCharArray(); } } // Encode and write out the site password. System.out.println(MasterKey.create(userName, masterPassword).encode(siteName, siteType, siteCounter, variant, context)); }
From source file:com.mobogenie.framework.spring.LogGenerator.java
public static Map<String, String> next(HttpServletRequest request) { Map<String, String> map = Maps.newLinkedHashMap(); map.put("uri", request.getRequestURI()); map.put("timestamp", System.currentTimeMillis() + ""); StringBuilder sb = new StringBuilder(); Map<String, String> paramMap = request.getParameterMap(); Set<String> keys = paramMap.keySet(); for (String paramName : keys) { String paramValue = request.getParameter(paramName).trim(); if (!Strings.isNullOrEmpty(paramValue)) { sb.append(paramName + ":" + paramValue + ","); }/*from www .j a va 2 s . c o m*/ } String valueString = sb.toString(); valueString = valueString.replaceAll(",$", ""); map.put("params", "[" + valueString + "]"); map.put("clientId", IpAddressUtil.getIpAddr(request)); HttpSession session = request.getSession(false); if (session != null) { map.put("session", session.getId()); } return map; }
From source file:org.carrot2.util.attribute.constraint.ValueHintMappingUtils.java
/** * Returns a bidirectional mapping between valid attribute values (keys) and their * enum constants (values). Keys in the returned map are ordered according to enum's * declaration.//from w ww .jav a2 s. c o m */ public static Map<String, Enum<?>> getValidValuesMap(Class<? extends Enum<?>> clazz) { final LinkedHashMap<String, Enum<?>> valueSet = Maps.newLinkedHashMap(); for (Enum<?> e : clazz.getEnumConstants()) { String value = e.name(); if (e instanceof IValueHintMapping) { value = ((IValueHintMapping) e).getAttributeValue(); } valueSet.put(value, e); } return valueSet; }
From source file:nl.knaw.huygens.tei.XmlUtils.java
public static Map<String, String> newAttributes() { // use LinkedHashMap to preserve attribute order return Maps.newLinkedHashMap(); }
From source file:org.auraframework.throwable.quickfix.CreateBaseComponentDefQuickFix.java
protected static Map<String, Object> createMap(DefDescriptor<?> descriptor) { Map<String, Object> ret = Maps.newLinkedHashMap(); ret.put("descriptor", String.format("%s:%s", descriptor.getNamespace(), descriptor.getName())); return ret;//from w w w . j av a 2 s . c om }