Example usage for com.google.common.collect Multimap put

List of usage examples for com.google.common.collect Multimap put

Introduction

In this page you can find the example usage for com.google.common.collect Multimap put.

Prototype

boolean put(@Nullable K key, @Nullable V value);

Source Link

Document

Stores a key-value pair in this multimap.

Usage

From source file:io.github.swagger2markup.internal.utils.TagUtils.java

/**
 * Groups the operations by tag. The key of the Multimap is the tag name.
 * The value of the Multimap is a PathOperation
 *
 * @param allOperations     all operations
 * @param operationOrdering comparator for operations, for a given tag
 * @return Operations grouped by Tag/*from   w  w w  . ja  va 2 s .c o  m*/
 */
public static Multimap<String, PathOperation> groupOperationsByTag(List<PathOperation> allOperations,
        Comparator<PathOperation> operationOrdering) {

    Multimap<String, PathOperation> operationsGroupedByTag;
    if (operationOrdering == null) {
        operationsGroupedByTag = LinkedHashMultimap.create();
    } else {
        operationsGroupedByTag = MultimapBuilder.linkedHashKeys().treeSetValues(operationOrdering).build();
    }
    for (PathOperation operation : allOperations) {
        List<String> tags = operation.getOperation().getTags();

        Validate.notEmpty(tags, "Can't GroupBy.TAGS. Operation '%s' has no tags", operation);
        for (String tag : tags) {
            if (logger.isDebugEnabled()) {
                logger.debug("Added path operation '{}' to tag '{}'", operation, tag);
            }
            operationsGroupedByTag.put(tag, operation);
        }
    }

    return operationsGroupedByTag;
}

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

/**
 * Computes the set of Labels corresponding to a collection of PathFragments representing absolute
 * import paths.// w w  w  .j av a  2 s . c om
 *
 * @return a map from the computed {@link Label}s to the corresponding {@link PathFragment}s;
 *     {@code null} if any Skyframe dependencies are unavailable.
 * @throws SkylarkImportFailedException
 */
@Nullable
static ImmutableMap<PathFragment, Label> labelsForAbsoluteImports(ImmutableSet<PathFragment> pathsToLookup,
        Environment env) throws SkylarkImportFailedException, InterruptedException {

    // Import PathFragments are absolute, so there is a 1-1 mapping from corresponding Labels.
    ImmutableMap.Builder<PathFragment, Label> outputMap = new ImmutableMap.Builder<>();

    // The SkyKey here represents the directory containing an import PathFragment, hence there
    // can in general be multiple imports per lookup.
    Multimap<SkyKey, PathFragment> lookupMap = LinkedHashMultimap.create();
    for (PathFragment importPath : pathsToLookup) {
        PathFragment relativeImportPath = importPath.toRelative();
        PackageIdentifier pkgToLookUp = PackageIdentifier
                .createInMainRepo(relativeImportPath.getParentDirectory());
        lookupMap.put(ContainingPackageLookupValue.key(pkgToLookUp), importPath);
    }

    // Attempt to find a package for every directory containing an import.
    Map<SkyKey, ValueOrException2<BuildFileNotFoundException, InconsistentFilesystemException>> lookupResults = env
            .getValuesOrThrow(lookupMap.keySet(), BuildFileNotFoundException.class,
                    InconsistentFilesystemException.class);
    if (env.valuesMissing()) {
        return null;
    }
    try {
        // Process lookup results.
        for (Entry<SkyKey, ValueOrException2<BuildFileNotFoundException, InconsistentFilesystemException>> entry : lookupResults
                .entrySet()) {
            ContainingPackageLookupValue lookupValue = (ContainingPackageLookupValue) entry.getValue().get();
            if (!lookupValue.hasContainingPackage()) {
                // Although multiple imports may be in the same package-less directory, we only
                // report an error for the first one.
                PackageIdentifier lookupKey = ((PackageIdentifier) entry.getKey().argument());
                PathFragment importFile = lookupKey.getPackageFragment();
                throw SkylarkImportFailedException.noBuildFile(importFile);
            }
            PackageIdentifier pkgIdForImport = lookupValue.getContainingPackageName();
            PathFragment containingPkgPath = pkgIdForImport.getPackageFragment();
            for (PathFragment importPath : lookupMap.get(entry.getKey())) {
                PathFragment relativeImportPath = importPath.toRelative();
                String targetNameForImport = relativeImportPath.relativeTo(containingPkgPath).toString();
                try {
                    outputMap.put(importPath, Label.create(pkgIdForImport, targetNameForImport));
                } catch (LabelSyntaxException e) {
                    // While the Label is for the most part guaranteed to be well-formed by construction, an
                    // error is still possible if the filename itself is malformed, e.g., contains control
                    // characters. Since we expect this error to be very rare, for code simplicity, we allow
                    // the error message to refer to a Label even though the filename was specified via a
                    // simple path.
                    throw new SkylarkImportFailedException(e);
                }
            }
        }
    } catch (BuildFileNotFoundException e) {
        // Thrown when there are IO errors looking for BUILD files.
        throw new SkylarkImportFailedException(e);
    } catch (InconsistentFilesystemException e) {
        throw new SkylarkImportFailedException(e);
    }

    return outputMap.build();
}

From source file:com.eucalyptus.vm.NetworkGroupsMetadata.java

private static String generateTopology() {
    StringBuilder buf = new StringBuilder();
    Multimap<String, String> networks = ArrayListMultimap.create();
    Multimap<String, String> rules = ArrayListMultimap.create();
    final EntityTransaction db = Entities.get(VmInstance.class);
    try {// w w w .  j  a v  a  2  s.c o  m
        Predicate<VmInstance> filter = VmStateSet.TORNDOWN.not();
        for (VmInstance vm : VmInstances.list(filter)) {
            try {
                for (NetworkGroup ruleGroup : vm.getNetworkGroups()) {
                    try {
                        ruleGroup = Entities.merge(ruleGroup);
                        networks.put(ruleGroup.getClusterNetworkName(), vm.getPrivateAddress());
                        if (!rules.containsKey(ruleGroup.getNaturalId())) {
                            for (NetworkRule netRule : ruleGroup.getNetworkRules()) {
                                try {
                                    String rule = String.format("-P %s -%s %d%s%d ", netRule.getProtocol(),
                                            (NetworkRule.Protocol.icmp.equals(netRule.getProtocol()) ? "t"
                                                    : "p"),
                                            netRule.getLowPort(),
                                            (NetworkRule.Protocol.icmp.equals(netRule.getProtocol()) ? ":"
                                                    : "-"),
                                            netRule.getHighPort());
                                    for (NetworkPeer peer : netRule.getNetworkPeers()) {
                                        Account groupAccount = Accounts
                                                .lookupAccountById(peer.getUserQueryKey());
                                        String groupId = NetworkGroups
                                                .lookup(AccountFullName.getInstance(groupAccount),
                                                        peer.getGroupName())
                                                .getNaturalId();
                                        String ruleString = String.format("%s -o %s -u %s", rule, groupId,
                                                groupAccount.getAccountNumber());
                                        if (!rules.get(ruleGroup.getClusterNetworkName())
                                                .contains(ruleString)) {
                                            rules.put(ruleGroup.getClusterNetworkName(), ruleString);
                                        }
                                    }
                                    for (String cidr : netRule.getIpRanges()) {
                                        String ruleString = String.format("%s -s %s", rule, cidr);
                                        if (!rules.get(ruleGroup.getClusterNetworkName())
                                                .contains(ruleString)) {
                                            rules.put(ruleGroup.getClusterNetworkName(), ruleString);
                                        }
                                    }
                                } catch (Exception ex) {
                                    LOG.error(ex, ex);
                                }
                            }
                        }
                    } catch (Exception ex) {
                        LOG.error(ex, ex);
                    }
                }
            } catch (Exception ex) {
                LOG.error(ex, ex);
            }
        }
        buf.append(rulesToString(rules));
        buf.append(groupsToString(networks));
    } catch (Exception ex) {
        LOG.error(ex, ex);
    } finally {
        db.rollback();
    }
    return buf.toString();
}

From source file:com.zxy.commons.poi.excel.ExcelUtils.java

/**
 * table?multimap/* ww w .j  a va  2  s .co  m*/
 * 
 * @param table table
 * @return multimap
*/
public static Multimap<String, String> table2map(Table<Integer, String, String> table) {
    Multimap<String, String> multimap = LinkedHashMultimap.create();

    Set<Integer> rowNames = table.rowKeySet();
    // Set<String> columnNames = table.columnKeySet();

    for (Integer rowName : rowNames) {
        Map<String, String> items = table.row(rowName);
        for (Map.Entry<String, String> entry : items.entrySet()) {
            String columnName = entry.getKey();
            String value = entry.getValue();
            multimap.put(columnName, value);
        }
    }
    return multimap;
}

From source file:org.modeshape.graph.query.process.QueryResultColumns.java

protected static Set<Column> findColumnsWithSameNames(List<Column> columns) {
    Multimap<String, Column> columnNames = ArrayListMultimap.create();
    for (Column column : columns) {
        String columnName = column.columnName() != null ? column.columnName() : column.propertyName();
        columnNames.put(columnName, column);
    }//from  www.  j a  v a 2s  .co m
    Set<Column> results = new HashSet<Column>();
    for (Map.Entry<String, Collection<Column>> entry : columnNames.asMap().entrySet()) {
        if (entry.getValue().size() > 1) {
            results.addAll(entry.getValue());
        }
    }
    return results;
}

From source file:org.jboss.errai.marshalling.rebind.DefinitionsFactoryImpl.java

/**
 * Recursive subroutine of {@link #fillInheritanceMap(org.jboss.errai.codegen.meta.MetaClass)}.
 *//*  ww w  .j  av a2  s. c  o  m*/
private static void fillInheritanceMap(final Multimap<String, String> inheritanceMap, final MetaClass visiting,
        final MetaClass mappingClass) {
    if (visiting == null || visiting.equals(MetaClassFactory.get(Object.class)))
        return;

    if (!visiting.equals(mappingClass)) {
        inheritanceMap.put(visiting.getFullyQualifiedName(), mappingClass.getFullyQualifiedName());
    }

    fillInheritanceMap(inheritanceMap, visiting.getSuperClass(), mappingClass);

    for (final MetaClass iface : visiting.getInterfaces()) {
        fillInheritanceMap(inheritanceMap, iface, mappingClass);
    }
}

From source file:com.ikanow.aleph2.core.shared.utils.DataServiceUtils.java

/** Gets a minimal of service instances and associated service names
 *  (since each service instance can actually implement multiple services)
 * @param data_schema//from w w w. j a  v  a2  s  .c  o m
 * @param context
 * @return
 */
@SuppressWarnings("unchecked")
public static Multimap<IDataServiceProvider, String> selectDataServices(final DataSchemaBean data_schema,
        final IServiceContext context) {
    final Multimap<IDataServiceProvider, String> mutable_output = HashMultimap.create();
    if (null == data_schema) { //(rare NPE check! - lets calling client invoke bucket.data_schema() without having to worry about it)
        return mutable_output;
    }

    listDataSchema(data_schema).forEach(schema_name -> {
        Optional.of(schema_name._1()).flatMap(s -> getDataServiceInterface(schema_name._2()))
                .flatMap(ds_name -> context.getService((Class<IUnderlyingService>) (Class<?>) ds_name,
                        Optional.ofNullable(schema_name._1().<String>get(service_name_))))
                .ifPresent(ds -> mutable_output.put((IDataServiceProvider) ds, schema_name._2()));
        ;
    });

    return mutable_output;
}

From source file:org.apache.hadoop.hive.ql.optimizer.SharedScanOptimizer.java

private static Multimap<String, Entry<String, TableScanOperator>> splitTableScanOpsByTable(ParseContext pctx) {
    Multimap<String, Entry<String, TableScanOperator>> tableNameToOps = ArrayListMultimap.create();
    for (Entry<String, TableScanOperator> e : pctx.getTopOps().entrySet()) {
        TableScanOperator tsOp = e.getValue();
        tableNameToOps.put(tsOp.getConf().getTableMetadata().getDbName() + "."
                + tsOp.getConf().getTableMetadata().getTableName(), e);
    }//from  w  w w  . j av a 2  s .c o m
    return tableNameToOps;
}

From source file:io.github.robwin.swagger2markup.utils.TagUtils.java

/**
 * Groups the operations by tag. The key of the Multimap is the tag name.
 * The value of the Multimap is a PathOperation
 *
 * @param allOperations all operations// www .  j  a  v a  2 s.c  o  m
 * @param tagOrdering comparator for tags
 * @param operationOrdering comparator for operations, for a given tag
 * @return Operations grouped by Tag
 */
public static Multimap<String, PathOperation> groupOperationsByTag(Set<PathOperation> allOperations,
        Comparator<String> tagOrdering, Comparator<PathOperation> operationOrdering) {
    MultimapBuilder.MultimapBuilderWithKeys<String> multimapBuilderWithKeys;

    if (tagOrdering == null)
        multimapBuilderWithKeys = MultimapBuilder.SortedSetMultimapBuilder.treeKeys(Ordering.<String>natural()); // FIXME as-is sorting not supported because of limitations in MultiMap::hashkeys(). Replaced with Ordering.natural()
    else
        multimapBuilderWithKeys = MultimapBuilder.SortedSetMultimapBuilder.treeKeys(tagOrdering);

    Multimap<String, PathOperation> operationsGroupedByTag;
    if (operationOrdering == null)
        operationsGroupedByTag = multimapBuilderWithKeys.hashSetValues().build();
    else
        operationsGroupedByTag = multimapBuilderWithKeys.treeSetValues(operationOrdering).build();

    for (PathOperation operation : allOperations) {
        List<String> tags = operation.getOperation().getTags();
        Validate.notEmpty(tags, "Can't GroupBy.TAGS > Operation '%s' has not tags", operation);
        for (String tag : tags) {
            if (LOG.isInfoEnabled()) {
                LOG.info("Added path operation '{}' to tag '{}'", operation, tag);
            }
            operationsGroupedByTag.put(tag, operation);
        }
    }

    return operationsGroupedByTag;
}

From source file:com.google.template.soy.soytree.MsgSubstUnitBaseVarNameUtils.java

/**
 * Generates base names for all the expressions in a list, where for each expression, we use the
 * shortest candidate base name that does not collide with any of the candidate base names
 * generated from other expressions in the list. Two candidate base names are considered to
 * collide if they are identical or if one is a suffix of the other beginning after an underscore
 * character.//from www. j  a v  a  2  s  .c  o  m
 *
 * For example, given the expressions $userGender and $target.gender, the generated base names
 * would be USER_GENDER and TARGET_GENDER. (Even though the shortest candidate base names are
 * USER_GENDER and GENDER, the latter one is not used since it collides with the former one.)
 *
 * Note: We prefer the shorter candidate base names when possible, because the translator usually
 * doesn't care about all the names. E.g. $data.actionTargets[0].personInfo.gender turns into
 * GENDER as opposed to DATA_ACTION_TARGETS_0_PERSON_INFO_GENDER, which is overkill and probably
 * more confusing. Another reason is that refactorings that change higher-level names should not
 * change messages unnecessarily. E.g. a refactoring that changes
 * $data.actionTargets[0].personInfo.gender -> $userData.actionTargets[0].personInfo.gender
 * should not change the placeholder name.
 *
 * @param exprNodes The expr nodes of the expressions to generate noncolliding base names for.
 * @param fallbackBaseName The fallback base name.
 * @param errorReporter For reporting collision errors.
 * @return The list of generated noncolliding base names.
 */
public static List<String> genNoncollidingBaseNamesForExprs(List<ExprNode> exprNodes, String fallbackBaseName,
        ErrorReporter errorReporter) {

    int numExprs = exprNodes.size();

    // --- Compute candidate base names for each expression. ---
    List<List<String>> candidateBaseNameLists = Lists.newArrayListWithCapacity(numExprs);
    for (ExprNode exprRoot : exprNodes) {
        candidateBaseNameLists.add(genCandidateBaseNamesForExpr(exprRoot));
    }

    // --- Build a multiset of collision strings (if key has > 1 values, then it's a collision). ---
    // Note: We could combine this loop with the previous loop, but it's more readable this way.
    Multimap<String, ExprNode> collisionStrToLongestCandidatesMultimap = HashMultimap.create();
    for (int i = 0; i < numExprs; i++) {
        ExprNode exprRoot = exprNodes.get(i);
        List<String> candidateBaseNameList = candidateBaseNameLists.get(i);
        if (candidateBaseNameList.isEmpty()) {
            continue;
        }
        String longestCandidate = candidateBaseNameList.get(candidateBaseNameList.size() - 1);
        // Add longest candidate as a collision string.
        collisionStrToLongestCandidatesMultimap.put(longestCandidate, exprRoot);
        // Add all suffixes that begin after an underscore char as collision strings.
        for (int j = 0, n = longestCandidate.length(); j < n; j++) {
            if (longestCandidate.charAt(j) == '_') {
                collisionStrToLongestCandidatesMultimap.put(longestCandidate.substring(j + 1), exprRoot);
            }
        }
    }

    // --- Find the shortest noncolliding candidate base name for each expression. ---
    List<String> noncollidingBaseNames = Lists.newArrayListWithCapacity(numExprs);

    OUTER: for (int i = 0; i < numExprs; i++) {
        List<String> candidateBaseNameList = candidateBaseNameLists.get(i);

        if (!candidateBaseNameList.isEmpty()) {
            // Has candidates: Use the shortest candidate that doesn't collide.

            for (String candidateBaseName : candidateBaseNameList) {
                if (collisionStrToLongestCandidatesMultimap.get(candidateBaseName).size() == 1) {
                    // Found candidate with 1 value in multimap, which means no collision.
                    noncollidingBaseNames.add(candidateBaseName);
                    continue OUTER;
                }
            }

            // Did not find any candidate with no collision.
            ExprNode exprRoot = exprNodes.get(i);
            String longestCandidate = candidateBaseNameList.get(candidateBaseNameList.size() - 1);
            ExprNode collidingExprRoot = null;
            for (ExprNode er : collisionStrToLongestCandidatesMultimap.get(longestCandidate)) {
                if (er != exprRoot) {
                    collidingExprRoot = er;
                    break;
                }
            }
            assert collidingExprRoot != null;
            errorReporter.report(collidingExprRoot.getSourceLocation(), COLLIDING_EXPRESSIONS,
                    exprRoot.toSourceString(), collidingExprRoot.toSourceString());
            return noncollidingBaseNames;
        } else {
            // No candidates: Use fallback.
            noncollidingBaseNames.add(fallbackBaseName);
        }
    }

    return noncollidingBaseNames;
}