List of usage examples for com.google.common.collect Multimap isEmpty
boolean isEmpty();
From source file:com.google.errorprone.bugpatterns.ModifyingCollectionWithItself.java
private List<Fix> buildValidReplacements(Multimap<Integer, JCVariableDecl> potentialReplacements, Function<JCVariableDecl, Fix> replacementFunction) { if (potentialReplacements.isEmpty()) { return ImmutableList.of(); }/*from w w w .ja va 2 s. c o m*/ // Take all of the potential edit-distance replacements with the same minimum distance, // then suggest them as individual fixes. return FluentIterable.from(potentialReplacements.get(Collections.min(potentialReplacements.keySet()))) .transform(replacementFunction).toList(); }
From source file:com.palantir.atlasdb.keyvalue.impl.ValidatingQueryRewritingKeyValueService.java
@Override public void putWithTimestamps(String tableName, Multimap<Cell, Value> cellValues) throws KeyAlreadyExistsException { if (cellValues.isEmpty()) { return;/* www . j av a 2 s . c o m*/ } Validate.isTrue(!tableName.equals(TransactionConstants.TRANSACTION_TABLE), TRANSACTION_ERROR); long lastTimestamp = -1; boolean allAtSameTimestamp = true; for (Value value : cellValues.values()) { long timestamp = value.getTimestamp(); Validate.isTrue(timestamp != Long.MAX_VALUE); Validate.isTrue(timestamp >= 0); if (lastTimestamp != -1 && timestamp != lastTimestamp) { allAtSameTimestamp = false; } lastTimestamp = timestamp; } if (allAtSameTimestamp) { Multimap<Cell, byte[]> cellValuesWithStrippedTimestamp = Multimaps.transformValues(cellValues, Value.GET_VALUE); Map<Cell, byte[]> putMap = Maps.transformValues(cellValuesWithStrippedTimestamp.asMap(), new Function<Collection<byte[]>, byte[]>() { @Override public byte[] apply(Collection<byte[]> input) { try { return Iterables.getOnlyElement(input); } catch (IllegalArgumentException e) { log.error( "Application tried to put multiple same-cell values in at same timestamp; attempting to perform last-write-wins, but ordering is not guaranteed."); return Iterables.getLast(input); } } }); put(tableName, putMap, lastTimestamp); return; } delegate.putWithTimestamps(tableName, cellValues); }
From source file:com.qcadoo.mes.deviationCausesReporting.print.DeviationsProtocolPdf.java
private VerticalLayout createDetailedSummarySection(final DeviationsReportCriteria criteria, final Locale locale) { Multimap<String, DeviationSummary> summariesByType = deviationSummariesDataProvider .getDeviationsByCauseType(criteria); if (summariesByType.isEmpty()) { return VerticalLayout.empty(); }// w ww . java 2 s.c o m Map<String, PdfPTable> deviationCausesWithSummary = Maps.transformValues(summariesByType.asMap(), getSummariesToTableConverter(locale)); List<VerticalLayout> causeAndSummaryLayouts = FluentIterable.from(deviationCausesWithSummary.entrySet()) .transform(CAUSE_AND_SUMMARY_TABLE_IN_VERTICAL_LAYOUT).toList(); VerticalLayout tables = Fold.fold(causeAndSummaryLayouts, VerticalLayout.create(), VerticalLayout.REDUCE_BY_MERGE); Paragraph header = Headers .big(translate("deviationCausesReporting.report.deviationDetailsByType.header", locale)); return VerticalLayout.create().append(header).merge(tables); }
From source file:net.shibboleth.idp.attribute.filter.impl.policyrule.saml.AttributeInMetadataPolicyRule.java
/** {@inheritDoc} */ @Override//from ww w. ja va2 s .c om @Nonnull public Set<IdPAttributeValue<?>> getMatchingValues(@Nonnull final IdPAttribute attribute, @Nonnull final AttributeFilterContext filterContext) { ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this); final Multimap<String, IdPRequestedAttribute> requestedAttributes = filterContext .getRequestedIdPAttributes(); if (null == requestedAttributes || requestedAttributes.isEmpty()) { if (matchIfMetadataSilent) { log.debug("{} The peer's metadata did not have appropriate requested attributes available" + ", returning all the input values", getLogPrefix()); return Collections.unmodifiableSet(attribute.getValues()); } else { log.debug("{} The peer's metadata did not have appropriate requested attributes available" + ", returning no values", getLogPrefix()); return Collections.EMPTY_SET; } } final Collection<IdPRequestedAttribute> requestedAttributeList = requestedAttributes.get(attribute.getId()); if (null == requestedAttributeList) { log.debug("{} Attribute {} not found in metadata", getLogPrefix(), attribute.getId()); return Collections.EMPTY_SET; } final Set<IdPAttributeValue<?>> values = new HashSet<>(); for (final IdPRequestedAttribute requestedAttribute : requestedAttributeList) { if (null == requestedAttribute) { log.info("{} Attribute {} found in metadata but with no values that" + " could be decoded, values not matched", getLogPrefix(), attribute.getId()); continue; } if (!requestedAttribute.getIsRequired() && onlyIfRequired) { log.debug("{} Attribute {} found in metadata, but was not required" + ", values not matched", getLogPrefix(), attribute.getId()); continue; } values.addAll(filterValues(attribute, requestedAttribute.getValues())); } return values; }
From source file:org.eclipse.sirius.business.internal.session.SessionEventBrokerImpl.java
@Override public Command transactionAboutToCommit(ResourceSetChangeEvent event) throws RollbackException { CompoundCommand compoundCommand = new CompoundCommand(); Multimap<ModelChangeTrigger, Notification> listenersToNotify = collectListenersToNotify( event.getNotifications());/*from w w w .j a v a2 s . c om*/ if (listenersToNotify != null && !listenersToNotify.isEmpty()) { Ordering<ModelChangeTrigger> priorityOrdering = Ordering.natural() .onResultOf(SessionEventBrokerImpl.getPriorityFunction); List<ModelChangeTrigger> sortedKeys = priorityOrdering.sortedCopy(listenersToNotify.keySet()); for (ModelChangeTrigger key : sortedKeys) { Collection<Notification> notif = listenersToNotify.get(key); if (notif != null && !notif.isEmpty()) { Option<Command> triggerCmdOption = key.localChangesAboutToCommit(notif); if (triggerCmdOption.some() && triggerCmdOption.get().canExecute()) { compoundCommand.append(triggerCmdOption.get()); } } } } return compoundCommand; }
From source file:org.apache.aurora.scheduler.async.preemptor.PendingTaskProcessor.java
@Override public void run() { metrics.recordTaskProcessorRun();/*from w w w .j a va2 s .c o m*/ storage.read(new Storage.Work.Quiet<Void>() { @Override public Void apply(StoreProvider store) { Multimap<String, PreemptionVictim> slavesToActiveTasks = clusterState.getSlavesToActiveTasks(); if (slavesToActiveTasks.isEmpty()) { // No preemption victims to consider. return null; } // Group the offers by slave id so they can be paired with active tasks from the same slave. Map<String, HostOffer> slavesToOffers = Maps.uniqueIndex(offerManager.getOffers(), OFFER_TO_SLAVE_ID); Set<String> allSlaves = Sets .newHashSet(Iterables.concat(slavesToOffers.keySet(), slavesToActiveTasks.keySet())); // The algorithm below attempts to find a reservation for every task group by matching // it against all available slaves until a preemption slot is found. Groups are evaluated // in a round-robin fashion to ensure fairness (e.g.: G1, G2, G3, G1, G2). // A slave is removed from further matching once a reservation is made. Similarly, all // identical task group instances are removed from further iteration if none of the // available slaves could yield a preemption proposal. A consuming iterator is used for // task groups to ensure iteration order is preserved after a task group is removed. LoadingCache<IJobKey, AttributeAggregate> jobStates = attributeCache(store); List<TaskGroupKey> pendingGroups = fetchIdlePendingGroups(store); Iterator<TaskGroupKey> groups = Iterators.consumingIterator(pendingGroups.iterator()); while (!pendingGroups.isEmpty()) { boolean matched = false; TaskGroupKey group = groups.next(); ITaskConfig task = group.getTask(); metrics.recordPreemptionAttemptFor(task); Iterator<String> slaveIterator = allSlaves.iterator(); while (slaveIterator.hasNext()) { String slaveId = slaveIterator.next(); Optional<ImmutableSet<PreemptionVictim>> candidates = preemptionVictimFilter .filterPreemptionVictims(task, slavesToActiveTasks.get(slaveId), jobStates.getUnchecked(task.getJob()), Optional.fromNullable(slavesToOffers.get(slaveId)), store); metrics.recordSlotSearchResult(candidates, task); if (candidates.isPresent()) { // Slot found -> remove slave to avoid multiple task reservations. slaveIterator.remove(); slotCache.put(new PreemptionProposal(candidates.get(), slaveId), group); matched = true; break; } } if (!matched) { // No slot found for the group -> remove group and reset group iterator. pendingGroups.removeAll(ImmutableSet.of(group)); groups = Iterators.consumingIterator(pendingGroups.iterator()); } } return null; } }); }
From source file:eu.mondo.driver.fourstore.FourStoreGraphDriverReadWrite.java
@Override public void deleteEdges(final Multimap<String, String> edges, final String type) throws IOException { if (edges.isEmpty()) { return;/*from www . ja v a 2 s . c o m*/ } deleteEdgesPartition(edges, type); }
From source file:org.mondo.collaboration.security.lens.arbiter.LockArbiter.java
private void preInitializeMatchers(Multimap<IQuerySpecification<?>, Lock> lockQueries) throws IncQueryException { if (!lockQueries.isEmpty()) new GenericPatternGroup(lockQueries.keySet()).prepare(getQueryEngine()); for (IQuerySpecification<?> lockQuery : lockQueries.keySet()) { IncQueryMatcher<? extends IPatternMatch> matcher = getQueryEngine().getMatcher(lockQuery); for (Lock lock : lockQueries.get(lockQuery)) { matcherForLock.put(lock, matcher); }//from ww w .ja va 2 s.c o m } }
From source file:com.b2international.snowowl.snomed.importer.rf2.validation.SnomedTaxonomyValidator.java
private Collection<SnomedValidationDefect> doValidate() { try {/*from www . j ava2 s . c o m*/ final Multimap<String, InvalidRelationship> invalidRelationships = processTaxonomy(); if (!invalidRelationships.isEmpty()) { String messageWithEffectiveTime = "'%s' relationship refers to an inactive concept '%s' (%s) in effective time '%s'"; String messageWithOutEffectiveTime = "'%s' relationship refers to an inactive concept '%s' (%s)"; List<String> validationMessages = invalidRelationships.asMap().entrySet().stream() .flatMap(entry -> { String effectiveTime = entry.getKey(); Collection<InvalidRelationship> relationships = entry.getValue(); return relationships.stream().map(relationship -> { String relationshipId = String.valueOf(relationship.getRelationshipId()); String missingReference = MissingConcept.DESTINATION == relationship .getMissingConcept() ? String.valueOf(relationship.getDestinationId()) : String.valueOf(relationship.getSourceId()); String missingReferenceLabel = relationship.getMissingConcept().getLabel(); if (!Strings.isNullOrEmpty(effectiveTime)) { return String.format(messageWithEffectiveTime, relationshipId, missingReference, missingReferenceLabel, effectiveTime); } else { return String.format(messageWithOutEffectiveTime, relationshipId, missingReference, missingReferenceLabel); } }); }).collect(toList()); LOGGER.info("{} SNOMED CT ontology validation successfully finished. {} taxonomy {} identified.", Concepts.STATED_RELATIONSHIP.equals(characteristicType) ? "Stated" : "Inferred", validationMessages.size(), validationMessages.size() > 1 ? "issues were" : "issue was"); return singleton(new SnomedIncompleteTaxonomyValidationDefect(relationshipsFile.getName(), validationMessages)); } } catch (final IOException e) { LOGGER.error("Validation failed.", e); return singleton(new SnomedValidationDefect(relationshipsFile.getName(), DefectType.IO_PROBLEM, Collections.<String>emptySet())); } LOGGER.info("{} SNOMED CT ontology validation successfully finished. No errors were found.", Concepts.STATED_RELATIONSHIP.equals(characteristicType) ? "Stated" : "Inferred"); return emptySet(); }
From source file:org.artifactory.ui.rest.service.builds.buildsinfo.tabs.licenses.BuildLicensesService.java
@Override public void execute(ArtifactoryRestRequest request, RestResponse response) { try {/*www. j a va 2 s .c om*/ String name = request.getPathParamByKey("name"); String buildNumber = request.getPathParamByKey("number"); String buildStarted = DateUtils.formatBuildDate(Long.parseLong(request.getPathParamByKey("date"))); Boolean authFind = Boolean.valueOf(request.getQueryParamByKey("autoFind")); Build build = getBuild(name, buildNumber, buildStarted, response); // fetch license Multimap<RepoPath, ModuleLicenseModel> repoPathLicenseModuleModel = getRepoPathLicenseModuleModelMultimap( build, authFind); if (repoPathLicenseModuleModel != null && !repoPathLicenseModuleModel.isEmpty()) { Collection<ModuleLicenseModel> values = repoPathLicenseModuleModel.values(); // fetch published modules Set<ModuleLicenseModel> publishedModules = getPublishedModulesFromModelList(values, build.getModules()); // filter published modules from licenses publishedModules.forEach(published -> values.remove(published)); // fetch build license summary Set<String> scopes = getScopeMapping(values); BuildLicenseModel buildLicenseModel = new BuildLicenseModel(values, publishedModules, scopes); response.iModel(buildLicenseModel); // get scopes } } catch (ParseException e) { log.error(e.toString()); response.error("error with retrieving build licenses"); return; } }