List of usage examples for com.google.common.collect Multimap containsKey
boolean containsKey(@Nullable Object key);
From source file:com.moz.fiji.hive.utils.DataRequestOptimizer.java
/** * This method propogates the configuration of a family in a FijiDataRequest by replacing * it with a page of fully qualified columns with the same configuration. * * @param fijiDataRequest to use as a base. * @param qualifiersPage a page of fully qualified columns to replace families in the original * data request with. * @return A new data request with the appropriate families replaced with the page of fully * qualified columns.//from w ww .j av a 2 s. c om */ public static FijiDataRequest expandFamilyWithPagedQualifiers(FijiDataRequest fijiDataRequest, Collection<FijiColumnName> qualifiersPage) { // Organize the page of column names by family. Multimap<String, FijiColumnName> familyToQualifiersMap = ArrayListMultimap.create(); for (FijiColumnName fijiColumnName : qualifiersPage) { familyToQualifiersMap.put(fijiColumnName.getFamily(), fijiColumnName); } // Build a new data request FijiDataRequestBuilder qualifierRequestBuilder = FijiDataRequest.builder(); for (Column column : fijiDataRequest.getColumns()) { FijiColumnName fijiColumnName = column.getColumnName(); if (fijiColumnName.isFullyQualified() || !familyToQualifiersMap.containsKey(fijiColumnName.getFamily())) { // If the column is fully qualified or it's not in qualifiersPage add this column as is. qualifierRequestBuilder.newColumnsDef(column); } else { // Iterate through the paged qualifiers and add for (FijiColumnName columnName : familyToQualifiersMap.get(fijiColumnName.getFamily())) { qualifierRequestBuilder.newColumnsDef().withFilter(column.getFilter()) .withPageSize(column.getPageSize()).withMaxVersions(column.getMaxVersions()) .add(columnName.getFamily(), columnName.getQualifier()); } } } return qualifierRequestBuilder.build(); }
From source file:eu.interedition.collatex.util.ParallelSegmentationApparatus.java
public static void generate(VariantGraphRanking ranking, GeneratorCallback callback) { callback.start();//from w w w .j a v a 2s.c o m final Set<Witness> allWitnesses = ranking.witnesses(); for (Iterator<Map.Entry<Integer, Collection<VariantGraph.Vertex>>> rowIt = ranking.getByRank().asMap() .entrySet().iterator(); rowIt.hasNext();) { final Map.Entry<Integer, Collection<VariantGraph.Vertex>> row = rowIt.next(); final int rank = row.getKey(); final Collection<VariantGraph.Vertex> vertices = row.getValue(); if (vertices.size() == 1 && Iterables.getOnlyElement(vertices).tokens().isEmpty()) { // skip start and end vertex continue; } // spreading vertices with same rank according to their registered transpositions final Multimap<Integer, VariantGraph.Vertex> verticesByTranspositionRank = HashMultimap.create(); for (VariantGraph.Vertex v : vertices) { int transpositionRank = 0; for (VariantGraph.Transposition transposition : v.transpositions()) { for (VariantGraph.Vertex tv : transposition) { transpositionRank += (ranking.apply(tv).intValue() - rank); } } verticesByTranspositionRank.put(transpositionRank, v); } // render segments for (Iterator<Integer> transpositionRankIt = Ordering.natural() .immutableSortedCopy(verticesByTranspositionRank.keySet()).iterator(); transpositionRankIt .hasNext();) { final Multimap<Witness, Token> tokensByWitness = HashMultimap.create(); for (VariantGraph.Vertex v : verticesByTranspositionRank.get(transpositionRankIt.next())) { for (Token token : v.tokens()) { tokensByWitness.put(token.getWitness(), token); } } final SortedMap<Witness, Iterable<Token>> cellContents = Maps.newTreeMap(Witness.SIGIL_COMPARATOR); for (Witness witness : allWitnesses) { cellContents.put(witness, tokensByWitness.containsKey(witness) ? Iterables.unmodifiableIterable(tokensByWitness.get(witness)) : Collections.<Token>emptySet()); } callback.segment(cellContents); } } callback.end(); }
From source file:net.sourcedestination.sai.comparison.matching.MatchingGenerator.java
@SuppressWarnings("unchecked") public static MatchingGenerator createCompleteMatchingGenerator(final FeatureSetCompatibilityChecker fscc, final GraphMatchingHeuristic h) { return (g1, g2) -> { final Multimap<Integer, Integer> possibilities = getNodeMatchingPossibilities(fscc, g1, g2); //put node ID's in an array to insure they remain in the same order List<Integer> nodeIDsTemp = Lists.newArrayList(); g1.getNodeIDs().forEach(n1 -> { if (possibilities.containsKey(n1)) nodeIDsTemp.add(n1);/*from ww w .j av a 2 s.c o m*/ }); final Integer[] nodeIDs = nodeIDsTemp.toArray(new Integer[nodeIDsTemp.size()]); //create an iterator for the possible complete mappings Iterator<GraphMatching> i = new Iterator<GraphMatching>() { private int[] currentMap = new int[nodeIDs.length]; private GraphMatching nextMatching = nextMatching(); @Override public boolean hasNext() { return nextMatching != null; } @Override public GraphMatching next() { if (nextMatching == null) throw new IllegalStateException("no more matchings left"); GraphMatching currentMatching = nextMatching; nextMatching = nextMatching(); return currentMatching; } public GraphMatching nextMatching() { BiMap<Integer, Integer> nodeMap = null; while (nodeMap == null && currentMap != null) { nodeMap = HashBiMap.create(); //create map object for (int i = 0; i < nodeIDs.length; i++) { int skip = currentMap[i]; // it is assumed the following iterator is deterministic Iterator<Integer> ii = possibilities.get(nodeIDs[i]).iterator(); while (skip > 0) { skip--; ii.next(); } int mapToNode = ii.next(); if (nodeMap.containsValue(mapToNode)) { //don't map two g1 nodes to the same g2 node //nodeMap = null; //break; continue; } nodeMap.put(nodeIDs[i], mapToNode); } //increment to next map: boolean incremented = false; for (int i = 0; i < currentMap.length; i++) { if (currentMap[i] < possibilities.get(nodeIDs[i]).size() - 1) { currentMap[i]++; incremented = true; break; } currentMap[i] = 0; } if (!incremented) currentMap = null; } if (nodeMap == null) return null; return induceEdgeMatching(createBasicNodeMatching(g1, g2, nodeMap), fscc); } }; Iterable<GraphMatching> iterable = () -> i; Stream<GraphMatching> s = StreamSupport.stream(iterable.spliterator(), false); // TODO: determine why there is a syntax error without the reference below // h extends Function<GraphMatching,Double>, but isn't recognized as such // this is also corrected with a cast, but this is shorter return argmax(h::apply, s); }; }
From source file:grakn.core.graql.gremlin.RelationTypeInference.java
private static Multimap<Variable, Variable> getRelationRolePlayerMap(Set<Fragment> allFragments, Multimap<Variable, Type> instanceVarTypeMap) { // get all relation vars and its role player vars Multimap<Variable, Variable> relationRolePlayerMap = HashMultimap.create(); allFragments.stream().filter(OutRolePlayerFragment.class::isInstance) .forEach(fragment -> relationRolePlayerMap.put(fragment.start(), fragment.end())); Multimap<Variable, Variable> inferrableRelationsRolePlayerMap = HashMultimap.create(); allFragments.stream().filter(OutRolePlayerFragment.class::isInstance) .filter(fragment -> !instanceVarTypeMap.containsKey(fragment.start())) // filter out known rel types .forEach(fragment -> {//from w w w . j ava 2s .c om Variable relation = fragment.start(); // the relation should have at least 2 known role players so we can infer something useful int numRolePlayersHaveType = 0; for (Variable rolePlayer : relationRolePlayerMap.get(relation)) { if (instanceVarTypeMap.containsKey(rolePlayer)) { numRolePlayersHaveType++; } } if (numRolePlayersHaveType >= 2) { inferrableRelationsRolePlayerMap.put(relation, fragment.end()); } }); return inferrableRelationsRolePlayerMap; }
From source file:com.redprairie.moca.components.mocatest.ClusterTestComponent.java
/** * Gets a result set of node|roles which is each * node URL to a comma separated list of roles * @return/* w w w. jav a2 s .c o m*/ */ public static MocaResults getNodesToRoles() { SimpleResults res = new SimpleResults(); res.addColumn("node", MocaType.STRING); res.addColumn("roles", MocaType.STRING); ClusterRoleManager manager = ServerUtils.globalAttribute(ClusterRoleManager.class); MocaClusterAdministration admin = (MocaClusterAdministration) ServerUtils.globalContext() .getAttribute(MocaClusterAdministration.class.getName()); if (manager != null && admin != null) { Multimap<Node, RoleDefinition> multiMap = manager.getClusterRoles(); Map<Node, InstanceUrl> urls = admin.getKnownNodes(); _logger.info("Cluster URLs: " + urls.entrySet()); _logger.info("Node to Roles: " + multiMap.asMap().entrySet()); Multimap<InstanceUrl, RoleDefinition> urlRoleMap = HashMultimap.create(); for (Entry<Node, Collection<RoleDefinition>> entry : multiMap.asMap().entrySet()) { InstanceUrl url = urls.get(entry.getKey()); // TODO: trying to handle that cluster URLs is wrong and doesn't contain the entry if (url == null) { url = new InstanceUrl(false, entry.getKey().toString(), 0); } urlRoleMap.putAll(url, entry.getValue()); } for (Entry<Node, InstanceUrl> url : urls.entrySet()) { if (!urlRoleMap.containsKey(url.getValue())) { urlRoleMap.put(url.getValue(), EMPTY_ROLE); } } // Sort by the node url Map<InstanceUrl, Collection<RoleDefinition>> sortedMap = new TreeMap<InstanceUrl, Collection<RoleDefinition>>( new Comparator<InstanceUrl>() { @Override public int compare(InstanceUrl o1, InstanceUrl o2) { return o1.toString().compareTo(o2.toString()); } }); sortedMap.putAll(urlRoleMap.asMap()); for (Map.Entry<InstanceUrl, Collection<RoleDefinition>> entry : sortedMap.entrySet()) { res.addRow(); res.setStringValue("node", entry.getKey().toString()); res.setStringValue("roles", Joiner.on(',').join(entry.getValue())); } } else { _logger.info("Cluster manager and/or admin not set"); } return res; }
From source file:com.eucalyptus.vm.NetworkGroupsMetadata.java
private static String generateTopology() { StringBuilder buf = new StringBuilder(); Multimap<String, String> networks = ArrayListMultimap.create(); Multimap<String, String> rules = ArrayListMultimap.create(); final EntityTransaction db = Entities.get(VmInstance.class); try {//from www. j a v a 2 s.c om Predicate<VmInstance> filter = VmStateSet.TORNDOWN.not(); for (VmInstance vm : VmInstances.list(filter)) { try { for (NetworkGroup ruleGroup : vm.getNetworkGroups()) { try { ruleGroup = Entities.merge(ruleGroup); networks.put(ruleGroup.getClusterNetworkName(), vm.getPrivateAddress()); if (!rules.containsKey(ruleGroup.getNaturalId())) { for (NetworkRule netRule : ruleGroup.getNetworkRules()) { try { String rule = String.format("-P %s -%s %d%s%d ", netRule.getProtocol(), (NetworkRule.Protocol.icmp.equals(netRule.getProtocol()) ? "t" : "p"), netRule.getLowPort(), (NetworkRule.Protocol.icmp.equals(netRule.getProtocol()) ? ":" : "-"), netRule.getHighPort()); for (NetworkPeer peer : netRule.getNetworkPeers()) { Account groupAccount = Accounts .lookupAccountById(peer.getUserQueryKey()); String groupId = NetworkGroups .lookup(AccountFullName.getInstance(groupAccount), peer.getGroupName()) .getNaturalId(); String ruleString = String.format("%s -o %s -u %s", rule, groupId, groupAccount.getAccountNumber()); if (!rules.get(ruleGroup.getClusterNetworkName()) .contains(ruleString)) { rules.put(ruleGroup.getClusterNetworkName(), ruleString); } } for (String cidr : netRule.getIpRanges()) { String ruleString = String.format("%s -s %s", rule, cidr); if (!rules.get(ruleGroup.getClusterNetworkName()) .contains(ruleString)) { rules.put(ruleGroup.getClusterNetworkName(), ruleString); } } } catch (Exception ex) { LOG.error(ex, ex); } } } } catch (Exception ex) { LOG.error(ex, ex); } } } catch (Exception ex) { LOG.error(ex, ex); } } buf.append(rulesToString(rules)); buf.append(groupsToString(networks)); } catch (Exception ex) { LOG.error(ex, ex); } finally { db.rollback(); } return buf.toString(); }
From source file:org.jboss.weld.util.Interceptors.java
/** * Merge class-level interceptor bindings with interceptor bindings inherited from interceptor bindings and stereotypes. *//* www .j a v a 2s . com*/ public static Multimap<Class<? extends Annotation>, Annotation> mergeBeanInterceptorBindings( BeanManagerImpl beanManager, AnnotatedType<?> clazz, Collection<Annotation> classBindingAnnotations, Collection<Annotation> inheritedBindingAnnotations) { Multimap<Class<? extends Annotation>, Annotation> mergedBeanBindings = HashMultimap.create(); Set<Annotation> acceptedInheritedBindings = new HashSet<Annotation>(); // add all class-level interceptor bindings (these have precedence) for (Annotation bindingAnnotation : classBindingAnnotations) { mergedBeanBindings.put(bindingAnnotation.annotationType(), bindingAnnotation); } // add inherited interceptor bindings for (Annotation bindingAnnotation : inheritedBindingAnnotations) { Class<? extends Annotation> bindingAnnotationType = bindingAnnotation.annotationType(); // replace the previous interceptor binding with current binding if (!mergedBeanBindings.containsKey(bindingAnnotationType)) { acceptedInheritedBindings.add(bindingAnnotation); } } for (Annotation bindingAnnotation : acceptedInheritedBindings) { mergedBeanBindings.put(bindingAnnotation.annotationType(), bindingAnnotation); } return mergedBeanBindings; }
From source file:org.jboss.weld.annotated.enhanced.jlr.EnhancedAnnotatedTypeImpl.java
private static boolean isOverridden(EnhancedAnnotatedMethod<?, ?> method, Multimap<MethodSignature, Package> seenMethods) { if (method.isPrivate()) { return false; } else if (method.isPackagePrivate() && seenMethods.containsKey(method.getSignature())) { return seenMethods.get(method.getSignature()).contains(method.getPackage()); } else {/*ww w .java 2 s . c o m*/ return seenMethods.containsKey(method.getSignature()); } }
From source file:org.eclipse.incquery.tooling.core.project.ProjectGenerationHelper.java
/** * @param extensionMap/*from ww w .j a va 2 s.com*/ * @param extension * @param id * @return */ private static boolean isExtensionInMap(Multimap<String, IPluginExtension> extensionMap, final IPluginExtension extension, String id) { boolean extensionToCreateFound = false; if (extensionMap.containsKey(id)) { extensionToCreateFound = Iterables.any(extensionMap.get(id), new Predicate<IPluginExtension>() { @Override public boolean apply(IPluginExtension ex) { return ex.getPoint().equals(extension.getPoint()); } }); } return extensionToCreateFound; }
From source file:com.google.devtools.build.lib.analysis.config.ConfigurationResolver.java
/** * Variation of {@link Multimap#put} that triggers an exception if a value already exists. *///from w w w.j a v a2 s.c o m @VisibleForTesting public static <K, V> void putOnlyEntry(Multimap<K, V> map, K key, V value) { // Performance note: while "Verify.verify(!map.containsKey(key, value), String.format(...)))" // is simpler code, profiling shows a substantial performance penalty to that approach // (~10% extra analysis phase time on a simple cc_binary). Most of that is from the cost of // evaluating value.toString() on every call. This approach essentially eliminates the overhead. if (map.containsKey(key)) { throw new VerifyException( String.format("couldn't insert %s: map already has key %s", value.toString(), key.toString())); } map.put(key, value); }