Example usage for com.google.common.collect Maps asMap

List of usage examples for com.google.common.collect Maps asMap

Introduction

In this page you can find the example usage for com.google.common.collect Maps asMap.

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V> NavigableMap<K, V> asMap(NavigableSet<K> set, Function<? super K, V> function) 

Source Link

Document

Returns a view of the navigable set as a map, mapping keys from the set according to the specified function.

Usage

From source file:forge.game.combat.Combat.java

public final Map<Card, GameEntity> getAttackersAndDefenders() {
    return Maps.asMap(getAttackers(), new Function<Card, GameEntity>() {
        @Override/*from w w w. j  a v a  2 s  .  c om*/
        public GameEntity apply(final Card attacker) {
            return getDefenderByAttacker(attacker);
        }
    });
}

From source file:org.grouplens.grapht.InjectionContainer.java

private Map<Desire, Instantiator> makeDependencyMap(DAGNode<Component, Dependency> node,
        SetMultimap<DAGNode<Component, Dependency>, DAGEdge<Component, Dependency>> backEdges) {
    Set<DAGEdge<Component, Dependency>> edges = node.getOutgoingEdges();
    if (backEdges.containsKey(node)) {
        ImmutableSet.Builder<DAGEdge<Component, Dependency>> bld = ImmutableSet.builder();
        edges = bld.addAll(edges).addAll(backEdges.get(node)).build();
    }/*from ww w. j  a  v  a2s .  com*/

    ImmutableSet.Builder<Desire> desires = ImmutableSet.builder();
    for (DAGEdge<Component, Dependency> edge : edges) {
        desires.add(edge.getLabel().getInitialDesire());
    }
    return Maps.asMap(desires.build(), new DepLookup(edges, backEdges));
}

From source file:com.microsoft.rest.ServiceResponseBuilder.java

@Override
public <THeader> ServiceResponseWithHeaders<T, THeader> buildEmptyWithHeaders(final Response<Void> response,
        Class<THeader> headerType) throws IOException {
    ServiceResponse<T> bodyResponse = buildEmpty(response);
    THeader headers = serializerAdapter.deserialize(
            serializerAdapter.serialize(Maps.asMap(response.headers().names(), new Function<String, String>() {
                @Override//from  ww  w.  j  a  va 2  s .  c  o m
                public String apply(String s) {
                    return response.headers().get(s);
                }
            })), headerType);
    ServiceResponseWithHeaders<T, THeader> serviceResponse = new ServiceResponseWithHeaders<>(headers,
            bodyResponse.headResponse());
    serviceResponse.withBody(bodyResponse.body());
    return serviceResponse;
}

From source file:ninja.leaping.permissionsex.extrabackends.groupmanager.GroupManagerSubjectData.java

@Override
public Map<Set<Map.Entry<String, String>>, Integer> getAllDefaultValues() {
    return Maps.filterValues(Maps.asMap(getActiveContexts(), this::getDefaultValue),
            input -> input != null && input != 0);
}

From source file:org.apache.aurora.scheduler.updater.JobDiff.java

/**
 * Creates a map of {@code instanceCount} copies of {@code config}.
 *
 * @param config Configuration to generate an instance mapping for.
 * @param instanceCount Number of instances to represent.
 * @return A map of instance IDs (from 0 to {@code instanceCount - 1}) to {@code config}.
 *///from   w w  w .  ja  v  a2 s  .  co m
public static Map<Integer, ITaskConfig> asMap(ITaskConfig config, int instanceCount) {
    requireNonNull(config);

    Set<Integer> desiredInstances = ContiguousSet.create(Range.closedOpen(0, instanceCount),
            DiscreteDomain.integers());
    return ImmutableMap.copyOf(Maps.asMap(desiredInstances, Functions.constant(config)));
}

From source file:org.apache.aurora.scheduler.state.SchedulerCoreImpl.java

@Override
public void addInstances(final IJobKey jobKey, final ImmutableSet<Integer> instanceIds,
        final ITaskConfig config) throws ScheduleException {

    storage.write(new MutateWork.NoResult<ScheduleException>() {
        @Override//from  ww  w  .j  a v  a2  s .c  o m
        protected void execute(MutableStoreProvider storeProvider) throws ScheduleException {
            validateTaskLimits(config, instanceIds.size());

            ImmutableSet<IScheduledTask> tasks = storeProvider.getTaskStore()
                    .fetchTasks(Query.jobScoped(jobKey).active());

            Set<Integer> existingInstanceIds = FluentIterable.from(tasks)
                    .transform(Tasks.SCHEDULED_TO_INSTANCE_ID).toSet();
            if (!Sets.intersection(existingInstanceIds, instanceIds).isEmpty()) {
                throw new ScheduleException("Instance ID collision detected.");
            }

            stateManager.insertPendingTasks(Maps.asMap(instanceIds, Functions.constant(config)));
        }
    });
}

From source file:com.twitter.aurora.scheduler.state.SchedulerCoreImpl.java

@Override
public void addInstances(final IJobKey jobKey, final ImmutableSet<Integer> instanceIds,
        final ITaskConfig config) throws ScheduleException {

    runJobFilters(jobKey, config, instanceIds.size(), true);
    storage.write(new MutateWork.NoResult<ScheduleException>() {
        @Override//from  ww  w  . j ava2  s  .c  om
        protected void execute(MutableStoreProvider storeProvider) throws ScheduleException {

            ImmutableSet<IScheduledTask> tasks = storeProvider.getTaskStore()
                    .fetchTasks(Query.jobScoped(jobKey).active());

            Set<Integer> existingInstanceIds = FluentIterable.from(tasks)
                    .transform(Tasks.SCHEDULED_TO_INSTANCE_ID).toSet();
            if (!Sets.intersection(existingInstanceIds, instanceIds).isEmpty()) {
                throw new ScheduleException("Instance ID collision detected.");
            }

            stateManager.insertPendingTasks(Maps.asMap(instanceIds, Functions.constant(config)));
        }
    });
}

From source file:com.facebook.buck.distributed.DistBuildArtifactCacheImpl.java

@Override
public synchronized void prewarmRemoteContains(ImmutableSet<BuildRule> rulesToBeChecked) {
    @SuppressWarnings("PMD.PrematureDeclaration")
    Stopwatch stopwatch = Stopwatch.createStarted();
    Set<BuildRule> unseenRules = rulesToBeChecked.stream()
            .filter(rule -> !remoteCacheContainsFutures.containsKey(rule)).collect(Collectors.toSet());

    if (unseenRules.isEmpty()) {
        return;/*from  www . j a  v a2  s.  c  o  m*/
    }

    LOG.info("Checking remote cache for [%d] new rules.", unseenRules.size());
    Map<BuildRule, ListenableFuture<RuleKey>> rulesToKeys = Maps.asMap(unseenRules,
            rule -> ruleKeyCalculator.calculate(eventBus, rule));

    ListenableFuture<Map<RuleKey, CacheResult>> keysToCacheResultFuture = Futures
            .transformAsync(Futures.allAsList(rulesToKeys.values()), ruleKeys -> {
                LOG.info("Computing RuleKeys for %d new rules took %dms.", unseenRules.size(),
                        stopwatch.elapsed(TimeUnit.MILLISECONDS));
                stopwatch.reset();
                stopwatch.start();
                return multiContainsAsync(ruleKeys);
            }, executorService);

    Map<BuildRule, ListenableFuture<Boolean>> containsResultsForUnseenRules = Maps
            .asMap(unseenRules,
                    rule -> Futures.transform(keysToCacheResultFuture, keysToCacheResult -> Objects
                            .requireNonNull(keysToCacheResult.get(Futures.getUnchecked(rulesToKeys.get(rule))))
                            .getType().isSuccess(), MoreExecutors.directExecutor()));

    remoteCacheContainsFutures.putAll(containsResultsForUnseenRules);
    Futures.allAsList(containsResultsForUnseenRules.values())
            .addListener(() -> LOG.info("Checking the remote cache for %d rules took %dms.", unseenRules.size(),
                    stopwatch.elapsed(TimeUnit.MILLISECONDS)), MoreExecutors.directExecutor());
}

From source file:com.facebook.buck.cxx.Omnibus.java

protected static OmnibusSpec buildSpec(final CxxPlatform cxxPlatform,
        final Iterable<? extends NativeLinkTarget> includedRoots,
        final Iterable<? extends NativeLinkable> excludedRoots) {

    // A map of targets to native linkable objects.  We maintain this, so that we index our
    // bookkeeping around `BuildTarget` and avoid having to guarantee that all other types are
    // hashable.//from   www .j  a  va2  s  .c o m
    final Map<BuildTarget, NativeLinkable> nativeLinkables = new LinkedHashMap<>();

    // The nodes which should *not* be included in the omnibus link.
    final Set<BuildTarget> excluded = new LinkedHashSet<>();

    // Process all the roots included in the omnibus link.
    final Map<BuildTarget, NativeLinkTarget> roots = new LinkedHashMap<>();
    Map<BuildTarget, NativeLinkable> rootDeps = new LinkedHashMap<>();
    for (NativeLinkTarget root : includedRoots) {
        roots.put(root.getBuildTarget(), root);
        for (NativeLinkable dep : NativeLinkables.getNativeLinkables(cxxPlatform,
                root.getNativeLinkTargetDeps(cxxPlatform), Linker.LinkableDepType.SHARED).values()) {
            Linker.LinkableDepType linkStyle = NativeLinkables
                    .getLinkStyle(dep.getPreferredLinkage(cxxPlatform), Linker.LinkableDepType.SHARED);
            Preconditions.checkState(linkStyle != Linker.LinkableDepType.STATIC);

            // We only consider deps which aren't *only* statically linked.
            if (linkStyle == Linker.LinkableDepType.SHARED) {
                rootDeps.put(dep.getBuildTarget(), dep);
                nativeLinkables.put(dep.getBuildTarget(), dep);
            }
        }
    }

    // Process all roots excluded from the omnibus link, and add them to our running list of
    // excluded nodes.
    for (NativeLinkable root : excludedRoots) {
        nativeLinkables.put(root.getBuildTarget(), root);
        excluded.add(root.getBuildTarget());
    }

    // Perform the first walk starting from the native linkable nodes immediately reachable via the
    // included roots.  We'll accomplish two things here:
    // 1. Build up the map of node names to their native linkable objects.
    // 2. Perform an initial discovery of dependency nodes to exclude from the omnibus link.
    new AbstractBreadthFirstTraversal<BuildTarget>(rootDeps.keySet()) {
        @Override
        public ImmutableSet<BuildTarget> visit(BuildTarget target) {
            NativeLinkable nativeLinkable = Preconditions.checkNotNull(nativeLinkables.get(target));
            ImmutableMap<BuildTarget, NativeLinkable> deps = Maps
                    .uniqueIndex(getDeps(nativeLinkable, cxxPlatform), HasBuildTarget::getBuildTarget);
            nativeLinkables.putAll(deps);
            if (nativeLinkable.getPreferredLinkage(cxxPlatform) == NativeLinkable.Linkage.SHARED) {
                excluded.add(target);
            }
            return deps.keySet();
        }
    }.start();

    // Do another walk to flesh out the transitively excluded nodes.
    new AbstractBreadthFirstTraversal<BuildTarget>(excluded) {
        @Override
        public Iterable<BuildTarget> visit(BuildTarget target) {
            NativeLinkable nativeLinkable = Preconditions.checkNotNull(nativeLinkables.get(target));
            ImmutableMap<BuildTarget, NativeLinkable> deps = Maps
                    .uniqueIndex(getDeps(nativeLinkable, cxxPlatform), HasBuildTarget::getBuildTarget);
            nativeLinkables.putAll(deps);
            excluded.add(target);
            return deps.keySet();
        }
    }.start();

    // And then we can do one last walk to create the actual graph which contain only root and body
    // nodes to include in the omnibus link.
    final MutableDirectedGraph<BuildTarget> graphBuilder = new MutableDirectedGraph<>();
    final Set<BuildTarget> deps = new LinkedHashSet<>();
    new AbstractBreadthFirstTraversal<BuildTarget>(Sets.difference(rootDeps.keySet(), excluded)) {
        @Override
        public Iterable<BuildTarget> visit(BuildTarget target) {
            graphBuilder.addNode(target);
            Set<BuildTarget> keep = new LinkedHashSet<>();
            for (BuildTarget dep : Iterables.transform(getDeps(target, roots, nativeLinkables, cxxPlatform),
                    HasBuildTarget::getBuildTarget)) {
                if (excluded.contains(dep)) {
                    deps.add(dep);
                } else {
                    keep.add(dep);
                    graphBuilder.addEdge(target, dep);
                }
            }
            return keep;
        }
    }.start();
    DirectedAcyclicGraph<BuildTarget> graph = new DirectedAcyclicGraph<>(graphBuilder);

    // Since we add all undefined root symbols into the omnibus library, we also need to include
    // any excluded root deps as deps of omnibus, as they may fulfill these undefined symbols.
    // Also add any excluded nodes that are also root dependencies.
    deps.addAll(Sets.intersection(rootDeps.keySet(), excluded));

    return ImmutableOmnibusSpec.builder().graph(graph).roots(roots)
            .body(FluentIterable.from(graph.getNodes()).filter(Predicates.not(roots.keySet()::contains))
                    .toMap(Functions.forMap(nativeLinkables)))
            .deps(Maps.asMap(deps, Functions.forMap(nativeLinkables)))
            .excluded(Maps.asMap(excluded, Functions.forMap(nativeLinkables))).build();
}

From source file:com.google.devtools.build.lib.skyframe.GraphBackedRecursivePackageProvider.java

private void collectPackagesUnder(final RepositoryName repository, Set<TraversalInfo> traversals,
        ImmutableList.Builder<PathFragment> builder) throws InterruptedException {
    Map<TraversalInfo, SkyKey> traversalToKeyMap = Maps.asMap(traversals,
            new Function<TraversalInfo, SkyKey>() {
                @Override//from   ww  w . j ava2 s .  co  m
                public SkyKey apply(TraversalInfo traversalInfo) {
                    return CollectPackagesUnderDirectoryValue.key(repository, traversalInfo.rootedDir,
                            traversalInfo.excludedSubdirectories);
                }
            });
    Map<SkyKey, SkyValue> values = graph.getSuccessfulValues(traversalToKeyMap.values());

    ImmutableSet.Builder<TraversalInfo> subdirTraversalBuilder = ImmutableSet.builder();
    for (Map.Entry<TraversalInfo, SkyKey> entry : traversalToKeyMap.entrySet()) {
        TraversalInfo info = entry.getKey();
        SkyKey key = entry.getValue();
        SkyValue val = values.get(key);
        CollectPackagesUnderDirectoryValue collectPackagesValue = (CollectPackagesUnderDirectoryValue) val;
        if (collectPackagesValue != null) {
            if (collectPackagesValue.isDirectoryPackage()) {
                builder.add(info.rootedDir.getRelativePath());
            }

            ImmutableMap<RootedPath, Boolean> subdirectoryTransitivelyContainsPackages = collectPackagesValue
                    .getSubdirectoryTransitivelyContainsPackages();
            for (RootedPath subdirectory : subdirectoryTransitivelyContainsPackages.keySet()) {
                if (subdirectoryTransitivelyContainsPackages.get(subdirectory)) {
                    PathFragment subdirectoryRelativePath = subdirectory.getRelativePath();
                    ImmutableSet<PathFragment> excludedSubdirectoriesBeneathThisSubdirectory = PathFragment
                            .filterPathsStartingWith(info.excludedSubdirectories, subdirectoryRelativePath);
                    subdirTraversalBuilder.add(
                            new TraversalInfo(subdirectory, excludedSubdirectoriesBeneathThisSubdirectory));
                }
            }
        }
    }

    ImmutableSet<TraversalInfo> subdirTraversals = subdirTraversalBuilder.build();
    if (!subdirTraversals.isEmpty()) {
        collectPackagesUnder(repository, subdirTraversals, builder);
    }
}