List of usage examples for com.google.common.collect Multimap asMap
Map<K, Collection<V>> asMap();
From source file:com.b2international.snowowl.snomed.datastore.id.cis.CisSnomedIdentifierService.java
@Override public void register(final Set<String> componentIds) { LOGGER.debug(String.format("Registering {} component IDs.", componentIds.size())); final Map<String, SctId> sctIds = getSctIds(componentIds); final Map<String, SctId> problemSctIds = ImmutableMap.copyOf(Maps.filterValues(sctIds, Predicates.<SctId>not(Predicates.or(SctId::isAvailable, SctId::isReserved, SctId::isAssigned)))); if (!problemSctIds.isEmpty()) { throw new SctIdStatusException( "Cannot register %s component IDs because they are not available, reserved, or already assigned.", problemSctIds);//from w ww.j av a2s. c o m } final Map<String, SctId> availableOrReservedSctIds = ImmutableMap .copyOf(Maps.filterValues(sctIds, Predicates.or(SctId::isAvailable, SctId::isReserved))); if (availableOrReservedSctIds.isEmpty()) { return; } HttpPost registerRequest = null; String currentNamespace = null; try { if (availableOrReservedSctIds.size() > 1) { final Multimap<String, String> componentIdsByNamespace = toNamespaceMultimap( availableOrReservedSctIds.keySet()); for (final Entry<String, Collection<String>> entry : componentIdsByNamespace.asMap().entrySet()) { currentNamespace = entry.getKey(); for (final Collection<String> bulkIds : Iterables.partition(entry.getValue(), BULK_LIMIT)) { LOGGER.debug( String.format("Sending bulk registration request for namespace %s with size %d.", currentNamespace, bulkIds.size())); registerRequest = httpPost(String.format("sct/bulk/register?token=%s", getToken()), createBulkRegistrationData(bulkIds)); execute(registerRequest); } } } else { final String componentId = Iterables.getOnlyElement(availableOrReservedSctIds.keySet()); currentNamespace = SnomedIdentifiers.getNamespace(componentId); registerRequest = httpPost(String.format("sct/register?token=%s", getToken()), createRegistrationData(componentId)); execute(registerRequest); } } catch (IOException e) { throw new SnowowlRuntimeException( String.format("Exception while reserving IDs for namespace %s.", currentNamespace), e); } finally { release(registerRequest); } }
From source file:com.b2international.snowowl.snomed.datastore.id.cis.CisSnomedIdentifierService.java
@Override public void deprecate(final Set<String> componentIds) { LOGGER.debug("Deprecating {} component IDs.", componentIds.size()); final Map<String, SctId> sctIds = getSctIds(componentIds); final Map<String, SctId> problemSctIds = ImmutableMap.copyOf(Maps.filterValues(sctIds, Predicates.<SctId>not(Predicates.or(SctId::isAssigned, SctId::isPublished, SctId::isDeprecated)))); if (!problemSctIds.isEmpty()) { throw new SctIdStatusException( "Cannot deprecate %s component IDs because they are not assigned, published, or already deprecated.", problemSctIds);/*from w ww .ja v a2s . co m*/ } final Map<String, SctId> assignedOrPublishedSctIds = ImmutableMap .copyOf(Maps.filterValues(sctIds, Predicates.or(SctId::isAssigned, SctId::isPublished))); if (assignedOrPublishedSctIds.isEmpty()) { return; } HttpPut deprecateRequest = null; String currentNamespace = null; try { if (assignedOrPublishedSctIds.size() > 1) { final Multimap<String, String> componentIdsByNamespace = toNamespaceMultimap( assignedOrPublishedSctIds.keySet()); for (final Entry<String, Collection<String>> entry : componentIdsByNamespace.asMap().entrySet()) { currentNamespace = entry.getKey(); for (final Collection<String> bulkIds : Iterables.partition(entry.getValue(), BULK_LIMIT)) { LOGGER.debug( String.format("Sending bulk deprecation request for namespace %s with size %d.", currentNamespace, bulkIds.size())); deprecateRequest = httpPut(String.format("sct/bulk/deprecate?token=%s", getToken()), createBulkDeprecationData(currentNamespace, bulkIds)); execute(deprecateRequest); } } } else { final String componentId = Iterables.getOnlyElement(assignedOrPublishedSctIds.keySet()); currentNamespace = SnomedIdentifiers.getNamespace(componentId); deprecateRequest = httpPut(String.format("sct/deprecate?token=%s", getToken()), createDeprecationData(componentId)); execute(deprecateRequest); } } catch (IOException e) { throw new SnowowlRuntimeException( String.format("Exception while deprecating IDs for namespace %s.", currentNamespace), e); } finally { release(deprecateRequest); } }
From source file:io.airlift.drift.codec.metadata.AbstractThriftMetadataBuilder.java
protected final void inferThriftFieldIds(Multimap<String, FieldMetadata> fieldsByName, Set<String> fieldsWithConflictingIds) { // for each name group, set the ids on the fields without ids for (Entry<String, Collection<FieldMetadata>> entry : fieldsByName.asMap().entrySet()) { Collection<FieldMetadata> fields = entry.getValue(); String fieldName = entry.getKey(); // skip all entries without a name or singleton groups... we'll deal with these later if (fields.size() <= 1) { continue; }/*from www . jav a2 s . c o m*/ // all ids used by this named field Set<Short> ids = fields.stream().map(FieldMetadata::getId).filter(Objects::nonNull).collect(toSet()); // multiple conflicting ids if (ids.size() > 1) { if (!fieldsWithConflictingIds.contains(fieldName)) { metadataErrors.addError("Thrift class '%s' field '%s' has multiple ids: %s", structName, fieldName, ids.toString()); fieldsWithConflictingIds.add(fieldName); } continue; } // single id, so set on all fields in this group (groups with no id are handled later), // and validate isLegacyId is consistent and correct. if (ids.size() == 1) { short id = Iterables.getOnlyElement(ids); boolean isLegacyId = extractFieldIsLegacyId(id, fieldName, fields); // propagate the id data to all fields in this group for (FieldMetadata field : fields) { field.setId(id); field.setIsLegacyId(isLegacyId); } } } }
From source file:org.jetbrains.jet.lang.resolve.TypeHierarchyResolver.java
private void checkSupertypesForConsistency() { for (MutableClassDescriptor mutableClassDescriptor : topologicalOrder) { Multimap<TypeConstructor, TypeProjection> multimap = SubstitutionUtils .buildDeepSubstitutionMultimap(mutableClassDescriptor.getDefaultType()); for (Map.Entry<TypeConstructor, Collection<TypeProjection>> entry : multimap.asMap().entrySet()) { Collection<TypeProjection> projections = entry.getValue(); if (projections.size() > 1) { TypeConstructor typeConstructor = entry.getKey(); DeclarationDescriptor declarationDescriptor = typeConstructor.getDeclarationDescriptor(); assert declarationDescriptor instanceof TypeParameterDescriptor : declarationDescriptor; TypeParameterDescriptor typeParameterDescriptor = (TypeParameterDescriptor) declarationDescriptor; // Immediate arguments of supertypes cannot be projected Set<JetType> conflictingTypes = Sets.newLinkedHashSet(); for (TypeProjection projection : projections) { conflictingTypes.add(projection.getType()); }/*from w w w . j av a 2s. c om*/ switch (typeParameterDescriptor.getVariance()) { case INVARIANT: // Leave conflicting types as is break; case IN_VARIANCE: // Filter out those who have supertypes in this set (common supertype) Filter.REMOVE_IF_SUPERTYPE_IN_THE_SET.proceed(conflictingTypes); break; case OUT_VARIANCE: // Filter out those who have subtypes in this set (common subtype) Filter.REMOVE_IF_SUBTYPE_IN_THE_SET.proceed(conflictingTypes); break; } if (conflictingTypes.size() > 1) { DeclarationDescriptor containingDeclaration = typeParameterDescriptor .getContainingDeclaration(); assert containingDeclaration instanceof ClassDescriptor : containingDeclaration; JetClassOrObject psiElement = (JetClassOrObject) BindingContextUtils .classDescriptorToDeclaration(trace.getBindingContext(), mutableClassDescriptor); JetDelegationSpecifierList delegationSpecifierList = psiElement .getDelegationSpecifierList(); assert delegationSpecifierList != null; // trace.getErrorHandler().genericError(delegationSpecifierList.getNode(), "Type parameter " + typeParameterDescriptor.getName() + " of " + containingDeclaration.getName() + " has inconsistent values: " + conflictingTypes); trace.report(INCONSISTENT_TYPE_PARAMETER_VALUES.on(delegationSpecifierList, typeParameterDescriptor, (ClassDescriptor) containingDeclaration, conflictingTypes)); } } } } }
From source file:es.usc.citius.composit.core.composition.optimization.FunctionalDominanceOptimizer.java
public Collection<Collection<Operation<E>>> functionalOutputDominance(Collection<Operation<E>> operations, ServiceMatchNetwork<E, T> network, int level) { Multimap<Set<E>, Operation<E>> providers = HashMultimap.create(); Set<Operation<E>> consumers = new HashSet<Operation<E>>(); for (Operation<E> o : operations) { // Check operations that consumes the outputs of this op. for (E output : o.getSignature().getOutputs()) { for (E target : network.getTargetElementsMatchedBy(output).keySet()) { consumers.addAll(Sets.newHashSet(network.getOperationsWithInput(target))); }// w ww . java2 s. c o m } // Remove all the consumers that are not in the subsequent layers consumers.retainAll(network.getOperationsAfterLevel(level)); // Compute all the inputs matched by operation o Set<E> inputsMatched = new HashSet<E>(); for (Operation<E> consumer : consumers) { inputsMatched.addAll( network.partialMatch(o.getSignature().getOutputs(), consumer.getSignature().getInputs()) .getTargetElements()); } providers.get(inputsMatched).add(o); } // Now, build a new multi map moving all dominated elements Multimap<Set<E>, Operation<E>> nonDominatedProviders = HashMultimap.create(); // Inefficient subset elimination algorithm O(n^2) for (Set<E> m1 : providers.keys()) { // Check whether m1 is dominated or not boolean dominated = false; for (Set<E> m2 : providers.keys()) { if (m2.size() > m1.size()) { // m1 could be dominated by m2 if (m2.containsAll(m1)) { // m2 dominates m1 dominated = true; break; } } } if (!dominated) { // Copy nonDominatedProviders.get(m1).addAll(providers.get(m1)); } } return nonDominatedProviders.asMap().values(); }
From source file:io.prestosql.sql.analyzer.Analysis.java
public void addTableColumnReferences(AccessControl accessControl, Identity identity, Multimap<QualifiedObjectName, String> tableColumnMap) { AccessControlInfo accessControlInfo = new AccessControlInfo(accessControl, identity); Map<QualifiedObjectName, Set<String>> references = tableColumnReferences.computeIfAbsent(accessControlInfo, k -> new LinkedHashMap<>()); tableColumnMap.asMap() .forEach((key, value) -> references.computeIfAbsent(key, k -> new HashSet<>()).addAll(value)); }
From source file:eu.itesla_project.online.StateAnalyzer.java
private void putResultsIntoContext(Integer stateId, ImpactAnalysisResult simulationResult, ForecastAnalysisResults results) { Objects.requireNonNull(stateId, "state id is null"); Objects.requireNonNull(simulationResult, "simulation result is null"); Objects.requireNonNull(results, "forecast analysis result is null"); List<SecurityIndex> securityIndexesList = new ArrayList<SecurityIndex>(); if (parameters.getSecurityIndexes() == null) securityIndexesList = simulationResult.getSecurityIndexes(); else {/* ww w.j a v a2 s. c o m*/ securityIndexesList = simulationResult.getSecurityIndexes().stream() .filter(x -> parameters.getSecurityIndexes().contains(x.getId().getSecurityIndexType())) .collect(Collectors.toList()); if (securityIndexesList.isEmpty()) { logger.info("Empty filter security indexes -> using all the indexes"); securityIndexesList = simulationResult.getSecurityIndexes(); } } //Multimap<String, SecurityIndex> securityIndexes = Multimaps.index(simulationResult.getSecurityIndexes(), new Function<SecurityIndex, String>() { Multimap<String, SecurityIndex> securityIndexes = Multimaps.index(securityIndexesList, new Function<SecurityIndex, String>() { @Override public String apply(SecurityIndex index) { return index.getId().getContingencyId(); } }); synchronized (results) { for (Map.Entry<String, Collection<SecurityIndex>> entry : securityIndexes.asMap().entrySet()) { boolean isSafe = OnlineUtils.isSafe(entry.getValue()); if (!isSafe) { logger.info("{}: unsafe for contingency {} afer time domain simulation", stateId, entry.getKey()); results.addUnsafeStateWithIndexes(entry.getKey(), stateId, new ArrayList<>(entry.getValue())); } else { logger.info("{}: safe for contingency {} afer time domain simulation", stateId, entry.getKey()); if (parameters.validation()) // if validation add anyway to results results.addUnsafeStateWithIndexes(entry.getKey(), stateId, new ArrayList<>(entry.getValue())); } } } }
From source file:org.pshdl.model.types.builtIn.busses.BusGenerator.java
private HDLGenerationInfo annotateSignals(HDLGenerationInfo hdgi, Unit unit) { final HDLUnit hdlUnit = hdgi.unit; final ModificationSet ms = new ModificationSet(); ms.addTo(hdlUnit, HDLUnit.fAnnotations, busDescription.create(unit.toCompactString())); final Multimap<String, String> mm = TreeMultimap.create(); for (final Entry<String, NamedElement> e : unit.declarations.entrySet()) { final NamedElement value = e.getValue(); if (value instanceof Row) { final Row row = (Row) value; for (final NamedElement def : row.definitions) { final String dName = def.getName(); mm.put(dName, row.name); }//from w ww . j a v a 2 s .c om } } for (final Entry<String, Collection<String>> e : mm.asMap().entrySet()) { final String dName = e.getKey(); final String row = Joiner.on(ROW_SEPARTOR).join(e.getValue()); final Collection<HDLVariable> lastSegmentIs = HDLQuery.select(HDLVariable.class).from(hdlUnit) .where(HDLVariable.fName).lastSegmentIs(dName).getAll(); for (final HDLVariable hdlVariable : lastSegmentIs) { ms.replace(hdlVariable, hdlVariable.addAnnotations(busTagetSignal.create(row))); } } final HDLGenerationInfo hdgiRef = new HDLGenerationInfo(ms.apply(hdlUnit)); hdgiRef.files = hdgi.files; return hdgiRef; }
From source file:com.facebook.presto.server.remotetask.HttpRemoteTask.java
@Override public synchronized void addSplits(Multimap<PlanNodeId, Split> splitsBySource) { requireNonNull(splitsBySource, "splitsBySource is null"); // only add pending split if not done if (getTaskStatus().getState().isDone()) { return;//from w w w . j a v a 2 s .co m } for (Entry<PlanNodeId, Collection<Split>> entry : splitsBySource.asMap().entrySet()) { PlanNodeId sourceId = entry.getKey(); Collection<Split> splits = entry.getValue(); checkState(!noMoreSplits.contains(sourceId), "noMoreSplits has already been set for %s", sourceId); int added = 0; for (Split split : splits) { if (pendingSplits.put(sourceId, new ScheduledSplit(nextSplitId.getAndIncrement(), sourceId, split))) { added++; } } if (planFragment.isPartitionedSources(sourceId)) { pendingSourceSplitCount += added; partitionedSplitCountTracker.setPartitionedSplitCount(getPartitionedSplitCount()); } needsUpdate.set(true); } updateSplitQueueSpace(); scheduleUpdate(); }
From source file:org.immutables.value.processor.Gsons.java
public Iterable<TypeAdapterTypes> typeAdapters() { Multimap<AbstractDeclaring, ValueType> byDeclaring = HashMultimap.create(); for (ValueType value : values().values()) { Protoclass protoclass = value.constitution.protoclass(); if (protoclass.kind().isValue()) { Optional<AbstractDeclaring> typeAdaptersProvider = protoclass.typeAdaptersProvider(); if (typeAdaptersProvider.isPresent()) { byDeclaring.put(typeAdaptersProvider.get(), value); } else if (protoclass.gsonTypeAdapters().isPresent() && protoclass.declaringType().isPresent()) { DeclaringType topLevel = protoclass.declaringType().get().associatedTopLevel(); byDeclaring.put(topLevel, value); }//w w w .j a v a 2s . c o m } } ImmutableList.Builder<TypeAdapterTypes> builder = ImmutableList.builder(); for (Entry<AbstractDeclaring, Collection<ValueType>> entry : byDeclaring.asMap().entrySet()) { builder.add(ImmutableTypeAdapterTypes.builder().definedBy(entry.getKey()).addAllTypes(entry.getValue()) .build()); } return builder.build(); }