下面列出了java.util.function.BooleanSupplier#getAsBoolean ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected void doScheduleWithinConstraints(Consumer<ReschedulingAttempt> task, BooleanSupplier condition, ReschedulingAttempt previousAttempt) {
if (condition != null && !condition.getAsBoolean()) {
return;
}
for (ContextConstraint constraint : constraints) {
if (!constraint.isCorrectContext()) {
constraint.schedule(new RunnableReschedulingAttempt(constraint, previousAttempt) {
@Override
public void run() {
LOG.assertTrue(constraint.isCorrectContext());
doScheduleWithinConstraints(task, condition, this);
}
});
return;
}
}
task.accept(previousAttempt);
}
/**
* 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;
}
};
}
@Override
public void run() {
String newValue = comboBoxInput.getText();
BooleanSupplier sameValue = () -> String.valueOf(comboBoxModel.getSelectedItem()).equals(newValue);
BooleanSupplier alreadyStored = () -> Objects.equals(newValue, savedValue.getAndSet(newValue));
if (comboBoxInput.hasFocus() && !sameValue.getAsBoolean() && !alreadyStored.getAsBoolean()) {
final int start = comboBoxInput.getSelectionStart();
final int end = comboBoxInput.getSelectionEnd();
SwingTools.invokeAndWait(() -> {
comboBox.setSelectedItem(comboBoxInput.getText());
comboBoxInput.setCaretPosition(end);
comboBoxInput.moveCaretPosition(start);
});
}
}
@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);
}
}
}
}
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)));
}
}
/**
* Follow output until execution completes and output is fully read, or interrupted
* @param id execution id
* @param max max lines to retrieve with each request
* @param compacted if true, request compacted data
* @param receiver receive log events
* @param waitFunc function for waiting, return false to halt
*
* @return true if execution is successful
*
*/
public static boolean followOutput(
final ServiceClient<RundeckApi> serviceClient,
final ExecOutput output,
final String id,
long max,
final boolean compacted,
Consumer<List<ExecLog>> receiver,
BooleanSupplier waitFunc
) throws IOException
{
boolean done = false;
String status = null;
ExecOutput execOutput = output;
while (!done) {
receiver.accept(execOutput.decompactEntries());
status = execOutput.execState;
done = execOutput.execCompleted && execOutput.completed;
if (!done) {
if (!waitFunc.getAsBoolean()){
break;
}
final ExecOutput passOutput = execOutput;
execOutput = serviceClient.apiCall(api -> api.getOutput(
id,
passOutput.offset,
passOutput.lastModified,
max,
compacted
));
}
}
return "succeeded".equals(status);
}
private static void awaitEvent(BooleanSupplier condition, long timeToWait, String description) {
long timeToSleep = 200;
for (int i = 0 ; i < Math.floor(timeToWait / timeToSleep); i++) {
if (condition.getAsBoolean()) {
return;
}
try {
Thread.sleep(timeToSleep);
}
catch (InterruptedException e) {
throw new IllegalStateException("Interrupted while waiting for " + description, e);
}
}
throw new IllegalStateException("Timed out waiting for " + description);
}
public static boolean waitForCondition(BooleanSupplier booleanSupplier) throws Exception {
int maxChecks = 20;
int i = 0;
while (true) {
if (booleanSupplier.getAsBoolean()) {
return true;
} else {
Thread.sleep(100);
}
if (i++ >= maxChecks) {
return true;
}
}
}
public static void yieldUntilDone(final BooleanSupplier isDone)
{
while (!isDone.getAsBoolean())
{
Thread.yield();
checkInterruptStatus();
}
}
private void wait(BooleanSupplier condition, int maxTries, String errorMessage) {
int tryCount = 0;
while (tryCount < maxTries) {
tryCount++;
waitForConditionWithoutFailing(condition);
if (condition.getAsBoolean()) {
break;
}
}
debugBusyModel();
assertTrue(errorMessage, condition.getAsBoolean());
}
/**
* Execute the provided callable in a read lock.
*
* @param aSupplier
* Callable to be executed. May not be <code>null</code>.
* @return The return value of the callable. May be <code>null</code>.
*/
public boolean readLockedBoolean (@Nonnull final BooleanSupplier aSupplier)
{
readLock ().lock ();
try
{
return aSupplier.getAsBoolean ();
}
finally
{
readLock ().unlock ();
}
}
/**
* 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();
}
static void assertEventuallyTrue(BooleanSupplier predicate) throws Exception {
// wait up to 3 seconds
for (int i = 0; i < 30 && !predicate.getAsBoolean(); i++) {
Thread.sleep(100);
}
assertTrue(predicate.getAsBoolean());
}
/**
* 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;
}
}
}
}
static void spinWaitUntil(BooleanSupplier predicate, long timeoutMillis) {
long startTime = -1L;
while (!predicate.getAsBoolean()) {
if (startTime == -1L)
startTime = System.nanoTime();
else if (millisElapsedSince(startTime) > timeoutMillis)
throw new AssertionError(
String.format("timed out after %s ms", timeoutMillis));
Thread.yield();
}
}
private static boolean checkCapabilities(Capabilities capabilities, BooleanSupplier supplier)
{
return capabilities != null && supplier.getAsBoolean();
}
static void block(BooleanSupplier isBlocked) throws InterruptedException {
for(; isBlocked.getAsBoolean(); ) {
RaftServerConfigKeys.Rpc.TIMEOUT_MAX_DEFAULT.sleep();
}
}
static void block(BooleanSupplier isBlocked) throws InterruptedException {
for(; isBlocked.getAsBoolean(); ) {
RaftServerConfigKeys.Rpc.TIMEOUT_MAX_DEFAULT.sleep();
}
}
/**
*
* Every contract has a tag, which support the hierarchical form,
* like Java package naming.
* <p>
* The convention is to use the className.methodName for the tag, like:
* <pre>{@code
* contract()
* }</pre>
*
* @param prefixedLabel
* @param contractSupplier
*/
public static final void contract(String prefixedLabel,
BooleanSupplier contractSupplier) {
if (TRICK && !contractSupplier.getAsBoolean())
throw new ContractViolatedException(prefixedLabel + ":" +
" the contract "+ contractSupplier +
" fails to be kept!");
}
/**
* Get a boolean from the TOML document, or return a default.
*
* @param path The key path.
* @param defaultValue A supplier for the default value.
* @return The value, or the default.
* @throws TomlInvalidTypeException If the value is present but not a boolean, or any element of the path preceding
* the final key is not a table.
*/
default boolean getBoolean(List<String> path, BooleanSupplier defaultValue) {
requireNonNull(defaultValue);
Boolean value = getBoolean(path);
if (value != null) {
return value;
}
return defaultValue.getAsBoolean();
}