Example usage for com.google.common.collect Multimap put

List of usage examples for com.google.common.collect Multimap put

Introduction

In this page you can find the example usage for com.google.common.collect Multimap put.

Prototype

boolean put(@Nullable K key, @Nullable V value);

Source Link

Document

Stores a key-value pair in this multimap.

Usage

From source file:org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer.java

private static void registerTopLevelFqName(@NotNull Multimap<FqName, JetElement> topLevelFqNames,
        @NotNull JetNamedDeclaration declaration, @NotNull DeclarationDescriptor descriptor) {
    if (DescriptorUtils.isTopLevelDeclaration(descriptor)) {
        FqName fqName = declaration.getFqName();
        if (fqName != null) {
            topLevelFqNames.put(fqName, declaration);
        }//ww w  . j a  v  a 2s. c o  m
    }
}

From source file:com.google.cloud.dataflow.sdk.options.PipelineOptionsReflector.java

/**
 * Extract pipeline options and their respective getter methods from a series of
 * {@link Method methods}. A single pipeline option may appear in many methods.
 *
 * @return A mapping of option name to the input methods which declare it.
 *///from ww w .ja  va 2  s.  co m
static Multimap<String, Method> getPropertyNamesToGetters(Iterable<Method> methods) {
    Multimap<String, Method> propertyNamesToGetters = HashMultimap.create();
    for (Method method : methods) {
        String methodName = method.getName();
        if ((!methodName.startsWith("get") && !methodName.startsWith("is"))
                || method.getParameterTypes().length != 0 || method.getReturnType() == void.class) {
            continue;
        }
        String propertyName = Introspector
                .decapitalize(methodName.startsWith("is") ? methodName.substring(2) : methodName.substring(3));
        propertyNamesToGetters.put(propertyName, method);
    }
    return propertyNamesToGetters;
}

From source file:org.apache.calcite.rel.metadata.RelMdCollation.java

/** Helper method to determine a {@link Project}'s collation. */
public static List<RelCollation> project(RelMetadataQuery mq, RelNode input, List<? extends RexNode> projects) {
    final SortedSet<RelCollation> collations = new TreeSet<>();
    final List<RelCollation> inputCollations = mq.collations(input);
    if (inputCollations == null || inputCollations.isEmpty()) {
        return ImmutableList.of();
    }/* ww  w .  ja  v  a 2 s  .  c  o m*/
    final Multimap<Integer, Integer> targets = LinkedListMultimap.create();
    final Map<Integer, SqlMonotonicity> targetsWithMonotonicity = new HashMap<>();
    for (Ord<RexNode> project : Ord.zip(projects)) {
        if (project.e instanceof RexInputRef) {
            targets.put(((RexInputRef) project.e).getIndex(), project.i);
        } else if (project.e instanceof RexCall) {
            final RexCall call = (RexCall) project.e;
            final RexCallBinding binding = RexCallBinding.create(input.getCluster().getTypeFactory(), call,
                    inputCollations);
            targetsWithMonotonicity.put(project.i, call.getOperator().getMonotonicity(binding));
        }
    }
    final List<RelFieldCollation> fieldCollations = new ArrayList<>();
    loop: for (RelCollation ic : inputCollations) {
        if (ic.getFieldCollations().isEmpty()) {
            continue;
        }
        fieldCollations.clear();
        for (RelFieldCollation ifc : ic.getFieldCollations()) {
            final Collection<Integer> integers = targets.get(ifc.getFieldIndex());
            if (integers.isEmpty()) {
                continue loop; // cannot do this collation
            }
            fieldCollations.add(ifc.copy(integers.iterator().next()));
        }
        assert !fieldCollations.isEmpty();
        collations.add(RelCollations.of(fieldCollations));
    }

    final List<RelFieldCollation> fieldCollationsForRexCalls = new ArrayList<>();
    for (Map.Entry<Integer, SqlMonotonicity> entry : targetsWithMonotonicity.entrySet()) {
        final SqlMonotonicity value = entry.getValue();
        switch (value) {
        case NOT_MONOTONIC:
        case CONSTANT:
            break;
        default:
            fieldCollationsForRexCalls
                    .add(new RelFieldCollation(entry.getKey(), RelFieldCollation.Direction.of(value)));
            break;
        }
    }

    if (!fieldCollationsForRexCalls.isEmpty()) {
        collations.add(RelCollations.of(fieldCollationsForRexCalls));
    }

    return ImmutableList.copyOf(collations);
}

From source file:ai.grakn.graql.internal.query.QueryOperationExecutor.java

private static Multimap<VarProperty, Var> equivalentProperties(Set<VarAndProperty> properties) {
    Multimap<VarProperty, Var> equivalentProperties = HashMultimap.create();

    for (VarAndProperty varAndProperty : properties) {
        if (varAndProperty.uniquelyIdentifiesConcept()) {
            equivalentProperties.put(varAndProperty.property(), varAndProperty.var());
        }//from  w  w w. ja  va2  s .  co  m
    }

    return equivalentProperties;
}

From source file:org.sonar.java.resolve.LeastUpperBound.java

/**
 * For any element G of MEC that is a generic type, let the "relevant" parameterizations of G, Relevant(G), be:
 * Relevant(G) = { V | 1  i  k: V in ST(Ui) and V = G<...> }
 *
 * @param minimalErasedCandidates MEC/*from   ww w  .j a v a 2  s  .c o m*/
 * @param supertypes
 * @return the set of known parameterizations for each generic type G of MEC 
 */
private static Multimap<Type, Type> relevantParameterizations(List<Type> minimalErasedCandidates,
        List<Set<Type>> supertypes) {
    Multimap<Type, Type> result = Multimaps.newSetMultimap(new HashMap<>(), LinkedHashSet::new);
    for (Set<Type> supertypesSet : supertypes) {
        for (Type supertype : supertypesSet) {
            Type erasedSupertype = supertype.erasure();
            if (minimalErasedCandidates.contains(erasedSupertype)) {
                result.put(erasedSupertype, supertype);
            }
        }
    }
    return result;
}

From source file:eu.interedition.collatex.medite.Matches.java

public static Matches between(VariantGraph.Vertex[][] vertices, SuffixTree<Token> suffixTree,
        Function<SortedSet<VertexMatch.WithTokenIndex>, Integer> matchEvaluator) {

    final Multimap<Integer, MatchThreadElement> matchThreads = HashMultimap.create();
    for (int rank = 0; rank < vertices.length; rank++) {
        for (VariantGraph.Vertex vertex : vertices[rank]) {
            final MatchThreadElement matchThreadElement = new MatchThreadElement(suffixTree).advance(vertex,
                    rank);/*from  ww  w  .jav  a  2 s. c  o m*/
            if (matchThreadElement != null) {
                matchThreads.put(rank, matchThreadElement);
            }
        }
        for (MatchThreadElement matchThreadElement : matchThreads.get(rank - 1)) {
            for (VariantGraph.Vertex vertex : vertices[rank]) {
                final MatchThreadElement advanced = matchThreadElement.advance(vertex, rank);
                if (advanced != null) {
                    matchThreads.put(rank, advanced);
                }
            }
        }
    }

    final Matches matches = new Matches(matchThreads.size());
    for (MatchThreadElement matchThreadElement : matchThreads.values()) {
        final List<SortedSet<VertexMatch.WithTokenIndex>> threadPhrases = Lists.newArrayList();
        boolean firstElement = true;
        for (MatchThreadElement threadElement : matchThreadElement.thread()) {
            final SuffixTree<Token>.EquivalenceClass equivalenceClass = threadElement.cursor.matchedClass();
            for (int mc = 0; mc < equivalenceClass.length; mc++) {
                final int tokenCandidate = equivalenceClass.members[mc];
                if (firstElement) {
                    final SortedSet<VertexMatch.WithTokenIndex> phrase = new TreeSet<VertexMatch.WithTokenIndex>();
                    phrase.add(new VertexMatch.WithTokenIndex(threadElement.vertex, threadElement.vertexRank,
                            tokenCandidate));
                    threadPhrases.add(phrase);
                } else {
                    for (SortedSet<VertexMatch.WithTokenIndex> phrase : threadPhrases) {
                        if ((phrase.last().token + 1) == tokenCandidate) {
                            phrase.add(new VertexMatch.WithTokenIndex(threadElement.vertex,
                                    threadElement.vertexRank, tokenCandidate));
                        }
                    }
                }
            }
            firstElement = false;
        }
        matches.addAll(threadPhrases);
    }
    Collections.sort(matches, maximalUniqueMatchOrdering(matchEvaluator));

    return matches;
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLKeyValueServices.java

public static void waitForSchemaVersionsToCoalesce(String encapsulatingOperationDescription,
        CQLKeyValueService kvs) {//  www . j  a  v a 2s  .c om
    PreparedStatement peerInfoQuery = kvs.getPreparedStatement(CassandraConstants.NO_TABLE,
            "select peer, schema_version from system.peers;", kvs.session);
    peerInfoQuery.setConsistencyLevel(ConsistencyLevel.ALL);

    Multimap<UUID, InetAddress> peerInfo = ArrayListMultimap.create();
    long start = System.currentTimeMillis();
    long sleepTime = 100;
    do {
        peerInfo.clear();
        for (Row row : kvs.session.execute(peerInfoQuery.bind()).all()) {
            peerInfo.put(row.getUUID("schema_version"), row.getInet("peer"));
        }

        if (peerInfo.keySet().size() <= 1) { // full schema agreement
            return;
        }
        sleepTime = Math.min(sleepTime * 2, 5000);
    } while (System.currentTimeMillis() < start + CassandraConstants.SECONDS_WAIT_FOR_VERSIONS * 1000);

    StringBuilder sb = new StringBuilder();
    sb.append(String.format(
            "Cassandra cluster cannot come to agreement on schema versions, during operation: %s.",
            encapsulatingOperationDescription));

    for (Entry<UUID, Collection<InetAddress>> versionToPeer : peerInfo.asMap().entrySet()) {
        sb.append(String.format("\nAt schema version %s:", versionToPeer.getKey()));
        for (InetAddress peer : versionToPeer.getValue()) {
            sb.append(String.format("\n\tNode: %s", peer));
        }
    }
    sb.append("\nFind the nodes above that diverge from the majority schema "
            + "(or have schema 'UNKNOWN', which likely means they are down/unresponsive) "
            + "and examine their logs to determine the issue. Fixing the underlying issue and restarting Cassandra "
            + "should resolve the problem. You can quick-check this with 'nodetool describecluster'.");
    throw new IllegalStateException(sb.toString());
}

From source file:com.google.gerrit.httpd.restapi.ParameterParser.java

static void splitQueryString(String queryString, Multimap<String, String> config,
        Multimap<String, String> params) {
    if (!Strings.isNullOrEmpty(queryString)) {
        for (String kvPair : Splitter.on('&').split(queryString)) {
            Iterator<String> i = Splitter.on('=').limit(2).split(kvPair).iterator();
            String key = Url.decode(i.next());
            String val = i.hasNext() ? Url.decode(i.next()) : "";
            if (RESERVED_KEYS.contains(key)) {
                config.put(key, val);
            } else {
                params.put(key, val);
            }/*from   w  w w . j  av a2  s.c o  m*/
        }
    }
}

From source file:grakn.core.graql.executor.WriteExecutor.java

static WriteExecutor create(TransactionOLTP transaction, ImmutableSet<Writer> writers) {
    transaction.checkMutationAllowed();//from  ww  w  .  j  a v  a2  s  .c o m
    /*
    We build several many-to-many relations, indicated by a `Multimap<X, Y>`. These are used to represent
    the dependencies between properties and variables.
            
    `propertyToItsRequiredVars.containsEntry(prop, var)` indicates that the property `prop` cannot be inserted until
    the concept represented by the variable `var` is created.
            
    For example, the property `$x isa $y` depends on the existence of the concept represented by `$y`.
     */
    Multimap<Writer, Variable> executorToRequiredVars = HashMultimap.create();

    for (Writer writer : writers) {
        for (Variable requiredVar : writer.requiredVars()) {
            executorToRequiredVars.put(writer, requiredVar);
        }
    }

    /*
    `varToItsProducerProperties.containsEntry(var, prop)` indicates that the concept represented by the variable `var`
    cannot be created until the property `prop` is inserted.
            
    For example, the concept represented by `$x` will not exist before the property `$x isa $y` is inserted.
     */
    Multimap<Variable, Writer> varToProducingWriter = HashMultimap.create();

    for (Writer executor : writers) {
        for (Variable producedVar : executor.producedVars()) {
            varToProducingWriter.put(producedVar, executor);
        }
    }

    /*
    Equivalent vars are variables that must represent the same concept as another var.
            
         $X label movie, sub entity;
         $Y label movie;
         $z isa $Y;
            
    In this example, `$z isa $Y` must not be inserted before `$Y` is. However, `$Y` does not have enough
    information to insert on its own. It also needs a super type!
            
    We know `$Y` must represent the same concept as `$X`, because they both share the same label property.
    Therefore, we can share their dependencies, such that:
            
        varToItsProducerProperties.containsEntry($X, prop) <=> varToItsProducerProperties.containsEntry($Y, prop)
            
    Therefore:
            
        varToItsProducerProperties.containsEntry($X, `$X sub entity`) => varToItsProducerProperties.containsEntry($Y, `$X sub entity`)
            
    Now we know that `$Y` depends on `$X sub entity` as well as `$X label movie`, which is enough information to
    insert the type!
     */

    Partition<Variable> equivalentVars = Partition.singletons(Collections.emptyList());

    propertyToEquivalentVars(writers).asMap().values().forEach(vars -> {
        // These vars must refer to the same concept, so share their dependencies
        Collection<Writer> producingWriters = vars.stream()
                .flatMap(var -> varToProducingWriter.get(var).stream()).collect(toList());

        Variable first = vars.iterator().next();

        vars.forEach(var -> {
            varToProducingWriter.replaceValues(var, producingWriters);
            equivalentVars.merge(first, var);
        });
    });

    /*
    Together, `propertyToItsRequiredVars` and `varToItsProducerProperties` can be composed into a single many-to-many relation:
            
        propertyDependencies = propertyToItsRequiredVars  varToItsProducerProperties
            
    By doing so, we map directly between properties, skipping the vars. For example, if we previously had:
            
        propertyToItsRequiredVars.containsEntry(`$x isa $y`, `$y`);             // `$x isa $y` depends on `$y`
        varToItsProducerProperties.containsEntry(`$y`, `$y label movie`);       // `$y` depends on `$y label movie`
            
    Then it follows that:
            
        propertyDependencies.containsEntry(`$x isa $y`, `$y label movie`);      // `$x isa $y` depends on `$y label movie`
            
    The `propertyDependencies` relation contains all the information to decide what order to execute the properties.
     */
    Multimap<Writer, Writer> writerDependencies = writerDependencies(executorToRequiredVars,
            varToProducingWriter);

    return new WriteExecutor(transaction, writers, equivalentVars, writerDependencies);
}

From source file:net.minecraftforge.common.config.ConfigManager.java

public static void loadData(ASMDataTable data) {
    FMLLog.fine("Loading @Config anotation data");
    for (ASMData target : data.getAll(Config.class.getName())) {
        String modid = (String) target.getAnnotationInfo().get("modid");
        Multimap<Config.Type, ASMData> map = asm_data.get(modid);
        if (map == null) {
            map = ArrayListMultimap.create();
            asm_data.put(modid, map);//from   w  ww  .ja  v a 2s  .c om
        }

        EnumHolder tholder = (EnumHolder) target.getAnnotationInfo().get("type");
        Config.Type type = tholder == null ? Config.Type.INSTANCE : Config.Type.valueOf(tholder.getValue());

        map.put(type, target);
    }
}