List of usage examples for com.google.common.collect Multimap entries
Collection<Map.Entry<K, V>> entries();
From source file:grakn.core.graql.reasoner.atom.binary.RelationAtom.java
private <T extends Predicate> Multimap<Role, T> getRolePredicateMap(Class<T> type) { HashMultimap<Role, T> rolePredicateMap = HashMultimap.create(); HashMultimap<Variable, T> predicateMap = HashMultimap.create(); getPredicates(type).forEach(p -> p.getVarNames().forEach(v -> predicateMap.put(v, p))); Multimap<Role, Variable> roleMap = getRoleVarMap(); roleMap.entries().stream().filter(e -> predicateMap.containsKey(e.getValue())) .forEach(e -> rolePredicateMap.putAll(e.getKey(), predicateMap.get(e.getValue()))); return rolePredicateMap; }
From source file:uk.ac.ebi.apps.benchmark.ChemicalNameSearch.java
@Override public void process() { loadNames();/*from w ww . j a v a 2 s. c o m*/ if (getCommandLine().getOptionValues("s").length > 1) { testMultiple(); return; } final NameService<Identifier> service = (NameService<Identifier>) getNameService(get("service", "none")); if (!service.startup()) { LOGGER.error("Unable to start service"); } service.setMaxResults(100); Multimap<String, Identifier> results = ArrayListMultimap.create(); // doing the search long searchStart = System.currentTimeMillis(); for (String name : names) { Collection<? extends Identifier> hits = service.searchName(name, has("a")); results.putAll(name, hits); found += hits.isEmpty() ? 0 : 1; } long searchEnd = System.currentTimeMillis(); Long searchTime = (searchEnd - searchStart); Multimap<String, Set<String>> nameResults = ArrayListMultimap.create(); // resolving System.out.println("Transforming for performance test"); long resolveStart = System.currentTimeMillis(); for (Map.Entry<String, Identifier> e : results.entries()) { Identifier id = e.getValue(); nameResults.put(e.getKey(), new HashSet<String>(service.getNames(id))); } long resolveEnd = System.currentTimeMillis(); Long resolveTime = (resolveEnd - resolveStart); int trueFound = getRealScore(nameResults, new ChemicalFingerprintEncoder(), null); SummaryStatistics statistics = getHitIndices(nameResults, new ChemicalFingerprintEncoder()); String[] row = new String[] { get("service", "unknown"), searchTime.toString(), resolveTime.toString(), Integer.toString(found), Integer.toString(trueFound), Double.toString(statistics.getMax()), Double.toString(statistics.getMean()), Double.toString(statistics.getStandardDeviation()) }; System.out.println(Joiner.on("\t").join(row)); }
From source file:com.torodb.torod.db.backends.query.QueryEvaluator.java
@Nonnull private Map<Integer, DatabaseQuery> createDatabaseQueryByStructure(@Nullable QueryCriteria criteria, DSLContext dsl) {//from www.j a va2 s . c o m Map<Integer, DatabaseQuery> result; if (criteria == null) { BiMap<Integer, DocStructure> allStructures = colSchema.getStructuresCache().getAllStructures(); result = Maps.newHashMapWithExpectedSize(allStructures.size()); DatabaseQuery databaseQuery = SelectAllDatabaseQuery.getInstance(); for (Integer sid : colSchema.getStructuresCache().getAllStructures().keySet()) { result.put(sid, databaseQuery); } } else { Multimap<Integer, QueryCriteria> candidateStructures = QueryStructureFilter.filterStructures(colSchema, criteria); if (candidateStructures.isEmpty()) { result = Collections.emptyMap(); } else { result = Maps.newHashMapWithExpectedSize(candidateStructures.size()); for (Map.Entry<Integer, QueryCriteria> entry : candidateStructures.entries()) { Integer sid = entry.getKey(); DocStructure rootStructure = colSchema.getStructuresCache().getStructure(sid); DatabaseQuery databaseQuery = createDatabaseQuery(entry.getValue(), sid, rootStructure, dsl); if (!(databaseQuery instanceof FalseDatabaseQuery)) { result.put(sid, databaseQuery); } } } } return result; }
From source file:co.cask.cdap.client.AdapterClient.java
public String getLogs(Id.Adapter adapter, @Nullable Long start, @Nullable Long stop, @Nullable Boolean escape, @Nullable String filter) throws IOException, AdapterNotFoundException, UnauthorizedException { Multimap<String, String> queryParams = HashMultimap.create(); queryParams.put("adapterid", adapter.getId()); if (start != null) { queryParams.put("start", Long.toString(start)); }//from ww w.ja v a 2s . co m if (stop != null) { queryParams.put("stop", Long.toString(stop)); } if (escape != null) { queryParams.put("escape", Boolean.toString(escape)); } if (filter != null) { queryParams.put("filter", filter); } String queryString = Joiner.on("&").join(queryParams.entries()); AdapterDetail adapterDetail = get(adapter); ProgramId program = adapterDetail.getProgram(); // TODO: currently doesn't work for workflows since getting workflow logs is not implemented yet URL url = config.resolveNamespacedURLV3(adapter.getNamespace(), String.format("apps/%s/%s/%s/logs?%s", program.getApplication(), program.getType().getCategoryName(), program.getId(), queryString)); HttpResponse response = restClient.execute(HttpMethod.GET, url, config.getAccessToken(), HttpURLConnection.HTTP_NOT_FOUND); if (response.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { throw new AdapterNotFoundException(adapter); } return response.getResponseBodyAsString(); }
From source file:co.cask.cdap.data.tools.PFSUpgrader.java
private void upgradePartitionedFileSets() throws Exception { final DatasetInstanceMDS dsInstancesMDS; try {//from w w w . j a v a2 s . c o m dsInstancesMDS = new DatasetMetaTableUtil(dsFramework).getInstanceMetaTable(); } catch (Exception e) { LOG.error("Failed to access Datasets instances meta table."); throw e; } TransactionExecutor executor = executorFactory .createExecutor(ImmutableList.of((TransactionAware) dsInstancesMDS)); executor.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { MDSKey key = new MDSKey.Builder().add(DatasetInstanceMDS.INSTANCE_PREFIX).build(); Map<MDSKey, DatasetSpecification> dsSpecs = dsInstancesMDS.listKV(key, DatasetSpecification.class); // first, upgrade all the specifications, while keeping track of the tables that need migrating Multimap<Id.Namespace, DatasetSpecification> partitionDatasetsToMigrate = HashMultimap.create(); for (Map.Entry<MDSKey, DatasetSpecification> entry : dsSpecs.entrySet()) { DatasetSpecification dsSpec = entry.getValue(); if (!needsConverting(dsSpec)) { continue; } DatasetSpecification migratedSpec = recursivelyMigrateSpec(extractNamespace(entry.getKey()), dsSpec.getName(), dsSpec, partitionDatasetsToMigrate); dsInstancesMDS.write(entry.getKey(), migratedSpec); } // migrate the necessary tables LOG.info("Tables to migrate: {}", partitionDatasetsToMigrate); for (Map.Entry<Id.Namespace, DatasetSpecification> entry : partitionDatasetsToMigrate.entries()) { pfsTableMigrator.upgrade(entry.getKey(), entry.getValue()); } } }); }
From source file:com.tinspx.util.net.Headers.java
public Headers addAll(@NonNull Multimap<String, String> headers) { return addAll(headers.entries()); }
From source file:org.terasology.crafting.ui.workstation.StationAvailableRecipesWidget.java
private void appendCategory(Multimap<String, String> categoryRelationships, Map<String, Multimap<String, CraftingStationRecipe.CraftingStationResult>> categoryRecipesMap, String category, int level) { Multimap<String, CraftingStationRecipe.CraftingStationResult> directRecipes = categoryRecipesMap .get(category);/*w w w . j a va 2 s. c o m*/ Collection<String> childCategories = categoryRelationships.get(category); int count = 0; if (directRecipes != null) { count += directRecipes.size(); } count += childCategories.size(); boolean isOpen = openCategories.contains(category); RecipeCategoryWidget categoryWidget = new RecipeCategoryWidget(isOpen, 25 * level, getCategoryName(category), count, new CategoryToggleCallbackImpl(category)); layout.addWidget(categoryWidget); if (isOpen) { for (String childCategory : childCategories) { appendCategory(categoryRelationships, categoryRecipesMap, childCategory, level + 1); } if (directRecipes != null) { appendRecipes(level + 1, directRecipes.entries()); } } }
From source file:grakn.core.graql.reasoner.atom.binary.RelationAtom.java
private Multimap<Role, Type> getRoleTypeMap(boolean inferTypes) { ImmutableMultimap.Builder<Role, Type> builder = ImmutableMultimap.builder(); Multimap<Role, Variable> roleMap = getRoleVarMap(); SetMultimap<Variable, Type> varTypeMap = getParentQuery().getVarTypeMap(inferTypes); roleMap.entries().stream().sorted(Comparator.comparing(e -> e.getKey().label())) .flatMap(e -> varTypeMap.get(e.getValue()).stream().map(type -> new Pair<>(e.getKey(), type))) .sorted(Comparator.comparing(Pair::hashCode)).forEach(p -> builder.put(p.getKey(), p.getValue())); return builder.build(); }
From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLKeyValueService.java
@Override public void putWithTimestamps(String tableName, Multimap<Cell, Value> values) { try {//from w w w . j av a 2s . c o m putInternal(tableName, values.entries(), TransactionType.NONE); } catch (Throwable t) { throw Throwables.throwUncheckedException(t); } }
From source file:com.ning.metrics.collector.processing.db.DatabaseCounterStorage.java
/** * Insert the given counter data into the metrics buffer * @param dailyCounters Map of namespace to the set of counter events * observed in that namespace/*from w w w . ja va2 s .c o m*/ */ @Override public void bufferMetrics(final Multimap<String, CounterEventData> dailyCounters) { dbi.withHandle(new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { PreparedBatch batch = handle.prepareBatch("insert into metrics_buffer " + "(`namespace`,`metrics`,`timestamp`) values " + "(:namespace, :metrics, :timestamp)"); for (Entry<String, CounterEventData> entry : dailyCounters.entries()) { batch.bind("namespace", entry.getKey()) .bind("metrics", mapper.writeValueAsString(entry.getValue())) .bind("timestamp", DAILY_METRICS_DATE_FORMAT.print(entry.getValue().getCreatedTime())) .add(); } batch.execute(); return null; } }); }