public static boolean awaitBusy(BooleanSupplier breakSupplier, long maxWaitTime, TimeUnit unit) throws InterruptedException { long maxTimeInMillis = TimeUnit.MILLISECONDS.convert(maxWaitTime, unit); long timeInMillis = 1; long sum = 0; while (sum + timeInMillis < maxTimeInMillis) { if (breakSupplier.getAsBoolean()) { return true; } Thread.sleep(timeInMillis); sum += timeInMillis; timeInMillis = Math.min(AWAIT_BUSY_THRESHOLD, timeInMillis * 2); } timeInMillis = maxTimeInMillis - sum; Thread.sleep(Math.max(timeInMillis, 0)); return breakSupplier.getAsBoolean(); }
private void doVisitAttribuut(final MetaAttribuut attribuut, final Onderzoekbundel onderzoekbundel) { final BooleanSupplier ontbrekendGegeven = () -> onderzoekbundel.isOntbrekend() && attribuut.getAttribuutElement().equals(onderzoekbundel.getElement()); final BooleanSupplier voorkomenGegeven = () -> onderzoekbundel.getElementVoorkomensleutel() != null && attribuut.getParentRecord().getVoorkomensleutel() == onderzoekbundel.getElementVoorkomensleutel(); final BooleanSupplier objectGegeven = () -> onderzoekbundel.getElementObjectsleutel() != null && attribuut.getParentRecord().getParentGroep().getParentObject() .getObjectsleutel() == onderzoekbundel.getElementObjectsleutel(); if (ontbrekendGegeven.getAsBoolean() || voorkomenGegeven.getAsBoolean() || objectGegeven.getAsBoolean()) { //voor bepaalde attributen in onderzoek moet het object in onderzoek geplaatst worden if (onderzoekbundel.getElementObjectsleutel() != null) { gegevensInOnderzoekTemp.put(onderzoekbundel, attribuut.getParentRecord().getParentGroep().getParentObject()); } else { gegevensInOnderzoekTemp.put(onderzoekbundel, attribuut); } } }
private void doConditionalAction(final BooleanSupplier condition, final Action action, ExceptionBehaviour exceptionBehaviour) { if (condition.getAsBoolean()) { switch (exceptionBehaviour) { case CATCH: try { action.doWork(); } catch (Exception e) { logger.error("Error performing action", e); } break; case THROW: action.doWork(); break; } } }
@Override public boolean test(final MetaAttribuut metaAttribuut) { //actieinhoud, actieverval, actie aanpassing geldigheid final BooleanSupplier isToekomstigVerantwoordingAttribuut = () -> metaAttribuut.getAttribuutElement().isVerantwoording() && toekomstigeHandelingen.contains(metaAttribuut.<Actie>getWaarde().getAdministratieveHandeling()); //ts verval, nadere aanduiding verval. Voor afnemerindicaties is alleen nu van belang bij bepaling actueel. final BooleanSupplier isToekomstigVervalGerelateerdAttribuut = () -> metaAttribuut.getAttribuutElement().isDatumTijdVerval() && (metaAttribuut.getParentRecord().getParentGroep().getGroepElement().getVerantwoordingCategorie() == VerantwoordingCategorie.D || toekomstigeHandelingen.contains(metaAttribuut.getParentRecord().getActieVerval().getAdministratieveHandeling())); //verwijder actieverval indien actievervalmutlev gevuld is EN niet in tot toekomstige handeling behoort (actieverval is in dit geval leidend) final BooleanSupplier isVervalMetMutLevVervalGevuld = () -> metaAttribuut.getAttribuutElement().isActieVerval() && metaAttribuut.getParentRecord().getActieVervalTbvLeveringMutaties() != null && toekomstigeHandelingen.contains(metaAttribuut.getParentRecord().getActieVervalTbvLeveringMutaties().getAdministratieveHandeling()); //true is behouden return !Lists.newArrayList(isToekomstigVerantwoordingAttribuut, isToekomstigVervalGerelateerdAttribuut, isVervalMetMutLevVervalGevuld).stream().anyMatch(BooleanSupplier::getAsBoolean); }
/** Attempt to wait the given condition to return true multiple times. */ static void attempt( BooleanSupplier condition, int numAttempts, long sleepMs, String name, Logger log) throws InterruptedException { Objects.requireNonNull(condition, "condition == null"); Preconditions.assertTrue(numAttempts > 0, () -> "numAttempts = " + numAttempts + " <= 0"); Preconditions.assertTrue(sleepMs >= 0L, () -> "sleepMs = " + sleepMs + " < 0"); for(int i = 1; i <= numAttempts; i++) { if (condition.getAsBoolean()) { return; } if (log != null && log.isWarnEnabled()) { log.warn("FAILED " + name + " attempt #" + i + "/" + numAttempts + ": sleep " + sleepMs + "ms and then retry."); } if (sleepMs > 0) { Thread.sleep(sleepMs); } } if (!condition.getAsBoolean()) { throw new IllegalStateException("Failed " + name + " for " + numAttempts + " attempts."); } }
protected boolean waitUntil(final BooleanSupplier supplier, final long timeout) { final long start = System.currentTimeMillis(); while (true) { if (supplier.getAsBoolean()) { return true; } try { Thread.sleep(10); } catch (final InterruptedException ignore) { } final long now = System.currentTimeMillis(); if (now - start > timeout) { return false; } } }
/** * Allow to run method at specified interval on EDT * <p> * Inside boolean supplier, return false to stop timer * * @param interval * @param run */ public static void runTimerOnEDT(int interval, BooleanSupplier run) { ActionListener action = (e) -> { if (SwingUtilities.isEventDispatchThread() == false) { throw new IllegalStateException("Do not run this method on Event Dispatch Thread"); } // perform action and get return value boolean continueTimer = run.getAsBoolean(); // if return false, stop timer if (continueTimer == false) { ((Timer) e.getSource()).stop(); } }; // launch timer Timer timer = new Timer(interval, action); timer.start(); }
private static BooleanSupplier getPeriodicPredicate(long periodInMillis) { return new BooleanSupplier() { private long lastRun = INIT_TIME; @Override public boolean getAsBoolean() { long now = System.currentTimeMillis(); boolean result = now - lastRun >= periodInMillis; if (result) { lastRun = now; } return result; } }; }
/** * Geeft aan of deze Autorisatiebundel geldig is op de opgegeven datum. Checkt dat toegangleveringautorisatie geldig en niet geblokkeerd is. Checkt dat * leveringautorisatie geldig en niet geblokkeerd is. Checkt dat dienstbundel hij niet geblokkeerd is (check op geldigheid niet nodig) Checkt dat dienst * geldig en niet geblokkeerd is. Checkt dat partijrol geldig is. Checkt dat partij geldig is. * @param datum de datum * @param tla de ToegangLeveringsAutorisatie * @param dienst @return true als deze geldig is op de gegeven datum, anders false */ @Bedrijfsregel(Regel.R1261) @Bedrijfsregel(Regel.R1265) @Bedrijfsregel(Regel.R2056) @Bedrijfsregel(Regel.R1263) @Bedrijfsregel(Regel.R1264) @Bedrijfsregel(Regel.R1258) @Bedrijfsregel(Regel.R2239) @Bedrijfsregel(Regel.R2242) @Bedrijfsregel(Regel.R2245) private static boolean isGeldigOp(final Integer datum, final ToegangLeveringsAutorisatie tla, final Dienst dienst) { final PartijRol geautoriseerde = tla.getGeautoriseerde(); final List<BooleanSupplier> predicateList = Lists.newArrayList( () -> AutAutUtil.isGeldigEnNietGeblokkeerdInclusiefLeveringsautorisatie(tla, datum), () -> AutAutUtil.isGeldigEnNietGeblokkeerd(dienst, datum), () -> AutAutUtil.isGeldigEnNietGeblokkeerd(dienst.getDienstbundel(), datum), () -> AutAutUtil.isGeldigOp(datum, geautoriseerde.getDatumIngang(), geautoriseerde.getDatumEinde()), () -> AutAutUtil.isGeldigOp(datum, geautoriseerde.getPartij().getDatumIngang(), geautoriseerde.getPartij().getDatumEinde()) ); return predicateList.stream().allMatch(BooleanSupplier::getAsBoolean); }
private static Datumdeel getDag(final BRPExpressietaalParser.DayContext dagCtx, final Datumdeel jaar, final Datumdeel maand) { final Datumdeel datumdeel; if (DatumLiteral.ONBEKEND_DATUMDEEL_STRING.equals(dagCtx.getText())) { datumdeel = Datumdeel.ONBEKEND_DATUMDEEL; } else { final int dagWaarde = Integer.parseInt(dagCtx.getText()); if (dagWaarde != 0) { final BooleanSupplier geldigBinnenRange = () -> ChronoField.DAY_OF_MONTH.range().isValidIntValue(dagWaarde); final BooleanSupplier jaarEnMaandBekend = () -> jaar != Datumdeel.ONBEKEND_DATUMDEEL && jaar.getWaarde() != 0 && maand != Datumdeel.ONBEKEND_DATUMDEEL && maand.getWaarde() != 0; final BooleanSupplier geldigBinnenMaandRange = () -> DatumLiteral.dagenInMaand(jaar.getWaarde(), maand.getWaarde()) >= dagWaarde; if (!geldigBinnenRange.getAsBoolean() || jaarEnMaandBekend.getAsBoolean() && !geldigBinnenMaandRange.getAsBoolean()) { throw new ExpressieParseException("Dag incorrect: " + dagWaarde); } } datumdeel = Datumdeel.valueOf(dagWaarde); } return datumdeel; }
static void gcAwait(BooleanSupplier s) { for (int i = 0; i < 10; i++) { if (s.getAsBoolean()) return; forceFullGc(); } throw new AssertionError("failed to satisfy condition"); }
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(); } }
@Override public BooleanSupplier parse(JsonContext context, JsonObject json) { if (json.has("value") && CustomConfiguration.configValues.containsKey(json.get("value").getAsString())) { return () -> CustomConfiguration.configValues.get(json.get("value").getAsString()); } return () -> false; }
public HysteresisPollingTrigger(BooleanSupplier risingCheck, BooleanSupplier fallingCheck, Runnable risingAction, Runnable fallingAction, State initialState, Duration interval) { this.risingCheck = risingCheck; this.fallingCheck = fallingCheck; this.risingAction = risingAction; this.fallingAction = fallingAction; this.interval = interval; this.state = initialState; }
/** * Waits until at least a give number of document is visible for searchers * * @param numDocs number of documents to wait for * @param maxWaitTime if not progress have been made during this time, fail the test * @param maxWaitTimeUnit the unit in which maxWaitTime is specified * @param indexer a {@link org.elasticsearch.test.BackgroundIndexer}. If supplied it will be first checked for documents indexed. * This saves on unneeded searches. * @return the actual number of docs seen. */ public long waitForDocs(final long numDocs, int maxWaitTime, TimeUnit maxWaitTimeUnit, @Nullable final BackgroundIndexer indexer) throws InterruptedException { final AtomicLong lastKnownCount = new AtomicLong(-1); long lastStartCount = -1; BooleanSupplier testDocs = () -> { if (indexer != null) { lastKnownCount.set(indexer.totalIndexedDocs()); } if (lastKnownCount.get() >= numDocs) { try { long count = client().prepareSearch().setSize(0).setQuery(matchAllQuery()).execute().actionGet().getHits().getTotalHits(); if (count == lastKnownCount.get()) { // no progress - try to refresh for the next time client().admin().indices().prepareRefresh().get(); } lastKnownCount.set(count); } catch (Exception e) { // count now acts like search and barfs if all shards failed... logger.debug("failed to executed count", e); return false; } logger.debug("[{}] docs visible for search. waiting for [{}]", lastKnownCount.get(), numDocs); } else { logger.debug("[{}] docs indexed. waiting for [{}]", lastKnownCount.get(), numDocs); } return lastKnownCount.get() >= numDocs; }; while (!awaitBusy(testDocs, maxWaitTime, maxWaitTimeUnit)) { if (lastStartCount == lastKnownCount.get()) { // we didn't make any progress fail("failed to reach " + numDocs + "docs"); } lastStartCount = lastKnownCount.get(); } return lastKnownCount.get(); }
public void consumeIntegers(BooleanSupplier continuation, Runnable completion, Collection<String> topics, Consumer<ConsumerRecord<String, Integer>> consumerFunction) { Deserializer<String> keyDes = new StringDeserializer(); Deserializer<Integer> valDes = new IntegerDeserializer(); String randomId = UUID.randomUUID().toString(); OffsetCommitCallback offsetCommitCallback = null; this.consume(randomId, randomId, OffsetResetStrategy.EARLIEST, keyDes, valDes, continuation, (OffsetCommitCallback) offsetCommitCallback, completion, topics, consumerFunction); }
/** * 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 successful */ 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(); }
public static BooleanSupplier conditionTrueForNIterations(BooleanSupplier condition, int iters) { final AtomicInteger ai = new AtomicInteger(0); return () -> { if (condition.getAsBoolean()) { int i = ai.incrementAndGet(); return i >= iters; } else { ai.set(0); return false; } }; }
public static void assertEventually(String message, BooleanSupplier condition, long interval, long timeout) throws InterruptedException { try { waitFor(condition, null, interval, timeout); } catch (TimeoutException x) { throw new AssertionError(message, x); } }
/** * Creates a new {@link Guard} for {@code this} monitor. * * @Param isSatisfied The guards boolean condition. See {@link Guard#isSatisfied}. */ public Guard newGuard(final BooleanSupplier isSatisfied) { checkNotNull(isSatisfied, "isSatisfied"); return new Guard(this) { @Override public boolean isSatisfied() { return isSatisfied.getAsBoolean(); } }; }
/** * Use the supplied function to asynchronously consume messages from the cluster. * * @param groupId the name of the group; may not be null * @param clientId the name of the client; may not be null * @param autoOffsetReset how to pick a starting offset when there is no initial offset in ZooKeeper or if an offset is * out of range; may be null for the default to be used * @param keyDeserializer the deserializer for the keys; may not be null * @param valueDeserializer the deserializer for the values; may not be null * @param continuation the function that determines if the consumer should continue; may not be null * @param offsetCommitCallback the callback that should be used after committing offsets; may be null if offsets are * not to be committed * @param completion the function to call when the consumer terminates; may be null * @param topics the set of topics to consume; may not be null or empty * @param consumerFunction the function to consume the messages; may not be null */ public <K, V> void consume(String groupId, String clientId, OffsetResetStrategy autoOffsetReset, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer, BooleanSupplier continuation, OffsetCommitCallback offsetCommitCallback, Runnable completion, Collection<String> topics, java.util.function.Consumer<ConsumerRecord<K, V>> consumerFunction) { Properties props = getConsumerProperties(groupId, clientId, autoOffsetReset); Thread t = new Thread(() -> { LOGGER.info("Starting consumer {} to read messages", clientId); try (KafkaConsumer<K, V> consumer = new KafkaConsumer<>(props, keyDeserializer, valueDeserializer)) { consumer.subscribe(new ArrayList<>(topics)); while (continuation.getAsBoolean()) { consumer.poll(10).forEach(record -> { LOGGER.info("Consumer {}: consuming message {}", clientId, record); consumerFunction.accept(record); if (offsetCommitCallback != null) { consumer.commitAsync(offsetCommitCallback); } }); } } finally { if (completion != null) completion.run(); LOGGER.debug("Stopping consumer {}", clientId); } }); t.setName(clientId + "-thread"); t.start(); }
public void setAccessFunc(BooleanSupplier func) { accessFunc = func; if (func != null) limitedAccess = true; else limitedAccess = false; }
public static BooleanSupplier urlReturnsCode(String url, int... codes) { return () -> { try { int responseCode = HttpClient.get(url).code(); return ArrayUtils.contains(codes, responseCode); } catch (IOException x) { return false; } }; }
public static BooleanSupplier urlResponseContains(String url, String expectedResponse) { return () -> { try { return HttpClient.get(url).bearerAuth(openshift.getContext().getToken()).response().contains(expectedResponse); } catch (IOException x) { return false; } }; }
protected BooleanSupplier continueIfNotExpired(BooleanSupplier continuation, long timeout, TimeUnit unit) { return new BooleanSupplier() { long stopTime = 0L; public boolean getAsBoolean() { if (this.stopTime == 0L) { this.stopTime = System.currentTimeMillis() + unit.toMillis(timeout); } return continuation.getAsBoolean() && System.currentTimeMillis() <= this.stopTime; } }; }
public static BooleanSupplier textAppears(WebDriver driver, By element, String text) { return () -> { try { return text.equalsIgnoreCase(driver.findElement(element).getText()); } catch (Exception x) { // stale elements and such... return false; } }; }
public Reader(Ignite ignite, KafkaFactory kafkaFactory, ClusterConfig config, Serializer serializer, CommitStrategy commitStrategy, BooleanSupplier needToCommitToKafka, long bufferClearPeriod, UUID readerId, Predicate<Map<Long, TransactionData>> bufferOverflowCondition, long bufferCheckPeriod) { this.kafkaFactory = kafkaFactory; lead = ignite.services().serviceProxy(LeadService.NAME, LeadService.class, false); this.config = config; this.serializer = serializer; this.commitStrategy = commitStrategy; this.readerId = readerId; this.needToCommitToKafka = needToCommitToKafka; this.bufferClearPeriod = bufferClearPeriod; this.bufferOverflowCondition = bufferOverflowCondition; this.bufferCheckPeriod = bufferCheckPeriod; }
private static void autorisatieGeldig(final Partij partij, final Regel regel) throws AutorisatieException { final List<BooleanSupplier> predicateList = Lists.newArrayList( () -> !partij.isActueelEnGeldigVoorVrijBericht(), () -> partij.getDatumIngangVrijBericht() > DatumUtil.vandaag(), () -> partij.getDatumEindeVrijBericht() != null && partij.getDatumEindeVrijBericht() <= DatumUtil.vandaag() ); if (predicateList.stream().anyMatch(BooleanSupplier::getAsBoolean)) { throw new AutorisatieException(new Melding(regel)); } }
private static void partijGeldig(final Partij partij, final Regel regel) throws AutorisatieException { final List<BooleanSupplier> predicateList = Lists.newArrayList( () -> partij == null, () -> partij.getDatumIngang() > DatumUtil.vandaag(), () -> partij.getDatumEinde() != null && partij.getDatumEinde() <= DatumUtil.vandaag() ); if (predicateList.stream().anyMatch(BooleanSupplier::getAsBoolean)) { throw new AutorisatieException(new Melding(regel)); } }
private static void transporteurCorrect(final Partij partij, final String oinTransporteur, final Regel regel) throws AutorisatieException { final List<BooleanSupplier> predicateList = Lists.newArrayList( () -> partij.getOin() == null, () -> partij.getTransporteurVrijBericht() == null && !partij.getOin().equals(oinTransporteur), () -> partij.getTransporteurVrijBericht() != null && partij.getTransporteurVrijBericht().getOin() == null, () -> partij.getTransporteurVrijBericht() != null && !partij.getTransporteurVrijBericht().getOin().equals(oinTransporteur) ); if (predicateList.stream().anyMatch(BooleanSupplier::getAsBoolean)) { throw new AutorisatieException(new Melding(regel)); } }
/** * 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); } }
/** * Controleert of de types van twee expressies vergelijkbaar zijn, rekening houdend met mogelijke NULL-waarden. * * @param expressie1 Eerste expressie. * @param expressie2 Tweede expressie. * @param errorHandler De error handler * @return Code van de gevonden typefout, anders ParserFoutCode.GEEN_FOUT. */ static ParserFoutCode checkComparedTypes(final Expressie expressie1, final Expressie expressie2, final Function<ParserFoutCode, ExpressieParseException> errorHandler) { final ExpressieType type1 = getExpressieType(expressie1); final ExpressieType type2 = getExpressieType(expressie2); final BooleanSupplier isGelijk = () -> type1.equals(type2); final BooleanSupplier isCompatibel = () -> type1.isCompatibel(type2); final BooleanSupplier isOnbekendOfNull = () -> type1.isOnbekendOfNull() || type2.isOnbekendOfNull(); final BooleanSupplier isLijst = () -> type1 == ExpressieType.LIJST || type2 == ExpressieType.LIJST; if (!(isGelijk.getAsBoolean() || isCompatibel.getAsBoolean() || isOnbekendOfNull.getAsBoolean() || isLijst.getAsBoolean())) { throw errorHandler.apply(getMissingTypeError(type1)); } return ParserFoutCode.GEEN_FOUT; }
@Override public HeartBeatChain<T> until(BooleanSupplier booleanSupplier) { heartBeat.getHeartBeatConfig().setRunningPredicate(t -> booleanSupplier.getAsBoolean()); return new InternalHeartBeatChain<>(heartBeat); }
@Override public HeartBeatChain<T> onlyIf(BooleanSupplier booleanSupplier) { heartBeat.getHeartBeatConfig().addActivePredicate(t -> booleanSupplier.getAsBoolean()); return new InternalHeartBeatChain<>(heartBeat); }