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:uk.ac.open.kmi.iserve.sal.manager.impl.ServiceManagerIndexRdf.java

/**
 * Given an operation, this method obtains the list of output URIs mapped to their annotated types (i.e., modelReferences).
 * Note that the same input may have several annotations indicating the type.
 *
 * @param operationUri the URI for which we want to obtain the outputs and their annotated types
 * @return a Multimap with the outputs and their corresponding types.
 *//*from  w w w  .j a v  a 2s.  com*/
@Override
public Multimap<URI, URI> listTypedOutputs(URI operationUri) {
    if (operationUri == null) {
        return ImmutableMultimap.of();
    }

    ImmutableMultimap.Builder<URI, URI> result = ImmutableMultimap.builder();
    for (URI output : this.opOutputMap.get(operationUri)) {
        result.putAll(output, this.modelReferencesMap.get(output));
    }

    return result.build();
}

From source file:com.facebook.presto.metadata.DatabaseShardManager.java

@Override
public Multimap<Long, String> getCommittedShardNodesByTableId(TableHandle tableHandle) {
    checkNotNull(tableHandle, "tableHandle is null");
    checkState(tableHandle instanceof NativeTableHandle, "tableHandle not a native table");
    final long tableId = ((NativeTableHandle) tableHandle).getTableId();

    ImmutableMultimap.Builder<Long, String> map = ImmutableMultimap.builder();
    for (ShardNode shardNode : dao.getCommittedShardNodesByTableId(tableId)) {
        map.put(shardNode.getShardId(), shardNode.getNodeIdentifier());
    }/*from  w ww .  ja  v a 2s .c o m*/
    return map.build();
}

From source file:org.sosy_lab.cpachecker.util.precondition.segkro.RefineSolverBasedItp.java

private Multimap<CFANode, BooleanFormula> predsFromTrace(final PathPosition pFinalWpPosition,
        final PathFormula pInstanciatedTracePrecond)
        throws SolverException, InterruptedException, CPATransferException {

    Preconditions.checkNotNull(pInstanciatedTracePrecond);
    Preconditions.checkNotNull(pFinalWpPosition);

    ImmutableMultimap.Builder<CFANode, BooleanFormula> result = ImmutableMultimap.builder();

    // TODO: It might be possible to use this code to also derive the predicate for the first sate.

    // Get additional predicates from the states along the trace
    //    (or the WPs along the trace)...

    PathFormula preAtK = pInstanciatedTracePrecond; // FIXME: The paper might be wrong here... or hard to understand... (we should start with the negation)

    PathIterator reverseIt = pFinalWpPosition.reverseIterator();

    while (reverseIt.hasNext()) {

        final CFAEdge t = reverseIt.getIncomingEdge();
        reverseIt.advance();//from  w  ww  . j  a  v  a  2  s  .  co m
        final PathPosition nextPos = reverseIt.getPosition();

        if (t == null) {
            continue;
        }

        if (t.getEdgeType() != CFAEdgeType.BlankEdge) {

            //
            //           X                         X'
            //        varphi_k                 varphi_k+1
            //    ...--->o------------------------->o---...
            //         psi_E         t_k
            //

            // 1. Compute the two formulas (A/B) that are needed to compute a Craig interpolant
            //      afterTransCond === varphi_{k+1}

            // Formula A
            PathFormula preAtKp1 = pre(nextPos, FormulaMode.INSTANTIATED);

            if (bmgr.isTrue(preAtKp1.getFormula())) {
                continue;
            }

            final List<BooleanFormula> predsNew = enp.extractNewPreds(preAtKp1.getFormula());
            if (predsNew.size() > 0) {
                preAtKp1 = alterPf(preAtKp1, bmgr.and(preAtKp1.getFormula(), bmgr.and(predsNew)));
            }

            // Formula B
            final PathFormula transFromPreAtK = computeCounterCondition(t,
                    alterPf(preAtK, bmgr.not(preAtK.getFormula())));

            // Compute an interpolant; use a set of candidate predicates.
            //    The candidates for the interpolant are taken from Formula A (since that formula should get over-approximated)

            final SSAMap instantiateWith = transFromPreAtK.getSsa();
            preAtK = alterPf(transFromPreAtK,
                    ipc.getInterpolant(mgrv.instantiate(preAtKp1.getFormula(), instantiateWith),
                            transFromPreAtK.getFormula(), mgrv.instantiate(predsNew, instantiateWith),
                            t.getSuccessor()));

            result.putAll(t.getSuccessor(), uninstantiatedLiterals(preAtK.getFormula()));
        }
    }

    return result.build();
}

From source file:com.facebook.buck.android.PreDexedFilesSorter.java

public Result sortIntoPrimaryAndSecondaryDexes(BuildContext context, ImmutableList.Builder<Step> steps) {
    List<DexWithClasses> primaryDexContents = Lists.newArrayList();
    List<List<DexWithClasses>> secondaryDexesContents = Lists.newArrayList();

    int primaryDexSize = 0;
    // R.class files should always be in the primary dex.
    if (rDotJavaDex.isPresent()) {
        primaryDexSize += rDotJavaDex.get().getSizeEstimate();
        primaryDexContents.add(rDotJavaDex.get());
    }//from www  .  jav a 2 s  .c o  m

    // Sort dex files so that there's a better chance of the same set of pre-dexed files to end up
    // in a given secondary dex file.
    ImmutableList<DexWithClasses> sortedDexFilesToMerge = FluentIterable.from(dexFilesToMerge)
            .toSortedList(DexWithClasses.DEX_WITH_CLASSES_COMPARATOR);

    // Bucket each DexWithClasses into the appropriate dex file.
    List<DexWithClasses> currentSecondaryDexContents = null;
    int currentSecondaryDexSize = 0;
    for (DexWithClasses dexWithClasses : sortedDexFilesToMerge) {
        if (mustBeInPrimaryDex(dexWithClasses)) {
            // Case 1: Entry must be in the primary dex.
            primaryDexSize += dexWithClasses.getSizeEstimate();
            if (primaryDexSize > linearAllocHardLimit) {
                context.logError(
                        "DexWithClasses %s with cost %s puts the linear alloc estimate for the primary dex "
                                + "at %s, exceeding the maximum of %s.",
                        dexWithClasses.getPathToDexFile(), dexWithClasses.getSizeEstimate(), primaryDexSize,
                        linearAllocHardLimit);
                throw new HumanReadableException("Primary dex exceeds linear alloc limit.");
            }
            primaryDexContents.add(dexWithClasses);
        } else {
            // Case 2: Entry must go in a secondary dex.

            // If the individual DexWithClasses exceeds the limit for a secondary dex, then we have done
            // something horribly wrong.
            if (dexWithClasses.getSizeEstimate() > linearAllocHardLimit) {
                context.logError(
                        "DexWithClasses %s with cost %s exceeds the max cost %s for a secondary dex file.",
                        dexWithClasses.getPathToDexFile(), dexWithClasses.getSizeEstimate(),
                        linearAllocHardLimit);
                throw new HumanReadableException("Secondary dex exceeds linear alloc limit.");
            }

            // If there is no current secondary dex, or dexWithClasses would put the current secondary
            // dex over the cost threshold, then create a new secondary dex and initialize it with a
            // canary.
            if (currentSecondaryDexContents == null
                    || dexWithClasses.getSizeEstimate() + currentSecondaryDexSize > linearAllocHardLimit) {
                DexWithClasses canary = createCanary(secondaryDexesContents.size() + 1, steps);

                currentSecondaryDexContents = Lists.newArrayList(canary);
                currentSecondaryDexSize = canary.getSizeEstimate();
                secondaryDexesContents.add(currentSecondaryDexContents);
            }

            // Now add the contributions from the dexWithClasses entry.
            currentSecondaryDexContents.add(dexWithClasses);
            currentSecondaryDexSize += dexWithClasses.getSizeEstimate();
        }
    }

    ImmutableSet<Path> primaryDexInputs = FluentIterable.from(primaryDexContents)
            .transform(DexWithClasses.TO_PATH).toSet();

    Map<Path, DexWithClasses> metadataTxtEntries = Maps.newHashMap();

    String pattern = "secondary-%d" + dexStore.getExtension();
    ImmutableMultimap.Builder<Path, Path> secondaryOutputToInputs = ImmutableMultimap.builder();
    for (int index = 0; index < secondaryDexesContents.size(); index++) {
        String secondaryDexFilename = String.format(pattern, index + 1);
        Path pathToSecondaryDex = secondaryDexJarFilesDir.resolve(secondaryDexFilename);
        metadataTxtEntries.put(pathToSecondaryDex, secondaryDexesContents.get(index).get(0));
        Collection<Path> dexContentPaths = Collections2.transform(secondaryDexesContents.get(index),
                DexWithClasses.TO_PATH);
        secondaryOutputToInputs.putAll(pathToSecondaryDex, dexContentPaths);
    }

    return new Result(primaryDexInputs, secondaryOutputToInputs.build(), metadataTxtEntries,
            getDexInputsHashes(primaryDexContents, secondaryDexesContents));
}

From source file:com.facebook.presto.metadata.DatabaseShardManager.java

@Override
public Multimap<Long, String> getShardNodes(long tableId, String partitionName) {
    ImmutableMultimap.Builder<Long, String> map = ImmutableMultimap.builder();
    for (ShardNode shardNode : dao.getAllShardNodes(tableId, partitionName)) {
        map.put(shardNode.getShardId(), shardNode.getNodeIdentifier());
    }//from  w  w w . j  a v a2s . c  om
    return map.build();
}

From source file:org.tensorics.core.tensor.operations.InnerTensorOperation.java

@Override
public Tensor<V> perform(Tensor<V> left, Tensor<V> right) {
    checkNotNull(left, "left tensor must not be null!");
    checkNotNull(right, "right tensor must not be null!");

    List<CoContraDimensionPair> allPairs = CoContraDimensionPairs.coContraPairsOf(left.shape(), right.shape());
    List<CoContraDimensionPair> pairsToReduce = CoContraDimensionPairs.chooseOnePerContravariantPart(allPairs);
    Set<Class<?>> dimensionsNotToBroadcast = CoContraDimensionPairs.allDimensionsIn(pairsToReduce);

    TensorPair<V> broadcasted = broadcast(left, right, dimensionsNotToBroadcast);

    Set<Class<?>> leftDimensionsToReduce = CoContraDimensionPairs.leftDimensionsIn(pairsToReduce);
    Set<Class<?>> rightDimensionsToReduce = CoContraDimensionPairs.rightDimensionsIn(pairsToReduce);

    Set<Class<?>> remainingLeftDimensions = Sets
            .difference(broadcasted.left().shape().dimensionSet(), leftDimensionsToReduce).immutableCopy();
    Set<Class<?>> remainingRightDimensions = Sets
            .difference(broadcasted.right().shape().dimensionSet(), rightDimensionsToReduce).immutableCopy();

    Set<Class<?>> targetDimensions = Sets.union(remainingLeftDimensions, remainingRightDimensions)
            .immutableCopy();/*from  w w w.jav a2  s .co m*/
    Set<Class<?>> remainingCommonDimensions = Sets.intersection(remainingLeftDimensions,
            remainingRightDimensions);

    /*
     * produce a multimap from positions, consisting of all but the unique right dimensions to positions.
     */
    Set<Class<?>> uniqueLeftDimensions = Sets.difference(remainingLeftDimensions, remainingCommonDimensions);
    Set<Class<?>> uniqueRightDimensions = Sets.difference(remainingRightDimensions, remainingCommonDimensions);
    Multimap<Position, Position> nonUniqueToRightPositions = Positions
            .mapByStripping(broadcasted.right().shape().positionSet(), uniqueRightDimensions);

    DimensionStripper stripper = Positions.stripping(uniqueLeftDimensions);

    DimensionStripper targetLeftStripper = Positions.stripping(leftDimensionsToReduce);
    DimensionStripper targetRightStripper = Positions.stripping(rightDimensionsToReduce);

    ImmutableMultimap.Builder<Position, PositionPair> builder = ImmutableMultimap.builder();
    for (Position leftPosition : broadcasted.left().shape().positionSet()) {
        Position remainingLeftPosition = targetLeftStripper.apply(leftPosition);

        Position nonUniqueLeftPosition = stripper.apply(leftPosition);
        Position nonUniqueRightPosition = CoContraDimensionPairs.convertToRight(nonUniqueLeftPosition,
                pairsToReduce);
        Collection<Position> rightPositions = nonUniqueToRightPositions.get(nonUniqueRightPosition);
        for (Position rightPosition : rightPositions) {
            Position remainingRightPosition = targetRightStripper.apply(rightPosition);
            Position targetPosition = Positions.combineDimensions(remainingLeftPosition, remainingRightPosition,
                    targetDimensions);
            builder.put(targetPosition, PositionPair.fromLeftRight(leftPosition, rightPosition));
        }
    }

    Multimap<Position, PositionPair> targetPositionToPairs = builder.build();

    ListMultimap<Position, ValuePair<V>> valuePairs = broadcasted.mapValues(targetPositionToPairs);

    ListMultimap<Position, V> targetPositionToValueSet = Operations.mapAll(valuePairs, elementOperation);

    Map<Position, V> result = IterableOperations.reduce(targetPositionToValueSet, reductionOperation);

    ContextPropagationStrategy cps = optionRegistry.get(ContextPropagationStrategy.class);
    Position resultingContext = cps.contextForLeftRight(left.context(), right.context());

    TensorBuilder<V> finalBuilder = Tensorics.builder(targetDimensions);
    finalBuilder.putAll(result);
    finalBuilder.context(resultingContext);
    return finalBuilder.build();
}

From source file:com.android.tools.idea.templates.TemplateMetadata.java

private Multimap<Parameter, Parameter> computeRelatedParameters() {
    ImmutableMultimap.Builder<Parameter, Parameter> builder = ImmutableMultimap.builder();
    for (Parameter p : myParameterMap.values()) {
        for (Parameter p2 : myParameterMap.values()) {
            if (p == p2) {
                continue;
            }/*  w w w .j ava 2s.  c om*/
            if (p.isRelated(p2)) {
                builder.put(p, p2);
            }
        }
    }
    return builder.build();
}

From source file:com.facebook.buck.android.CompileStringsStep.java

/**
 * Groups a list of file paths matching STRING_FILE_PATTERN by the locale.
 *
 * eg. given the following list://from   w  w w  .j  a  v a 2s .c  o  m
 *
 * ImmutableSet.of(
 *   Paths.get("one/res/values-es/strings.xml"),
 *   Paths.get("two/res/values-es/strings.xml"),
 *   Paths.get("three/res/values-pt-rBR/strings.xml"),
 *   Paths.get("four/res/values/-pt-rPT/strings.xml"));
 *
 * returns:
 *
 * ImmutableMap.of(
 *   "es", ImmutableSet.of(Paths.get("one/res/values-es/strings.xml"),
 *        Paths.get("two/res/values-es/strings.xml")),
 *   "pt_BR", ImmutableSet.of(Paths.get("three/res/values-pt-rBR/strings.xml'),
 *   "pt_PT", ImmutableSet.of(Paths.get("four/res/values/-pt-rPT/strings.xml")));
 */
@VisibleForTesting
ImmutableMultimap<String, Path> groupFilesByLocale(ImmutableSet<Path> files) {
    ImmutableMultimap.Builder<String, Path> localeToFiles = ImmutableMultimap.builder();

    for (Path filepath : files) {
        Matcher matcher = STRING_FILE_PATTERN.matcher(filepath.toString());
        if (!matcher.matches()) {
            continue;
        }

        String baseLocale = matcher.group(1);
        String country = matcher.group(2);
        String locale = country == null ? baseLocale : baseLocale + "_" + country;
        if (country != null && !regionSpecificToBaseLocaleMap.containsKey(locale)) {
            regionSpecificToBaseLocaleMap.put(locale, baseLocale);
        }

        localeToFiles.put(locale, filepath);
    }

    return localeToFiles.build();
}

From source file:org.apache.awf.web.http.HttpRequestImpl.java

private ImmutableMultimap<String, String> parseParameters(String params) {
    ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();

    String[] paramArray = PARAM_STRING_PATTERN.split(params);
    for (String keyValue : paramArray) {
        String[] keyValueArray = KEY_VALUE_PATTERN.split(keyValue);
        // We need to check if the parameter has a value associated with
        // it./*from   w  w w .  j  a v a2s. c  o  m*/
        if (keyValueArray.length > 1) {
            String value = keyValueArray[1];
            try {
                value = URLDecoder.decode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // Should not happen
            }
            builder.put(keyValueArray[0], value);
        }
    }

    return builder.build();
}

From source file:org.jclouds.aws.util.AWSUtils.java

public static <R extends HttpRequest> R indexMapOfIterableToFormValuesWithPrefix(R request, String prefix,
        String keySuffix, String valueSuffix, Object input) {
    checkArgument(checkNotNull(input, "input") instanceof Map<?, ?>,
            "this binder is only valid for Map<?,Iterable<?>>: " + input.getClass());
    Map<Object, Iterable<Object>> map = (Map<Object, Iterable<Object>>) input;
    Builder<String, String> builder = ImmutableMultimap.builder();
    int i = 1;/*from  ww  w . j  a v a  2  s .c o m*/
    for (Map.Entry<Object, Iterable<Object>> entry : map.entrySet()) {
        builder.put(prefix + "." + i + "." + keySuffix,
                checkNotNull(entry.getKey().toString(), keySuffix.toLowerCase() + "s[" + i + "]"));
        Iterable<Object> iterable = entry.getValue();
        if (!Iterables.isEmpty(iterable)) {
            int j = 1;
            for (Object v : iterable) {
                builder.put(prefix + "." + i + "." + valueSuffix + "." + j, v.toString());
                j++;
            }
        }
        i++;
    }
    ImmutableMultimap<String, String> forms = builder.build();
    return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}