Example usage for com.google.common.collect Multiset add

List of usage examples for com.google.common.collect Multiset add

Introduction

In this page you can find the example usage for com.google.common.collect Multiset add.

Prototype

@Override
boolean add(E element);

Source Link

Document

Adds a single occurrence of the specified element to this multiset.

Usage

From source file:org.sonar.plugins.qi.AbstractViolationsDecorator.java

/**
 * Counts the number of violation by priority
 *
 * @param context the context/*  w  w w .  ja v a 2  s . com*/
 * @return a multiset of priority count
 */
protected Multiset<RulePriority> countViolationsBySeverity(DecoratorContext context) {
    List<Violation> violations = context.getViolations();
    Multiset<RulePriority> violationsBySeverity = HashMultiset.create();

    for (Violation violation : violations) {
        if (violation.getRule().getPluginName().equals(getPluginKey())) {
            violationsBySeverity.add(violation.getSeverity());
        }
    }
    return violationsBySeverity;
}

From source file:org.mule.runtime.extension.internal.loader.validator.ConnectionProviderNameModelValidator.java

@Override
public void validate(ExtensionModel model, ProblemsReporter problemsReporter)
        throws IllegalModelDefinitionException {
    Multiset<String> names = HashMultiset.create();
    Set<ConnectionProviderModel> models = new HashSet<>();
    new IdempotentExtensionWalker() {

        @Override/*from www . j a  va 2s  . c  o m*/
        public void onConnectionProvider(ConnectionProviderModel model) {
            models.add(model);
            names.add(model.getName());
        }
    }.walk(model);

    Set<ConnectionProviderModel> repeatedNameModels = models.stream()
            .filter(cp -> names.count(cp.getName()) > 1).collect(toSet());

    if (!repeatedNameModels.isEmpty()) {
        problemsReporter.addError(new Problem(model,
                format("There are %d connection providers with repeated names. Offending names are: [%s]",
                        repeatedNameModels.size(),
                        repeatedNameModels.stream().map(NamedObject::getName).collect(joining(",")))));
    }
}

From source file:qa.qcri.nadeef.core.pipeline.EquivalentClass.java

/**
 * {@inheritDoc}//from   w  w w . ja  v  a2  s.  c  o  m
 */
@Override
public Collection<Fix> decide(Collection<Fix> fixes) {
    List<HashSet<Cell>> clusters = Lists.newArrayList();
    // a map between a cell and n
    HashMap<Cell, HashSet<Cell>> clusterMap = Maps.newHashMap();
    HashMap<Cell, String> assignMap = Maps.newHashMap();
    // a map between cell and fix, used for getting the original vid.
    HashMap<Cell, Fix> fixMap = Maps.newHashMap();

    // Clustering all the fixes.
    int count = 0;
    for (Fix fix : fixes) {
        Cell leftCell = fix.getLeft();
        fixMap.put(leftCell, fix);

        if (fix.isRightConstant()) {
            // TODO: do a statistic on the assign count.
            assignMap.put(leftCell, fix.getRightValue());
            continue;
        }

        Cell rightCell = fix.getRight();
        fixMap.put(rightCell, fix);
        if (assignMap.containsKey(leftCell)) {
            assignMap.remove(leftCell);
        }

        if (assignMap.containsKey(rightCell)) {
            assignMap.remove(rightCell);
        }

        HashSet<Cell> leftCluster = null;
        HashSet<Cell> rightCluster = null;

        // when the left column is already in a cluster
        if (clusterMap.containsKey(leftCell)) {
            leftCluster = clusterMap.get(leftCell);
            if (!leftCluster.contains(rightCell)) {
                // union of two cluster of cell sets.
                if (clusterMap.containsKey(rightCell)) {
                    rightCluster = clusterMap.get(rightCell);
                    for (Cell cell : rightCluster) {
                        leftCluster.add(cell);
                        clusterMap.put(cell, leftCluster);
                    }

                    rightCluster.clear();
                    clusters.remove(rightCluster);
                } else {
                    clusterMap.put(rightCell, leftCluster);
                    leftCluster.add(rightCell);
                }
            }
        } else if (clusterMap.containsKey(rightCell)) {
            // when the right column is already in the cluster
            rightCluster = clusterMap.get(rightCell);
            if (!rightCluster.contains(leftCell)) {
                // union of two cluster of cell sets.
                if (clusterMap.containsKey(leftCell)) {
                    leftCluster = clusterMap.get(leftCell);
                    for (Cell cell : leftCluster) {
                        rightCluster.add(cell);
                        clusterMap.put(cell, rightCluster);
                    }

                    for (Cell cell : leftCluster) {
                        leftCluster.remove(cell);
                    }

                    clusters.remove(leftCluster);
                } else {
                    clusterMap.put(leftCell, rightCluster);
                    rightCluster.add(leftCell);
                }
            }
        } else {
            // both left and right are not in any of the cluster
            // create a new cluster of containing both.
            HashSet<Cell> cluster = Sets.newHashSet();
            cluster.add(leftCell);
            cluster.add(rightCell);
            clusterMap.put(leftCell, cluster);
            clusterMap.put(rightCell, cluster);
            clusters.add(cluster);
        }
    }

    // start to count each cluster and decide the final fix based on
    // percentage.
    List<Fix> result = Lists.newArrayList();
    // for final execution of all the fixes, we use 0 as default as the fix id.
    Fix.Builder fixBuilder = new Fix.Builder();
    count = 0;
    for (HashSet<Cell> cluster : clusters) {
        Multiset<Object> countSet = HashMultiset.create();
        for (Cell cell : cluster) {
            countSet.add(cell.getValue());
        }

        countSet = Multisets.copyHighestCountFirst(countSet);
        Object value = countSet.iterator().next();
        for (Cell cell : cluster) {
            if (cell.getValue().equals(value)) {
                // skip the correct value.
                continue;
            }
            Fix originalFix = fixMap.get(cell);
            Fix newFix = fixBuilder.vid(originalFix.getVid()).left(cell).right(value.toString()).build();
            result.add(newFix);
        }
        count++;
    }

    // collect the remaining constant assign fix.
    Set<Map.Entry<Cell, String>> entries = assignMap.entrySet();
    for (Map.Entry<Cell, String> entry : entries) {
        Fix newFix = fixBuilder.left(entry.getKey()).right(entry.getValue()).build();
        result.add(newFix);
    }

    setPercentage(1.0f);
    return result;
}

From source file:annis.ql.parser.SemanticValidator.java

public void checkAlternative(QueryData data, List<QueryNode> alternative, int alternativeIndex) {
    // check if there is at least one search expression
    if (alternative.isEmpty()) {
        throw new AnnisQLSemanticsException("Missing search expression.");
    }/*from  ww w .  j a va 2  s  . co m*/

    // there are not linguistic binary relations allowed if there is only one node
    if (alternative.size() == 1) {
        QueryNode n = alternative.get(0);
        for (Join j : n.getOutgoingJoins()) {
            if (j.getTarget() != null) {
                throw new AnnisQLSemanticsException(
                        "No binary linguistic relations allowed if there is only one node in query.");
            }
        }
    }

    // get all nodes connected to the first one
    Multimap<Long, QueryNode> connected = calculateConnected(alternative);
    Set<Long> transitiveHull = new HashSet<>();
    transitiveHull.add(alternative.get(0).getId());
    createTransitiveHull(alternative.get(0), connected, transitiveHull);

    Multiset<String> variableNames = TreeMultiset.create();

    Set<Long> unconnectedNodes = new HashSet<>();
    for (QueryNode n : alternative) {
        unconnectedNodes.add(n.getId());
        variableNames.add(n.getVariable());
    }
    unconnectedNodes.removeAll(transitiveHull);

    // check if each node is contained in the connected nodes
    if (!unconnectedNodes.isEmpty()) {
        List<String> variables = new LinkedList<>();
        for (QueryNode n : alternative) {
            if (unconnectedNodes.contains(n.getId())) {
                variables.add(n.getVariable());
            }
        }

        if (alternative.size() == 1) {
            throw new AnnisQLSemanticsException("Variable(s) [" + Joiner.on(",").join(variables)
                    + "] not bound (use linguistic operators).");
        } else {
            throw new AnnisQLSemanticsException("Variable(s) [" + Joiner.on(",").join(variables)
                    + "] not bound in alternative " + alternativeIndex + "(use linguistic operators). "
                    + "Normalized query is: \n" + data.toAQL());
        }
    }

    // check if any variable name was given more than once
    List<String> invalidNames = new LinkedList<>();
    for (Multiset.Entry<String> e : variableNames.entrySet()) {
        if (e.getCount() > 1) {
            invalidNames.add(e.getElement());
        }
    }
    if (!invalidNames.isEmpty()) {
        throw new AnnisQLSemanticsException(
                "The following variable names are " + "used for more than one node: "
                        + Joiner.on(", ").join(invalidNames) + "\nNormalized Query is: \n" + data.toAQL());
    }
}

From source file:org.carrot2.text.clustering.MultilingualClustering.java

private List<Cluster> clusterInMajorityLanguage(List<Document> documents,
        IMonolingualClusteringAlgorithm algorithm) {
    final Multiset<LanguageCode> counts = HashMultiset.create();
    for (Document d : documents) {
        counts.add(d.getLanguage());
    }/*from  w w w  . j  av  a2 s. c o  m*/
    LanguageCode majorityLanguage = defaultLanguage;
    int maxCount = 0;
    for (Entry<LanguageCode> entry : counts.entrySet()) {
        if (entry.getElement() != null) {
            if (entry.getCount() > maxCount) {
                maxCount = entry.getCount();
                majorityLanguage = entry.getElement();
                this.majorityLanguage = entry.getElement().getIsoCode();
            }
        }
        languageCounts.put(entry.getElement() != null ? entry.getElement().getIsoCode() : "", entry.getCount());
    }

    logger.debug("Performing clustering in majority language: " + majorityLanguage);
    final List<Cluster> clusters = algorithm.process(documents, majorityLanguage);
    Cluster.appendOtherTopics(documents, clusters);
    return clusters;
}

From source file:org.opennms.features.jmxconfiggenerator.webui.ui.validators.UniqueAttributeNameValidator.java

@Override
protected boolean isValidValue(String value) {
    if (value == null || !(value instanceof String))
        return false; //validation not possible
    String alias = (String) value;
    //count name occurance
    Multiset<String> nameMultiSet = HashMultiset.create();
    for (Entry<Object, String> entry : provider.getNames().entrySet()) {
        Object itemId = entry.getKey();
        String name = entry.getValue();
        //use name from textFieldItemMap if an entry for itemId exists, otherwise use name from provider
        nameMultiSet.add(
                textFieldItemMap.get(itemId) == null ? name : (String) textFieldItemMap.get(itemId).getValue());
    }/*from   w ww. j  a v a 2s .c  o m*/
    return nameMultiSet.count(alias) <= 1; //is only valid if name exists 0 or 1 times 
}

From source file:org.immutables.value.processor.meta.ValueTypeComposer.java

private void checkAttributeNamesForDuplicates(ValueType type, Protoclass protoclass) {
    if (!type.attributes.isEmpty()) {
        Multiset<String> attributeNames = HashMultiset.create(type.attributes.size());
        for (ValueAttribute attribute : type.attributes) {
            attributeNames.add(attribute.name());
        }//from   www . j  av  a 2s  .  co  m

        List<String> duplicates = Lists.newArrayList();
        for (Multiset.Entry<String> entry : attributeNames.entrySet()) {
            if (entry.getCount() > 1) {
                duplicates.add(entry.getElement());
            }
        }

        if (!duplicates.isEmpty()) {
            protoclass.report().error(
                    "Duplicate attribute names %s. You should check if correct @Value.Style applied",
                    duplicates);
        }
    }
}

From source file:com.b2international.index.mapping.Mappings.java

public Mappings(Collection<Class<?>> types) {
    checkArgument(!types.isEmpty(), "At least one document type should be specified");
    final Multiset<String> duplicates = HashMultiset.create();
    for (Class<?> type : ImmutableSet.copyOf(types)) {
        // XXX register only root mappings, nested mappings should be looked up via the parent/ancestor mapping
        DocumentMapping mapping = new DocumentMapping(type);
        mappingsByType.put(type, mapping);
        duplicates.add(mapping.typeAsString());
    }/*from   w  ww.j a va  2 s .c om*/
    for (Entry<String> duplicate : duplicates.entrySet()) {
        if (duplicate.getCount() > 1) {
            throw new IllegalArgumentException(
                    "Multiple Java types with the same document name: " + duplicate.getElement());
        }
    }
}

From source file:com.synflow.cx.internal.compiler.helpers.FsmBeautifier.java

/**
 * Renames the states of the FSM.//from  w  w w  . ja va  2s .c om
 * 
 * @param actorName
 *            base name of the states (simple name of the actor)
 */
private void renameStates(String actorName) {
    // the "currentName" is set by a state with a name
    String currentName = null;
    for (State state : fsm.getStates()) {
        String stateName = state.getName();
        if (stateName == null) {
            if (currentName == null) {
                // this is the case for an actor whose first state has no name
                currentName = "FSM_" + actorName;
            }
            state.setName(currentName);
        } else {
            currentName = stateName;
        }
    }

    // rename consecutive states
    Multiset<String> visited = HashMultiset.create();
    for (State state : fsm.getStates()) {
        String name = state.getName();
        int n = visited.count(name);
        if (n > 0) {
            state.setName(name + "_" + n);
        }

        visited.add(name);
    }
}

From source file:org.corpus_tools.annis.ql.parser.SemanticValidator.java

public void checkAlternative(QueryData data, List<QueryNode> alternative, int alternativeIndex,
        boolean queryWasNormalized) {
    // check if there is at least one search expression
    if (alternative.isEmpty()) {
        throw new AnnisQLSemanticsException("Missing search expression.");
    }//w ww.j  av a  2  s  .c  om

    // there are not linguistic binary relations allowed if there is only one node
    if (alternative.size() == 1) {
        QueryNode n = alternative.get(0);
        for (Join j : n.getOutgoingJoins()) {
            if (j.getTarget() != null) {
                throw new AnnisQLSemanticsException(j.getParseLocation(),
                        "No binary linguistic relations allowed if there is only one node in query.");
            }
        }
    }

    // get all nodes connected to the first one
    Multimap<Long, QueryNode> connected = calculateConnected(alternative);
    Set<Long> transitiveHull = new HashSet<>();
    transitiveHull.add(alternative.get(0).getId());
    createTransitiveHull(alternative.get(0), connected, transitiveHull);

    Multiset<String> variableNames = TreeMultiset.create();

    Set<Long> unconnectedNodes = new HashSet<>();
    for (QueryNode n : alternative) {
        unconnectedNodes.add(n.getId());
        variableNames.add(n.getVariable());
    }
    unconnectedNodes.removeAll(transitiveHull);

    // check if each node is contained in the connected nodes
    if (!unconnectedNodes.isEmpty()) {
        List<AqlParseError> errors = new LinkedList<>();

        for (QueryNode n : alternative) {
            if (unconnectedNodes.contains(n.getId())) {
                errors.add(new AqlParseError(n,
                        "variable \"" + n.getVariable() + "\" not bound (use linguistic operators)"));

            }
        }

        if (!errors.isEmpty()) {
            if (queryWasNormalized) {
                // add the normalized query as "error" so the user is able to see it
                errors.add(new AqlParseError("Normalized query is: \n" + data.toAQL()));
            }

            throw new AnnisQLSemanticsException("Not all variables bound", errors);
        }
    }

    // check if any variable name was given more than once
    List<String> invalidNames = new LinkedList<>();
    for (Multiset.Entry<String> e : variableNames.entrySet()) {
        if (e.getCount() > 1) {
            invalidNames.add(e.getElement());
        }
    }
    if (!invalidNames.isEmpty()) {
        throw new AnnisQLSemanticsException(
                "The following variable names are " + "used for more than one node: "
                        + Joiner.on(", ").join(invalidNames) + "\nNormalized Query is: \n" + data.toAQL());
    }

    // check no non-reflexive operator is used with the same operands
    for (QueryNode source : alternative) {
        for (Join join : source.getOutgoingJoins()) {
            if (join instanceof Inclusion || join instanceof SameSpan || join instanceof Overlap
                    || join instanceof RightOverlap || join instanceof LeftOverlap
                    || join instanceof RightAlignment || join instanceof LeftAlignment) {
                if (source.equals(join.getTarget())) {
                    throw new AnnisQLSemanticsException(join,
                            "Not-reflexive operator used with the same node as argument.");
                }
            }
        }
    }
}