Example usage for com.google.common.collect ImmutableMultimap copyOf

List of usage examples for com.google.common.collect ImmutableMultimap copyOf

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMultimap copyOf.

Prototype

@Beta
public static <K, V> ImmutableMultimap<K, V> copyOf(
        Iterable<? extends Entry<? extends K, ? extends V>> entries) 

Source Link

Document

Returns an immutable multimap containing the specified entries.

Usage

From source file:org.glowroot.agent.live.ClasspathCache.java

synchronized void updateCache() {
    Multimap<String, Location> newClassNameLocations = HashMultimap.create();
    for (ClassLoader loader : getKnownClassLoaders()) {
        updateCache(loader, newClassNameLocations);
    }/*w  w  w  . j a  v  a  2 s.c o  m*/
    updateCacheWithClasspathClasses(newClassNameLocations);
    updateCacheWithBootstrapClasses(newClassNameLocations);
    if (!newClassNameLocations.isEmpty()) {
        // multimap that sorts keys and de-dups values while maintains value ordering
        SetMultimap<String, Location> newMap = MultimapBuilder.treeKeys().linkedHashSetValues().build();
        newMap.putAll(classNameLocations);
        newMap.putAll(newClassNameLocations);
        classNameLocations = ImmutableMultimap.copyOf(newMap);
    }
}

From source file:org.lightjason.agentspeak.agent.IBaseAgent.java

@Override
public final Multimap<IPath, ILiteral> runningplans() {
    return ImmutableMultimap.copyOf(m_runningplans);
}

From source file:org.bitcoinj.protocols.channels.StoredPaymentChannelClientStates.java

/**
 * Get a copy of all {@link StoredClientChannel}s
 *//*  w w w  .  j a  v  a 2  s .  c o  m*/
public Multimap<Sha256Hash, StoredClientChannel> getChannelMap() {
    lock.lock();
    try {
        return ImmutableMultimap.copyOf(mapChannels);
    } finally {
        lock.unlock();
    }
}

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

private static QueryOperationExecutor create(Collection<VarPatternAdmin> patterns, GraknTx graph,
        ExecutionType executionType) {// w w w  .  ja  va 2  s .  co m
    ImmutableSet<VarAndProperty> properties = patterns.stream().flatMap(VarAndProperty::fromPattern)
            .collect(toImmutableSet());

    /*
    We build several many-to-many relations, indicated by a `Multimap<X, Y>`. These are used to represent
    the dependencies between properties and variables.
            
    `propDependencies.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<VarAndProperty, Var> propDependencies = HashMultimap.create();

    for (VarAndProperty property : properties) {
        for (Var requiredVar : property.executor(executionType).requiredVars()) {
            propDependencies.put(property, requiredVar);
        }
    }

    /*
    `varDependencies.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<Var, VarAndProperty> varDependencies = HashMultimap.create();

    for (VarAndProperty property : properties) {
        for (Var producedVar : property.executor(executionType).producedVars()) {
            varDependencies.put(producedVar, property);
        }
    }

    /*
    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:
            
        varDependencies.containsEntry($X, prop) <=> varDependencies.containsEntry($Y, prop)
            
    Therefore:
            
        varDependencies.containsEntry($X, `$X sub entity`) => varDependencies.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<Var> equivalentVars = Partition.singletons(Collections.emptyList());

    equivalentProperties(properties).asMap().values().forEach(vars -> {
        // These vars must refer to the same concept, so share their dependencies
        Collection<VarAndProperty> producers = vars.stream().flatMap(var -> varDependencies.get(var).stream())
                .collect(toList());

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

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

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

    return new QueryOperationExecutor(graph, properties, equivalentVars, ImmutableMultimap.copyOf(dependencies),
            executionType);
}

From source file:com.opengamma.integration.tool.portfolio.xml.TradePositionResolver.java

/**
 * Mark the resolved as resolved and perform the calculations required. After calling
 * this method, calls to the accessor methods are enabled and calls to
 * {@link #addToPosition(String, String)} will be disallowed.
 */// w  w  w. j a v a  2  s  .  co  m
public void resolve() {

    if (!_isResolved) {
        _isResolved = true;
        _positions = _positionBuilder.build();
        _invertedPositions = _positions.inverse();
        _orphanTrades = determineOrphanTrades();
        _duplicateTrades = ImmutableMultimap.copyOf(determineDuplicatedTrades());
        _unknownTrades = determineUnknownTrades();
    }
}

From source file:com.google.template.soy.passes.IndirectParamsCalculator.java

public IndirectParamsInfo calculateIndirectParams(TemplateMetadata template) {

    visitedCallSituations = Sets.newHashSet();
    indirectParams = Maps.newHashMap();/*  w w  w .  j ava 2  s. c  o m*/
    paramKeyToCalleesMultimap = HashMultimap.create();
    indirectParamTypes = LinkedHashMultimap.create();
    mayHaveIndirectParamsInExternalCalls = false;
    mayHaveIndirectParamsInExternalDelCalls = false;
    visit(template, new HashSet<>(), new HashSet<>());

    return new IndirectParamsInfo(ImmutableSortedMap.copyOf(indirectParams),
            ImmutableMultimap.copyOf(paramKeyToCalleesMultimap), ImmutableMultimap.copyOf(indirectParamTypes),
            mayHaveIndirectParamsInExternalCalls, mayHaveIndirectParamsInExternalDelCalls);
}

From source file:org.eclipse.viatra.transformation.evm.api.RuleEngine.java

/**
 * @return the immutable set of rules in the EVM
 *//*  w  w  w . j  a  v  a 2  s  .  c o m*/
public Multimap<RuleSpecification<?>, EventFilter<?>> getRuleSpecificationMultimap() {
    return ImmutableMultimap.copyOf(ruleBase.getRuleSpecificationMultimap());
}

From source file:io.prestosql.plugin.accumulo.index.ColumnCardinalityCache.java

/**
 * Gets the cardinality for each {@link AccumuloColumnConstraint}.
 * Given constraints are expected to be indexed! Who knows what would happen if they weren't!
 *
 * @param schema Schema name//from w  w w .  j  a v a2  s.  c  om
 * @param table Table name
 * @param auths Scan authorizations
 * @param idxConstraintRangePairs Mapping of all ranges for a given constraint
 * @param earlyReturnThreshold Smallest acceptable cardinality to return early while other tasks complete
 * @param pollingDuration Duration for polling the cardinality completion service
 * @return An immutable multimap of cardinality to column constraint, sorted by cardinality from smallest to largest
 * @throws TableNotFoundException If the metrics table does not exist
 * @throws ExecutionException If another error occurs; I really don't even know anymore.
 */
public Multimap<Long, AccumuloColumnConstraint> getCardinalities(String schema, String table,
        Authorizations auths, Multimap<AccumuloColumnConstraint, Range> idxConstraintRangePairs,
        long earlyReturnThreshold, Duration pollingDuration) {
    // Submit tasks to the executor to fetch column cardinality, adding it to the Guava cache if necessary
    CompletionService<Pair<Long, AccumuloColumnConstraint>> executor = new ExecutorCompletionService<>(
            executorService);
    idxConstraintRangePairs.asMap().forEach((key, value) -> executor.submit(() -> {
        long cardinality = getColumnCardinality(schema, table, auths, key.getFamily(), key.getQualifier(),
                value);
        LOG.debug("Cardinality for column %s is %s", key.getName(), cardinality);
        return Pair.of(cardinality, key);
    }));

    // Create a multi map sorted by cardinality
    ListMultimap<Long, AccumuloColumnConstraint> cardinalityToConstraints = MultimapBuilder.treeKeys()
            .arrayListValues().build();
    try {
        boolean earlyReturn = false;
        int numTasks = idxConstraintRangePairs.asMap().entrySet().size();
        do {
            // Sleep for the polling duration to allow concurrent tasks to run for this time
            Thread.sleep(pollingDuration.toMillis());

            // Poll each task, retrieving the result if it is done
            for (int i = 0; i < numTasks; ++i) {
                Future<Pair<Long, AccumuloColumnConstraint>> futureCardinality = executor.poll();
                if (futureCardinality != null && futureCardinality.isDone()) {
                    Pair<Long, AccumuloColumnConstraint> columnCardinality = futureCardinality.get();
                    cardinalityToConstraints.put(columnCardinality.getLeft(), columnCardinality.getRight());
                }
            }

            // If the smallest cardinality is present and below the threshold, set the earlyReturn flag
            Optional<Entry<Long, AccumuloColumnConstraint>> smallestCardinality = cardinalityToConstraints
                    .entries().stream().findFirst();
            if (smallestCardinality.isPresent()) {
                if (smallestCardinality.get().getKey() <= earlyReturnThreshold) {
                    LOG.info("Cardinality %s, is below threshold. Returning early while other tasks finish",
                            smallestCardinality);
                    earlyReturn = true;
                }
            }
        } while (!earlyReturn && cardinalityToConstraints.entries().size() < numTasks);
    } catch (ExecutionException | InterruptedException e) {
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throw new PrestoException(UNEXPECTED_ACCUMULO_ERROR, "Exception when getting cardinality", e);
    }

    // Create a copy of the cardinalities
    return ImmutableMultimap.copyOf(cardinalityToConstraints);
}

From source file:com.facebook.presto.accumulo.index.ColumnCardinalityCache.java

/**
 * Gets the cardinality for each {@link AccumuloColumnConstraint}.
 * Given constraints are expected to be indexed! Who knows what would happen if they weren't!
 *
 * @param schema Schema name/*from  w w  w  .  j  a  v a2 s . co  m*/
 * @param table Table name
 * @param auths Scan authorizations
 * @param idxConstraintRangePairs Mapping of all ranges for a given constraint
 * @param earlyReturnThreshold Smallest acceptable cardinality to return early while other tasks complete
 * @param pollingDuration Duration for polling the cardinality completion service
 * @return An immutable multimap of cardinality to column constraint, sorted by cardinality from smallest to largest
 * @throws TableNotFoundException If the metrics table does not exist
 * @throws ExecutionException If another error occurs; I really don't even know anymore.
 */
public Multimap<Long, AccumuloColumnConstraint> getCardinalities(String schema, String table,
        Authorizations auths, Multimap<AccumuloColumnConstraint, Range> idxConstraintRangePairs,
        long earlyReturnThreshold, Duration pollingDuration) throws ExecutionException, TableNotFoundException {
    // Submit tasks to the executor to fetch column cardinality, adding it to the Guava cache if necessary
    CompletionService<Pair<Long, AccumuloColumnConstraint>> executor = new ExecutorCompletionService<>(
            executorService);
    idxConstraintRangePairs.asMap().forEach((key, value) -> executor.submit(() -> {
        long cardinality = getColumnCardinality(schema, table, auths, key.getFamily(), key.getQualifier(),
                value);
        LOG.debug("Cardinality for column %s is %s", key.getName(), cardinality);
        return Pair.of(cardinality, key);
    }));

    // Create a multi map sorted by cardinality
    ListMultimap<Long, AccumuloColumnConstraint> cardinalityToConstraints = MultimapBuilder.treeKeys()
            .arrayListValues().build();
    try {
        boolean earlyReturn = false;
        int numTasks = idxConstraintRangePairs.asMap().entrySet().size();
        do {
            // Sleep for the polling duration to allow concurrent tasks to run for this time
            Thread.sleep(pollingDuration.toMillis());

            // Poll each task, retrieving the result if it is done
            for (int i = 0; i < numTasks; ++i) {
                Future<Pair<Long, AccumuloColumnConstraint>> futureCardinality = executor.poll();
                if (futureCardinality != null && futureCardinality.isDone()) {
                    Pair<Long, AccumuloColumnConstraint> columnCardinality = futureCardinality.get();
                    cardinalityToConstraints.put(columnCardinality.getLeft(), columnCardinality.getRight());
                }
            }

            // If the smallest cardinality is present and below the threshold, set the earlyReturn flag
            Optional<Entry<Long, AccumuloColumnConstraint>> smallestCardinality = cardinalityToConstraints
                    .entries().stream().findFirst();
            if (smallestCardinality.isPresent()) {
                if (smallestCardinality.get().getKey() <= earlyReturnThreshold) {
                    LOG.info("Cardinality %s, is below threshold. Returning early while other tasks finish",
                            smallestCardinality);
                    earlyReturn = true;
                }
            }
        } while (!earlyReturn && cardinalityToConstraints.entries().size() < numTasks);
    } catch (ExecutionException | InterruptedException e) {
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throw new PrestoException(UNEXPECTED_ACCUMULO_ERROR, "Exception when getting cardinality", e);
    }

    // Create a copy of the cardinalities
    return ImmutableMultimap.copyOf(cardinalityToConstraints);
}

From source file:org.sosy_lab.cpachecker.cpa.predicate.persistence.PredicateAbstractionsStorage.java

private void parseAbstractionTree() throws IOException, PredicateParsingFailedException {
    Multimap<Integer, Integer> resultTree = LinkedHashMultimap.create();
    Map<Integer, AbstractionNode> resultAbstractions = Maps.newTreeMap();
    Set<Integer> abstractionsWithParents = Sets.newTreeSet();

    String source = abstractionsFile.getName();
    try (BufferedReader reader = abstractionsFile.asCharSource(StandardCharsets.US_ASCII)
            .openBufferedStream()) {//from  ww  w  . ja  v a  2 s.co m

        // first, read first section with initial set of function definitions
        Pair<Integer, String> defParsingResult = PredicatePersistenceUtils.parseCommonDefinitions(reader,
                abstractionsFile.toString());
        int lineNo = defParsingResult.getFirst();
        String commonDefinitions = defParsingResult.getSecond();

        String currentLine;
        int currentAbstractionId = -1;
        Optional<Integer> currentLocationId = Optional.absent();
        Set<Integer> currentSuccessors = Sets.newTreeSet();

        AbstractionsParserState parserState = AbstractionsParserState.EXPECT_NODE_DECLARATION;
        while ((currentLine = reader.readLine()) != null) {
            lineNo++;
            currentLine = currentLine.trim();

            if (currentLine.isEmpty()) {
                // blank lines separates sections
                continue;
            }

            if (currentLine.startsWith("//")) {
                // comment
                continue;
            }

            if (parserState == AbstractionsParserState.EXPECT_NODE_DECLARATION) {
                // we expect a new section header
                if (!currentLine.endsWith(":")) {
                    throw new PredicateParsingFailedException(
                            currentLine + " is not a valid abstraction header", source, lineNo);
                }

                currentLine = currentLine.substring(0, currentLine.length() - 1).trim(); // strip off ":"
                if (currentLine.isEmpty()) {
                    throw new PredicateParsingFailedException("empty header is not allowed", source, lineNo);
                }

                if (!NODE_DECLARATION_PATTERN.matcher(currentLine).matches()) {
                    throw new PredicateParsingFailedException(
                            currentLine + " is not a valid abstraction header", source, lineNo);
                }

                currentLocationId = null;
                StringTokenizer declarationTokenizer = new StringTokenizer(currentLine, " (,):");
                currentAbstractionId = Integer.parseInt(declarationTokenizer.nextToken());
                while (declarationTokenizer.hasMoreTokens()) {
                    String token = declarationTokenizer.nextToken().trim();
                    if (token.length() > 0) {
                        if (token.startsWith("@")) {
                            currentLocationId = Optional.of(Integer.parseInt(token.substring(1)));
                        } else {
                            int successorId = Integer.parseInt(token);
                            currentSuccessors.add(successorId);
                        }
                    }
                }

                parserState = AbstractionsParserState.EXPECT_NODE_ABSTRACTION;

            } else if (parserState == AbstractionsParserState.EXPECT_NODE_ABSTRACTION) {
                if (!currentLine.startsWith("(assert ") && currentLine.endsWith(")")) {
                    throw new PredicateParsingFailedException("unexpected line " + currentLine, source, lineNo);
                }

                BooleanFormula f;
                try {
                    f = fmgr.parse(commonDefinitions + currentLine);
                } catch (IllegalArgumentException e) {
                    throw new PredicateParsingFailedException(e, "Formula parsing", lineNo);
                }

                AbstractionNode abstractionNode = new AbstractionNode(currentAbstractionId, f,
                        currentLocationId);
                resultAbstractions.put(currentAbstractionId, abstractionNode);
                resultTree.putAll(currentAbstractionId, currentSuccessors);
                abstractionsWithParents.addAll(currentSuccessors);
                currentAbstractionId = -1;
                currentSuccessors.clear();

                parserState = AbstractionsParserState.EXPECT_NODE_DECLARATION;
            }
        }
    }

    // Determine root node
    Set<Integer> nodesWithNoParents = Sets.difference(resultAbstractions.keySet(), abstractionsWithParents);
    assert nodesWithNoParents.size() <= 1;
    if (!nodesWithNoParents.isEmpty()) {
        this.rootAbstractionId = nodesWithNoParents.iterator().next();
    } else {
        this.rootAbstractionId = null;
    }

    // Set results
    this.abstractions = ImmutableMap.copyOf(resultAbstractions);
    this.abstractionTree = ImmutableMultimap.copyOf(resultTree);
}