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.arpnetworking.metrics.mad.Bucket.java

private void computeStatistics(final ConcurrentMap<String, Collection<Calculator<?>>> calculatorsByMetric,
        final BiFunction<String, Statistic, Boolean> specified,
        final ImmutableMultimap.Builder<String, AggregatedData> data) {

    final AggregatedData.Builder datumBuilder = new AggregatedData.Builder();

    for (final Map.Entry<String, Collection<Calculator<?>>> entry : calculatorsByMetric.entrySet()) {
        final String metric = entry.getKey();
        final Collection<Calculator<?>> calculators = entry.getValue();

        // Build calculator dependencies for metric
        // TODO(vkoskela): This is a waste of time. [NEXT]
        // - Single set of calculators per metric and per statistic (no distinction between non-aux and aux)
        // - Check the set of statistics to see if the calculator should be published
        // - Still need both sets of statistics in order to create new set of calculators
        final Map<Statistic, Calculator<?>> dependencies = Maps.newHashMap();
        Optional<Calculator<?>> countStatisticCalculator = Optional.empty();
        for (final Calculator<?> calculator : calculators) {
            if (COUNT_STATISTIC.equals(calculator.getStatistic())) {
                countStatisticCalculator = Optional.of(calculator);
            }//from w ww .ja  v a2  s .  co  m
            dependencies.put(calculator.getStatistic(), calculator);
        }
        CalculatedValue<?> populationSize = new CalculatedValue.Builder<>()
                .setValue(new Quantity.Builder().setValue(-1.0).build()).build();
        if (countStatisticCalculator.isPresent()) {
            populationSize = countStatisticCalculator.get().calculate(dependencies);
        }

        // Compute each calculated value requested by the client
        for (final Calculator<?> calculator : calculators) {
            datumBuilder.setSupportingData(null);
            final CalculatedValue<?> calculatedValue = calculator.calculate(dependencies);
            data.put(metric,
                    datumBuilder.setValue(calculatedValue.getValue())
                            .setIsSpecified(specified.apply(metric, calculator.getStatistic()))
                            .setPopulationSize((long) populationSize.getValue().getValue())
                            .setSupportingData(calculatedValue.getData())
                            .setStatistic(calculator.getStatistic()).build());
        }
    }
}

From source file:com.google.errorprone.bugpatterns.LambdaFunctionalInterface.java

private ImmutableMultimap<String, MethodInvocationTree> methodCallsForSymbol(Symbol sym, ClassTree classTree) {
    ImmutableMultimap.Builder<String, MethodInvocationTree> methodMap = ImmutableMultimap.builder();
    classTree.accept(new TreeScanner<Void, Void>() {
        @Override/*from   w w  w .  j  a v a 2s . c  o m*/
        public Void visitMethodInvocation(MethodInvocationTree callTree, Void unused) {
            final MethodSymbol methodSymbol = getSymbol(callTree);
            if (methodSymbol != null && sym.equals(methodSymbol)) {
                methodMap.put(methodSymbol.toString(), callTree);
            }
            return super.visitMethodInvocation(callTree, unused);
        }
    }, null);

    return methodMap.build();
}

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

public <M extends Metadata> Multimap<Method, MetadataHandler<M>> handlers(MetadataDef<M> def) {
    final ImmutableMultimap.Builder<Method, MetadataHandler<M>> builder = ImmutableMultimap.builder();
    for (Map.Entry<Method, MetadataHandler> entry : handlerMap.entries()) {
        if (def.methods.contains(entry.getKey())) {
            //noinspection unchecked
            builder.put(entry.getKey(), entry.getValue());
        }//from  w  ww.  j  av  a  2 s .  c  om
    }
    return builder.build();
}

From source file:org.jclouds.s3.options.CopyObjectOptions.java

@Override
public Multimap<String, String> buildRequestHeaders() {
    checkState(headerTag != null, "headerTag should have been injected!");
    checkState(metadataPrefix != null, "metadataPrefix should have been injected!");
    ImmutableMultimap.Builder<String, String> returnVal = ImmutableMultimap.builder();
    for (Entry<String, String> entry : headers.entries()) {
        returnVal.put(entry.getKey().replace(DEFAULT_AMAZON_HEADERTAG, headerTag), entry.getValue());
    }/*  ww  w  .  j  a v  a2 s  .  c  o m*/
    if (metadata != null) {
        returnVal.put(METADATA_DIRECTIVE.replace(DEFAULT_AMAZON_HEADERTAG, headerTag), "REPLACE");
        for (Map.Entry<String, String> entry : metadata.entrySet()) {
            String key = entry.getKey();
            returnVal.put(key.startsWith(metadataPrefix) ? key : metadataPrefix + key, entry.getValue());
        }
    }
    return returnVal.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
 * upstream depending on the classes it instantiates.
 *
 * 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 w  w .j av  a  2s . co  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<?>> classifyOperatorsUpstream(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<?>> allParent = new ArrayList<Operator<?>>();
        for (Operator<?> op : ops) {
            for (Class<? extends Operator<?>> clazz : classes) {
                if (clazz.isInstance(op)) {
                    resultMap.put(clazz, op);
                }
            }
            if (op.getParentOperators() != null) {
                allParent.addAll(op.getParentOperators());
            }
        }
        ops = allParent;
    }
    return resultMap.build();
}

From source file:org.tensorics.core.tensor.Positions.java

public static Multimap<Position, Position> mapByStripping(Iterable<Position> positions,
        Set<Class<?>> dimensionsToStrip) {
    DimensionStripper stripper = stripping(dimensionsToStrip);
    ImmutableMultimap.Builder<Position, Position> builder = ImmutableMultimap.builder();
    for (Position position : positions) {
        builder.put(stripper.apply(position), position);
    }//from   ww  w  . j  av a  2s .  c o  m
    return builder.build();
}

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

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

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

    WorkspaceGenerator workspaceGenerator = new WorkspaceGenerator(rootCell.getFilesystem(),
            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();
    ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescription.Arg, ?>> testsBuilder = ImmutableSetMultimap
            .builder();

    buildWorkspaceSchemes(projectGraph, projectGeneratorOptions.contains(ProjectGenerator.Option.INCLUDE_TESTS),
            projectGeneratorOptions.contains(ProjectGenerator.Option.INCLUDE_DEPENDENCIES_TESTS), workspaceName,
            workspaceArguments, schemeConfigsBuilder, schemeNameToSrcTargetNodeBuilder,
            buildForTestNodesBuilder, testsBuilder);

    ImmutableMap<String, XcodeWorkspaceConfigDescription.Arg> schemeConfigs = schemeConfigsBuilder.build();
    ImmutableSetMultimap<String, Optional<TargetNode<?, ?>>> schemeNameToSrcTargetNode = schemeNameToSrcTargetNodeBuilder
            .build();
    ImmutableSetMultimap<String, TargetNode<?, ?>> buildForTestNodes = buildForTestNodesBuilder.build();
    ImmutableSetMultimap<String, TargetNode<AppleTestDescription.Arg, ?>> tests = testsBuilder.build();

    ImmutableSet<BuildTarget> targetsInRequiredProjects = Stream
            .concat(schemeNameToSrcTargetNode.values().stream().flatMap(Optionals::toStream),
                    buildForTestNodes.values().stream())
            .map(HasBuildTarget::getBuildTarget).collect(MoreCollectors.toImmutableSet());
    ImmutableMultimap.Builder<BuildTarget, PBXTarget> buildTargetToPbxTargetMapBuilder = ImmutableMultimap
            .builder();
    ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();
    Optional<BuildTarget> targetToBuildWithBuck = getTargetToBuildWithBuck();
    generateProjects(projectGenerators, listeningExecutorService, workspaceName, outputDirectory,
            workspaceGenerator, targetsInRequiredProjects, buildTargetToPbxTargetMapBuilder,
            targetToProjectPathMapBuilder, targetToBuildWithBuck);
    final Multimap<BuildTarget, PBXTarget> buildTargetToTarget = buildTargetToPbxTargetMapBuilder.build();

    writeWorkspaceSchemes(workspaceName, outputDirectory, schemeConfigs, schemeNameToSrcTargetNode,
            buildForTestNodes, tests, targetToProjectPathMapBuilder.build(),
            input -> buildTargetToTarget.get(input.getBuildTarget()),
            getTargetNodeToPBXTargetTransformFunction(buildTargetToTarget, buildWithBuck));

    return workspaceGenerator.writeWorkspace();
}

From source file:com.facebook.presto.execution.SqlStageExecution.java

private synchronized RemoteTask scheduleTask(Node node, PlanNodeId sourceId, Iterable<Split> sourceSplits) {
    TaskId taskId = new TaskId(stateMachine.getStageId(), String.valueOf(nextTaskId.getAndIncrement()));

    ImmutableMultimap.Builder<PlanNodeId, Split> initialSplits = ImmutableMultimap.builder();
    for (Split sourceSplit : sourceSplits) {
        initialSplits.put(sourceId, sourceSplit);
    }/*from   w  w  w. j av  a 2  s. com*/
    for (Entry<PlanNodeId, URI> entry : exchangeLocations.entries()) {
        initialSplits.put(entry.getKey(), createRemoteSplitFor(taskId, entry.getValue()));
    }

    RemoteTask task = remoteTaskFactory.createRemoteTask(stateMachine.getSession(), taskId, node,
            stateMachine.getFragment(), initialSplits.build(), outputBuffers.get(),
            nodeTaskMap.getSplitCountChangeListener(node));

    completeSources.forEach(task::noMoreSplits);

    allTasks.add(taskId);
    tasks.computeIfAbsent(node, key -> newConcurrentHashSet()).add(task);
    nodeTaskMap.addTask(node, task);

    task.addStateChangeListener(taskInfo -> {
        StageState stageState = getState();
        if (stageState.isDone()) {
            return;
        }

        TaskState taskState = taskInfo.getState();
        if (taskState == TaskState.FAILED) {
            RuntimeException failure = taskInfo.getFailures().stream().findFirst()
                    .map(ExecutionFailureInfo::toException).orElse(new PrestoException(
                            StandardErrorCode.INTERNAL_ERROR, "A task failed for an unknown reason"));
            stateMachine.transitionToFailed(failure);
        } else if (taskState == TaskState.ABORTED) {
            // A task should only be in the aborted state if the STAGE is done (ABORTED or FAILED)
            stateMachine.transitionToFailed(new PrestoException(StandardErrorCode.INTERNAL_ERROR,
                    "A task is in the ABORTED state but stage is " + stageState));
        } else if (taskState == TaskState.FINISHED) {
            finishedTasks.add(task.getTaskId());
        }

        if (stageState == StageState.SCHEDULED || stageState == StageState.RUNNING) {
            if (taskState == TaskState.RUNNING) {
                stateMachine.transitionToRunning();
            }
            if (finishedTasks.containsAll(allTasks)) {
                stateMachine.transitionToFinished();
            }
        }
    });

    if (!stateMachine.getState().isDone()) {
        task.start();
    } else {
        // stage finished while we were scheduling this task
        task.abort();
    }

    return task;
}

From source file:io.prestosql.execution.SqlStageExecution.java

public synchronized void addExchangeLocations(PlanFragmentId fragmentId, Set<RemoteTask> sourceTasks,
        boolean noMoreExchangeLocations) {
    requireNonNull(fragmentId, "fragmentId is null");
    requireNonNull(sourceTasks, "sourceTasks is null");

    RemoteSourceNode remoteSource = exchangeSources.get(fragmentId);
    checkArgument(remoteSource != null, "Unknown remote source %s. Known sources are %s", fragmentId,
            exchangeSources.keySet());//w  w  w .  ja v  a 2s .  c o  m

    this.sourceTasks.putAll(remoteSource.getId(), sourceTasks);

    for (RemoteTask task : getAllTasks()) {
        ImmutableMultimap.Builder<PlanNodeId, Split> newSplits = ImmutableMultimap.builder();
        for (RemoteTask sourceTask : sourceTasks) {
            URI exchangeLocation = sourceTask.getTaskStatus().getSelf();
            newSplits.put(remoteSource.getId(), createRemoteSplitFor(task.getTaskId(), exchangeLocation));
        }
        task.addSplits(newSplits.build());
    }

    if (noMoreExchangeLocations) {
        completeSourceFragments.add(fragmentId);

        // is the source now complete?
        if (completeSourceFragments.containsAll(remoteSource.getSourceFragmentIds())) {
            completeSources.add(remoteSource.getId());
            for (RemoteTask task : getAllTasks()) {
                task.noMoreSplits(remoteSource.getId());
            }
        }
    }
}

From source file:com.facebook.buck.apple.xcode.ProjectGenerator.java

public ProjectGenerator(PartialGraph partialGraph, Set<BuildTarget> initialTargets,
        ProjectFilesystem projectFilesystem, ExecutionContext executionContext, Path outputDirectory,
        String projectName, Set<Option> options) {
    this.partialGraph = Preconditions.checkNotNull(partialGraph);
    this.initialTargets = ImmutableSet.copyOf(initialTargets);
    this.projectFilesystem = Preconditions.checkNotNull(projectFilesystem);
    this.executionContext = Preconditions.checkNotNull(executionContext);
    this.outputDirectory = Preconditions.checkNotNull(outputDirectory);
    this.projectName = Preconditions.checkNotNull(projectName);
    this.options = ImmutableSet.copyOf(options);
    this.placedAssetCatalogBuildPhaseScript = this.projectFilesystem.getPathForRelativePath(
            BuckConstant.BIN_PATH.resolve("xcode-scripts/compile_asset_catalogs_build_phase.sh"));

    this.projectPath = outputDirectory.resolve(projectName + ".xcodeproj");
    this.repoRootRelativeToOutputDirectory = this.outputDirectory.normalize().toAbsolutePath()
            .relativize(projectFilesystem.getRootPath().toAbsolutePath());
    this.project = new PBXProject(projectName);

    this.buildRuleToXcodeTarget = CacheBuilder.newBuilder()
            .build(new CacheLoader<BuildRule, Optional<PBXTarget>>() {
                @Override//from   w w  w.  j  a v a2 s.c o  m
                public Optional<PBXTarget> load(BuildRule key) throws Exception {
                    return generateTargetForBuildRule(key);
                }
            });

    xcodeConfigurationLayersMultimapBuilder = ImmutableMultimap.builder();
}