use of java.util.function.BiConsumer in project intellij-community by JetBrains.
the class ProgressIndicatorUtils method scheduleWithWriteActionPriority.
@NotNull
public static CompletableFuture<?> scheduleWithWriteActionPriority(@NotNull final ProgressIndicator progressIndicator, @NotNull final Executor executor, @NotNull final ReadTask readTask) {
final Application application = ApplicationManager.getApplication();
// invoke later even if on EDT
// to avoid tasks eagerly restarting immediately, allocating many pooled threads
// which get cancelled too soon when a next write action arrives in the same EDT batch
// (can happen when processing multiple VFS events or writing multiple files on save)
// use SwingUtilities instead of application.invokeLater
// to tolerate any immediate modality changes (e.g. https://youtrack.jetbrains.com/issue/IDEA-135180)
CompletableFuture<?> future = new CompletableFuture<>();
//noinspection SSBasedInspection
EdtInvocationManager.getInstance().invokeLater(() -> {
if (application.isDisposed() || progressIndicator.isCanceled()) {
future.complete(null);
return;
}
final ApplicationAdapter listener = new ApplicationAdapter() {
@Override
public void beforeWriteActionStart(@NotNull Object action) {
if (!progressIndicator.isCanceled()) {
progressIndicator.cancel();
readTask.onCanceled(progressIndicator);
}
}
};
application.addApplicationListener(listener);
future.whenComplete((BiConsumer<Object, Throwable>) (o, throwable) -> application.removeApplicationListener(listener));
try {
executor.execute(new Runnable() {
@Override
public void run() {
final ReadTask.Continuation continuation;
try {
continuation = runUnderProgress(progressIndicator, readTask);
} catch (Throwable e) {
future.completeExceptionally(e);
throw e;
}
if (continuation == null) {
future.complete(null);
} else {
application.invokeLater(new Runnable() {
@Override
public void run() {
try {
if (!progressIndicator.isCanceled()) {
continuation.getAction().run();
}
} finally {
future.complete(null);
}
}
@Override
public String toString() {
return "continuation of " + readTask;
}
}, continuation.getModalityState());
}
}
@Override
public String toString() {
return readTask.toString();
}
});
} catch (RuntimeException | Error e) {
application.removeApplicationListener(listener);
future.completeExceptionally(e);
throw e;
}
});
return future;
}
use of java.util.function.BiConsumer in project lucene-solr by apache.
the class MetricUtils method toMaps.
/**
* Convert selected metrics to maps or to flattened objects.
* @param registry source of metrics
* @param shouldMatchFilters metrics must match any of these filters
* @param mustMatchFilter metrics must match this filter
* @param propertyFilter limit what properties of a metric are returned
* @param skipHistograms discard any {@link Histogram}-s and histogram parts of {@link Timer}-s.
* @param skipAggregateValues discard internal values of {@link AggregateMetric}-s.
* @param compact use compact representation for counters and gauges.
* @param simple use simplified representation for complex metrics - instead of a (name, map)
* only the selected (name "." key, value) pairs will be produced.
* @param consumer consumer that accepts produced objects
*/
public static void toMaps(MetricRegistry registry, List<MetricFilter> shouldMatchFilters, MetricFilter mustMatchFilter, PropertyFilter propertyFilter, boolean skipHistograms, boolean skipAggregateValues, boolean compact, boolean simple, BiConsumer<String, Object> consumer) {
final Map<String, Metric> metrics = registry.getMetrics();
final SortedSet<String> names = registry.getNames();
names.stream().filter(s -> shouldMatchFilters.stream().anyMatch(metricFilter -> metricFilter.matches(s, metrics.get(s)))).filter(s -> mustMatchFilter.matches(s, metrics.get(s))).forEach(n -> {
Metric metric = metrics.get(n);
convertMetric(n, metric, propertyFilter, skipHistograms, skipAggregateValues, compact, simple, consumer);
});
}
use of java.util.function.BiConsumer in project nifi by apache.
the class TestReportLineageToAtlas method validateAtlasUrls.
@Test
public void validateAtlasUrls() throws Exception {
final ReportLineageToAtlas reportingTask = new ReportLineageToAtlas();
final MockProcessContext processContext = new MockProcessContext(reportingTask);
final MockValidationContext validationContext = new MockValidationContext(processContext);
processContext.setProperty(ATLAS_NIFI_URL, "http://nifi.example.com:8080/nifi");
processContext.setProperty(ATLAS_USER, "admin");
processContext.setProperty(ATLAS_PASSWORD, "admin");
BiConsumer<Collection<ValidationResult>, Consumer<ValidationResult>> assertResults = (rs, a) -> {
assertTrue(rs.iterator().hasNext());
for (ValidationResult r : rs) {
logger.info("{}", r);
final String subject = r.getSubject();
if (ATLAS_URLS.getDisplayName().equals(subject)) {
a.accept(r);
}
}
};
// Default setting.
assertResults.accept(reportingTask.validate(validationContext), r -> assertTrue("Atlas URLs is required", !r.isValid()));
// Invalid URL.
processContext.setProperty(ATLAS_URLS, "invalid");
assertResults.accept(reportingTask.validate(validationContext), r -> assertTrue("Atlas URLs is invalid", !r.isValid()));
// Valid URL
processContext.setProperty(ATLAS_URLS, "http://atlas.example.com:21000");
assertTrue(processContext.isValid());
// Valid URL with Expression
processContext.setProperty(ATLAS_URLS, "http://atlas.example.com:${literal(21000)}");
assertTrue(processContext.isValid());
// Valid URLs
processContext.setProperty(ATLAS_URLS, "http://atlas1.example.com:21000, http://atlas2.example.com:21000");
assertTrue(processContext.isValid());
// Invalid and Valid URLs
processContext.setProperty(ATLAS_URLS, "invalid, http://atlas2.example.com:21000");
assertResults.accept(reportingTask.validate(validationContext), r -> assertTrue("Atlas URLs is invalid", !r.isValid()));
}
use of java.util.function.BiConsumer in project nifi by apache.
the class TestWaitNotifyProtocol method testReleaseCandidateTotal.
@Test
public void testReleaseCandidateTotal() throws Exception {
final List<Integer> candidates = IntStream.range(0, 10).boxed().collect(Collectors.toList());
final Signal signal = new Signal();
final List<Integer> released = new ArrayList<>();
final List<Integer> waiting = new ArrayList<>();
// Test empty counter name, should use total counters.
final String emptyCounterName = null;
final BiConsumer<Long, Integer> releaseCandidate = (requiredCountForPass, releasableCandidatePerPass) -> {
released.clear();
waiting.clear();
signal.releaseCandidates(emptyCounterName, requiredCountForPass, releasableCandidatePerPass, candidates, r -> released.addAll(r), w -> waiting.addAll(w));
};
final String counterA = "counterA";
final String counterB = "counterB";
final String counterC = "counterC";
final Field releasableCount = Signal.class.getDeclaredField("releasableCount");
releasableCount.setAccessible(true);
// No counter, should wait.
releaseCandidate.accept(3L, 1);
assertEquals(0, released.size());
assertEquals(10, waiting.size());
assertEquals(0, signal.getCount(emptyCounterName));
assertEquals(0, signal.getCount(CONSUMED_COUNT_NAME));
assertEquals(0, releasableCount.getInt(signal));
// Counter is not enough yet.
signal.getCounts().put(counterA, 1L);
signal.getCounts().remove(CONSUMED_COUNT_NAME);
releaseCandidate.accept(3L, 1);
assertEquals(0, released.size());
assertEquals(10, waiting.size());
// Counter incremented, but not enough
assertEquals(1, signal.getCount(emptyCounterName));
assertEquals(0, signal.getCount(CONSUMED_COUNT_NAME));
assertEquals(0, releasableCount.getInt(signal));
// Counter reached the target.
signal.getCounts().put(counterA, 1L);
signal.getCounts().put(counterB, 1L);
signal.getCounts().put(counterC, 1L);
signal.getCounts().remove(CONSUMED_COUNT_NAME);
releaseCandidate.accept(3L, 1);
assertEquals(1, released.size());
assertEquals(9, waiting.size());
// Counter 3 was converted into 1 release
assertEquals(0, signal.getCount(emptyCounterName));
assertEquals(-3, signal.getCount(CONSUMED_COUNT_NAME));
assertEquals(0, releasableCount.getInt(signal));
// Counter reached the target for two candidates.
signal.getCounts().put(counterA, 1L);
signal.getCounts().put(counterB, 2L);
signal.getCounts().put(counterC, 3L);
signal.getCounts().remove(CONSUMED_COUNT_NAME);
releaseCandidate.accept(3L, 1);
assertEquals(2, released.size());
assertEquals(8, waiting.size());
// Counter 3 was converted into 1 release
assertEquals(0, signal.getCount(emptyCounterName));
assertEquals(-6, signal.getCount(CONSUMED_COUNT_NAME));
assertEquals(0, releasableCount.getInt(signal));
// Counter reached the target for two candidates, and reminder is 2.
signal.getCounts().put(counterA, 3L);
signal.getCounts().put(counterB, 3L);
signal.getCounts().put(counterC, 5L);
signal.getCounts().remove(CONSUMED_COUNT_NAME);
releaseCandidate.accept(3L, 1);
// 11 / 3 = 3
assertEquals(3, released.size());
assertEquals(7, waiting.size());
assertEquals(2, signal.getCount(emptyCounterName));
assertEquals(-9, signal.getCount(CONSUMED_COUNT_NAME));
assertEquals(0, releasableCount.getInt(signal));
// Counter reached the target for two pass count and each pass can release 2 candidates.
signal.getCounts().put(counterA, 1L);
signal.getCounts().put(counterB, 2L);
signal.getCounts().put(counterC, 3L);
signal.getCounts().remove(CONSUMED_COUNT_NAME);
releaseCandidate.accept(3L, 2);
// (6 / 3) * 2 = 4
assertEquals(4, released.size());
assertEquals(6, waiting.size());
assertEquals(0, signal.getCount(emptyCounterName));
assertEquals(-6, signal.getCount(CONSUMED_COUNT_NAME));
assertEquals(0, releasableCount.getInt(signal));
// If there are counts more than enough to release current candidates, unused releasableCount should remain.
signal.getCounts().put(counterA, 10L);
signal.getCounts().put(counterB, 20L);
signal.getCounts().put(counterC, 20L);
signal.getCounts().remove(CONSUMED_COUNT_NAME);
releaseCandidate.accept(3L, 2);
// (50 / 3) * 2 = 32. Used 10.
assertEquals(10, released.size());
assertEquals(0, waiting.size());
// 50 % 3 = 2.
assertEquals(2, signal.getCount(emptyCounterName));
// 50 % 3 = 2.
assertEquals(-48, signal.getCount(CONSUMED_COUNT_NAME));
// 32 - 10 = 22.
assertEquals(22, releasableCount.getInt(signal));
}
use of java.util.function.BiConsumer in project dhis2-core by dhis2.
the class AnalyticalObjectEmbeddedDimensionUpgrader method executeInTransaction.
@Override
public void executeInTransaction() {
BiConsumer<BaseDimensionalEmbeddedObject, AnalyticalObject> dataElementGroupSetConsumer = (embeddedDimension, analyticalObject) -> {
DataElementGroupSetDimension dimension = new DataElementGroupSetDimension();
dimension.setDimension((DataElementGroupSet) embeddedDimension.getDimension());
dimension.setItems(DimensionalObjectUtils.asTypedList(embeddedDimension.getItems()));
analyticalObject.addDataElementGroupSetDimension(dimension);
};
BiConsumer<BaseDimensionalEmbeddedObject, AnalyticalObject> orgUnitGroupSetConsumer = (embeddedDimension, analyticalObject) -> {
OrganisationUnitGroupSetDimension dimension = new OrganisationUnitGroupSetDimension();
dimension.setDimension((OrganisationUnitGroupSet) embeddedDimension.getDimension());
dimension.setItems(DimensionalObjectUtils.asTypedList(embeddedDimension.getItems()));
analyticalObject.addOrganisationUnitGroupSetDimension(dimension);
};
BiConsumer<BaseDimensionalEmbeddedObject, AnalyticalObject> categoryOptionGroupSetConsumer = (embeddedDimension, analyticalObject) -> {
CategoryOptionGroupSetDimension dimension = new CategoryOptionGroupSetDimension();
dimension.setDimension((CategoryOptionGroupSet) embeddedDimension.getDimension());
dimension.setItems(DimensionalObjectUtils.asTypedList(embeddedDimension.getItems()));
analyticalObject.addCategoryOptionGroupSetDimension(dimension);
};
try {
upgradeGrupSetDimensions("reporttable", "orgunitgroupset", "orgunitgroup", ReportTable.class, OrganisationUnitGroupSet.class, OrganisationUnitGroup.class, orgUnitGroupSetConsumer);
upgradeGrupSetDimensions("reporttable", "dataelementgroupset", "dataelementgroup", ReportTable.class, DataElementGroupSet.class, DataElementGroup.class, dataElementGroupSetConsumer);
upgradeGrupSetDimensions("reporttable", "categoryoptiongroupset", "categoryoptiongroup", ReportTable.class, CategoryOptionGroupSet.class, CategoryOptionGroup.class, categoryOptionGroupSetConsumer);
upgradeGrupSetDimensions("chart", "orgunitgroupset", "orgunitgroup", Chart.class, OrganisationUnitGroupSet.class, OrganisationUnitGroup.class, orgUnitGroupSetConsumer);
upgradeGrupSetDimensions("chart", "dataelementgroupset", "dataelementgroup", Chart.class, DataElementGroupSet.class, DataElementGroup.class, dataElementGroupSetConsumer);
upgradeGrupSetDimensions("chart", "categoryoptiongroupset", "categoryoptiongroup", Chart.class, CategoryOptionGroupSet.class, CategoryOptionGroup.class, categoryOptionGroupSetConsumer);
upgradeGrupSetDimensions("eventreport", "orgunitgroupset", "orgunitgroup", EventReport.class, OrganisationUnitGroupSet.class, OrganisationUnitGroup.class, orgUnitGroupSetConsumer);
upgradeGrupSetDimensions("eventchart", "orgunitgroupset", "orgunitgroup", EventChart.class, OrganisationUnitGroupSet.class, OrganisationUnitGroup.class, orgUnitGroupSetConsumer);
} catch (Exception ex) {
log.debug("Error during group set dimensions upgrade of favorite, probably because upgrade was already done", ex);
return;
}
}
Aggregations