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

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

Introduction

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

Prototype

Collection<V> values();

Source Link

Document

Returns a view collection containing the value from each key-value pair contained in this multimap, without collapsing duplicates (so values().size() == size() ).

Usage

From source file:de.itemis.xcore2java.XcoreReader.java

@Override
protected void invokeInternal(WorkflowContext ctx, ProgressMonitor monitor, Issues issues) {
    ResourceSet resourceSet = getResourceSet();

    // due to some Xcore peculiarity we have to access the IAllContainerState here
    // to trigger some lazy init logic
    IAllContainersState allContainerState = (IAllContainersState) EcoreUtil.getAdapter(resourceSet.eAdapters(),
            IAllContainersState.class);
    allContainerState.isEmpty("");

    Multimap<String, URI> uris = getPathTraverser().resolvePathes(pathes, new Predicate<URI>() {
        @Override//  w w  w  . j a va2  s.co m
        public boolean apply(URI input) {
            return input.fileExtension().equals(XCORE_FILE_EXT);
        }
    });
    List<Resource> resources = new ArrayList<>();
    for (URI uri : uris.values()) {
        logger.info(uri);
        try {
            resources.add(parse(uri, resourceSet));
        } catch (Exception e) {
            logger.error("Problem during loading of resource @ " + uri, e);
        }
    }
    installIndex(resourceSet);
    for (Resource r : resources) {
        EcoreUtil.resolveAll(r);
        for (Diagnostic x : r.getErrors()) {
            issues.addError(x.getMessage(), x);
        }

    }
    ctx.set(slot, resources);
}

From source file:com.cinchapi.concourse.server.storage.db.SearchRecord.java

/**
 * Return the Set of primary keys for records that match {@code query}.
 * //from   www  .j  a v  a  2s  . c o  m
 * @param query
 * @return the Set of PrimaryKeys
 */
public Set<PrimaryKey> search(Text query) {
    read.lock();
    try {
        Multimap<PrimaryKey, Integer> reference = HashMultimap.create();
        String[] toks = query.toString().toLowerCase()
                .split(TStrings.REGEX_GROUP_OF_ONE_OR_MORE_WHITESPACE_CHARS);
        boolean initial = true;
        int offset = 0;
        for (String tok : toks) {
            Multimap<PrimaryKey, Integer> temp = HashMultimap.create();
            if (STOPWORDS.contains(tok)) {
                // When skipping a stop word, we must record an offset to
                // correctly determine if the next term match is in the
                // correct relative position to the previous term match
                ++offset;
                continue;
            }
            Set<Position> positions = get(Text.wrap(tok));
            for (Position position : positions) {
                PrimaryKey key = position.getPrimaryKey();
                int pos = position.getIndex();
                if (initial) {
                    temp.put(key, pos);
                } else {
                    for (int current : reference.get(key)) {
                        if (pos == current + 1 + offset) {
                            temp.put(key, pos);
                        }
                    }
                }
            }
            initial = false;
            reference = temp;
            offset = 0;
        }

        // Result Scoring: Scoring is simply the number of times the query
        // appears in a document [e.g. the number of Positions mapped from
        // key: #reference.get(key).size()]. The total number of positions
        // in #reference is equal to the total number of times a document
        // appears in the corpus [e.g. reference.asMap().values().size()].
        Multimap<Integer, PrimaryKey> sorted = TreeMultimap.create(Collections.<Integer>reverseOrder(),
                PrimaryKey.Sorter.INSTANCE);
        for (Entry<PrimaryKey, Collection<Integer>> entry : reference.asMap().entrySet()) {
            sorted.put(entry.getValue().size(), entry.getKey());
        }
        return Sets.newLinkedHashSet(sorted.values());
    } finally {
        read.unlock();
    }
}

From source file:org.xacml4j.v30.pdp.PolicySet.java

/**
 * Gets all combiner parameters for a given policy set identifier
 *
 * @param policySetId a policy set identifier
 * @return a collection of combiner parameters
 *///from   w w  w.  j av a 2s . c om
public Collection<CombinerParameter> getPolicySetCombinerParams(String policySetId) {
    Multimap<String, CombinerParameter> p = policySetCombinerParameters.get(policySetId);
    return (p == null) ? ImmutableList.<CombinerParameter>of() : p.values();
}

From source file:eu.uqasar.util.UQasarUtil.java

/**
 * Traverse the tree in postorder and update tree values
 * @param node//  w ww.j a v a  2s .  com
 */
private static void postorderWithParticularNode(TreeNode node, TreeNode projectTreeNode) {

    if (node == null) {
        return;
    }

    if (projectTreeNode == null) {
        return;
    }

    logger.debug("------------postorder: " + projectTreeNode.getName() + "---------------");

    logger.debug("Traversing project tree in postorder..." + projectTreeNode.toString());
    // Update the value
    try {
        InitialContext ic = new InitialContext();
        AdapterDataService adapterDataService = new AdapterDataService();
        TreeNodeService treeNodeService = (TreeNodeService) ic.lookup("java:module/TreeNodeService");

        if (projectTreeNode instanceof Metric) {
            Metric metric = (Metric) projectTreeNode;
            logger.debug("Recomputing the value of the Metric " + projectTreeNode);
            Float value = null;
            if (metric.getMetricSource() == MetricSource.Manual) {
                metric.updateQualityStatus();
            } else {
                value = adapterDataService.getMetricValue(metric.getMetricSource(), metric.getMetricType(),
                        metric.getProject());
                metric.setValue(value);
            }
            metric.setLastUpdated(getLatestTreeUpdateDate());
            metric.addHistoricValue();
            // End Metric node treatment 
        } else if (projectTreeNode instanceof QualityIndicator) {
            logger.info("Recomputing the value of the Quality Indicator " + projectTreeNode);
            QualityIndicator qi = (QualityIndicator) projectTreeNode;
            if (qi.getUseFormula()) {
                String formulaToEval = Formula.parseFormula(qi.getViewFormula());
                if (formulaToEval != null && !formulaToEval.isEmpty()) {

                    Float computedValue = Formula.evalFormula(formulaToEval);
                    if (computedValue != null && !computedValue.isNaN()) {
                        qi.setValue(computedValue);
                        qi.setLastUpdated(getLatestTreeUpdateDate());
                        treeNodeService.update(qi);
                    }

                }
            } else {
                float achieved = 0;
                float denominator = 0;
                for (final TreeNode me : qi.getChildren()) {
                    float weight = ((Metric) me).getWeight();
                    if (me.getQualityStatus() == QualityStatus.Green) {
                        achieved += weight;
                    }
                    denominator += weight;
                }
                if (denominator == 0)
                    qi.getChildren().size();
                qi.setValue(achieved * 100 / denominator);
            }
            qi.setLastUpdated(getLatestTreeUpdateDate());
            qi.addHistoricValue();
            // End Q.Indicator node treatment 
        } else if (projectTreeNode instanceof QualityObjective) {
            logger.info("Recomputing the value of the Quality Objective " + projectTreeNode);
            QualityObjective qo = (QualityObjective) projectTreeNode;
            if (qo.getUseFormula()) {
                String formulaToEval = Formula.parseFormula(qo.getViewFormula());
                if (formulaToEval != null && !formulaToEval.isEmpty()) {

                    Float computedValue = Formula.evalFormula(formulaToEval);
                    if (computedValue != null && !computedValue.isNaN()) {
                        qo.setValue(computedValue);
                        qo.setLastUpdated(getLatestTreeUpdateDate());
                    }

                }
            } else {
                float denominator = 0;
                float achieved = 0;
                for (final TreeNode qi : qo.getChildren()) {
                    float weight = ((QualityIndicator) qi).getWeight();
                    if (qi.getQualityStatus() == QualityStatus.Green) {
                        achieved += weight;
                    }
                    denominator += weight;
                }
                qo.setValue(achieved * 100 / denominator);
            }
            qo.setLastUpdated(getLatestTreeUpdateDate());
            qo.addHistoricValue();
            // End Quality Objective node treatment 
        } else if (projectTreeNode instanceof Project) {
            logger.info("Recomputing the value of the Project " + projectTreeNode);
            Project prj = (Project) projectTreeNode;
            double qoValueSum = 0;
            double denominator = 0;
            for (Object o : projectTreeNode.getChildren()) {
                QualityObjective qo = (QualityObjective) o;
                if (qo.getWeight() == 0) {
                    continue;
                }
                qoValueSum += qo.getValue() * (prj.isFormulaAverage() ? qo.getWeight() : 1);
                denominator += prj.isFormulaAverage() ? qo.getWeight() : 1;
            }

            // bad idea to divide something under 0
            if (denominator == 0) {
                denominator = 1;
            }

            Double computedValue = qoValueSum / denominator;

            if (computedValue != null && !computedValue.isNaN() && !computedValue.isInfinite()) {
                prj.setValue(computedValue);
            }

            prj.setLastUpdated(getLatestTreeUpdateDate());
            prj.addHistoricValue();
            logger.debug(" [" + qoValueSum + "] denominator [" + denominator + "] " + computedValue);
            // End Project node treatment 
        }

        // Get a (possible) suggestion for the tree node
        Multimap<?, ?> suggestions = getSuggestionForNode(projectTreeNode);
        //TODO: take all the suggestions into account
        Object[] types = suggestions.keys().toArray();
        Object[] suggestionsValues = suggestions.values().toArray();
        if (types.length > 0) {
            // for now use the first item as suggestion
            SuggestionType stype = (SuggestionType) types[0];
            projectTreeNode.setSuggestionType(stype);
            if (suggestionsValues[0] != null && !suggestionsValues[0].equals("")) {
                projectTreeNode.setSuggestionValue((String) suggestionsValues[0]);
            }
        }

        treeNodeService.update(projectTreeNode);

    } catch (NamingException e) {
        e.printStackTrace();
    }

    // Iterate the node children
    TreeNode nodeChild = projectTreeNode.getParent();
    UQasarUtil.postorderWithParticularNode(projectTreeNode, nodeChild);

    return;
}

From source file:org.cinchapi.concourse.server.storage.db.SearchRecord.java

/**
 * Return the Set of primary keys for records that match {@code query}.
 * /*from  w  w  w.j  ava2  s. c o m*/
 * @param query
 * @return the Set of PrimaryKeys
 */
public Set<PrimaryKey> search(Text query) {
    read.lock();
    try {
        Multimap<PrimaryKey, Integer> reference = HashMultimap.create();
        String[] toks = query.toString().toLowerCase()
                .split(TStrings.REGEX_GROUP_OF_ONE_OR_MORE_WHITESPACE_CHARS);
        boolean initial = true;
        int offset = 0;
        for (String tok : toks) {
            Multimap<PrimaryKey, Integer> temp = HashMultimap.create();
            if (STOPWORDS.contains(tok)) {
                // When skipping a stop word, we must record an offset to
                // correctly determine if the next term match is in the
                // correct relative position to the previous term match
                offset++;
                continue;
            }
            Set<Position> positions = get(Text.wrap(tok));
            for (Position position : positions) {
                PrimaryKey key = position.getPrimaryKey();
                int pos = position.getIndex();
                if (initial) {
                    temp.put(key, pos);
                } else {
                    for (int current : reference.get(key)) {
                        if (pos == current + 1 + offset) {
                            temp.put(key, pos);
                        }
                    }
                }
            }
            initial = false;
            reference = temp;
            offset = 0;
        }

        // Result Scoring: Scoring is simply the number of times the query
        // appears in a document [e.g. the number of Positions mapped from
        // key: #reference.get(key).size()]. The total number of positions
        // in #reference is equal to the total number of times a document
        // appears in the corpus [e.g. reference.asMap().values().size()].
        Multimap<Integer, PrimaryKey> sorted = TreeMultimap.create(Collections.<Integer>reverseOrder(),
                PrimaryKey.Sorter.INSTANCE);
        for (Entry<PrimaryKey, Collection<Integer>> entry : reference.asMap().entrySet()) {
            sorted.put(entry.getValue().size(), entry.getKey());
        }
        return Sets.newLinkedHashSet(sorted.values());
    } finally {
        read.unlock();
    }
}

From source file:dmg.util.command.TextHelpPrinter.java

private String getSignature(Class<?> clazz) {
    StringBuilder signature = new StringBuilder();

    Multimap<String, Field> options = AnnotatedCommandUtils.getOptionsByCategory(clazz);
    for (Field field : options.values()) {
        Class<?> type = field.getType();
        Option option = field.getAnnotation(Option.class);
        if (option != null) {
            if (!type.isArray()) {
                if (!option.required()) {
                    signature.append("[");
                }//  ww w.jav  a  2 s  .c  o  m

                signature.append(literal("-" + option.name()));

                if (!Boolean.class.equals(type) && !Boolean.TYPE.equals(type)) {
                    signature.append("=").append(getMetaVar(type, option));
                }

                if (!option.required()) {
                    signature.append("]");
                }
            } else if (option.separator().isEmpty()) {
                if (!option.required()) {
                    signature.append("[");
                }

                signature.append(literal("-" + option.name()));
                signature.append("=").append(getMetaVar(type.getComponentType(), option));

                if (!option.required()) {
                    signature.append("]");
                }
                signature.append(value("..."));
            } else {
                if (!option.required()) {
                    signature.append("[");
                }

                String metaVar = getMetaVar(type.getComponentType(), option);
                signature.append(literal("-" + option.name()));
                signature.append("=").append(metaVar);
                signature.append("[").append(option.separator()).append(metaVar).append("]")
                        .append(value("..."));

                if (!option.required()) {
                    signature.append("]").append(value("..."));
                }
            }
            signature.append(" ");
        }
        CommandLine commandLine = field.getAnnotation(CommandLine.class);
        if (commandLine != null && commandLine.allowAnyOption()) {
            signature.append(valuespec(commandLine.valueSpec())).append(" ");
        }
    }

    for (Field field : AnnotatedCommandUtils.getArguments(clazz)) {
        Argument argument = field.getAnnotation(Argument.class);
        String metaVar = getMetaVar(field, argument);
        if (argument.required()) {
            signature.append(metaVar);
        } else {
            signature.append("[").append(metaVar).append("]");
        }
        if (field.getType().isArray()) {
            signature.append("...");
        }
        signature.append(" ");
    }

    return signature.toString();
}

From source file:org.eclipse.emf.mwe2.language.validation.Mwe2JavaValidator.java

@Check
public void checkReferables(Module referable) {
    TreeIterator<EObject> iterator = referable.eResource().getAllContents();
    Set<String> referenced = Sets.newHashSet();
    Multimap<String, Referrable> declared = HashMultimap.create();
    while (iterator.hasNext()) {
        EObject next = iterator.next();//  w  w w  .  j a  va  2s .co  m
        if (next instanceof Referrable) {
            String name = ((Referrable) next).getName();
            if (name != null) {
                declared.put(name, (Referrable) next);
            }
        } else if (next instanceof AbstractReference) {
            referenced.add(((AbstractReference) next).getReferable().getName());
        }
        if (next instanceof Component) {
            Component component = (Component) next;
            if (component.isAutoInject()) {
                Set<String> featureNames = collectFeatureNames(component);
                Set<String> explicitlyAssignedFeature = Sets.newHashSet();
                for (Assignment assignment : component.getAssignment()) {
                    explicitlyAssignedFeature.add(assignment.getFeatureName());
                }
                featureNames.removeAll(explicitlyAssignedFeature);
                featureNames.retainAll(declared.keySet());
                referenced.addAll(featureNames);
            }
        }
    }
    Multimap<String, Referrable> copy = HashMultimap.create(declared);
    copy.keySet().removeAll(referenced);
    for (Referrable referrable : copy.values()) {
        warning("The var '" + referrable.getName() + "' is never read locally.", referrable,
                Mwe2Package.Literals.REFERRABLE__NAME, ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
                UNUSED_LOCAL);
    }
    for (String name : declared.keySet()) {
        Collection<Referrable> collection = declared.get(name);
        if (collection.size() > 1) {
            for (Referrable referrable : collection) {
                error("Duplicate var '" + referrable.getName() + "'.", referrable,
                        Mwe2Package.Literals.REFERRABLE__NAME, ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
                        DUPLICATE_LOCAL);
            }
        }
    }
}

From source file:to.lean.tools.gmail.importer.gmail.GmailSyncer.java

/**
 * Synchronizes the given list of messages with Gmail. When this operation
 * completes, all of the messages will appear in Gmail with the same labels
 * (folers) that they have in the local store. The message state, including
 * read/unread, will also be synchronized, but might not match exactly if
 * the message is already in Gmail./*from  w  w w .  ja  v  a2s  . c om*/
 *
 * <p>Note that some errors can prevent some messages from being uploaded.
 * In this case, the failure policy dictates what happens.
 *
 * @param messages the list of messages to synchronize. These messages may
 *     or may not already exist in Gmail.
 * @throws IOException if something goes wrong with the connection
 */
public void sync(List<LocalMessage> messages) throws IOException {
    Preconditions.checkState(initialized, "GmailSyncer.init() must be called first");
    Multimap<LocalMessage, Message> map = mailbox.mapMessageIds(messages);
    messages.stream().filter(message -> !map.containsKey(message)).forEach(message -> {
        try {
            Message gmailMessage = mailbox.uploadMessage(message);
            map.put(message, gmailMessage);
        } catch (GoogleJsonResponseException e) {
            // Message couldn't be uploaded, but we know why
        }
    });
    mailbox.fetchExistingLabels(map.values());
    mailbox.syncLocalLabelsToGmail(map);
}

From source file:com.android.tools.idea.gradle.structure.configurables.android.dependencies.module.treeview.DependencyNodes.java

@NotNull
static List<AbstractPsModelNode<?>> createNodesFor(@NotNull AndroidArtifactNode parent,
        @NotNull Collection<PsDependency> dependencies) {
    List<AbstractPsModelNode<?>> children = Lists.newArrayList();

    List<PsDependency> declared = new SortedList<>(PsDependencyComparator.INSTANCE);
    Multimap<PsDependency, PsDependency> allTransitive = HashMultimap.create();
    List<PsDependency> mayBeTransitive = Lists.newArrayList();

    for (PsDependency dependency : dependencies) {
        Collection<DependencyModel> parsedModels = dependency.getParsedModels();
        if (parsedModels.isEmpty()) {
            mayBeTransitive.add(dependency);
        } else {/*from  w  ww.ja  v a  2 s.co  m*/
            for (DependencyModel parsedModel : parsedModels) {
                // In Android Libraries, the model will include artifacts declared in the "main" artifact in other artifacts as well. For example:
                //   compile 'com.android.support:appcompat-v7:23.0.1'
                // will be include as a dependency in "main", "android test" and "unit test" artifacts. Even though this is correct, it is
                // inconsistent with what Android App models return. In the case of Android Apps, 'appcompat' will be included only in the
                // "main" artifact.
                for (PsAndroidArtifact artifact : parent.getModels()) {
                    if (artifact.contains(parsedModel)) {
                        declared.add(dependency);
                        break;
                    }
                }
            }
            addTransitive(dependency, allTransitive);
        }
    }

    Collection<PsDependency> uniqueTransitives = allTransitive.values();
    declared.addAll(mayBeTransitive.stream().filter(dependency -> !uniqueTransitives.contains(dependency))
            .collect(Collectors.toList()));

    for (PsDependency dependency : declared) {
        AbstractDependencyNode<?> child = AbstractDependencyNode.createNode(parent, dependency);
        if (child != null) {
            children.add(child);
        }
    }

    return children;
}

From source file:org.spongepowered.despector.ast.type.TypeEntry.java

protected MethodEntry findMethod(String name, String sig, Multimap<String, MethodEntry> map) {
    for (MethodEntry m : map.values()) {
        if (m.getName().equals(name) && m.getSignature().equals(sig)) {
            return m;
        }/*from   w w w.j  a  va  2s.c o m*/
    }
    //        if (this.actual_class != null) {
    //            List<TypeEntry> params = Lists.newArrayList();
    //            for (String param : TypeHelper.splitSig(sig)) {
    //                params.add(this.set.get(TypeHelper.descToType(param)));
    //            }
    //            Class<?>[] args = new Class<?>[params.size()];
    //            for (int i = 0; i < args.length; i++) {
    //                args[i] = params.get(i).getActualClass();
    //            }
    //            if ("<init>".equals(name)) {
    //                try {
    //                    Constructor<?> ctor = this.actual_class.getConstructor(args);
    //                    MethodEntry dummy = new MethodEntry(this, AccessModifier.fromModifiers(ctor.getModifiers()), name, sig, false);
    //                    dummy.setReturnType(ClasspathSourceSet.void_t);
    //                    this.methods.put(name, dummy);
    //                    return dummy;
    //                } catch (NoSuchMethodException | SecurityException e) {
    //                    // TODO cache failures
    //                }
    //                MethodEntry dummy = new MethodEntry(this, AccessModifier.PACKAGE_PRIVATE, name, sig, false);
    //                dummy.setReturnType(ClasspathSourceSet.void_t);
    //                this.methods.put(name, dummy);
    //                return dummy;
    //            }
    //            try {
    //                Method method = this.actual_class.getDeclaredMethod(name, args);
    //                MethodEntry dummy = new MethodEntry(this, AccessModifier.fromModifiers(method.getModifiers()), name, sig,
    //                        Modifier.isStatic(method.getModifiers()));
    //                dummy.setReturnType(this.set.get(Type.getInternalName(method.getReturnType())));
    //                if (Modifier.isStatic(method.getModifiers())) {
    //                    this.static_methods.put(name, dummy);
    //                } else {
    //                    this.methods.put(name, dummy);
    //                }
    //                return dummy;
    //            } catch (NoSuchMethodException | SecurityException e) {
    //                e.printStackTrace();
    //            }
    //        }
    //        if (name.equals("clone") && sig.equals("()Ljava/lang/Object;")) {
    //            MethodEntry dummy = new MethodEntry(this, AccessModifier.PUBLIC, name, sig, false);
    //            dummy.setReturnType(ClasspathSourceSet.object_t);
    //            this.methods.put(name, dummy);
    //            return dummy;
    //        } else if (getClass() == EnumEntry.class) {
    //            if (name.equals("ordinal") && sig.equals("()I")) {
    //                MethodEntry dummy = new MethodEntry(this, AccessModifier.PUBLIC, name, sig, false);
    //                dummy.setReturnType(ClasspathSourceSet.int_t);
    //                this.methods.put(name, dummy);
    //                return dummy;
    //            }
    //        }
    return null;
}