Example usage for com.google.common.collect Multimaps index

List of usage examples for com.google.common.collect Multimaps index

Introduction

In this page you can find the example usage for com.google.common.collect Multimaps index.

Prototype

public static <K, V> ImmutableListMultimap<K, V> index(Iterator<V> values, Function<? super V, K> keyFunction) 

Source Link

Document

Creates an index ImmutableListMultimap that contains the results of applying a specified function to each item in an Iterator of values.

Usage

From source file:org.opentestsystem.authoring.testauth.validation.ScoringRuleValidator.java

@Override
public void validate(final Object obj, final Errors errors) {
    // execute JSR-303 validations (annotations)
    this.jsrValidator.validate(obj, errors);

    final ScoringRule scoringRule = (ScoringRule) obj;

    // parameterDataMap can only be evaluated if corresponding ComputationRule is passed along
    if (StringUtils.isNotBlank(scoringRule.getComputationRuleId())
            && scoringRule.getComputationRule() != null) {
        validateFileUploads(errors, scoringRule);

        if (!CollectionUtils.isEmpty(scoringRule.getParameters())) {
            // check for duplicate parameter names
            final Map<String, Collection<ScoringRuleParameter>> duplicates = Maps.filterEntries(
                    Multimaps.index(scoringRule.getParameters(), RULE_PARAMETER_TO_NAME_TRANSFORMER).asMap(),
                    PARAMETER_DUPLICATE_FILTER);
            if (!duplicates.isEmpty()) {
                rejectValue(errors, PARAMETERS,
                        getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_DUPLICATES,
                        duplicates.keySet().toString());
            }//  w  w  w . j  a va2 s  .  co m

            for (int i = 0; i < scoringRule.getParameters().size(); i++) {
                final ScoringRuleParameter scoringRuleParameter = scoringRule.getParameters().get(i);
                try {
                    errors.pushNestedPath(PARAMETERS + "[" + i + "]");
                    final ComputationRuleParameter computationRuleParameter = Iterables
                            .find(scoringRule.getComputationRule().getParameters(), FUNCTION_PARAMETER_FINDER
                                    .getInstance(scoringRuleParameter.getComputationRuleParameterName()));
                    if (computationRuleParameter == null) {
                        rejectValue(errors, PARAMETER_NAME,
                                getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_NOT_FOUND,
                                scoringRuleParameter.getComputationRuleParameterName());
                    } else {
                        // evaluate every value within the rule parameter to ensure it adheres to the constraints of the ComputationRuleParameter
                        ValidationUtils.invokeValidator(this.scoringRuleParameterValidator,
                                scoringRuleParameter, errors, computationRuleParameter);
                    }
                } catch (final NoSuchElementException e) {
                    rejectValue(errors, PARAMETER_NAME,
                            getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_NOT_FOUND,
                            scoringRuleParameter.getComputationRuleParameterName());
                } finally {
                    errors.popNestedPath();
                }
            }

            for (final ComputationRuleParameter computationRuleParameter : scoringRule.getComputationRule()
                    .getParameters()) {
                if (!Iterables.any(scoringRule.getParameters(),
                        RULE_PARAMETER_FINDER.getInstance(computationRuleParameter.getParameterName()))) {
                    rejectValue(errors, PARAMETERS,
                            getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_MISSING,
                            computationRuleParameter.getParameterName());
                }
            }
        }
    }
}

From source file:dagger.internal.codegen.MapMultibindingValidator.java

private void checkForDuplicateMapKeys(dagger.model.Binding multiboundMapBinding,
        ImmutableSet<ContributionBinding> contributions, DiagnosticReporter diagnosticReporter) {
    ImmutableSetMultimap<Object, ContributionBinding> contributionsByMapKey = ImmutableSetMultimap
            .copyOf(Multimaps.index(contributions, ContributionBinding::mapKey));

    for (Set<ContributionBinding> contributionsForOneMapKey : Multimaps.asMap(contributionsByMapKey).values()) {
        if (contributionsForOneMapKey.size() > 1) {
            diagnosticReporter.reportBinding(ERROR, multiboundMapBinding,
                    duplicateMapKeyErrorMessage(contributionsForOneMapKey, multiboundMapBinding.key()));
        }//from w w  w .  jav  a  2s .  c om
    }
}

From source file:org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer.java

public NetconfMessageTransformer(final SchemaContext schemaContext) {
    this.counter = new MessageCounter();
    this.schemaContext = schemaContext;
    parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER,
            schemaContext);/*from   w ww .j ava  2 s .c o  m*/

    mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
    mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
}

From source file:org.opentestsystem.authoring.testauth.validation.ItemSelectionAlgorithmValidator.java

@Override
public void validate(final Object obj, final Errors errors) {
    // execute JSR-303 validations (annotations)
    this.jsrValidator.validate(obj, errors);

    final ItemSelectionAlgorithm algorithm = (ItemSelectionAlgorithm) obj;
    if (algorithm.getParameters() != null) {
        // custom validation for each itemSelectionAlgorithmParameter
        for (int i = 0; i < algorithm.getParameters().size(); i++) {
            final ItemSelectionAlgorithmParameter nextParameter = algorithm.getParameters().get(i);
            try {
                errors.pushNestedPath(PARAMETERS_FIELD + "[" + i + "]");
                ValidationUtils.invokeValidator(this.itemSelectionAlgorithmParameterValidator, nextParameter,
                        errors);/*from   w  w  w  .java2 s .c om*/

                if (nextParameter.getPosition() > algorithm.getParameters().size()) {
                    rejectValue(errors, "position",
                            getErrorMessageRoot() + PARAMETERS_POSITION_FIELD + MSG_INVALID,
                            nextParameter.getPosition());
                }
            } finally {
                errors.popNestedPath();
            }
        }

        // check if parameters have duplicate names
        final Map<String, Collection<ItemSelectionAlgorithmParameter>> duplicates = Maps.filterEntries(
                Multimaps.index(algorithm.getParameters(),
                        ITEM_SELECTION_ALGORITHM_PARAMETER_TO_NAME_TRANSFORMER).asMap(),
                ITEM_SELECTION_ALGORITHM_PARAMETER_DUPLICATE_FILTER);
        if (!duplicates.isEmpty()) {
            rejectValue(errors, PARAMETERS_FIELD,
                    getErrorMessageRoot() + PARAMETERS_NAME_FIELD + MSG_DUPLICATES,
                    duplicates.keySet().toString());
        }

        // check if parameters have duplicate position
        final Map<String, Collection<ItemSelectionAlgorithmParameter>> duplicatePositions = Maps.filterEntries(
                Multimaps.index(algorithm.getParameters(),
                        ITEM_SELECTION_ALGORITHM_PARAMETER_TO_POSITION_TRANSFORMER).asMap(),
                ITEM_SELECTION_ALGORITHM_PARAMETER_DUPLICATE_FILTER);
        if (!duplicatePositions.isEmpty()) {
            rejectValue(errors, PARAMETERS_FIELD,
                    getErrorMessageRoot() + PARAMETERS_POSITION_FIELD + MSG_DUPLICATES,
                    duplicatePositions.keySet().toString());
        }
    }
    if (StringUtils.trimToNull(algorithm.getVersion()) != null) {
        String[] parts = algorithm.getVersion().split("\\.");
        if (parts.length != 2) { //not the right number version parts
            //should be 2 parts like "1.0"
            rejectValue(errors, "version", "version.format", new Object() {
            });
            return;
        }
        if (NumberUtils.toInt(parts[0], -1) < 1 || parts[1].length() > 1
                || (NumberUtils.toInt(parts[1], -1) < 0 || NumberUtils.toInt(parts[1], -1) > 9)) { //major is a negative number or some other character
            rejectValue(errors, "version", "version.majorminor.format", new Object() {
            });
        }
    }

    if (!errors.hasErrors()) {
        algorithm.trimParameterValues();
    }
}

From source file:brooklyn.entity.group.DynamicMultiGroupImpl.java

@Override
public void distributeEntities() {
    synchronized (memberChangeMutex) {
        Function<Entity, String> bucketFunction = getConfig(BUCKET_FUNCTION);
        EntitySpec<? extends BasicGroup> bucketSpec = getConfig(BUCKET_SPEC);
        if (bucketFunction == null || bucketSpec == null)
            return;
        Map<String, BasicGroup> buckets = MutableMap.copyOf(getAttribute(BUCKETS));

        // Bucketize the members where the function gives a non-null bucket
        Multimap<String, Entity> entityMapping = Multimaps.index(
                Iterables.filter(getMembers(), Predicates.compose(Predicates.notNull(), bucketFunction)),
                bucketFunction);//  w  w w . java  2 s . c om

        // Now fill the buckets
        for (String name : entityMapping.keySet()) {
            BasicGroup bucket = buckets.get(name);
            if (bucket == null) {
                bucket = addChild(EntitySpec.create(bucketSpec).displayName(name));
                Entities.manage(bucket);
                buckets.put(name, bucket);
            }
            bucket.setMembers(entityMapping.get(name));
        }

        // Remove any now-empty buckets
        Set<String> empty = ImmutableSet.copyOf(Sets.difference(buckets.keySet(), entityMapping.keySet()));
        for (String name : empty) {
            Group removed = buckets.remove(name);
            removeChild(removed);
            Entities.unmanage(removed);
        }

        // Save the bucket mappings
        setAttribute(BUCKETS, ImmutableMap.copyOf(buckets));
    }
}

From source file:org.apache.brooklyn.entity.group.DynamicMultiGroupImpl.java

@Override
public void distributeEntities() {
    synchronized (memberChangeMutex) {
        Function<Entity, String> bucketFunction = getConfig(BUCKET_FUNCTION);
        EntitySpec<? extends BasicGroup> bucketSpec = getConfig(BUCKET_SPEC);
        if (bucketFunction == null || bucketSpec == null)
            return;
        Map<String, BasicGroup> buckets = MutableMap.copyOf(getAttribute(BUCKETS));

        // Bucketize the members where the function gives a non-null bucket
        Multimap<String, Entity> entityMapping = Multimaps.index(
                Iterables.filter(getMembers(), Predicates.compose(Predicates.notNull(), bucketFunction)),
                bucketFunction);/* w w  w.  j ava 2 s . com*/

        // Now fill the buckets
        for (String name : entityMapping.keySet()) {
            BasicGroup bucket = buckets.get(name);
            if (bucket == null) {
                bucket = addChild(EntitySpec.create(bucketSpec).displayName(name));
                buckets.put(name, bucket);
            }
            bucket.setMembers(entityMapping.get(name));
        }

        // Remove any now-empty buckets
        Set<String> empty = ImmutableSet.copyOf(Sets.difference(buckets.keySet(), entityMapping.keySet()));
        for (String name : empty) {
            Group removed = buckets.remove(name);
            removeChild(removed);
            Entities.unmanage(removed);
        }

        // Save the bucket mappings
        sensors().set(BUCKETS, ImmutableMap.copyOf(buckets));
    }
}

From source file:org.eclipse.xtext.mwe.Validator.java

protected Multimap<URI, MWEDiagnostic> groupByURI(MWEDiagnostic[] diagnostic) {
    Multimap<URI, MWEDiagnostic> result = Multimaps.newMultimap(
            Maps.<URI, Collection<MWEDiagnostic>>newLinkedHashMap(), new Supplier<Collection<MWEDiagnostic>>() {
                @Override// w w w .  j a  va2  s  .  co  m
                public Collection<MWEDiagnostic> get() {
                    return Sets.newTreeSet(getDiagnosticComparator());
                }
            });
    result.putAll(Multimaps.index(Arrays.asList(diagnostic), new Function<MWEDiagnostic, URI>() {
        @Override
        public URI apply(MWEDiagnostic from) {
            Issue issue = (Issue) from.getElement();
            URI uriToProblem = issue.getUriToProblem();
            return uriToProblem != null ? uriToProblem.trimFragment() : NullURI;
        }
    }));
    return result;
}

From source file:msi.gaml.compilation.GamlIdiomsProvider.java

private void init() {

    sortedElements = Iterables.toArray(elements, IGamlDescription.class);
    if (titles == null) {
        Arrays.sort(sortedElements, (e1, e2) -> e1.getTitle().compareTo(e2.getTitle()));
    } else {//from w ww .j a va2s  . c o m
        Arrays.sort(sortedElements, (e1, e2) -> titles.get(e1).compareTo(titles.get(e2)));
    }
    byName = Multimaps.index(elements, (each) -> each.getName());

}

From source file:com.google.errorprone.bugpatterns.inject.guice.AssistedParameters.java

@Override
public final Description matchMethod(MethodTree constructor, final VisitorState state) {
    if (!IS_CONSTRUCTOR_WITH_INJECT_OR_ASSISTED.matches(constructor, state)) {
        return Description.NO_MATCH;
    }//from  ww w . ja  v a2  s .  c o  m

    // Gather @Assisted parameters, partition by type
    MultiMatchResult<VariableTree> assistedParameters = ASSISTED_PARAMETER_MATCHER.multiMatchResult(constructor,
            state);
    if (!assistedParameters.matches()) {
        return Description.NO_MATCH;
    }

    Multimap<Type, VariableTree> parametersByType = partitionParametersByType(
            assistedParameters.matchingNodes(), state);

    // If there's more than one parameter with the same type, they could conflict unless their
    // @Assisted values are different.
    List<ConflictResult> conflicts = new ArrayList<>();
    for (Map.Entry<Type, Collection<VariableTree>> typeAndParameters : parametersByType.asMap().entrySet()) {
        Collection<VariableTree> parametersForThisType = typeAndParameters.getValue();
        if (parametersForThisType.size() < 2) {
            continue;
        }

        // Gather the @Assisted value from each parameter. If any value is repeated amongst the
        // parameters in this type, it's a compile error.
        ImmutableListMultimap<String, VariableTree> keyForAssistedVariable = Multimaps
                .index(parametersForThisType, VALUE_FROM_ASSISTED_ANNOTATION);

        for (Entry<String, List<VariableTree>> assistedValueToParameters : Multimaps
                .asMap(keyForAssistedVariable).entrySet()) {
            if (assistedValueToParameters.getValue().size() > 1) {
                conflicts.add(ConflictResult.create(typeAndParameters.getKey(),
                        assistedValueToParameters.getKey(), assistedValueToParameters.getValue()));
            }
        }
    }

    if (conflicts.isEmpty()) {
        return Description.NO_MATCH;
    }

    return buildDescription(constructor).setMessage(buildErrorMessage(conflicts)).build();
}

From source file:io.prestosql.plugin.raptor.legacy.storage.organization.ShardOrganizerUtil.java

public static Collection<Collection<ShardIndexInfo>> getShardsByDaysBuckets(Table tableInfo,
        Collection<ShardIndexInfo> shards, TemporalFunction temporalFunction) {
    if (shards.isEmpty()) {
        return ImmutableList.of();
    }//from   w  w w . j  a v  a2  s. c  o m

    // Neither bucketed nor temporal, no partitioning required
    if (!tableInfo.getBucketCount().isPresent() && !tableInfo.getTemporalColumnId().isPresent()) {
        return ImmutableList.of(shards);
    }

    // if only bucketed, partition by bucket number
    if (tableInfo.getBucketCount().isPresent() && !tableInfo.getTemporalColumnId().isPresent()) {
        return Multimaps.index(shards, shard -> shard.getBucketNumber().getAsInt()).asMap().values();
    }

    // if temporal, partition into days first
    ImmutableMultimap.Builder<Long, ShardIndexInfo> shardsByDaysBuilder = ImmutableMultimap.builder();
    shards.stream().filter(shard -> shard.getTemporalRange().isPresent()).forEach(shard -> {
        long day = temporalFunction.getDayFromRange(shard.getTemporalRange().get());
        shardsByDaysBuilder.put(day, shard);
    });

    Collection<Collection<ShardIndexInfo>> byDays = shardsByDaysBuilder.build().asMap().values();

    // if table is bucketed further partition by bucket number
    if (!tableInfo.getBucketCount().isPresent()) {
        return byDays;
    }

    ImmutableList.Builder<Collection<ShardIndexInfo>> sets = ImmutableList.builder();
    for (Collection<ShardIndexInfo> s : byDays) {
        sets.addAll(Multimaps.index(s, ShardIndexInfo::getBucketNumber).asMap().values());
    }
    return sets.build();
}