下面列出了com.google.common.collect.Multimaps#index ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void discoverShards()
{
log.info("Discovering shards that need compaction...");
Set<ShardMetadata> allShards = shardManager.getNodeShards(currentNodeIdentifier);
ListMultimap<Long, ShardMetadata> tableShards = Multimaps.index(allShards, ShardMetadata::getTableId);
for (Entry<Long, List<ShardMetadata>> entry : Multimaps.asMap(tableShards).entrySet()) {
long tableId = entry.getKey();
if (!metadataDao.isCompactionEligible(tableId)) {
continue;
}
List<ShardMetadata> shards = entry.getValue();
Collection<OrganizationSet> organizationSets = filterAndCreateCompactionSets(tableId, shards);
log.info("Created %s organization set(s) for table ID %s", organizationSets.size(), tableId);
for (OrganizationSet set : organizationSets) {
organizer.enqueue(set);
}
}
}
private void assertStateUpdate(
IJobUpdateKey key,
JobUpdateStatus expected,
Multimap<Integer, JobUpdateAction> expectedActions) {
IJobUpdateDetails details = getDetails(key);
Iterable<IJobInstanceUpdateEvent> orderedEvents =
EVENT_ORDER.sortedCopy(details.getInstanceEvents());
Multimap<Integer, IJobInstanceUpdateEvent> eventsByInstance =
Multimaps.index(orderedEvents, EVENT_TO_INSTANCE);
Multimap<Integer, JobUpdateAction> actionsByInstance =
Multimaps.transformValues(eventsByInstance, JobUpdateControllerImpl.EVENT_TO_ACTION);
assertEquals(expectedActions, actionsByInstance);
assertEquals(expected, details.getUpdate().getSummary().getState().getStatus());
}
private void init() {
sortedElements = Iterables.toArray(elements, IGamlDescription.class);
if (titles == null) {
Arrays.sort(sortedElements, (e1, e2) -> e1.getTitle().compareTo(e2.getTitle()));
} else {
Arrays.sort(sortedElements, (e1, e2) -> titles.get(e1).compareTo(titles.get(e2)));
}
byName = Multimaps.index(elements, (each) -> each.getName());
}
@VisibleForTesting
Address getRichest(Collection<UnspentTransactionOutput> unspent, final NetworkParameters network) {
Preconditions.checkArgument(!unspent.isEmpty());
Function<UnspentTransactionOutput, Address> txout2Address = new Function<UnspentTransactionOutput, Address>() {
@Override
public Address apply(UnspentTransactionOutput input) {
return input.script.getAddress(network);
}
};
Multimap<Address, UnspentTransactionOutput> index = Multimaps.index(unspent, txout2Address);
Address ret = getRichest(index);
return Preconditions.checkNotNull(ret);
}
@Override
@Timed("snapshot_deduplicate")
public DeduplicatedSnapshot deduplicate(Snapshot snapshot) {
int numInputTasks = snapshot.getTasksSize();
LOG.info("Starting deduplication of a snapshot with {} tasks.", numInputTasks);
DeduplicatedSnapshot deduplicatedSnapshot = new DeduplicatedSnapshot()
.setPartialSnapshot(deepCopyWithoutTasks(snapshot));
// Nothing to do if we don't have any input tasks.
if (!snapshot.isSetTasks()) {
LOG.warn("Got snapshot with unset tasks field.");
return deduplicatedSnapshot;
}
// Match each unique TaskConfig to its hopefully-multiple ScheduledTask owners.
ListMultimap<TaskConfig, ScheduledTask> index = Multimaps.index(
snapshot.getTasks(),
SCHEDULED_TO_CONFIG);
for (Entry<TaskConfig, List<ScheduledTask>> entry : Multimaps.asMap(index).entrySet()) {
deduplicatedSnapshot.addToTaskConfigs(entry.getKey());
for (ScheduledTask scheduledTask : entry.getValue()) {
deduplicatedSnapshot.addToPartialTasks(new DeduplicatedScheduledTask()
.setPartialScheduledTask(deepCopyWithoutTaskConfig(scheduledTask))
.setTaskConfigId(deduplicatedSnapshot.getTaskConfigsSize() - 1));
}
}
int numOutputTasks = deduplicatedSnapshot.getTaskConfigsSize();
LOG.info(String.format(
"Finished deduplicating snapshot. Deduplication ratio: %d/%d = %.2f%%.",
numInputTasks,
numOutputTasks,
100.0 * numInputTasks / numOutputTasks));
return deduplicatedSnapshot;
}
@Override
public List<ConfiguredTarget> getPrerequisites(
QueryExpression caller,
ConfiguredTarget configuredTarget,
String attrName,
String errorMsgPrefix)
throws QueryException, InterruptedException {
Preconditions.checkArgument(
isRule(configuredTarget),
"%s %s is not a rule configured target",
errorMsgPrefix,
getLabel(configuredTarget));
Multimap<Label, ConfiguredTarget> depsByLabel =
Multimaps.index(
queryEnvironment.getFwdDeps(ImmutableList.of(configuredTarget)),
ConfiguredTarget::getLabel);
Rule rule = (Rule) getTargetFromConfiguredTarget(configuredTarget);
ImmutableMap<Label, ConfigMatchingProvider> configConditions =
((RuleConfiguredTarget) configuredTarget).getConfigConditions();
ConfiguredAttributeMapper attributeMapper =
ConfiguredAttributeMapper.of(rule, configConditions);
if (!attributeMapper.has(attrName)) {
throw new QueryException(
caller,
String.format(
"%s %s of type %s does not have attribute '%s'",
errorMsgPrefix, configuredTarget, rule.getRuleClass(), attrName));
}
ImmutableList.Builder<ConfiguredTarget> toReturn = ImmutableList.builder();
attributeMapper.visitLabels(attributeMapper.getAttributeDefinition(attrName)).stream()
.forEach(depEdge -> toReturn.addAll(depsByLabel.get(depEdge.getLabel())));
return toReturn.build();
}
public Result writeDiscovery(
Iterable<ApiConfig> configs, DiscoveryContext context, SchemaRepository schemaRepository) {
ImmutableListMultimap<ApiKey, ApiConfig> configsByKey = Multimaps.index(configs,
new Function<ApiConfig, ApiKey>() {
@Override public ApiKey apply(ApiConfig config) {
return config.getApiKey();
}
});
ImmutableMap.Builder<ApiKey, RestDescription> builder = ImmutableMap.builder();
// "Default" API versions were determined automagically in legacy endpoints.
// This version only allows to remove an API from default ones by adding
// defaultVersion = AnnotationBoolean.FALSE to @Api
ImmutableSet.Builder<ApiKey> preferred = ImmutableSet.builder();
for (ApiKey apiKey : configsByKey.keySet()) {
ImmutableList<ApiConfig> apiConfigs = configsByKey.get(apiKey);
if (context.generateAll || apiConfigs.get(0).getIsDiscoverable()) {
builder.put(apiKey, writeApi(apiKey, apiConfigs, context, schemaRepository));
// last config takes precedence (same as writeApi)
if (Iterables.getLast(apiConfigs).getIsDefaultVersion()) {
preferred.add(apiKey);
}
}
}
ImmutableMap<ApiKey, RestDescription> discoveryDocs = builder.build();
return Result.builder()
.setDiscoveryDocs(discoveryDocs)
.setDirectory(generateDirectory(discoveryDocs, preferred.build(), context))
.build();
}
@Override
public Multimap<String, IScheduledTask> createNamedGroups(Iterable<IScheduledTask> tasks) {
return Multimaps.index(tasks, Functions.compose(new Function<IJobKey, String>() {
@Override
public String apply(IJobKey jobKey) {
return "sla_" + JobKeys.canonicalString(jobKey) + "_";
}
}, Tasks::getJob));
}
private static ImmutableMultimap<TypeRoleFillerRealis, AssessedResponse> getEquivClassToAssessedResponse(final AnswerKey answerKey) {
final Function<Response, TypeRoleFillerRealis> equivalenceClassFunction =
TypeRoleFillerRealis.extractFromSystemResponse(answerKey
.corefAnnotation().strictCASNormalizerFunction());
final ImmutableMultimap<TypeRoleFillerRealis, AssessedResponse> equivClassToAnswerKeyResponses =
Multimaps.index(
answerKey.annotatedResponses(),
Functions.compose(equivalenceClassFunction, AssessedResponseFunctions.response()));
return equivClassToAnswerKeyResponses;
}
/**
* Returns a list sorted according to related groups of types.
*
* @param objects
* collection to sort
* @param mapping
* mapping function
* @param <T>
* object type
* @return sorted list
*/
public static <T> ListMultimap<EPackage, T> sortedEPackageGroups(final Iterable<T> objects, final Function<T, EClass> mapping) {
ListMultimap<EPackage, T> index = Multimaps.index(objects, new Function<T, EPackage>() {
@Override
public EPackage apply(final T from) {
return mapping.apply(from).getEPackage();
}
});
ListMultimap<EPackage, T> result = LinkedListMultimap.create(index.keySet().size());
for (EPackage pkg : index.keySet()) {
result.putAll(pkg, sortedGroups(index.get(pkg), mapping));
}
return result;
}
public void load() {
tabbedPane.removeAll();
List<Plugin> plugins = Session.get().getPluginManager().getPlugins();
Multimap<String, Plugin> pluginGroups = Multimaps.index(plugins, Plugin::getGroup);
for (String groupName : pluginGroups.keySet()) {
PluginGroup group = new PluginGroup(groupName, pluginGroups.get(groupName));
tabbedPane.addTab(group.getName(), group);
}
MateTabbedPane.Tab first = tabbedPane.getAt(0);
if (first != null) {
first.select();
}
}
FactoryMethodDescriptor generateDescriptorForConstructor(final AutoFactoryDeclaration declaration,
ExecutableElement constructor) {
checkNotNull(constructor);
checkArgument(constructor.getKind() == ElementKind.CONSTRUCTOR);
TypeElement classElement = MoreElements.asType(constructor.getEnclosingElement());
ImmutableListMultimap<Boolean, ? extends VariableElement> parameterMap =
Multimaps.index(constructor.getParameters(), Functions.forPredicate(
new Predicate<VariableElement>() {
@Override
public boolean apply(VariableElement parameter) {
return isAnnotationPresent(parameter, Provided.class);
}
}));
ImmutableSet<Parameter> providedParameters =
Parameter.forParameterList(parameterMap.get(true), types);
ImmutableSet<Parameter> passedParameters =
Parameter.forParameterList(parameterMap.get(false), types);
return FactoryMethodDescriptor.builder(declaration)
.name("create")
.returnType(classElement.asType())
.publicMethod(classElement.getModifiers().contains(PUBLIC))
.providedParameters(providedParameters)
.passedParameters(passedParameters)
.creationParameters(Parameter.forParameterList(constructor.getParameters(), types))
.isVarArgs(constructor.isVarArgs())
.build();
}
private static ImmutableListMultimap<String, DescriptorProtos.SourceCodeInfo.Location>
buildLocationMap(FileDescriptorProto file) {
return Multimaps.<String, DescriptorProtos.SourceCodeInfo.Location>index(
file.getSourceCodeInfo().getLocationList(),
new Function<DescriptorProtos.SourceCodeInfo.Location, String>() {
@Override
public String apply(DescriptorProtos.SourceCodeInfo.Location location) {
return DOT_JOINER.join(location.getPathList());
}
});
}
@Test
public void testGroupBy(){
List<UserEntity> all = LangUtils.newArrayList();
List<UserEntity> aa = createSameNameUserList("aa", 3);
List<UserEntity> bb = createSameNameUserList("bb", 1);
List<UserEntity> cc = createSameNameUserList("cc", 2);
all.addAll(aa);
all.addAll(bb);
all.addAll(cc);
ImmutableListMultimap<String, UserEntity> groups = Multimaps.index(all, new Function<UserEntity, String>() {
@Override
public String apply(UserEntity input) {
return input.getUserName();
}
});
System.out.println("groups:" + groups);
Assert.assertEquals(3, groups.get("aa").size());
Assert.assertEquals(1, groups.get("bb").size());
Assert.assertEquals(2, groups.get("cc").size());
Map<String, List<UserEntity>> userGroup = all.stream().collect(Collectors.groupingBy(u->u.getUserName()));
System.out.println("userGroup:" + userGroup);
Assert.assertEquals(3, userGroup.get("aa").size());
Assert.assertEquals(1, userGroup.get("bb").size());
Assert.assertEquals(2, userGroup.get("cc").size());
}
public static <Answerable> SystemOutputEquivalenceClasses<Answerable> forAnswerable(
final ArgumentOutput argumentOutput, final Function<Response, Answerable> answerableExtractor) {
return new SystemOutputEquivalenceClasses<Answerable>(argumentOutput,
Multimaps.index(argumentOutput.responses(), answerableExtractor));
}
public ListMultimap<String, MediaSegmentDescriptor> lookUpSegmentsOfObjects(
Iterable<String> objectIds) {
Stream<MediaSegmentDescriptor> descriptors =
this.lookUpSegmentsByField(FIELDNAMES[1], objectIds);
return Multimaps.index(descriptors.iterator(), MediaSegmentDescriptor::getObjectId);
}
private Collection<IRailLink<TPos>> findRailLinksConnectingTo(TPos pos){
if(destinationsToRailLinks == null) {
destinationsToRailLinks = Multimaps.index(getRailLinks().iterator(), IRailLink::getDestinationPos);
}
return destinationsToRailLinks.get(pos);
}
private void updateSubstation() {
if (substations == null) {
LOGGER.trace("Update substations...");
substations = new ArrayList<>();
node2voltageLevel = new HashMap<>();
UndirectedGraph<UcteNodeCode, Object> graph = createSubstationGraph(network);
for (Set<UcteNodeCode> substationNodes : new ConnectivityInspector<>(graph).connectedSets()) {
// the main node of the substation is not an xnode and the one with the highest voltage
// level and the lowest busbar number.
UcteNodeCode mainNode = substationNodes.stream()
.sorted((nodeCode1, nodeCode2) -> {
if (nodeCode1.getUcteCountryCode() == UcteCountryCode.XX &&
nodeCode2.getUcteCountryCode() != UcteCountryCode.XX) {
return 1;
} else if (nodeCode1.getUcteCountryCode() != UcteCountryCode.XX &&
nodeCode2.getUcteCountryCode() == UcteCountryCode.XX) {
return -1;
} else {
return compareVoltageLevelThenBusbar(nodeCode1, nodeCode2);
}
})
.findFirst()
.orElseThrow(AssertionError::new);
Multimap<UcteVoltageLevelCode, UcteNodeCode> nodesByVoltageLevel
= Multimaps.index(substationNodes, UcteNodeCode::getVoltageLevelCode);
String substationName = mainNode.getUcteCountryCode().getUcteCode() + mainNode.getGeographicalSpot();
List<UcteVoltageLevel> voltageLevels = new ArrayList<>();
UcteSubstation substation = new UcteSubstation(substationName, voltageLevels);
substations.add(substation);
LOGGER.trace("Define substation {}", substationName);
for (Map.Entry<UcteVoltageLevelCode, Collection<UcteNodeCode>> entry : nodesByVoltageLevel.asMap().entrySet()) {
UcteVoltageLevelCode vlc = entry.getKey();
Collection<UcteNodeCode> voltageLevelNodes = entry.getValue();
String voltageLevelName = mainNode.getUcteCountryCode().getUcteCode() + mainNode.getGeographicalSpot() + vlc.ordinal();
UcteVoltageLevel voltageLevel = new UcteVoltageLevel(voltageLevelName, substation, voltageLevelNodes);
voltageLevels.add(voltageLevel);
voltageLevelNodes.forEach(voltageLevelNode -> node2voltageLevel.put(voltageLevelNode, voltageLevel));
LOGGER.trace("Define voltage level {} as a group of {} nodes", voltageLevelName, voltageLevelNodes);
}
}
}
}
public void update() {
Lifecycle serverState = getAttribute(Attributes.SERVICE_STATE_ACTUAL);
if (Lifecycle.STOPPED.equals(serverState) || Lifecycle.STOPPING.equals(serverState)
|| Lifecycle.DESTROYED.equals(serverState) || !getAttribute(Attributes.SERVICE_UP)) {
LOG.debug("Skipped update of {} when service state is {} and running is {}",
new Object[]{this, getAttribute(Attributes.SERVICE_STATE_ACTUAL), getAttribute(SERVICE_UP)});
return;
}
synchronized (this) {
Iterable<Entity> availableEntities = FluentIterable.from(getEntities().getMembers())
.filter(new HasHostnameAndValidLifecycle());
LOG.debug("{} updating with entities: {}", this, Iterables.toString(availableEntities));
ImmutableListMultimap<String, Entity> hostnameToEntity = Multimaps.index(availableEntities,
new HostnameTransformer());
Map<String, String> octetToName = Maps.newHashMap();
BiMap<String, String> ipToARecord = HashBiMap.create();
Multimap<String, String> aRecordToCnames = MultimapBuilder.hashKeys().hashSetValues().build();
Multimap<String, String> ipToAllNames = MultimapBuilder.hashKeys().hashSetValues().build();
for (Map.Entry<String, Entity> entry : hostnameToEntity.entries()) {
String domainName = entry.getKey();
Entity entity = entry.getValue();
String address = null;
AttributeSensor<String> addressSensor = getConfig(ADDRESS_SENSOR);
if (addressSensor!=null) {
address = entity.getAttribute(addressSensor);
} else {
if (!hasLoggedDeprecationAboutAddressSensor) {
LOG.warn("BIND entity "+this+" is using legacy machine inspection to determine IP address; set the "+ADDRESS_SENSOR.getName()+" config to ensure compatibility with future versions");
hasLoggedDeprecationAboutAddressSensor = true;
}
Maybe<SshMachineLocation> location = Machines.findUniqueMachineLocation(entity.getLocations(), SshMachineLocation.class);
if (!location.isPresent()) {
LOG.debug("Member {} of {} does not have an hostname so will not be configured", entity, this);
} else if (ipToARecord.inverse().containsKey(domainName)) {
// already has a hostname, ignore (could log if domain is different?)
} else {
address = location.get().getAddress().getHostAddress();
}
}
if (Strings.isBlank(address)) {
continue;
}
ipToAllNames.put(address, domainName);
if (!ipToARecord.containsKey(address)) {
ipToARecord.put(address, domainName);
if (getReverseLookupNetwork().contains(new Cidr(address + "/32"))) {
String octet = Iterables.get(Splitter.on('.').split(address), 3);
if (!octetToName.containsKey(octet)) octetToName.put(octet, domainName);
}
} else {
aRecordToCnames.put(ipToARecord.get(address), domainName);
}
}
sensors().set(A_RECORDS, ImmutableMap.copyOf(ipToARecord.inverse()));
sensors().set(PTR_RECORDS, ImmutableMap.copyOf(octetToName));
sensors().set(CNAME_RECORDS, Multimaps.unmodifiableMultimap(aRecordToCnames));
sensors().set(ADDRESS_MAPPINGS, Multimaps.unmodifiableMultimap(ipToAllNames));
// Update Bind configuration files and restart the service
getDriver().updateBindConfiguration();
}
}
@Override
public Multimap<String, IScheduledTask> createNamedGroups(Iterable<IScheduledTask> tasks) {
return Multimaps.index(tasks, task -> "sla_cluster_");
}