下面列出了怎么用java.util.function.BooleanSupplier的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
};
}
@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);
}
@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();
}
}
@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")))));
}
/**
* 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));
});
}
/**
* 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());
}
@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());
}
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);
}
@Override
public void deleteFolder(final Repository repository,
final String treePath,
final DateTime timestamp,
final BooleanSupplier cancelledCheck)
{
boolean canDeleteComponent =
securityHelper.isPermitted(new RepositoryViewPermission(repository, BreadActions.DELETE))[0];
ComponentMaintenance componentMaintenance = repository.facet(ComponentMaintenance.class);
Queue<String> paths = new PriorityQueue<>();
paths.add(treePath);
while (!cancelledCheck.getAsBoolean() && !paths.isEmpty()) {
String basePath = paths.poll();
List<String> path = Arrays.asList(basePath.split("/"));
Iterable<BrowseNode<EntityId>> nodes =
browseNodeStore.getByPath(repository.getName(), path, configuration.getMaxNodes());
Iterator<BrowseNode<EntityId>> nodeIterator = nodes.iterator();
while (!cancelledCheck.getAsBoolean() && nodeIterator.hasNext()) {
BrowseNode<EntityId> node = nodeIterator.next();
if (!node.isLeaf()) {
paths.offer(basePath + "/" + node.getName());
}
else if (canDeleteComponent && node.getAssetId() == null && node.getComponentId() != null) {
deleteComponent(repository, node.getComponentId(), timestamp, componentMaintenance);
}
if (node.getAssetId() != null) {
deleteAsset(repository, node.getAssetId(), timestamp, componentMaintenance);
}
}
}
}
@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);
}
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)));
}
}
public <E extends Exception> void wait(CheckedRunnable<E> runnable, BooleanSupplier stopCondition) throws E
{
wait(
() -> {
runnable.run();
return (Void) null;
},
alwaysNull -> stopCondition.getAsBoolean()
);
}
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);
}
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);
});
}
@Override
public DeletionProgress run(final Repository repository,
final Iterable<EntityId> components,
final BooleanSupplier cancelledCheck)
{
return repository.facet(ComponentMaintenance.class).deleteComponents(components, cancelledCheck, batchSize);
}
public BatchPagingIterator(PagingIterator<Key, Row> pagingIterator,
Function<Key, KillableCompletionStage<? extends Iterable<? extends KeyIterable<Key, Row>>>> fetchMore,
BooleanSupplier isUpstreamExhausted,
Consumer<? super Throwable> closeCallback) {
this.pagingIterator = pagingIterator;
this.it = pagingIterator;
this.fetchMore = fetchMore;
this.isUpstreamExhausted = isUpstreamExhausted;
this.closeCallback = closeCallback;
}
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);
}
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);
}
/**
* 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);
}
}
/**
* @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;
}
@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);
}
});
}
/**
* 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();
});
}
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);
}
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);
}
/**
* 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;
}
}
}
}
/**
* 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());
}
}
/**
* 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);
}
}
/**
* 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;
}
}
}
@Nonnull
public ToStringGenerator appendIf (@Nonnull final String sField,
final boolean bValue,
@Nonnull final BooleanSupplier aFilter)
{
return aFilter.getAsBoolean () ? append (sField, bValue) : this;
}
/**
* 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;
}
}