Example usage for com.google.common.collect ListMultimap get

List of usage examples for com.google.common.collect ListMultimap get

Introduction

In this page you can find the example usage for com.google.common.collect ListMultimap get.

Prototype

@Override
List<V> get(@Nullable K key);

Source Link

Document

Because the values for a given key may have duplicates and follow the insertion ordering, this method returns a List , instead of the java.util.Collection specified in the Multimap interface.

Usage

From source file:org.sonar.server.dashboard.ws.ShowAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    DbSession dbSession = dbClient.openSession(false);
    try {//from www. j a  v a2  s.  co  m
        Integer userId = userSession.getUserId();
        DashboardDto dashboard = dbClient.dashboardDao().selectAllowedByKey(dbSession,
                request.mandatoryParamAsLong(PARAM_KEY), userId != null ? userId.longValue() : null);
        if (dashboard == null) {
            throw new NotFoundException();
        }

        JsonWriter json = response.newJsonWriter();
        json.beginObject();
        json.prop("key", dashboard.getKey());
        json.prop("name", dashboard.getName());
        json.prop("layout", dashboard.getColumnLayout());
        json.prop("desc", dashboard.getDescription());
        json.prop("global", dashboard.getGlobal());
        json.prop("shared", dashboard.getShared());
        if (dashboard.getUserId() != null) {
            UserDto user = dbClient.userDao().selectUserById(dashboard.getUserId());
            if (user != null) {
                json.name("owner").beginObject();
                // TODO to be shared and extracted from here
                json.prop("login", user.getLogin());
                json.prop("name", user.getName());
                json.endObject();
            }
        }
        // load widgets and related properties
        json.name("widgets").beginArray();
        Collection<WidgetDto> widgets = dbClient.widgetDao().findByDashboard(dbSession, dashboard.getKey());
        ListMultimap<Long, WidgetPropertyDto> propertiesByWidget = WidgetPropertyDto
                .groupByWidgetId(dbClient.widgetPropertyDao().selectByDashboard(dbSession, dashboard.getKey()));
        for (WidgetDto widget : widgets) {
            json.beginObject();
            json.prop("id", widget.getId());
            json.prop("key", widget.getWidgetKey());
            json.prop("name", widget.getName());
            json.prop("desc", widget.getDescription());
            json.prop("col", widget.getColumnIndex());
            json.prop("row", widget.getRowIndex());
            json.prop("configured", widget.getConfigured());
            json.prop("componentId", widget.getResourceId());
            json.name("props").beginArray();
            for (WidgetPropertyDto prop : propertiesByWidget.get(widget.getId())) {
                json.beginObject();
                json.prop("key", prop.getPropertyKey());
                json.prop("val", prop.getTextValue());
                json.endObject();
            }
            json.endArray().endObject();
        }

        json.endArray();
        json.endObject();
        json.close();
    } finally {
        dbSession.close();
    }
}

From source file:org.rf.ide.core.testdata.mapping.TwoModelReferencesLinker.java

@VisibleForTesting
protected void replaceNewReferenceByCorrespondingOld(final RobotFileOutput oldModifiedOutput,
        final ListMultimap<RobotTokenType, RobotToken> oldViewAboutTokens,
        final RobotFileOutput alreadyDumpedContent,
        final ListMultimap<RobotTokenType, RobotToken> newViewAboutTokens) {

    // general idea: 1. 'old tokens contains content as expected, so we only updating in them
    // position with clear dirty flag'
    // 2. next we are searching new token in new output line position and replacing it by old
    // 3. last we removing old lines and adding new lines in old output object
    final List<RobotLine> newContentLines = alreadyDumpedContent.getFileModel().getFileContent();

    for (final RobotTokenType type : oldViewAboutTokens.keySet()) {
        final List<RobotToken> oldToUpdate = oldViewAboutTokens.get(type);
        final List<RobotToken> newToCopy = newViewAboutTokens.get(type);

        final int tokSize = Math.min(oldToUpdate.size(), newToCopy.size());
        for (int index = 0; index < tokSize; index++) {
            final RobotToken oldToken = oldToUpdate.get(index);
            final RobotToken newToken = newToCopy.get(index);

            oldToken.setText(newToken.getText());
            oldToken.setRaw(newToken.getRaw());
            oldToken.setLineNumber(newToken.getLineNumber());
            oldToken.setStartColumn(newToken.getStartColumn());
            oldToken.setStartOffset(newToken.getStartOffset());
            oldToken.clearDirtyFlag();//w  w w.  j  a  v a  2 s  . co  m

            if (newToken.getLineNumber() >= 0) {
                final RobotLine robotLine = newContentLines.get(newToken.getLineNumber() - 1);
                final Optional<Integer> posToken = robotLine.getElementPositionInLine(newToken);
                if (posToken.isPresent()) {
                    robotLine.setLineElementAt(posToken.get(), oldToken);
                }
            }
        }
    }

    final RobotFile oldFileModel = oldModifiedOutput.getFileModel();
    oldFileModel.removeLines();
    for (final RobotLine line : newContentLines) {
        oldFileModel.addNewLine(line);
    }
}

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

/**
 * Private helper for genSubstUnitInfo(). Determines representative nodes and builds preliminary
 * maps.//from ww  w .ja v  a2s.  c o  m
 *
 * If there are multiple nodes in the message that should share the same var name, then the first
 * such node encountered becomes the "representative node" for the group ("repNode" in variable
 * names). The rest of the nodes in the group are non-representative ("nonRepNode").
 *
 * The baseNameToRepNodesMap is a multimap from each base name to its list of representative
 * nodes (they all generate the same base var name, but should not have the same final var name).
 * If we encounter a non-representative node, then we insert it into nonRepNodeToRepNodeMap,
 * mapping it to its corresponding representative node.
 *
 * The base var names are preliminary because some of the final var names will be the base names
 * plus a unique suffix.
 *
 * @param msgNode The MsgNode being processed.
 * @return A pair of (1) a multimap from each base name to its list of representative nodes, and
 *     (2) a map from each non-representative node to its respective representative node.
 */
@SuppressWarnings("unchecked")
private static Pair<ListMultimap<String, MsgSubstUnitNode>, Map<MsgSubstUnitNode, MsgSubstUnitNode>> genPrelimSubstUnitInfoMapsHelper(
        MsgNode msgNode) {

    ListMultimap<String, MsgSubstUnitNode> baseNameToRepNodesMap = LinkedListMultimap.create();
    Map<MsgSubstUnitNode, MsgSubstUnitNode> nonRepNodeToRepNodeMap = new HashMap<>();

    Deque<MsgSubstUnitNode> traversalQueue = new ArrayDeque<>();

    // Seed the traversal queue with the children of this MsgNode.
    for (SoyNode child : msgNode.getChildren()) {
        if (child instanceof MsgSubstUnitNode) {
            traversalQueue.add((MsgSubstUnitNode) child);
        }
    }

    while (!traversalQueue.isEmpty()) {
        MsgSubstUnitNode node = traversalQueue.remove();

        if ((node instanceof MsgSelectNode) || (node instanceof MsgPluralNode)) {
            for (CaseOrDefaultNode child : ((ParentSoyNode<CaseOrDefaultNode>) node).getChildren()) {
                for (SoyNode grandchild : child.getChildren()) {
                    if (grandchild instanceof MsgSubstUnitNode) {
                        traversalQueue.add((MsgSubstUnitNode) grandchild);
                    }
                }
            }
        }

        String baseName = node.getBaseVarName();
        if (!baseNameToRepNodesMap.containsKey(baseName)) {
            // Case 1: First occurrence of this base name.
            baseNameToRepNodesMap.put(baseName, node);
        } else {
            boolean isNew = true;
            for (MsgSubstUnitNode other : baseNameToRepNodesMap.get(baseName)) {
                if (node.shouldUseSameVarNameAs(other)) {
                    // Case 2: Should use same var name as another node we've seen.
                    nonRepNodeToRepNodeMap.put(node, other);
                    isNew = false;
                    break;
                }
            }
            if (isNew) {
                // Case 3: New representative node that has the same base name as another node we've seen,
                // but should not use the same var name.
                baseNameToRepNodesMap.put(baseName, node);
            }
        }
    }

    return Pair.of(baseNameToRepNodesMap, nonRepNodeToRepNodeMap);
}

From source file:fr.obeo.emf.specimen.SpecimenGenerator.java

/**
 * @param eObject/*from   ww w  . jav  a 2 s.  com*/
 * @param indexByKind
 */
private void generateCrossReferences(EObject eObject, ListMultimap<EClass, EObject> indexByKind) {
    Iterable<EReference> eAllNonContainment = ePackagesData.eAllNonContainment(eObject.eClass());
    for (EReference eReference : eAllNonContainment) {
        EClass eReferenceType = eReference.getEReferenceType();
        IntegerDistribution distribution = c.getDistributionFor(eReference);

        if (eReference.isMany()) {
            List<Object> values = (List<Object>) eObject.eGet(eReference);
            int sample = distribution.sample();
            for (int i = 0; i < sample; i++) {
                List<EObject> possibleValues = indexByKind.get(eReferenceType);
                if (!possibleValues.isEmpty()) {
                    final EObject nextEObject = possibleValues.get(generator.nextInt(possibleValues.size()));
                    values.add(nextEObject);
                }
            }
        } else {
            if (booleanInDistribution(distribution)) {
                List<EObject> possibleValues = indexByKind.get(eReferenceType);
                if (!possibleValues.isEmpty()) {
                    final EObject nextEObject = possibleValues.get(generator.nextInt(possibleValues.size()));
                    eObject.eSet(eReference, nextEObject);
                }
            }
        }
    }
}

From source file:org.apache.drill.exec.expr.fn.registry.LocalFunctionRegistry.java

/**
 * Validates all functions, present in jars.
 * Will throw {@link FunctionValidationException} if:
 * <ol>//from www .  j  av a2s. c  om
 *  <li>Jar with the same name has been already registered.</li>
 *  <li>Conflicting function with the similar signature is found.</li>
 *  <li>Aggregating function is not deterministic.</li>
 *</ol>
 * @param jarName jar name to be validated
 * @param scanResult scan of all classes present in jar
 * @return list of validated function signatures
 */
public List<String> validate(String jarName, ScanResult scanResult) {
    List<String> functions = Lists.newArrayList();
    FunctionConverter converter = new FunctionConverter();
    List<AnnotatedClassDescriptor> providerClasses = scanResult.getAnnotatedClasses();

    if (registryHolder.containsJar(jarName)) {
        throw new JarValidationException(
                String.format("Jar with %s name has been already registered", jarName));
    }

    final ListMultimap<String, String> allFuncWithSignatures = registryHolder.getAllFunctionsWithSignatures();

    for (AnnotatedClassDescriptor func : providerClasses) {
        DrillFuncHolder holder = converter.getHolder(func, ClassLoader.getSystemClassLoader());
        if (holder != null) {
            String functionInput = holder.getInputParameters();

            String[] names = holder.getRegisteredNames();
            for (String name : names) {
                String functionName = name.toLowerCase();
                String functionSignature = String.format(functionSignaturePattern, functionName, functionInput);

                if (allFuncWithSignatures.get(functionName).contains(functionSignature)) {
                    throw new FunctionValidationException(String.format("Found duplicated function in %s: %s",
                            registryHolder.getJarNameByFunctionSignature(functionName, functionSignature),
                            functionSignature));
                } else if (holder.isAggregating() && !holder.isDeterministic()) {
                    throw new FunctionValidationException(String
                            .format("Aggregate functions must be deterministic: %s", func.getClassName()));
                } else {
                    functions.add(functionSignature);
                    allFuncWithSignatures.put(functionName, functionSignature);
                }
            }
        } else {
            logger.warn("Unable to initialize function for class {}", func.getClassName());
        }
    }
    return functions;
}

From source file:brooklyn.basic.BrooklynDynamicType.java

/**
 * Finds the config keys defined on the entity's class, statics and optionally any non-static (discouraged).
 * Prefers keys which overwrite other keys, and prefers keys which are lower in the hierarchy;
 * logs warnings if there are two conflicting keys which don't have an overwriting relationship.
 *//*w  w w .  j a  va2 s. c  o m*/
protected static void buildConfigKeys(Class<? extends BrooklynObject> clazz,
        AbstractBrooklynObject optionalInstance, Map<String, FieldAndValue<ConfigKey<?>>> configKeys) {
    ListMultimap<String, FieldAndValue<ConfigKey<?>>> configKeysAll = ArrayListMultimap
            .<String, FieldAndValue<ConfigKey<?>>>create();

    for (Field f : FlagUtils.getAllFields(clazz)) {
        boolean isConfigKey = ConfigKey.class.isAssignableFrom(f.getType());
        if (!isConfigKey) {
            if (!HasConfigKey.class.isAssignableFrom(f.getType())) {
                // neither ConfigKey nor HasConfigKey
                continue;
            }
        }
        if (!Modifier.isStatic(f.getModifiers())) {
            // require it to be static or we have an instance
            LOG.warn("Discouraged use of non-static config key " + f + " defined in "
                    + (optionalInstance != null ? optionalInstance : clazz));
            if (optionalInstance == null)
                continue;
        }
        try {
            Object v = f.get(optionalInstance);

            if (v == null) {
                LOG.warn("no value defined for config key field (skipping): " + f);
            } else {
                ConfigKey<?> k = isConfigKey ? (ConfigKey<?>) v : ((HasConfigKey<?>) v).getConfigKey();
                configKeysAll.put(k.getName(), new FieldAndValue<ConfigKey<?>>(f, k));
            }
        } catch (IllegalAccessException e) {
            LOG.warn("cannot access config key (skipping): " + f);
        }
    }
    LinkedHashSet<String> keys = new LinkedHashSet<String>(configKeysAll.keys());
    for (String kn : keys) {
        List<FieldAndValue<ConfigKey<?>>> kk = Lists.newArrayList(configKeysAll.get(kn));
        if (kk.size() > 1) {
            // remove anything which extends another value in the list
            for (FieldAndValue<ConfigKey<?>> k : kk) {
                ConfigKey<?> key = value(k);
                if (key instanceof BasicConfigKeyOverwriting) {
                    ConfigKey<?> parent = ((BasicConfigKeyOverwriting<?>) key).getParentKey();
                    // find and remove the parent from consideration
                    for (FieldAndValue<ConfigKey<?>> k2 : kk) {
                        if (value(k2) == parent)
                            configKeysAll.remove(kn, k2);
                    }
                }
            }
            kk = Lists.newArrayList(configKeysAll.get(kn));
        }
        // multiple keys, not overwriting; if their values are the same then we don't mind
        FieldAndValue<ConfigKey<?>> best = null;
        for (FieldAndValue<ConfigKey<?>> k : kk) {
            if (best == null) {
                best = k;
            } else {
                Field lower = Reflections.inferSubbestField(k.field, best.field);
                ConfigKey<? extends Object> lowerV = lower == null ? null
                        : lower.equals(k.field) ? k.value : best.value;
                if (best.value == k.value) {
                    // same value doesn't matter which we take (but take lower if there is one)
                    if (LOG.isTraceEnabled())
                        LOG.trace(
                                "multiple definitions for config key {} on {}; same value {}; "
                                        + "from {} and {}, preferring {}",
                                new Object[] { best.value.getName(),
                                        optionalInstance != null ? optionalInstance : clazz,
                                        best.value.getDefaultValue(), k.field, best.field, lower });
                    best = new FieldAndValue<ConfigKey<?>>(lower != null ? lower : best.field, best.value);
                } else if (lower != null) {
                    // different value, but one clearly lower (in type hierarchy)
                    if (LOG.isTraceEnabled())
                        LOG.trace(
                                "multiple definitions for config key {} on {}; "
                                        + "from {} and {}, preferring lower {}, value {}",
                                new Object[] { best.value.getName(),
                                        optionalInstance != null ? optionalInstance : clazz, k.field,
                                        best.field, lower, lowerV.getDefaultValue() });
                    best = new FieldAndValue<ConfigKey<?>>(lower, lowerV);
                } else {
                    // different value, neither one lower than another in hierarchy
                    LOG.warn(
                            "multiple ambiguous definitions for config key {} on {}; "
                                    + "from {} and {}, values {} and {}; " + "keeping latter (arbitrarily)",
                            new Object[] { best.value.getName(),
                                    optionalInstance != null ? optionalInstance : clazz, k.field, best.field,
                                    k.value.getDefaultValue(), best.value.getDefaultValue() });
                    // (no change)
                }
            }
        }
        if (best == null) {
            // shouldn't happen
            LOG.error("Error - no matching config key from " + kk + " in class " + clazz
                    + ", even though had config key name " + kn);
            continue;
        } else {
            configKeys.put(best.value.getName(), best);
        }
    }
}

From source file:com.mysema.query.jpa.hibernate.sql.AbstractHibernateSQLQuery.java

private Query createQuery(boolean forCount) {
    NativeSQLSerializer serializer = (NativeSQLSerializer) serialize(forCount);
    String queryString = serializer.toString();
    logQuery(queryString, serializer.getConstantToLabel());
    org.hibernate.SQLQuery query = session.createSQLQuery(queryString);
    // set constants
    HibernateUtil.setConstants(query, serializer.getConstantToLabel(), queryMixin.getMetadata().getParams());

    if (!forCount) {
        ListMultimap<Expression<?>, String> aliases = serializer.getAliases();
        Set<String> used = Sets.newHashSet();
        // set entity paths
        List<? extends Expression<?>> projection = queryMixin.getMetadata().getProjection();
        Expression<?> proj = projection.get(0);
        if (proj instanceof FactoryExpression) {
            for (Expression<?> expr : ((FactoryExpression<?>) proj).getArgs()) {
                if (isEntityExpression(expr)) {
                    query.addEntity(extractEntityExpression(expr).toString(), expr.getType());
                } else if (aliases.containsKey(expr)) {
                    for (String scalar : aliases.get(expr)) {
                        if (!used.contains(scalar)) {
                            query.addScalar(scalar);
                            used.add(scalar);
                            break;
                        }/*  w ww.j a  v a2s.com*/
                    }
                }
            }
        } else if (isEntityExpression(proj)) {
            query.addEntity(extractEntityExpression(proj).toString(), proj.getType());
        } else if (aliases.containsKey(proj)) {
            for (String scalar : aliases.get(proj)) {
                if (!used.contains(scalar)) {
                    query.addScalar(scalar);
                    used.add(scalar);
                    break;
                }
            }
        }

        // set result transformer, if projection is a FactoryExpression instance
        if (projection.size() == 1 && proj instanceof FactoryExpression) {
            query.setResultTransformer(new FactoryExpressionTransformer((FactoryExpression<?>) proj));
        }
    }

    if (fetchSize > 0) {
        query.setFetchSize(fetchSize);
    }
    if (timeout > 0) {
        query.setTimeout(timeout);
    }
    if (cacheable != null) {
        query.setCacheable(cacheable);
    }
    if (cacheRegion != null) {
        query.setCacheRegion(cacheRegion);
    }
    if (readOnly != null) {
        query.setReadOnly(readOnly);
    }
    return query;
}

From source file:org.terasology.world.generation.WorldBuilder.java

private void determineProviderChainFor(Class<? extends WorldFacet> facet,
        ListMultimap<Class<? extends WorldFacet>, FacetProvider> result) {
    if (result.containsKey(facet)) {
        return;/* w ww  .jav a 2 s .  c o m*/
    }
    if (!facetCalculationInProgress.add(facet)) {
        throw new RuntimeException(
                "Circular dependency detected when calculating facet provider ordering for " + facet);
    }
    Set<FacetProvider> orderedProviders = Sets.newLinkedHashSet();
    for (FacetProvider provider : providersList) {
        if (producesFacet(provider, facet)) {
            Requires requirements = provider.getClass().getAnnotation(Requires.class);
            if (requirements != null) {
                for (Facet requirement : requirements.value()) {
                    determineProviderChainFor(requirement.value(), result);
                    orderedProviders.addAll(result.get(requirement.value()));
                }
            }
            orderedProviders.add(provider);
        }
        result.putAll(facet, orderedProviders);
        facetCalculationInProgress.remove(facet);
    }
}

From source file:com.google.devtools.j2objc.translate.UnsequencedExpressionRewriter.java

private List<VariableAccess> getUnsequencedAccesses() {
    if (!hasModification) {
        return Collections.emptyList();
    }/*w  w w  .j  ava  2 s  . c  o m*/
    ListMultimap<IVariableBinding, VariableAccess> accessesByVar = ArrayListMultimap.create();
    for (VariableAccess access : orderedAccesses) {
        accessesByVar.put(access.variable, access);
    }
    Set<VariableAccess> unsequencedAccesses = Sets.newHashSet();
    for (IVariableBinding var : accessesByVar.keySet()) {
        findUnsequenced(accessesByVar.get(var), unsequencedAccesses);
    }
    List<VariableAccess> orderedUnsequencedAccesses = Lists
            .newArrayListWithCapacity(unsequencedAccesses.size());
    for (VariableAccess access : orderedAccesses) {
        if (unsequencedAccesses.contains(access)) {
            orderedUnsequencedAccesses.add(access);
        }
    }
    return orderedUnsequencedAccesses;
}

From source file:eu.esdihumboldt.hale.ui.functions.core.SourceListParameterPage.java

/**
 * @see ParameterPage#setParameter(Set, ListMultimap)
 *///from ww w.  jav  a2 s . com
@Override
public void setParameter(Set<FunctionParameterDefinition> params,
        ListMultimap<String, ParameterValue> initialValues) {
    for (FunctionParameterDefinition param : params) {
        if (param.getName().equals(getParameterName())) {
            String description = param.getDescription();
            if (description != null) {
                setMessage(description);
            }
            String displayName = param.getDisplayName();
            if (displayName != null) {
                setTitle(displayName);
            }
            break;
        }
    }

    if (initialValues != null) {
        List<ParameterValue> initialData = initialValues.get(getParameterName());
        if (initialData.size() > 0)
            initialValue = initialData.get(0).as(String.class);
    }
}