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

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

Introduction

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

Prototype

public static <K, V> Builder<K, V> builder() 

Source Link

Document

Returns a new builder.

Usage

From source file:com.hippo.leveldb.impl.Version.java

public Multimap<Integer, FileMetaData> getFiles() {
    ImmutableMultimap.Builder<Integer, FileMetaData> builder = ImmutableMultimap.builder();
    builder = builder.orderKeysBy(natural());

    builder.putAll(0, level0.getFiles());

    for (Level level : levels) {
        builder.putAll(level.getLevelNumber(), level.getFiles());
    }//from  ww  w.ja  v a  2s .co m
    return builder.build();
}

From source file:org.apache.hadoop.hive.ql.exec.OperatorUtils.java

/**
 * Given an operator and a set of classes, it classifies the operators it finds
 * in the stream depending on the classes they instantiate.
 *
 * If a given operator object is an instance of more than one of the input classes,
 * e.g. the operator instantiates one of the classes in the input set that is a
 * subclass of another class in the set, the operator will be associated to both
 * classes in the output map./*from w ww  .j a  va 2s.c o  m*/
 *
 * @param start the start operator
 * @param classes the set of classes
 * @return a multimap from each of the classes to the operators that instantiate
 * them
 */
public static Multimap<Class<? extends Operator<?>>, Operator<?>> classifyOperators(Operator<?> start,
        Set<Class<? extends Operator<?>>> classes) {
    ImmutableMultimap.Builder<Class<? extends Operator<?>>, Operator<?>> resultMap = new ImmutableMultimap.Builder<Class<? extends Operator<?>>, Operator<?>>();
    List<Operator<?>> ops = new ArrayList<Operator<?>>();
    ops.add(start);
    while (!ops.isEmpty()) {
        List<Operator<?>> allChildren = new ArrayList<Operator<?>>();
        for (Operator<?> op : ops) {
            for (Class<? extends Operator<?>> clazz : classes) {
                if (clazz.isInstance(op)) {
                    resultMap.put(clazz, op);
                }
            }
            allChildren.addAll(op.getChildOperators());
        }
        ops = allChildren;
    }
    return resultMap.build();
}

From source file:com.arpnetworking.metrics.mad.Bucket.java

private void computeStatistics(final ConcurrentMap<String, Collection<Calculator<?>>> calculatorsByMetric,
        final LoadingCache<String, Optional<ImmutableSet<Statistic>>> specifiedStatistics,
        final ImmutableMultimap.Builder<String, AggregatedData> data) {
    computeStatistics(calculatorsByMetric, (metric, statistic) -> {
        final Optional<ImmutableSet<Statistic>> stats;
        try {/*from  w w w .j  a  v  a 2s  . co m*/
            stats = specifiedStatistics.get(metric);
        } catch (final ExecutionException e) {
            throw Throwables.propagate(e);
        }
        return stats.isPresent() && stats.get().contains(statistic);
    }, data);
}

From source file:me.yanaga.guava.stream.MoreCollectors.java

private static <T, K, V, B extends ImmutableMultimap.Builder<K, V>, M extends ImmutableMultimap<K, V>> Collector<T, ?, M> toImmutableMultimap(
        Supplier<B> supplier, Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends V> valueMapper, Collector.Characteristics... characteristics) {
    return Collector.of(supplier, new BiConsumer<B, T>() {
        @Override//from  w ww.  ja  v a  2s  .  co m
        public void accept(B objectBuilder, T t) {
            objectBuilder.put(keyMapper.apply(t), valueMapper.apply(t));
        }
    }, new BinaryOperator<B>() {
        @SuppressWarnings("unchecked")
        @Override
        public B apply(B objectBuilder, B objectBuilder2) {
            return (B) objectBuilder.putAll(objectBuilder2.build());
        }
    }, new Function<B, M>() {
        @SuppressWarnings("unchecked")
        @Override
        public M apply(B tBuilder) {
            return (M) tBuilder.build();
        }
    }, characteristics);
}

From source file:com.b2international.snowowl.snomed.datastore.request.IdRequest.java

private static Multimap<ComponentCategory, SnomedComponentCreateRequest> getComponentCreateRequests(
        final Request<?, ?> request) {
    final ImmutableMultimap.Builder<ComponentCategory, SnomedComponentCreateRequest> resultBuilder = ImmutableMultimap
            .builder();/*from  w ww .  j a  v  a 2s .com*/
    collectComponentCreateRequests(request, resultBuilder);
    return resultBuilder.build();
}

From source file:com.google.errorprone.bugpatterns.android.WakelockReleasedDangerously.java

/**
 * Finds all method invocations on the given symbol, and constructs a map of the called method's
 * name, to the {@link MethodInvocationTree} in which it was called.
 *///from  www.  ja va  2  s.  c o m
private ImmutableMultimap<String, MethodInvocationTree> methodCallsForSymbol(Symbol sym, ClassTree classTree) {
    Builder<String, MethodInvocationTree> methodMap = ImmutableMultimap.builder();
    // Populate map builder with names of method called : the tree in which it is called.
    classTree.accept(new TreeScanner<Void, Void>() {
        @Override
        public Void visitMethodInvocation(MethodInvocationTree callTree, Void unused) {
            if (sym.equals(getSymbol(getReceiver(callTree)))) {
                MethodSymbol methodSymbol = getSymbol(callTree);
                if (methodSymbol != null) {
                    methodMap.put(methodSymbol.getSimpleName().toString(), callTree);
                }
            }
            return super.visitMethodInvocation(callTree, unused);
        }
    }, null);
    return methodMap.build();
}

From source file:com.b2international.snowowl.snomed.datastore.request.IdRequest.java

private static void collectComponentCreateRequests(Request<?, ?> request,
        ImmutableMultimap.Builder<ComponentCategory, SnomedComponentCreateRequest> resultBuilder) {
    if (request instanceof DelegatingRequest) {
        collectComponentCreateRequests(((DelegatingRequest<?, ?, ?>) request).next(), resultBuilder);
    } else if (request instanceof TransactionalRequest) {
        collectComponentCreateRequests(((TransactionalRequest) request).getNext(), resultBuilder);
    } else if (request instanceof BaseSnomedComponentCreateRequest) {
        final BaseSnomedComponentCreateRequest createRequest = (BaseSnomedComponentCreateRequest) request;
        for (SnomedCoreComponentCreateRequest nestedRequest : createRequest.getNestedRequests()) {
            ComponentCategory category = getComponentCategory(nestedRequest);
            resultBuilder.put(category, (BaseSnomedComponentCreateRequest) nestedRequest);
            // XXX: we could recurse here, but only concept creation requests have actual nested requests at the moment
        }//from  w ww .  j  a  v  a  2 s .  c o m
    } else if (request instanceof BulkRequest) {
        final BulkRequest<?> bulkRequest = (BulkRequest<?>) request;
        for (Request<?, ?> bulkRequestItem : bulkRequest.getRequests()) {
            collectComponentCreateRequests(bulkRequestItem, resultBuilder);
        }
    }
}

From source file:com.facebook.buck.apple.WorkspaceAndProjectGenerator.java

public Path generateWorkspaceAndDependentProjects(Map<Path, ProjectGenerator> projectGenerators)
        throws IOException {
    LOG.debug("Generating workspace for target %s", workspaceBuildTarget);

    String workspaceName = XcodeWorkspaceConfigDescription.getWorkspaceNameFromArg(workspaceArguments);
    Path outputDirectory;//w  w w  .  j a v a 2 s .  c  o m
    if (combinedProject) {
        workspaceName += "-Combined";
        outputDirectory = BuildTargets.getGenPath(workspaceBuildTarget, "%s").getParent()
                .resolve(workspaceName + ".xcodeproj");
    } else {
        outputDirectory = workspaceBuildTarget.getBasePath();
    }

    WorkspaceGenerator workspaceGenerator = new WorkspaceGenerator(projectFilesystem,
            combinedProject ? "project" : workspaceName, outputDirectory);

    ImmutableMap.Builder<String, XcodeWorkspaceConfigDescription.Arg> schemeConfigsBuilder = ImmutableMap
            .builder();
    ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNodeBuilder = ImmutableSetMultimap
            .builder();
    ImmutableSetMultimap.Builder<String, TargetNode<?>> buildForTestNodesBuilder = ImmutableSetMultimap
            .builder();
    ImmutableMultimap.Builder<AppleTestBundleParamsKey, TargetNode<AppleTestDescription.Arg>> groupedTestsBuilder = ImmutableMultimap
            .builder();
    ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescription.Arg>> ungroupedTestsBuilder = ImmutableSetMultimap
            .builder();

    buildWorkspaceSchemes(getTargetToBuildWithBuck(), projectGraph,
            projectGeneratorOptions.contains(ProjectGenerator.Option.INCLUDE_TESTS),
            projectGeneratorOptions.contains(ProjectGenerator.Option.INCLUDE_DEPENDENCIES_TESTS),
            groupableTests, workspaceName, workspaceArguments, schemeConfigsBuilder,
            schemeNameToSrcTargetNodeBuilder, buildForTestNodesBuilder, groupedTestsBuilder,
            ungroupedTestsBuilder);

    ImmutableMap<String, XcodeWorkspaceConfigDescription.Arg> schemeConfigs = schemeConfigsBuilder.build();
    ImmutableSetMultimap<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNode = schemeNameToSrcTargetNodeBuilder
            .build();
    ImmutableSetMultimap<String, TargetNode<?>> buildForTestNodes = buildForTestNodesBuilder.build();
    ImmutableMultimap<AppleTestBundleParamsKey, TargetNode<AppleTestDescription.Arg>> groupedTests = groupedTestsBuilder
            .build();
    ImmutableSetMultimap<String, TargetNode<AppleTestDescription.Arg>> ungroupedTests = ungroupedTestsBuilder
            .build();
    Iterable<PBXTarget> synthesizedCombinedTestTargets = ImmutableList.of();

    ImmutableSet<BuildTarget> targetsInRequiredProjects = FluentIterable
            .from(Optional.presentInstances(schemeNameToSrcTargetNode.values()))
            .append(buildForTestNodes.values()).transform(HasBuildTarget.TO_TARGET).toSet();
    ImmutableMultimap.Builder<BuildTarget, PBXTarget> buildTargetToPbxTargetMapBuilder = ImmutableMultimap
            .builder();
    ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();
    Optional<BuildTarget> targetToBuildWithBuck = getTargetToBuildWithBuck();

    if (combinedProject) {
        LOG.debug("Generating a combined project");
        ProjectGenerator generator = new ProjectGenerator(projectGraph, targetsInRequiredProjects,
                projectFilesystem, outputDirectory.getParent(), workspaceName, buildFileName,
                projectGeneratorOptions, targetToBuildWithBuck, buildWithBuckFlags, executableFinder,
                environment, cxxPlatforms, defaultCxxPlatform, sourcePathResolverForNode, buckEventBus,
                attemptToDetermineBestCxxPlatform, halideBuckConfig, cxxBuckConfig)
                        .setAdditionalCombinedTestTargets(groupedTests)
                        .setTestsToGenerateAsStaticLibraries(groupableTests);
        combinedProjectGenerator = Optional.of(generator);
        generator.createXcodeProjects();

        workspaceGenerator.addFilePath(generator.getProjectPath(), Optional.<Path>absent());
        requiredBuildTargetsBuilder.addAll(generator.getRequiredBuildTargets());

        buildTargetToPbxTargetMapBuilder.putAll(generator.getBuildTargetToGeneratedTargetMap());
        for (PBXTarget target : generator.getBuildTargetToGeneratedTargetMap().values()) {
            targetToProjectPathMapBuilder.put(target, generator.getProjectPath());
        }
        synthesizedCombinedTestTargets = generator.getBuildableCombinedTestTargets();
        for (PBXTarget target : synthesizedCombinedTestTargets) {
            targetToProjectPathMapBuilder.put(target, generator.getProjectPath());
        }
    } else {
        ImmutableMultimap.Builder<Path, BuildTarget> projectDirectoryToBuildTargetsBuilder = ImmutableMultimap
                .builder();
        for (TargetNode<?> targetNode : projectGraph.getNodes()) {
            BuildTarget buildTarget = targetNode.getBuildTarget();
            projectDirectoryToBuildTargetsBuilder.put(buildTarget.getBasePath(), buildTarget);
        }
        ImmutableMultimap<Path, BuildTarget> projectDirectoryToBuildTargets = projectDirectoryToBuildTargetsBuilder
                .build();
        for (Path projectDirectory : projectDirectoryToBuildTargets.keySet()) {
            final ImmutableSet<BuildTarget> rules = filterRulesForProjectDirectory(projectGraph,
                    ImmutableSet.copyOf(projectDirectoryToBuildTargets.get(projectDirectory)));
            if (Sets.intersection(targetsInRequiredProjects, rules).isEmpty()) {
                continue;
            }

            ProjectGenerator generator = projectGenerators.get(projectDirectory);
            if (generator == null) {
                LOG.debug("Generating project for directory %s with targets %s", projectDirectory, rules);
                String projectName;
                if (projectDirectory.getNameCount() == 0) {
                    // If we're generating a project in the root directory, use a generic name.
                    projectName = "Project";
                } else {
                    // Otherwise, name the project the same thing as the directory we're in.
                    projectName = projectDirectory.getFileName().toString();
                }
                generator = new ProjectGenerator(projectGraph, rules, projectFilesystem, projectDirectory,
                        projectName, buildFileName, projectGeneratorOptions, Optionals.bind(
                                targetToBuildWithBuck, new Function<BuildTarget, Optional<BuildTarget>>() {
                                    @Override
                                    public Optional<BuildTarget> apply(BuildTarget input) {
                                        return rules.contains(input) ? Optional.of(input)
                                                : Optional.<BuildTarget>absent();
                                    }
                                }),
                        buildWithBuckFlags, executableFinder, environment, cxxPlatforms, defaultCxxPlatform,
                        sourcePathResolverForNode, buckEventBus, attemptToDetermineBestCxxPlatform,
                        halideBuckConfig, cxxBuckConfig).setTestsToGenerateAsStaticLibraries(groupableTests);

                generator.createXcodeProjects();
                requiredBuildTargetsBuilder.addAll(generator.getRequiredBuildTargets());
                projectGenerators.put(projectDirectory, generator);
            } else {
                LOG.debug("Already generated project for target %s, skipping", projectDirectory);
            }

            workspaceGenerator.addFilePath(generator.getProjectPath());

            buildTargetToPbxTargetMapBuilder.putAll(generator.getBuildTargetToGeneratedTargetMap());
            for (PBXTarget target : generator.getBuildTargetToGeneratedTargetMap().values()) {
                targetToProjectPathMapBuilder.put(target, generator.getProjectPath());
            }
        }

        if (!groupedTests.isEmpty()) {
            ProjectGenerator combinedTestsProjectGenerator = new ProjectGenerator(projectGraph,
                    ImmutableSortedSet.<BuildTarget>of(), projectFilesystem,
                    BuildTargets.getGenPath(workspaceBuildTarget, "%s-CombinedTestBundles"),
                    "_CombinedTestBundles", buildFileName, projectGeneratorOptions,
                    Optional.<BuildTarget>absent(), buildWithBuckFlags, executableFinder, environment,
                    cxxPlatforms, defaultCxxPlatform, sourcePathResolverForNode, buckEventBus,
                    attemptToDetermineBestCxxPlatform, halideBuckConfig, cxxBuckConfig);
            combinedTestsProjectGenerator.setAdditionalCombinedTestTargets(groupedTests).createXcodeProjects();
            workspaceGenerator.addFilePath(combinedTestsProjectGenerator.getProjectPath());
            requiredBuildTargetsBuilder.addAll(combinedTestsProjectGenerator.getRequiredBuildTargets());
            for (PBXTarget target : combinedTestsProjectGenerator.getBuildTargetToGeneratedTargetMap()
                    .values()) {
                targetToProjectPathMapBuilder.put(target, combinedTestsProjectGenerator.getProjectPath());
            }
            synthesizedCombinedTestTargets = combinedTestsProjectGenerator.getBuildableCombinedTestTargets();
            for (PBXTarget target : synthesizedCombinedTestTargets) {
                targetToProjectPathMapBuilder.put(target, combinedTestsProjectGenerator.getProjectPath());
            }
            this.combinedTestsProjectGenerator = Optional.of(combinedTestsProjectGenerator);
        }
    }

    Path workspacePath = workspaceGenerator.writeWorkspace();

    final Multimap<BuildTarget, PBXTarget> buildTargetToTarget = buildTargetToPbxTargetMapBuilder.build();
    final Function<BuildTarget, PBXTarget> targetNodeToPBXTargetTransformer = new Function<BuildTarget, PBXTarget>() {
        @Override
        public PBXTarget apply(BuildTarget input) {
            ImmutableList<PBXTarget> targets = ImmutableList.copyOf(buildTargetToTarget.get(input));
            if (targets.size() == 1) {
                return targets.get(0);
            }
            // The only reason why a build target would map to more than one project target is if
            // there are two project targets: one is the usual one, the other is a target that just
            // shells out to Buck.
            Preconditions.checkState(targets.size() == 2);
            PBXTarget first = targets.get(0);
            PBXTarget second = targets.get(1);
            Preconditions.checkState(first.getName().endsWith(ProjectGenerator.BUILD_WITH_BUCK_POSTFIX)
                    ^ second.getName().endsWith(ProjectGenerator.BUILD_WITH_BUCK_POSTFIX));
            PBXTarget buildWithBuckTarget;
            PBXTarget buildWithXcodeTarget;
            if (first.getName().endsWith(ProjectGenerator.BUILD_WITH_BUCK_POSTFIX)) {
                buildWithBuckTarget = first;
                buildWithXcodeTarget = second;
            } else {
                buildWithXcodeTarget = first;
                buildWithBuckTarget = second;
            }
            return buildWithBuck ? buildWithBuckTarget : buildWithXcodeTarget;
        }
    };

    writeWorkspaceSchemes(workspaceName, outputDirectory, schemeConfigs, schemeNameToSrcTargetNode,
            buildForTestNodes, ungroupedTests, targetToProjectPathMapBuilder.build(),
            synthesizedCombinedTestTargets, new Function<TargetNode<?>, Collection<PBXTarget>>() {
                @Override
                public Collection<PBXTarget> apply(TargetNode<?> input) {
                    return buildTargetToTarget.get(input.getBuildTarget());
                }
            }, targetNodeToPBXTargetTransformer);

    return workspacePath;
}

From source file:com.arpnetworking.metrics.mad.Bucket.java

private void computeStatistics(final ConcurrentMap<String, Collection<Calculator<?>>> calculatorsByMetric,
        final ImmutableSet<Statistic> specifiedStatistics,
        final ImmutableMultimap.Builder<String, AggregatedData> data) {
    computeStatistics(calculatorsByMetric, (metric, statistic) -> specifiedStatistics.contains(statistic),
            data);//from   w  w w .  j  av  a2s .  co m
}

From source file:com.continuuity.weave.yarn.ApplicationMasterService.java

private void doRun() throws Exception {

    // Orderly stores container requests.
    Queue<RunnableContainerRequest> runnableRequests = Lists.newLinkedList();
    for (WeaveSpecification.Order order : weaveSpec.getOrders()) {

        ImmutableMultimap.Builder<Resource, RuntimeSpecification> builder = ImmutableMultimap.builder();
        for (String runnableName : order.getNames()) {
            RuntimeSpecification runtimeSpec = weaveSpec.getRunnables().get(runnableName);
            Resource capability = createCapability(runtimeSpec.getResourceSpecification());
            builder.put(capability, runtimeSpec);
        }/*  w  w  w.java 2s  . c  om*/
        runnableRequests.add(new RunnableContainerRequest(order.getType(), builder.build()));
    }

    // The main loop
    Map.Entry<Resource, ? extends Collection<RuntimeSpecification>> currentRequest = null;
    Queue<ProvisionRequest> provisioning = Lists.newLinkedList();
    while (isRunning()) {
        // If nothing is in provisioning, and no pending request, move to next one
        while (provisioning.isEmpty() && currentRequest == null && !runnableRequests.isEmpty()) {
            currentRequest = runnableRequests.peek().takeRequest();
            if (currentRequest == null) {
                // All different types of resource request from current order is done, move to next one
                // TODO: Need to handle order type as well
                runnableRequests.poll();
            }
        }
        // Nothing in provision, makes the next batch of provision request
        if (provisioning.isEmpty() && currentRequest != null) {
            provisioning.addAll(addContainerRequests(currentRequest.getKey(), currentRequest.getValue()));
            currentRequest = null;
        }

        // Now call allocate
        AllocateResponse allocateResponse = amrmClient.allocate(0.0f);
        allocateResponse.getAMResponse().getResponseId();
        AMResponse amResponse = allocateResponse.getAMResponse();

        // Assign runnable to container
        launchRunnable(amResponse.getAllocatedContainers(), provisioning);
        TimeUnit.SECONDS.sleep(1);
    }
}