java.util.function.BooleanSupplier Java Examples
The following examples show how to use
java.util.function.BooleanSupplier.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GTree.java From ghidra with Apache License 2.0 | 6 votes |
/** * Requests that the node with the given name, in the given parent, be edited. <b>This * operation (as with many others on this tree) is asynchronous.</b> This request will be * buffered as needed to wait for the given node to be added to the parent, up to a timeout * period. * * @param parent the parent node * @param childName the child node name */ public void startEditing(GTreeNode parent, final String childName) { // we call this here, even though the JTree will do this for us, so that we will trigger // a load call before this task is run, in case lazy nodes are involved in this tree, // which must be loaded before we can edit expandPath(parent); // // The request to edit the node may be for a node that has not yet been added to this // tree. Further, some clients will buffer events, which means that the node the client // wishes to edit may not yet be in the parent node even if we run this request later on // the Swing thread. To deal with this, we use a construct that will run our request // once the given node has been added to the parent. // BooleanSupplier isReady = () -> parent.getChild(childName) != null; int expireMs = 3000; ExpiringSwingTimer.runWhen(isReady, expireMs, () -> { runTask(new GTreeStartEditingTask(GTree.this, tree, parent, childName)); }); }
Example #2
Source File: ExpiringSwingTimerTest.java From ghidra with Apache License 2.0 | 6 votes |
@Test public void testWorkOnlyHappensOnce() { BooleanSupplier isReady = () -> { return true; }; AtomicInteger runCount = new AtomicInteger(); Runnable r = () -> { runCount.incrementAndGet(); }; ExpiringSwingTimer timer = ExpiringSwingTimer.runWhen(isReady, 10000, r); waitFor(() -> !timer.isRunning()); assertEquals(1, runCount.get()); timer.start(); waitFor(() -> !timer.isRunning()); assertEquals(1, runCount.get()); }
Example #3
Source File: Planner.java From crate with Apache License 2.0 | 6 votes |
@VisibleForTesting public Planner(Settings settings, ClusterService clusterService, Functions functions, TableStats tableStats, NumberOfShards numberOfShards, TableCreator tableCreator, Schemas schemas, UserManager userManager, BooleanSupplier hasValidLicense, LoadedRules loadedRules, SessionSettingRegistry sessionSettingRegistry ) { this.clusterService = clusterService; this.functions = functions; this.tableStats = tableStats; this.logicalPlanner = new LogicalPlanner(functions, tableStats, () -> clusterService.state().nodes().getMinNodeVersion(), loadedRules); this.isStatementExecutionAllowed = new IsStatementExecutionAllowed(hasValidLicense); this.numberOfShards = numberOfShards; this.tableCreator = tableCreator; this.schemas = schemas; this.userManager = userManager; this.sessionSettingRegistry = sessionSettingRegistry; initAwarenessAttributes(settings); }
Example #4
Source File: AssertSubscriber.java From rsocket-java with Apache License 2.0 | 6 votes |
/** * Blocking method that waits until {@code conditionSupplier} returns true, or if it does not * before the specified timeout, throws an {@link AssertionError} with the specified error message * supplier. * * @param timeout the timeout duration * @param errorMessageSupplier the error message supplier * @param conditionSupplier condition to break out of the wait loop * @throws AssertionError */ public static void await( Duration timeout, Supplier<String> errorMessageSupplier, BooleanSupplier conditionSupplier) { Objects.requireNonNull(errorMessageSupplier); Objects.requireNonNull(conditionSupplier); Objects.requireNonNull(timeout); long timeoutNs = timeout.toNanos(); long startTime = System.nanoTime(); do { if (conditionSupplier.getAsBoolean()) { return; } try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } while (System.nanoTime() - startTime < timeoutNs); throw new AssertionError(errorMessageSupplier.get()); }
Example #5
Source File: Assertions.java From gocd with Apache License 2.0 | 6 votes |
public static void waitUntil(Timeout timeout, BooleanSupplier predicate, int sleepInMillis) { long end = System.currentTimeMillis() + timeout.inMillis(); Exception e = null; while (true) { try { if (predicate.getAsBoolean()) { return; } } catch (Exception caught) { System.err.println("retrying after catching exception in Assertions.waitUntil: " + caught); e = caught; } boolean timedout = System.currentTimeMillis() > end; if (timedout) { break; } else { sleepMillis(sleepInMillis); } } String msg = e == null ? "wait timed out after " + timeout + " for: " + predicate.toString() : e.getMessage(); throw new RuntimeException(msg, e); }
Example #6
Source File: Relay.java From strongback-java with MIT License | 6 votes |
/** * Obtain a relay that instantaneously switches from one state to another using the given functions. * * @param switcher the function that switches the state, where <code>true</code> represents {@link State#ON} and * <code>false</code> represents {@link State#OFF}; may not be null * @param onState the function that returns <code>true</code> if the current state is {@link State#ON}, or * <code>false</code> otherwise; may not be null * @return the relay; never null */ static Relay instantaneous(Consumer<Boolean> switcher, BooleanSupplier onState) { return new Relay() { @Override public State state() { return onState.getAsBoolean() ? State.ON : State.OFF; } @Override public Relay on() { switcher.accept(Boolean.TRUE); return this; } @Override public Relay off() { switcher.accept(Boolean.FALSE); return this; } }; }
Example #7
Source File: KeyStoreCertSignerFactoryTest.java From athenz with Apache License 2.0 | 6 votes |
@Test(expectedExceptions = { RuntimeException.class, IllegalArgumentException.class }, expectedExceptionsMessageRegExp = ".* Failed to get caPrivateKey/caCertificate from athenz.zts.keystore_signer.keystore_ca_alias property.") public void testCreateAliasNotFound() { final BooleanSupplier sysPropRestoreFunc = this.getSysPropRestoreLambda( "athenz.zts.keystore_signer.keystore_password", "athenz.zts.keystore_signer.keystore_path", "athenz.zts.keystore_signer.keystore_ca_alias" ); // test main String filePath = Resources.getResource("keystore.pkcs12").getFile(); System.setProperty("athenz.zts.keystore_signer.keystore_password", "123456"); System.setProperty("athenz.zts.keystore_signer.keystore_path", filePath); System.setProperty("athenz.zts.keystore_signer.keystore_ca_alias", "dummy"); try (KeyStoreCertSigner keyStoreCertSigner = (KeyStoreCertSigner) new KeyStoreCertSignerFactory().create()) { } finally { sysPropRestoreFunc.getAsBoolean(); } }
Example #8
Source File: PipelineSchedulerIntegrationTest.java From gocd with Apache License 2.0 | 6 votes |
@Test public void shouldPassOverriddenEnvironmentVariablesForScheduling() { final ScheduleOptions scheduleOptions = new ScheduleOptions(new HashMap<>(), Collections.singletonMap("KEY", "value"), new HashMap<>()); HttpOperationResult operationResult = new HttpOperationResult(); goConfigService.pipelineConfigNamed(new CaseInsensitiveString(PIPELINE_MINGLE)).setVariables(env("KEY", "somejunk")); serverHealthService.update(ServerHealthState.failToScheduling(HealthStateType.general(HealthStateScope.forPipeline(PIPELINE_MINGLE)), PIPELINE_MINGLE, "should wait till cleared")); pipelineScheduler.manualProduceBuildCauseAndSave(PIPELINE_MINGLE, Username.ANONYMOUS, scheduleOptions, operationResult); assertThat(operationResult.message(), operationResult.canContinue(),is(true)); Assertions.waitUntil(Timeout.ONE_MINUTE, new BooleanSupplier() { @Override public boolean getAsBoolean() { return serverHealthService.filterByScope(HealthStateScope.forPipeline(PIPELINE_MINGLE)).size() == 0; } }); BuildCause buildCause = pipelineScheduleQueue.toBeScheduled().get(new CaseInsensitiveString(PIPELINE_MINGLE)); EnvironmentVariables overriddenVariables = buildCause.getVariables(); assertThat(overriddenVariables, is(new EnvironmentVariables(Arrays.asList(new EnvironmentVariable("KEY", "value"))))); }
Example #9
Source File: Utils.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Wait until timeout for condition to be true for specified time * * @param condition, a condition to wait for * @param timeout a time in milliseconds to wait for condition to be true, * specifying -1 will wait forever * @param sleepTime a time to sleep value in milliseconds * @return condition value, to determine if wait was successfull */ public static final boolean waitForCondition(BooleanSupplier condition, long timeout, long sleepTime) { long startTime = System.currentTimeMillis(); while (!(condition.getAsBoolean() || (timeout != -1L && ((System.currentTimeMillis() - startTime) > timeout)))) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new Error(e); } } return condition.getAsBoolean(); }
Example #10
Source File: DrainUtils.java From reactor-core with Apache License 2.0 | 5 votes |
/** * Tries draining the queue if the source just completed. * * @param <T> the output value type * @param <F> the field type holding the requested amount * @param actual the consumer of values * @param queue the queue holding available values * @param field the field updater holding the requested amount * @param instance the parent instance of the requested field * @param isCancelled callback to detect cancellation */ public static <T, F> void postComplete(CoreSubscriber<? super T> actual, Queue<T> queue, AtomicLongFieldUpdater<F> field, F instance, BooleanSupplier isCancelled) { if (queue.isEmpty()) { actual.onComplete(); return; } if (postCompleteDrain(field.get(instance), actual, queue, field, instance, isCancelled)) { return; } for (; ; ) { long r = field.get(instance); if ((r & COMPLETED_MASK) != 0L) { return; } long u = r | COMPLETED_MASK; // (active, r) -> (complete, r) transition if (field.compareAndSet(instance, r, u)) { // if the requested amount was non-zero, drain the queue if (r != 0L) { postCompleteDrain(u, actual, queue, field, instance, isCancelled); } return; } } }
Example #11
Source File: Waiter.java From vividus with Apache License 2.0 | 5 votes |
public <E extends Exception> void wait(CheckedRunnable<E> runnable, BooleanSupplier stopCondition) throws E { wait( () -> { runnable.run(); return (Void) null; }, alwaysNull -> stopCondition.getAsBoolean() ); }
Example #12
Source File: ComparisonUtils.java From vividus with Apache License 2.0 | 5 votes |
private static void compareTables(BooleanSupplier condition, List<Map<?, ?>> table1, List<Map<?, ?>> table2, List<List<EntryComparisonResult>> results, Function<List<Map<?, ?>>, Map<?, ?>> tableRowProvider1, Function<List<Map<?, ?>>, Map<?, ?>> tableRowProvider2) { while (condition.getAsBoolean()) { results.add(compareMaps(tableRowProvider1.apply(table1), tableRowProvider2.apply(table2))); } }
Example #13
Source File: StreamSpliterators.java From j2objc with Apache License 2.0 | 5 votes |
@Override void initPartialTraversalState() { SpinedBuffer.OfLong b = new SpinedBuffer.OfLong(); buffer = b; bufferSink = ph.wrapSink((Sink.OfLong) b::accept); @WeakOuter BooleanSupplier weakOuter; pusher = weakOuter = () -> spliterator.tryAdvance(bufferSink); }
Example #14
Source File: NioAsyncLoadBalanceClient.java From nifi with Apache License 2.0 | 5 votes |
public synchronized void register(final String connectionId, final BooleanSupplier emptySupplier, final Supplier<FlowFileRecord> flowFileSupplier, final TransactionFailureCallback failureCallback, final TransactionCompleteCallback successCallback, final Supplier<LoadBalanceCompression> compressionSupplier, final BooleanSupplier honorBackpressureSupplier) { if (registeredPartitions.containsKey(connectionId)) { throw new IllegalStateException("Connection with ID " + connectionId + " is already registered"); } final RegisteredPartition partition = new RegisteredPartition(connectionId, emptySupplier, flowFileSupplier, failureCallback, successCallback, compressionSupplier, honorBackpressureSupplier); registeredPartitions.put(connectionId, partition); partitionQueue.add(partition); }
Example #15
Source File: HBaseTestingUtility.java From hbase with Apache License 2.0 | 5 votes |
/** * Await the successful return of {@code condition}, sleeping {@code sleepMillis} between * invocations. */ public static void await(final long sleepMillis, final BooleanSupplier condition) throws InterruptedException { try { while (!condition.getAsBoolean()) { Thread.sleep(sleepMillis); } } catch (RuntimeException e) { if (e.getCause() instanceof AssertionError) { throw (AssertionError) e.getCause(); } throw e; } }
Example #16
Source File: WorkProcessorUtils.java From presto with Apache License 2.0 | 5 votes |
static <T> WorkProcessor<T> finishWhen(WorkProcessor<T> processor, BooleanSupplier finishSignal) { requireNonNull(processor, "processor is null"); requireNonNull(finishSignal, "finishSignal is null"); return WorkProcessor.create(() -> { if (finishSignal.getAsBoolean()) { return ProcessState.finished(); } return getNextState(processor); }); }
Example #17
Source File: OfflineDsAssignmentStrategy.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
OfflineDsAssignmentStrategy(final TargetRepository targetRepository, final AfterTransactionCommitExecutor afterCommit, final EventPublisherHolder eventPublisherHolder, final ActionRepository actionRepository, final ActionStatusRepository actionStatusRepository, final QuotaManagement quotaManagement, final BooleanSupplier multiAssignmentsConfig) { super(targetRepository, afterCommit, eventPublisherHolder, actionRepository, actionStatusRepository, quotaManagement, multiAssignmentsConfig); }
Example #18
Source File: MasterScrollBook.java From Runescape-Web-Walker-Engine with Apache License 2.0 | 5 votes |
private static boolean waitTillAtDestination(Teleports location){ return Timing.waitCondition(new BooleanSupplier(){ @Override public boolean getAsBoolean() { General.sleep(50,200); return location.getDestination().distanceTo(Player.getPosition()) < 10; } }, 8000); }
Example #19
Source File: DrainUtils.java From reactor-core with Apache License 2.0 | 5 votes |
/** * Perform a potential post-completion request accounting. * * @param <T> the output value type * @param <F> the field type holding the requested amount * @param n the requested amount * @param actual the consumer of values * @param queue the queue holding the available values * @param field the field updater for the requested amount * @param instance the parent instance for the requested field * @param isCancelled callback to detect cancellation * @return true if the state indicates a completion state. */ static <T, F> boolean postCompleteRequest(long n, Subscriber<? super T> actual, Queue<T> queue, AtomicLongFieldUpdater<F> field, F instance, BooleanSupplier isCancelled) { for (; ; ) { long r = field.get(instance); // extract the current request amount long r0 = r & REQUESTED_MASK; // preserve COMPLETED_MASK and calculate new requested amount long u = (r & COMPLETED_MASK) | Operators.addCap(r0, n); if (field.compareAndSet(instance, r, u)) { // (complete, 0) -> (complete, n) transition then replay if (r == COMPLETED_MASK) { postCompleteDrain(n | COMPLETED_MASK, actual, queue, field, instance, isCancelled); return true; } // (active, r) -> (active, r + n) transition then continue with requesting from upstream return false; } } }
Example #20
Source File: ToStringGenerator.java From ph-commons with Apache License 2.0 | 5 votes |
@Nonnull public ToStringGenerator appendIf (@Nonnull final String sField, final boolean bValue, @Nonnull final BooleanSupplier aFilter) { return aFilter.getAsBoolean () ? append (sField, bValue) : this; }
Example #21
Source File: SHAOptionsBase.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Returns the predicate indicating whether or not CPU instructions required * by the option with name {@code optionName} are available. * * @param optionName The name of the option for which a predicate should be * returned. * @return The predicate on availability of CPU instructions required by the * option. */ public static BooleanSupplier getPredicateForOption(String optionName) { switch (optionName) { case SHAOptionsBase.USE_SHA_OPTION: return IntrinsicPredicates.ANY_SHA_INSTRUCTION_AVAILABLE; case SHAOptionsBase.USE_SHA1_INTRINSICS_OPTION: return IntrinsicPredicates.SHA1_INSTRUCTION_AVAILABLE; case SHAOptionsBase.USE_SHA256_INTRINSICS_OPTION: return IntrinsicPredicates.SHA256_INSTRUCTION_AVAILABLE; case SHAOptionsBase.USE_SHA512_INTRINSICS_OPTION: return IntrinsicPredicates.SHA512_INSTRUCTION_AVAILABLE; default: throw new Error("Unexpected option " + optionName); } }
Example #22
Source File: RegisteredPartition.java From nifi with Apache License 2.0 | 5 votes |
public RegisteredPartition(final String connectionId, final BooleanSupplier emptySupplier, final Supplier<FlowFileRecord> flowFileSupplier, final TransactionFailureCallback failureCallback, final TransactionCompleteCallback successCallback, final Supplier<LoadBalanceCompression> compressionSupplier, final BooleanSupplier honorBackpressureSupplier) { this.connectionId = connectionId; this.emptySupplier = emptySupplier; this.flowFileRecordSupplier = flowFileSupplier; this.failureCallback = failureCallback; this.successCallback = successCallback; this.compressionSupplier = compressionSupplier; this.honorBackpressureSupplier = honorBackpressureSupplier; }
Example #23
Source File: BaselineAutoAdjustExecutor.java From ignite with Apache License 2.0 | 5 votes |
/** * @param log Logger. * @param cluster Ignite cluster. * @param executorService Thread pool for changing baseline. * @param enabledSupplier Supplier return {@code true} if baseline auto-adjust enabled. */ public BaselineAutoAdjustExecutor(IgniteLogger log, IgniteClusterImpl cluster, ExecutorService executorService, BooleanSupplier enabledSupplier) { this.log = log; this.cluster = cluster; this.executorService = executorService; isBaselineAutoAdjustEnabled = enabledSupplier; }
Example #24
Source File: SHAOptionsBase.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * Returns the predicate indicating whether or not CPU instructions required * by the option with name {@code optionName} are available. * * @param optionName The name of the option for which a predicate should be * returned. * @return The predicate on availability of CPU instructions required by the * option. */ protected static BooleanSupplier getPredicateForOption(String optionName) { switch (optionName) { case SHAOptionsBase.USE_SHA_OPTION: return IntrinsicPredicates.ANY_SHA_INSTRUCTION_AVAILABLE; case SHAOptionsBase.USE_SHA1_INTRINSICS_OPTION: return IntrinsicPredicates.SHA1_INSTRUCTION_AVAILABLE; case SHAOptionsBase.USE_SHA256_INTRINSICS_OPTION: return IntrinsicPredicates.SHA256_INSTRUCTION_AVAILABLE; case SHAOptionsBase.USE_SHA512_INTRINSICS_OPTION: return IntrinsicPredicates.SHA512_INSTRUCTION_AVAILABLE; default: throw new Error("Unexpected option " + optionName); } }
Example #25
Source File: RxHubTest.java From RHub with Apache License 2.0 | 5 votes |
@Then("^Consumer\"([^\"]*)\" should receive Event\"([^\"]*)\"$") public void consumer_should_receive_Event(final String consumer,final String event) throws Throwable { helper.consumers.get(consumer).await(Duration.ofSeconds(3), "consumer " + consumer + " should_receive_Event: " + event, new BooleanSupplier() { @Override public boolean getAsBoolean() { return helper.consumers.get(consumer).values().contains(event); } }); }
Example #26
Source File: TestUtils.java From enmasse with Apache License 2.0 | 5 votes |
/** * Wait for a condition, throw exception otherwise. * * @param condition The condition to check, returning {@code true} means success. * @param timeout The maximum time to wait for * @param delay The delay between checks. * @param exceptionSupplier The supplier of the exception to throw. * @throws AssertionFailedError In case the timeout expired */ public static <X extends Throwable> void waitUntilConditionOrThrow(final BooleanSupplier condition, final Duration timeout, final Duration delay, final Supplier<X> exceptionSupplier) throws X { Objects.requireNonNull(exceptionSupplier); waitUntilCondition(condition, timeout, delay, () -> { throw exceptionSupplier.get(); }); }
Example #27
Source File: ShortcutHelper.java From user-interface-samples with Apache License 2.0 | 5 votes |
/** * Use this when interacting with ShortcutManager to show consistent error messages. */ private void callShortcutManager(BooleanSupplier r) { try { if (!r.getAsBoolean()) { Utils.showToast(mContext, "Call to ShortcutManager is rate-limited"); } } catch (Exception e) { Log.e(TAG, "Caught Exception", e); Utils.showToast(mContext, "Error while calling ShortcutManager: " + e.toString()); } }
Example #28
Source File: ConfigServerBootstrapTest.java From vespa with Apache License 2.0 | 5 votes |
private void waitUntil(BooleanSupplier booleanSupplier, String messageIfWaitingFails) throws InterruptedException { Duration timeout = Duration.ofSeconds(60); Instant endTime = Instant.now().plus(timeout); while (Instant.now().isBefore(endTime)) { if (booleanSupplier.getAsBoolean()) return; Thread.sleep(10); } throw new RuntimeException(messageIfWaitingFails); }
Example #29
Source File: KafkaUsage.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
private void consumeDoubles(BooleanSupplier continuation, Runnable completion, Collection<String> topics, Consumer<ConsumerRecord<String, Double>> consumerFunction) { Deserializer<String> keyDes = new StringDeserializer(); Deserializer<Double> valDes = new DoubleDeserializer(); String randomId = UUID.randomUUID().toString(); this.consume(randomId, randomId, OffsetResetStrategy.EARLIEST, keyDes, valDes, continuation, null, completion, topics, consumerFunction); }
Example #30
Source File: JavaScriptUtils.java From neodymium-library with MIT License | 5 votes |
/** * Wait until all conditions are true. One wait statement, so the timeouts don't sum up * * @param conditions * a list of conditions to verify */ public static void until(final List<BooleanSupplier> conditions) { final long timeout = Neodymium.configuration().javaScriptTimeout(); final long start = System.currentTimeMillis(); // loop if still is time for (final BooleanSupplier condition : conditions) { boolean endEarly = false; while (!endEarly && System.currentTimeMillis() - start < timeout) { try { final boolean result = condition.getAsBoolean(); if (result) { endEarly = true; continue; } } catch (final StaleElementReferenceException | NoSuchElementException e) { // we might have to limit the exception range } sleep(Neodymium.configuration().javaScriptPollingInterval()); // time is up? if (System.currentTimeMillis() - start >= timeout) { return; } } } }