List of usage examples for com.google.common.collect Multimap isEmpty
boolean isEmpty();
From source file:org.apache.twill.yarn.YarnTwillRunnerService.java
/** * Creates a {@link Runnable} for renewing {@link SecureStore} for running applications. * * @param scheduler the schedule to schedule next renewal execution * @param renewer the {@link SecureStoreRenewer} to use for renewal * @param retryRuns if non-empty, only the given set of application name and run id that need to have * secure store renewed; if empty, renew all running applications * @param retryDelay the delay before retrying applications that are failed to have secure store renewed * @param timeUnit the unit for the {@code delay} and {@code failureDelay}. * @return a {@link Runnable}/*from w w w. j a v a2 s . c om*/ */ private Runnable createSecureStoreUpdateRunnable(final ScheduledExecutorService scheduler, final SecureStoreRenewer renewer, final Multimap<String, RunId> retryRuns, final long retryDelay, final TimeUnit timeUnit) { return new Runnable() { @Override public void run() { // Collects the set of running application runs Table<String, RunId, YarnTwillController> liveApps; synchronized (YarnTwillRunnerService.this) { if (retryRuns.isEmpty()) { liveApps = HashBasedTable.create(controllers); } else { // If this is a renew retry, only renew the one in the retryRuns set liveApps = HashBasedTable.create(); for (Table.Cell<String, RunId, YarnTwillController> cell : controllers.cellSet()) { if (retryRuns.containsEntry(cell.getRowKey(), cell.getColumnKey())) { liveApps.put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); } } } } Multimap<String, RunId> failureRenews = renewSecureStore(liveApps, renewer, false); if (!failureRenews.isEmpty()) { // If there are failure during the renewal, schedule a retry with a new Runnable. LOG.info("Schedule to retry on secure store renewal for applications {} in {} {}", failureRenews.keySet(), retryDelay, timeUnit.name().toLowerCase()); try { scheduler.schedule(createSecureStoreUpdateRunnable(scheduler, renewer, failureRenews, retryDelay, timeUnit), retryDelay, timeUnit); } catch (RejectedExecutionException e) { // If the renewal is stopped, the scheduler will be stopped, // hence this exception will be thrown and can be safely ignore. } } } }; }
From source file:org.codice.ddf.admin.security.ldap.test.DirectoryStructTestMethod.java
@Override public Report test(LdapConfiguration configuration) { LdapConnectionAttempt connectionAttempt = ldapTestingCommons.bindUserToLdapConnection(configuration); if (connectionAttempt.result() != SUCCESSFUL_BIND) { return createReport(SUCCESS_TYPES, FAILURE_TYPES, WARNING_TYPES, Collections.singletonList(connectionAttempt.result().name())); }/*from w w w .ja v a 2 s .co m*/ Multimap<String, String> resultsWithConfigIds = ArrayListMultimap.create(); try (Connection ldapConnection = connectionAttempt.connection()) { if (checkUserDir(configuration, ldapConnection)) { resultsWithConfigIds.put(BASE_USER_DN_NOT_FOUND.name(), BASE_USER_DN); } else { checkUsersInDir(configuration, resultsWithConfigIds, ldapConnection); } if (checkGroupDir(configuration, ldapConnection)) { resultsWithConfigIds.put(BASE_GROUP_DN_NOT_FOUND.name(), BASE_GROUP_DN); } else { // First check the group objectClass is on at least one entry in the directory checkGroupObjectClass(configuration, resultsWithConfigIds, ldapConnection); // Then, check that there is a group entry (of the correct objectClass) that has // any member references checkGroup(configuration, resultsWithConfigIds, ldapConnection); } } if (resultsWithConfigIds.isEmpty()) { return createReport(SUCCESS_TYPES, FAILURE_TYPES, WARNING_TYPES, SUCCESSFUL_TEST); } return createReport(SUCCESS_TYPES, FAILURE_TYPES, WARNING_TYPES, resultsWithConfigIds); }
From source file:org.mule.module.launcher.StartupSummaryDeploymentListener.java
public void onAfterStartup() { if (!logger.isInfoEnabled()) { return;//from www .ja v a 2s .c o m } Multimap<String, String> applicationsPerDomain = LinkedListMultimap.create(); Map<String, ArtifactDeploymentStatusTracker.DeploymentState> domainDeploymentState = tracker .getDomainDeploymentStatusTracker().getDeploymentStates(); SimpleLoggingTable domainTable = new SimpleLoggingTable(); domainTable.addColumn(DOMAIN_OWNER_LABEL, ARTIFACT_NAME_LABEL_LENGTH); domainTable.addColumn(STATUS_LABEL, STATUS_LABEL_LENGTH); for (String domain : domainDeploymentState.keySet()) { String[] data = new String[] { domain, domainDeploymentState.get(domain).toString() }; domainTable.addDataRow(data); } Map<String, ArtifactDeploymentStatusTracker.DeploymentState> applicationStates = tracker .getApplicationDeploymentStatusTracker().getDeploymentStates(); for (String applicationName : applicationStates.keySet()) { Application application = deploymentService.findApplication(applicationName); applicationsPerDomain.put(application.getDomain().getArtifactName(), applicationName); } String message; if (!applicationsPerDomain.isEmpty()) { SimpleLoggingTable applicationTable = new SimpleLoggingTable(); applicationTable.addColumn(APPLICATION_LABEL, ARTIFACT_NAME_LABEL_LENGTH); applicationTable.addColumn(DOMAIN_OWNER_LABEL, DOMAIN_OWNER_LABEL_LENGTH); applicationTable.addColumn(STATUS_LABEL, STATUS_LABEL_LENGTH); for (String domainName : applicationsPerDomain.keySet()) { for (String app : applicationsPerDomain.get(domainName)) { String[] data = new String[] { app, domainName, applicationStates.get(app).toString() }; applicationTable.addDataRow(data); } } message = String.format("%n%s%n%s", domainTable, applicationTable); } else { message = String.format("%n%s", domainTable); } logger.info(message); }
From source file:org.eclipse.xtext.validation.impl.AssignmentQuantityAllocator.java
@Override public IQuantities getAssignmentQuantities(EObject obj, ISyntaxConstraint rule, List<IConcreteSyntaxDiagnostic> acceptor) { Multimap<EStructuralFeature, ISyntaxConstraint> assignments = HashMultimap.create(); collectAssignments(rule, obj, rule, assignments, acceptor); // Map<EStructuralFeature, Integer> quantities = Maps.newHashMap(); Quantities quants = createQuantities(obj); for (EStructuralFeature f : obj.eClass().getEAllStructuralFeatures()) { int quantity = getFeatureQuantity(obj, f); if (quantity > 0 && !assignments.containsKey(f)) acceptor.add(diagnosticProvider.createAssignmentMissingDiagnostic(rule, obj, f, Collections.<ISyntaxConstraint>emptySet())); else//from ww w .j a v a 2s . c o m quants.setFeatureQuantity(f, quantity); } Multimap<EStructuralFeature, ISyntaxConstraint> multipleAssignments = HashMultimap.create(); Multimap<EStructuralFeature, ISyntaxConstraint> allowTransients = HashMultimap.create(); for (Map.Entry<EStructuralFeature, Integer> f : quants.getFeatureQuantities().entrySet()) { Collection<ISyntaxConstraint> ass = assignments.get(f.getKey()); if (ass.isEmpty()) continue; boolean allowTransient = f.getKey() instanceof EAttribute && !f.getKey().isMany() && f.getValue() == 0 && allowTransient(obj, f.getKey(), ass); boolean multiNeeded = ass.size() > 1 && f.getValue() != 0; if (allowTransient) allowTransients.putAll(f.getKey(), ass); if (multiNeeded) multipleAssignments.putAll(f.getKey(), ass); if (!allowTransient && !multiNeeded) for (ISyntaxConstraint a : ass) quants.setAssignmentQuantity(a, f.getValue()); } if (multipleAssignments.isEmpty() && allowTransients.isEmpty()) return quants; for (Map.Entry<EStructuralFeature, Collection<ISyntaxConstraint>> e : allowTransients.asMap().entrySet()) { int min = 0; for (ISyntaxConstraint x : e.getValue()) min += intervalProvider.getMin(quants, x, Sets.<ISyntaxConstraint>newHashSet()); int val = min > 0 ? 1 : 0; quants.setFeatureQuantity(e.getKey(), val); if (e.getValue().size() == 1) quants.setAssignmentQuantity(e.getValue().iterator().next(), val); } // System.out.println("AllowTransientsQuantities: " + quants.toString()); if (multipleAssignments.isEmpty()) return quants; return null; // TODO: implement an algorithm to handle multipleAssignments. For details, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=310454 }
From source file:com.google.devtools.build.lib.query2.RdepsUnboundedVisitor.java
@Override protected Visit getVisitResult(Iterable<DepAndRdep> depAndRdeps) throws InterruptedException { Collection<SkyKey> validRdeps = new ArrayList<>(); // Multimap of dep to all the reverse deps in this visitation. Used to filter out the // disallowed deps. Multimap<SkyKey, SkyKey> reverseDepMultimap = ArrayListMultimap.create(); for (DepAndRdep depAndRdep : depAndRdeps) { // The "roots" of our visitation (see #preprocessInitialVisit) have a null 'dep' field. if (depAndRdep.dep == null) { validRdeps.add(depAndRdep.rdep); } else {/*from w ww . jav a 2s . c om*/ reverseDepMultimap.put(depAndRdep.dep, depAndRdep.rdep); } } Multimap<SkyKey, SkyKey> packageKeyToTargetKeyMap = env .makePackageKeyToTargetKeyMap(Iterables.concat(reverseDepMultimap.values())); Set<PackageIdentifier> pkgIdsNeededForTargetification = packageKeyToTargetKeyMap.keySet().stream() .map(SkyQueryEnvironment.PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER).collect(toImmutableSet()); packageSemaphore.acquireAll(pkgIdsNeededForTargetification); try { // Filter out disallowed deps. We cannot defer the targetification any further as we do not // want to retrieve the rdeps of unwanted nodes (targets). if (!reverseDepMultimap.isEmpty()) { Collection<Target> filteredTargets = env.filterRawReverseDepsOfTransitiveTraversalKeys( reverseDepMultimap.asMap(), packageKeyToTargetKeyMap); filteredTargets.stream().map(SkyQueryEnvironment.TARGET_TO_SKY_KEY).forEachOrdered(validRdeps::add); } } finally { packageSemaphore.releaseAll(pkgIdsNeededForTargetification); } ImmutableList<SkyKey> uniqueValidRdeps = validRdeps.stream().filter(validRdepUniquifier::unique) .collect(ImmutableList.toImmutableList()); // Retrieve the reverse deps as SkyKeys and defer the targetification and filtering to next // recursive visitation. ImmutableList.Builder<DepAndRdep> depAndRdepsToVisitBuilder = ImmutableList.builder(); env.graph .getReverseDeps( uniqueValidRdeps) .entrySet() .forEach(reverseDepsEntry -> depAndRdepsToVisitBuilder.addAll(Iterables.transform( Iterables.filter(reverseDepsEntry.getValue(), Predicates.and(SkyQueryEnvironment.IS_TTV, universe)), rdep -> new DepAndRdep(reverseDepsEntry.getKey(), rdep)))); return new Visit(/*keysToUseForResult=*/ uniqueValidRdeps, /*keysToVisit=*/ depAndRdepsToVisitBuilder.build()); }
From source file:com.google.livingstories.server.rpcimpl.ContentRpcImpl.java
private void sendEmailAlerts(EventContentItem eventContentItem) { PersistenceManager pm = PMF.get().getPersistenceManager(); // Get list of users Query query = pm.newQuery(UserLivingStoryEntity.class); query.setFilter("livingStoryId == livingStoryIdParam && subscribedToEmails == true"); query.declareParameters("long livingStoryIdParam"); try {/*ww w. ja v a 2s. c o m*/ @SuppressWarnings("unchecked") List<UserLivingStoryEntity> userLivingStoryEntities = (List<UserLivingStoryEntity>) query .execute(eventContentItem.getLivingStoryId()); Multimap<String, String> usersByLocale = HashMultimap.create(); for (UserLivingStoryEntity entity : userLivingStoryEntities) { usersByLocale.put(entity.getSubscriptionLocale(), entity.getParentEmailAddress()); } if (!usersByLocale.isEmpty()) { // Determine what all the placeholder text should be for the per-locale e-mails. // getServletContext() doesn't return a valid result at construction-time, so // we initialize the external properties lazily. if (cachedFromAddress == null && cachedPublisherName == null) { ExternalServiceKeyChain externalKeys = new ExternalServiceKeyChain(getServletContext()); cachedPublisherName = externalKeys.getPublisherName(); cachedFromAddress = externalKeys.getFromAddress(); } LivingStoryEntity livingStory = pm.getObjectById(LivingStoryEntity.class, eventContentItem.getLivingStoryId()); String baseLspUrl = getBaseServerUrl() + "/lsps/" + livingStory.getUrl(); String eventSummary = eventContentItem.getEventSummary(); String eventDetails = eventContentItem.getContent(); if (GlobalUtil.isContentEmpty(eventSummary) && !GlobalUtil.isContentEmpty(eventDetails)) { eventSummary = SnippetUtil.createSnippet(JavaNodeAdapter.fromHtml(eventDetails), EMAIL_ALERT_SNIPPET_LENGTH); } ImmutableMap<String, String> placeholderMap = new ImmutableMap.Builder<String, String>() .put("storyTitle", livingStory.getTitle()) .put("updateTitle", eventContentItem.getEventUpdate()) .put("publisherName", cachedPublisherName) .put("snippet", StringUtil.stripForExternalSites(eventSummary)) .put("linkUrl", baseLspUrl + "#OVERVIEW:false,false,false,false,n,n,n:" + eventContentItem.getId()) .put("loginUrl", DataImplFactory.getUserLoginService().createLoginUrl(baseLspUrl)).build(); for (String locale : usersByLocale.keySet()) { sendEmailsForLocale(placeholderMap, locale, usersByLocale.get(locale)); } } } finally { query.closeAll(); pm.close(); } }
From source file:com.b2international.snowowl.snomed.validation.detail.SnomedValidationIssueDetailExtension.java
private void extendConceptIssueLabels(BranchContext context, Collection<ValidationIssue> issues) { final RevisionSearcher searcher = context.service(RevisionSearcher.class); final List<ValidationIssue> conceptIssues = issues.stream() .filter(issue -> SnomedTerminologyComponentConstants.CONCEPT_NUMBER == issue.getAffectedComponent() .getTerminologyComponentId()) .collect(Collectors.toList()); if (conceptIssues.isEmpty()) { return;/*from w w w .j a v a 2 s .c o m*/ } final Multimap<String, ValidationIssue> issuesByConceptId = Multimaps.index(conceptIssues, issue -> issue.getAffectedComponent().getComponentId()); final Set<String> synonymIds = SnomedRequests.prepareGetSynonyms().build().execute(context).stream() .map(SnomedConcept::getId).collect(Collectors.toSet()); final Multimap<String, String> affectedComponentLabelsByConcept = HashMultimap.create(); searcher.scroll(Query.select(String[].class).from(SnomedDescriptionIndexEntry.class) .fields(SnomedDescriptionIndexEntry.Fields.CONCEPT_ID, SnomedDescriptionIndexEntry.Fields.TERM) .where(Expressions.builder().filter(SnomedDescriptionIndexEntry.Expressions.active()) .filter(SnomedDescriptionIndexEntry.Expressions.concepts(issuesByConceptId.keySet())) .filter(SnomedDescriptionIndexEntry.Expressions.types(ImmutableSet.<String>builder() .add(Concepts.FULLY_SPECIFIED_NAME).addAll(synonymIds).build())) .build()) .limit(SCROLL_SIZE).build()).forEach(hits -> { for (String[] hit : hits) { affectedComponentLabelsByConcept.put(hit[0], hit[1]); } }); if (!affectedComponentLabelsByConcept.isEmpty()) { issuesByConceptId.values().forEach(issue -> { final Collection<String> labels = affectedComponentLabelsByConcept .get(issue.getAffectedComponent().getComponentId()); issue.setAffectedComponentLabels(ImmutableList.copyOf(labels)); }); } }
From source file:com.b2international.snowowl.snomed.validation.detail.SnomedValidationIssueDetailExtension.java
private void extendRelationshipIssueLabels(BranchContext context, Collection<ValidationIssue> issues) { final RevisionSearcher searcher = context.service(RevisionSearcher.class); final List<ValidationIssue> relationshipIssues = issues.stream() .filter(issue -> SnomedTerminologyComponentConstants.RELATIONSHIP_NUMBER == issue .getAffectedComponent().getTerminologyComponentId()) .collect(Collectors.toList()); if (relationshipIssues.isEmpty()) { return;/*from w w w . j ava 2 s . com*/ } final Multimap<String, ValidationIssue> issuesByRelationshipId = Multimaps.index(relationshipIssues, issue -> issue.getAffectedComponent().getComponentId()); final Set<String> synonymIds = SnomedRequests.prepareGetSynonyms().build().execute(context).stream() .map(SnomedConcept::getId).collect(Collectors.toSet()); final Set<String> conceptsToFetch = newHashSet(); searcher.scroll(Query.select(String[].class).from(SnomedRelationshipIndexEntry.class) .fields(SnomedRelationshipIndexEntry.Fields.SOURCE_ID, SnomedRelationshipIndexEntry.Fields.TYPE_ID, SnomedRelationshipIndexEntry.Fields.DESTINATION_ID) .where(SnomedRelationshipIndexEntry.Expressions.ids(issuesByRelationshipId.keySet())) .limit(SCROLL_SIZE).build()).forEach(hits -> { for (String[] hit : hits) { conceptsToFetch.add(hit[0]); conceptsToFetch.add(hit[1]); conceptsToFetch.add(hit[2]); } }); final Multimap<String, String> affectedComponentLabelsByConcept = HashMultimap.create(); searcher.scroll(Query.select(String[].class).from(SnomedDescriptionIndexEntry.class) .fields(SnomedDescriptionIndexEntry.Fields.CONCEPT_ID, SnomedDescriptionIndexEntry.Fields.TERM) .where(Expressions.builder().filter(SnomedDescriptionIndexEntry.Expressions.active()) .filter(SnomedDescriptionIndexEntry.Expressions.concepts(conceptsToFetch)) .filter(SnomedDescriptionIndexEntry.Expressions.types(ImmutableSet.<String>builder() .add(Concepts.FULLY_SPECIFIED_NAME).addAll(synonymIds).build())) .build()) .limit(SCROLL_SIZE).build()).forEach(hits -> { for (String[] hit : hits) { affectedComponentLabelsByConcept.put(hit[0], hit[1]); } }); if (!affectedComponentLabelsByConcept.isEmpty()) { issuesByRelationshipId.values().forEach(issue -> { final Collection<String> labels = affectedComponentLabelsByConcept .get(issue.getAffectedComponent().getComponentId()); issue.setAffectedComponentLabels(ImmutableList.copyOf(labels)); }); } }
From source file:org.apache.beam.runners.apex.translation.operators.ApexTimerInternals.java
/** * Fire the timers that are ready. These are the timers * that are registered to be triggered at a time before the current time. * Timer processing may register new timers, which can cause the returned * timestamp to be before the the current time. The caller may repeat * the call until such backdated timers are cleared. * @return minimum timestamp of registered timers. *///from w w w.ja v a2 s . c o m public long fireReadyTimers(long currentTime, TimerProcessor<K> timerProcessor, TimeDomain timeDomain) { TimerSet timers = getTimerSet(timeDomain); // move minTimestamp first, // timer additions that result from firing may modify it timers.minTimestamp = currentTime; // we keep the timers to return in a different list and launch them later // because we cannot prevent a trigger from registering another timer, // which would lead to concurrent modification exception. Multimap<Slice, TimerInternals.TimerData> toFire = HashMultimap.create(); Iterator<Map.Entry<Slice, Set<Slice>>> it = timers.activeTimers.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Slice, Set<Slice>> keyWithTimers = it.next(); Iterator<Slice> timerIt = keyWithTimers.getValue().iterator(); while (timerIt.hasNext()) { try { TimerData timerData = CoderUtils.decodeFromByteArray(timers.timerDataCoder, timerIt.next().buffer); if (timerData.getTimestamp().isBefore(currentTime)) { toFire.put(keyWithTimers.getKey(), timerData); timerIt.remove(); } } catch (CoderException e) { throw new RuntimeException(e); } } if (keyWithTimers.getValue().isEmpty()) { it.remove(); } } // fire ready timers if (!toFire.isEmpty()) { for (Slice keyBytes : toFire.keySet()) { try { K key = CoderUtils.decodeFromByteArray(keyCoder, keyBytes.buffer); timerProcessor.fireTimer(key, toFire.get(keyBytes)); } catch (CoderException e) { throw new RuntimeException(e); } } } return timers.minTimestamp; }
From source file:org.apache.accumulo.examples.wikisearch.parser.FieldIndexQueryReWriter.java
private RewriterTreeNode orNormalizedTerms(RewriterTreeNode myroot, Multimap<String, String> indexedTerms) throws Exception { // we have multimap of FieldName to multiple FieldValues if (indexedTerms.isEmpty()) { throw new Exception("indexed Terms empty"); }/*from w w w . j a v a 2 s. c om*/ try { // NOTE: doing a depth first enumeration didn't work when I started // removing nodes halfway through. The following method does work, // it's essentially a reverse breadth first traversal. List<RewriterTreeNode> nodes = new ArrayList<RewriterTreeNode>(); Enumeration<?> bfe = myroot.breadthFirstEnumeration(); while (bfe.hasMoreElements()) { RewriterTreeNode node = (RewriterTreeNode) bfe.nextElement(); nodes.add(node); } // walk backwards for (int i = nodes.size() - 1; i >= 0; i--) { RewriterTreeNode node = nodes.get(i); if (log.isDebugEnabled()) { log.debug("orNormalizedTerms, analyzing node: " + node.toString() + " " + node.printNode()); } if (node.getType() == ParserTreeConstants.JJTANDNODE || node.getType() == ParserTreeConstants.JJTORNODE) { continue; } else if (node.getType() == ParserTreeConstants.JJTJEXLSCRIPT) { if (node.getChildCount() == 0) { if (log.isDebugEnabled()) { log.debug("orNormalizedTerms: Head node has no children!"); } throw new Exception(); // Head node has no children. } } else { if (log.isDebugEnabled()) { log.debug("Testing data location: " + node.getFieldName()); } String fName = node.getFieldName().toString(); String fValue = node.getFieldValue().toString(); if (indexedTerms.containsKey(fName + ":" + fValue)) { if (indexedTerms.get(fName + ":" + fValue).size() > 1) { // Replace node with an OR, and make children from the multimap collection node.setType(ParserTreeConstants.JJTORNODE); boolean neg = node.isNegated(); node.setNegated(false); node.setFieldName(null); node.setFieldValue(null); Collection<String> values = indexedTerms.get(fName + ":" + fValue); for (String value : values) { RewriterTreeNode n = new RewriterTreeNode(ParserTreeConstants.JJTEQNODE, fName, value, neg); node.add(n); } } else if (indexedTerms.get(fName + ":" + fValue).size() == 1) { // Straight replace Collection<String> values = indexedTerms.get(fName + ":" + fValue); for (String val : values) { // should only be 1 node.setFieldValue(val); } } } else { // throw new Exception("orNormalizedTerms, encountered a non-indexed term: " + node.getFieldName().toString()); } } } } catch (Exception e) { log.debug("Caught exception in orNormalizedTerms(): " + e); throw new Exception("exception in: orNormalizedTerms"); } return myroot; }