List of usage examples for com.google.common.collect Multimaps index
public static <K, V> ImmutableListMultimap<K, V> index(Iterator<V> values, Function<? super V, K> keyFunction)
From source file:com.facebook.presto.util.IterableTransformer.java
public <K> Multimap<K, E> index(Function<? super E, K> keyFunction) { return Multimaps.index(iterable, keyFunction); }
From source file:org.apache.aurora.scheduler.http.Maintenance.java
private Multimap<String, String> getTasksByHosts(StoreProvider provider, Iterable<String> hosts) { if (Iterables.isEmpty(hosts)) { return ImmutableMultimap.of(); }//w ww . j av a 2 s .co m ImmutableSet.Builder<IScheduledTask> drainingTasks = ImmutableSet.builder(); drainingTasks.addAll( provider.getTaskStore().fetchTasks(Query.slaveScoped(hosts).byStatus(Tasks.SLAVE_ASSIGNED_STATES))); return Multimaps.transformValues(Multimaps.index(drainingTasks.build(), Tasks::scheduledToSlaveHost), Tasks::id); }
From source file:org.jclouds.cloudstack.compute.functions.OrphanedGroupsByZoneId.java
public Multimap<String, String> apply(Set<? extends NodeMetadata> deadNodes) { Iterable<? extends NodeMetadata> nodesWithGroup = filter(deadNodes, NodePredicates.hasGroup()); Set<ZoneAndName> zoneAndGroupNames = ImmutableSet .copyOf(filter(transform(nodesWithGroup, new Function<NodeMetadata, ZoneAndName>() { @Override/*from w w w .j a v a2 s . co m*/ public ZoneAndName apply(NodeMetadata input) { String zoneId = input.getLocation().getScope() == LocationScope.HOST ? input.getLocation().getParent().getId() : input.getLocation().getId(); return ZoneAndName.fromZoneAndName(zoneId, input.getGroup()); } }), allNodesInGroupTerminated)); Multimap<String, String> zoneToZoneAndGroupNames = Multimaps.transformValues( Multimaps.index(zoneAndGroupNames, ZoneAndName.ZONE_FUNCTION), ZoneAndName.NAME_FUNCTION); return zoneToZoneAndGroupNames; }
From source file:org.opentestsystem.authoring.testauth.service.impl.BlueprintValidationHelper.java
/** * Handles hierarchical validation for each individual <code>BlueprintElement</code>. This includes: * <ul>/* w w w .java2 s . c o m*/ * <li>The sum of the child min values must be less than or equal to the parent max</li> * <li>The sum of the child max values must be greater than or equal to the parent min</li> * </ul> */ protected static List<ValidationResult<BlueprintElement>> validateBlueprintHierarchicalRelationships( final List<BlueprintElement> blueprintElementList) { final List<ValidationResult<BlueprintElement>> errors = Lists.newArrayList(); if (!CollectionUtils.isEmpty(blueprintElementList)) { final List<String> valueMapKeys = Lists .newArrayList(blueprintElementList.get(0).getBlueprintElementValueMap().keySet()); final Map<String, BlueprintElement> blueprintElementMap = Maps.uniqueIndex(blueprintElementList, BLUEPRINT_ELEMENT_UNIQUE_KEY_FUNCTION); final List<BlueprintElement> filteredChildrenBlueprintElementList = Lists .newArrayList(Iterables.filter(blueprintElementList, BLUEPRINT_ELEMENT_CHILD_FILTER)); final Map<String, Collection<BlueprintElement>> blueprintElementGroupedMap = Multimaps .index(filteredChildrenBlueprintElementList, BLUEPRINT_ELEMENT_PARENT_KEY_FUNCTION).asMap(); for (final Entry<String, Collection<BlueprintElement>> blueprintElementEntry : blueprintElementGroupedMap .entrySet()) { if (StringUtils.isNotBlank(blueprintElementEntry.getKey())) { final BlueprintElement parentBlueprintElement = blueprintElementMap .get(blueprintElementEntry.getKey()); if (parentBlueprintElement != null) { for (final String valueMapKey : valueMapKeys) { final List<BlueprintElementValue> bpValueList = Lists.transform( Lists.newArrayList(blueprintElementEntry.getValue()), BPE_BPEV_TRANSFORMER.getInstance(valueMapKey)); final BlueprintElementValue parentValue = parentBlueprintElement .getBlueprintElementValueMap().get(valueMapKey); final BlueprintElementValue childSummedValue = getActualListSum(bpValueList); if (childSummedValue.getOperationalItemMinValue() > parentValue .getOperationalItemMaxValue()) { errors.add(buildValidationResult(parentBlueprintElement, valueMapKey, OP_MAX_FIELD, String.format(PARENT_MESSAGE, "OP Max", parentValue.getOperationalItemMaxValue(), "less", "OP Min", childSummedValue.getOperationalItemMinValue()))); } if (childSummedValue.getOperationalItemMaxValue() < parentValue .getOperationalItemMinValue()) { errors.add(buildValidationResult(parentBlueprintElement, valueMapKey, OP_MIN_FIELD, String.format(PARENT_MESSAGE, "OP Min", parentValue.getOperationalItemMinValue(), "greater", "OP Max", childSummedValue.getOperationalItemMaxValue()))); } if (childSummedValue.getFieldTestItemMinValue() > parentValue .getFieldTestItemMaxValue()) { errors.add(buildValidationResult(parentBlueprintElement, valueMapKey, FT_MAX_FIELD, String.format(PARENT_MESSAGE, "FT Max", parentValue.getFieldTestItemMaxValue(), "less", "FT Min", childSummedValue.getFieldTestItemMinValue()))); } if (childSummedValue.getFieldTestItemMaxValue() < parentValue .getFieldTestItemMinValue()) { errors.add(buildValidationResult(parentBlueprintElement, valueMapKey, FT_MIN_FIELD, String.format(PARENT_MESSAGE, "FT Min", parentValue.getFieldTestItemMinValue(), "greater", "FT Max", childSummedValue.getFieldTestItemMaxValue()))); } } } } } } return errors; }
From source file:com.twitter.aurora.scheduler.http.Maintenance.java
private Multimap<String, String> getTasksByHosts(StoreProvider provider, Iterable<String> hosts) { ImmutableSet.Builder<IScheduledTask> drainingTasks = ImmutableSet.builder(); for (String host : hosts) { drainingTasks.addAll(provider.getTaskStore().fetchTasks(Query.slaveScoped(host).active())); }/* w ww . ja v a2s .c o m*/ return Multimaps.transformValues(Multimaps.index(drainingTasks.build(), TASK_TO_HOST), Tasks.SCHEDULED_TO_ID); }
From source file:org.jclouds.openstack.nova.v2_0.compute.functions.OrphanedGroupsByRegionId.java
public Multimap<String, String> apply(Set<? extends NodeMetadata> deadNodes) { Iterable<? extends NodeMetadata> nodesWithGroup = filter(deadNodes, NodePredicates.hasGroup()); Set<RegionAndName> regionAndGroupNames = ImmutableSet .copyOf(filter(transform(nodesWithGroup, new Function<NodeMetadata, RegionAndName>() { @Override/* w w w . j a v a 2 s. c o m*/ public RegionAndName apply(NodeMetadata input) { String regionId = input.getLocation().getScope() == LocationScope.HOST ? input.getLocation().getParent().getId() : input.getLocation().getId(); return RegionAndName.fromRegionAndName(regionId, input.getGroup()); } }), allNodesInGroupTerminated)); Multimap<String, String> regionToRegionAndGroupNames = Multimaps.transformValues( Multimaps.index(regionAndGroupNames, RegionAndName.REGION_FUNCTION), RegionAndName.NAME_FUNCTION); return regionToRegionAndGroupNames; }
From source file:dagger.internal.codegen.MapMultibindingValidation.java
private void checkForDuplicateMapKeys(BindingNode multiboundMapBindingNode, 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, multiboundMapBindingNode, duplicateMapKeyErrorMessage( contributionsForOneMapKey, multiboundMapBindingNode.binding().key())); }// w w w. j a va 2 s .c o m } }
From source file:com.madvay.tools.android.perf.common.Table.java
public Table<AggregateRow> groupAndAggregate(final String groupByColumn, final String weightColumn, final AggregationType aggregationType) { final RowAdapter<T> adapter = getAdapter(); final boolean groupNumeric = adapter.types .get(adapter.columns.indexOf(groupByColumn)) == RowAdapter.CoerceType.NUMERIC; boolean weightNumeric = adapter.types .get(adapter.columns.indexOf(weightColumn)) == RowAdapter.CoerceType.NUMERIC; ImmutableListMultimap<Object, T> indexed = Multimaps.index(rows, new Function<T, Object>() { @Override/*from ww w .j a v a 2s. c o m*/ public Object apply(T input) { return adapter.get(input, groupByColumn).toString(); } }); Map<Object, Long> map = Maps.transformEntries(Multimaps.asMap(indexed), new Maps.EntryTransformer<Object, List<T>, Long>() { @Override public Long transformEntry(Object key, List<T> value) { switch (aggregationType) { case COUNT: return (long) value.size(); case SUM: { long l = 0; for (T t : value) { l += Long.parseLong(adapter.get(t, weightColumn).toString()); } return l; } case UNIQUE: { Set<String> set = new HashSet<>(); for (T t : value) { set.add(adapter.get(t, weightColumn).toString()); } return (long) set.size(); } } throw new IllegalArgumentException(); } }); List<AggregateRow> newRows = Lists.newArrayList( Iterables.transform(map.entrySet(), new Function<Map.Entry<Object, Long>, AggregateRow>() { @Override public AggregateRow apply(Map.Entry<Object, Long> input) { return new AggregateRow(input.getValue(), input.getKey()); } })); Table<AggregateRow> ret = new Table<AggregateRow>(newRows) { final RowAdapter<AggregateRow> adap = new AggregateRow.Adapter(groupNumeric); @Override public RowAdapter<AggregateRow> getAdapter() { return adap; } }; return ret; }
From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java
public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext, ModelSchemaStore store, final ModelSchemaCache cache) { ModelType<R> type = extractionContext.getType(); Class<? super R> clazz = type.getRawClass(); if (isTarget(type)) { validateType(type, extractionContext); Iterable<Method> methods = Arrays.asList(clazz.getMethods()); if (!clazz.isInterface()) { methods = filterIgnoredMethods(methods); }// ww w . ja v a2s . co m ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods, new Function<Method, String>() { public String apply(Method method) { return method.getName(); } }); ensureNoOverloadedMethods(extractionContext, methodsByName); List<ModelProperty<?>> properties = Lists.newLinkedList(); List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length); ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering(); for (String methodName : methodsByName.keySet()) { if (methodName.startsWith("get") && !methodName.equals("get")) { ImmutableList<Method> getterMethods = methodsByName.get(methodName); // The overload check earlier verified that all methods for are equivalent for our purposes // So, taking the first one with the most specialized return type is fine. Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods); boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers()); if (sampleMethod.getParameterTypes().length != 0) { throw invalidMethod(extractionContext, "getter methods cannot take parameters", sampleMethod); } Character getterPropertyNameFirstChar = methodName.charAt(3); if (!Character.isUpperCase(getterPropertyNameFirstChar)) { throw invalidMethod(extractionContext, "the 4th character of the getter method name must be an uppercase character", sampleMethod); } ModelType<?> returnType = ModelType.returnType(sampleMethod); String propertyNameCapitalized = methodName.substring(3); String propertyName = StringUtils.uncapitalize(propertyNameCapitalized); String setterName = "set" + propertyNameCapitalized; ImmutableList<Method> setterMethods = methodsByName.get(setterName); boolean isWritable = !setterMethods.isEmpty(); if (isWritable) { Method setter = setterMethods.get(0); if (!abstractGetter) { throw invalidMethod(extractionContext, "setters are not allowed for non-abstract getters", setter); } validateSetter(extractionContext, returnType, setter); handled.addAll(setterMethods); } if (abstractGetter) { ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() { public ModelType<?> apply(Method input) { return ModelType.of(input.getDeclaringClass()); } })); boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() { public boolean apply(Method input) { return input.getAnnotation(Unmanaged.class) != null; } }); properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses, unmanaged)); } handled.addAll(getterMethods); } } Iterable<Method> notHandled = Iterables.filter(methodsByName.values(), Predicates.not(Predicates.in(handled))); // TODO - should call out valid getters without setters if (!Iterables.isEmpty(notHandled)) { throw invalidMethods(extractionContext, "only paired getter/setter methods are supported", notHandled); } Class<R> concreteClass = type.getConcreteClass(); final ModelSchema<R> schema = createSchema(extractionContext, store, type, properties, concreteClass); Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties, new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() { public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) { return toPropertyExtractionContext(extractionContext, property, cache); } }); return new ModelSchemaExtractionResult<R>(schema, propertyDependencies); } else { return null; } }
From source file:com.twitter.aurora.scheduler.base.Conversions.java
/** * Converts protobuf attributes into thrift-generated attributes. * * @param offer Resource offer./*from w w w . j a v a2 s .co m*/ * @return Equivalent thrift host attributes. */ public static HostAttributes getAttributes(Offer offer) { // Group by attribute name. Multimap<String, Protos.Attribute> valuesByName = Multimaps.index(offer.getAttributesList(), ATTRIBUTE_NAME); // TODO(William Farner): Include slave id. return new HostAttributes(offer.getHostname(), FluentIterable.from(valuesByName.asMap().entrySet()).transform(ATTRIBUTE_CONVERTER).toSet()) .setSlaveId(offer.getSlaveId().getValue()); }