Example usage for java.util.function Predicate test

List of usage examples for java.util.function Predicate test

Introduction

In this page you can find the example usage for java.util.function Predicate test.

Prototype

boolean test(T t);

Source Link

Document

Evaluates this predicate on the given argument.

Usage

From source file:org.codice.ddf.itests.common.ServiceManagerImpl.java

@Override
public void waitForFeature(String featureName, Predicate<FeatureState> predicate) throws Exception {
    boolean ready = false;

    long timeoutLimit = System.currentTimeMillis() + FEATURES_AND_BUNDLES_TIMEOUT;
    FeaturesService featuresService = getFeaturesService();

    while (!ready) {
        FeatureState state = null;/*  w  w w  . ja v a  2  s  .  c  om*/

        if (featuresService != null) {
            Feature feature = featuresService.getFeature(featureName);
            state = featuresService.getState(feature.getName() + "/" + feature.getVersion());

            if (state == null) {
                LOGGER.debug("No Feature found for featureName: {}", featureName);
                return;
            } else if (predicate.test(state)) {
                ready = true;
            }
        }

        if (!ready) {
            if (System.currentTimeMillis() > timeoutLimit) {
                printInactiveBundles();
                fail(String.format("Feature did not change to State [" + predicate + "] within %d minutes.",
                        TimeUnit.MILLISECONDS.toMinutes(FEATURES_AND_BUNDLES_TIMEOUT)));
            }
            LOGGER.info("Still waiting on feature [{}], current state [{}]...", featureName, state);
            Thread.sleep(1000);
        }
    }
}

From source file:com.github.drbookings.ui.controller.MainController.java

private int[] getIndicies(final Predicate<LocalDate> p) {
    final List<Integer> result = new ArrayList<>();
    for (int index = 0; index < tableView.getItems().size(); index++) {
        final LocalDate date = tableView.getItems().get(index).getDate();
        if (p.test(date)) {
            result.add(index);//from   w w  w .j a  v  a2s  . c o m
        }
    }
    if (result.isEmpty()) {
        return new int[0];
    }
    return ArrayUtils.toPrimitive(result.toArray(new Integer[] { result.size() }));

}

From source file:org.springframework.messaging.handler.invocation.reactive.AbstractMethodMessageHandler.java

private void initHandlerMethods() {
    if (this.applicationContext == null) {
        logger.warn("No ApplicationContext available for detecting beans with message handling methods.");
        return;/* w  w  w . j  av  a2s .  c  om*/
    }
    Predicate<Class<?>> handlerPredicate = initHandlerPredicate();
    if (handlerPredicate == null) {
        logger.warn("[" + getBeanName() + "] No auto-detection of handler methods (e.g. in @Controller).");
        return;
    }
    for (String beanName : this.applicationContext.getBeanNamesForType(Object.class)) {
        if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
            Class<?> beanType = null;
            try {
                beanType = this.applicationContext.getType(beanName);
            } catch (Throwable ex) {
                // An unresolvable bean type, probably from a lazy bean - let's ignore it.
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
                }
            }
            if (beanType != null && handlerPredicate.test(beanType)) {
                detectHandlerMethods(beanName);
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.quotas.SnapshotQuotaObserverChore.java

/**
 * Extracts the names of the store files referenced by this snapshot which satisfy the given
 * predicate (the predicate returns {@code true}).
 *//*from w  w  w  .  java2  s.co  m*/
Set<StoreFileReference> getStoreFilesFromSnapshot(SnapshotManifest manifest, Predicate<String> filter) {
    Set<StoreFileReference> references = new HashSet<>();
    // For each region referenced by the snapshot
    for (SnapshotRegionManifest rm : manifest.getRegionManifests()) {
        StoreFileReference regionReference = new StoreFileReference(
                HRegionInfo.convert(rm.getRegionInfo()).getEncodedName());

        // For each column family in this region
        for (FamilyFiles ff : rm.getFamilyFilesList()) {
            final String familyName = ff.getFamilyName().toStringUtf8();
            // And each store file in that family
            for (StoreFile sf : ff.getStoreFilesList()) {
                String storeFileName = sf.getName();
                // A snapshot only "inherits" a files size if it uniquely refers to it (no table
                // and no other snapshot references it).
                if (filter.test(storeFileName)) {
                    regionReference.addFamilyStoreFile(familyName, storeFileName);
                }
            }
        }
        // Only add this Region reference if we retained any files.
        if (!regionReference.getFamilyToFilesMapping().isEmpty()) {
            references.add(regionReference);
        }
    }
    return references;
}

From source file:org.codice.ddf.spatial.ogc.wfs.v110.catalog.source.WfsFilterDelegate.java

private String mapQueryPropertyToFeatureProperty(final String queryProperty,
        final Predicate<String> isWfsFeatureProperty) {
    final String featurePropertyName = Optional.ofNullable(metacardMapper.getFeatureProperty(queryProperty))
            .orElse(queryProperty);//from  w ww .  jav  a2s  . c o  m

    if (!isWfsFeatureProperty.test(featurePropertyName)) {
        throw new IllegalArgumentException(
                String.format("'%s' was mapped to '%s', which is not a feature property of '%s'", queryProperty,
                        featurePropertyName, featureMetacardType.getFeatureType()));
    }

    final FeatureAttributeDescriptor featureAttributeDescriptor = (FeatureAttributeDescriptor) featureMetacardType
            .getAttributeDescriptor(featurePropertyName);
    if (!featureAttributeDescriptor.isIndexed()) {
        throw new IllegalArgumentException(String.format(PROPERTY_NOT_QUERYABLE, featurePropertyName));
    }

    return featureAttributeDescriptor.getPropertyName();
}

From source file:org.briljantframework.array.Arrays.java

public static int arg(Predicate<Boolean> predicate, BooleanArray array) {
    for (int i = 0; i < array.size(); i++) {
        if (predicate.test(array.get(i))) {
            return i;
        }/*from   w w  w . j a va2 s .c o  m*/
    }
    return -1;
}

From source file:org.apache.hadoop.hbase.quotas.FileArchiverNotifierImpl.java

/**
 * Extracts the names of the store files referenced by this snapshot which satisfy the given
 * predicate (the predicate returns {@code true}).
 *//*from w  w  w  . jav  a  2  s  . c om*/
Set<StoreFileReference> getStoreFilesFromSnapshot(SnapshotManifest manifest, Predicate<String> filter) {
    Set<StoreFileReference> references = new HashSet<>();
    // For each region referenced by the snapshot
    for (SnapshotRegionManifest rm : manifest.getRegionManifests()) {
        StoreFileReference regionReference = new StoreFileReference(
                ProtobufUtil.toRegionInfo(rm.getRegionInfo()).getEncodedName());

        // For each column family in this region
        for (FamilyFiles ff : rm.getFamilyFilesList()) {
            final String familyName = ff.getFamilyName().toStringUtf8();
            // And each store file in that family
            for (StoreFile sf : ff.getStoreFilesList()) {
                String storeFileName = sf.getName();
                // A snapshot only "inherits" a files size if it uniquely refers to it (no table
                // and no other snapshot references it).
                if (filter.test(storeFileName)) {
                    regionReference.addFamilyStoreFile(familyName, storeFileName);
                }
            }
        }
        // Only add this Region reference if we retained any files.
        if (!regionReference.getFamilyToFilesMapping().isEmpty()) {
            references.add(regionReference);
        }
    }
    return references;
}

From source file:dk.dma.ais.packet.AisPacketKMLOutputSink.java

private void createKmlTracksFolder(Folder kmlNode, Predicate<? super ScenarioTracker.Target> trackFor) {
    Set<ScenarioTracker.Target> targets = scenarioTracker.getTargetsHavingPositionUpdates();

    Folder tracksFolder = kmlNode.createAndAddFolder().withName("Tracks").withOpen(false).withVisibility(false);

    Folder cargoTracksFolder = null;//  ww  w .  j a  v a  2  s  .co  m
    Folder tankersTracksFolder = null;
    Folder passengerTracksFolder = null;
    Folder fishingTracksFolder = null;
    Folder classBTracksFolder = null;
    Folder otherTracksFolder = null;

    for (ScenarioTracker.Target target : targets) {
        if (trackFor.test(target)) {
            Set<ScenarioTracker.Target.PositionReport> positionReportReports = target.getPositionReports();
            if (positionReportReports.size() > 0) {

                Folder folder = null;

                ShipTypeCargo shipTypeCargo = target.getShipTypeCargo();
                if (shipTypeCargo != null) {
                    ShipTypeCargo.ShipType shipType = shipTypeCargo.getShipType();
                    switch (shipType) {
                    case CARGO:
                        if (cargoTracksFolder == null) {
                            cargoTracksFolder = tracksFolder.createAndAddFolder().withName("Cargo")
                                    .withOpen(false).withVisibility(false);
                        }
                        folder = cargoTracksFolder;
                        break;
                    case TANKER:
                        if (tankersTracksFolder == null) {
                            tankersTracksFolder = tracksFolder.createAndAddFolder().withName("Tankers")
                                    .withOpen(false).withVisibility(false);
                        }
                        folder = tankersTracksFolder;
                        break;
                    case PASSENGER:
                        if (passengerTracksFolder == null) {
                            passengerTracksFolder = tracksFolder.createAndAddFolder().withName("Passenger")
                                    .withOpen(false).withVisibility(false);
                        }
                        folder = passengerTracksFolder;
                        break;
                    case FISHING:
                        if (fishingTracksFolder == null) {
                            fishingTracksFolder = tracksFolder.createAndAddFolder().withName("Fishing")
                                    .withOpen(false).withVisibility(false);
                        }
                        folder = fishingTracksFolder;
                        break;
                    case PLEASURE:
                    case SAILING:
                        if (classBTracksFolder == null) {
                            classBTracksFolder = tracksFolder.createAndAddFolder().withName("Class B")
                                    .withOpen(false).withVisibility(false);
                        }
                        folder = classBTracksFolder;
                        break;
                    }
                }
                if (folder == null) {
                    if (otherTracksFolder == null) {
                        otherTracksFolder = tracksFolder.createAndAddFolder().withName("Other").withOpen(false)
                                .withVisibility(false);
                    }
                    folder = otherTracksFolder;
                }

                Placemark placemark = folder.createAndAddPlacemark().withId(String.valueOf(target.getMmsi()))
                        .withName(target.getName());

                Style style = placemark.createAndAddStyle().withId("_" + target.getName() + "TrackStyle");
                style.createAndSetBalloonStyle().withText(
                        "<h2>Vessel details</h2>" + generateHtmlShipDescription(target, null, null, null));

                placemark.withStyleUrl(getStyle(target, false));

                LineString lineString = placemark.createAndSetLineString();
                for (ScenarioTracker.Target.PositionReport positionReport : positionReportReports) {
                    lineString.addToCoordinates(positionReport.getLongitude(), positionReport.getLatitude());
                }
            }
        }
    }
}

From source file:org.fede.calculator.service.InvestmentServiceImpl.java

private DetailedInvestmentReportDTO investmentReport(String currency, Predicate<Investment> filter,
        boolean includeTotal) {

    if (!MAP.containsKey(currency)) {
        throw new IllegalArgumentException("Currency " + currency + " does not have a known inflation index.");
    }/*from w w w  .  ja v a 2  s.co  m*/

    final List<Investment> investments = this.investmentSeries.stream()
            .flatMap(fileName -> SeriesReader.read(fileName, TYPE_REFERENCE).stream())
            .collect(Collectors.toList());

    final Inflation inflation = MAP.get(currency);
    final YearMonth until = inflation.getTo();
    final Date untilDate = until.asToDate();

    MoneyAmount initialAmount = new MoneyAmount(ZERO, currency);
    MoneyAmount currentAmount = new MoneyAmount(ZERO, currency);

    final List<InvestmentReportDTO> report = new ArrayList<>();

    //        final String header = "item.getType().name()\t"
    //                + "item.getInitialDate()\t"
    //                + "itemUntilDate\t"
    //                + "currency\t"
    //                + "initialAmount(item, currency).getAmount()\t"
    //                + "finalAmount\t"
    //                + "realAmountInvested";
    //
    //        System.out.println(header);

    for (Investment item : investments) {
        if (filter.test(item)) {

            final Date itemUntilDate = item.getOut() == null ? untilDate : item.getOut().getDate();
            final YearMonth itemUntilYearMonth = new YearMonth(itemUntilDate);

            if (includeTotal) {
                YearMonth start = new YearMonth(item.getInitialDate());
                initialAmount = initialAmount
                        .add(inflation.adjust(initialAmount(item, currency), start.getYear(), start.getMonth(),
                                itemUntilYearMonth.getYear(), itemUntilYearMonth.getMonth()));
                currentAmount = currentAmount.add(finalAmount(item, currency, itemUntilDate));
            }

            BigDecimal finalAmount = finalAmount(item, currency, itemUntilDate).getAmount();

            MoneyAmount investedAmount = initialAmount(item, currency);

            BigDecimal realAmount = realAmount(investedAmount, currency, item.getInitialDate(), itemUntilDate);

            report.add(new InvestmentReportDTO(item.getType().name(), item.getInitialDate(), itemUntilDate,
                    currency, initialAmount(item, currency).getAmount(), finalAmount,
                    inflation(currency, item.getInitialDate(), itemUntilDate),
                    item.getInvestment().getCurrency(),
                    finalAmount.subtract(realAmount).setScale(2, ROUNDING_MODE), realAmount));

            //String msg = "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}";
            //System.out.println(MessageFormat.format(msg, item.getType().name(),
            //                        item.getInitialDate(),
            //                        itemUntilDate,
            //                        currency,
            //                        initialAmount(item, currency).getAmount(),
            //                        finalAmount, realAmount));
        }
    }

    Collections.sort(report,
            (InvestmentReportDTO o1, InvestmentReportDTO o2) -> o1.getFrom().compareTo(o2.getFrom()));

    return new DetailedInvestmentReportDTO(includeTotal
            ? new InvestmentDTO(currency, initialAmount.getAmount(), currentAmount.getAmount(), untilDate)
            : null, report);
}

From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java

/**
 * Calls each supplied name individually to Mojang's servers, treating them
 * as previously used names which henceforth were changed. This method is
 * much slower than the other call methods, and should only be used
 * if there is a need to retrieve names which are now changed
 * /* w ww.ja  va 2  s .  c  om*/
 * @since 0.1.0
 * @version 0.1.0
 * 
 * @param output Whether or not to print output
 * @param log The {@link Logger} to print to
 * @param doOutput A {@link Predicate} representing when to output a number
 * @return A {@link Map} of supplied names to relevant {@link UserInfo}.
 *         Note that this map will contain the supplied names even if they
 *         are invalid or not actual usernames (in which case, they will
 *         be mapped to {@code null}). Note names that have never been
 *         changed before will be mapped as invalid per this method
 * @throws IOException If there's a problem sending or receiving the request
 * @throws ParseException If the request response cannot be read
 * @throws InterruptedException If the thread is interrupted while sleeping
 */
public Map<String, UserInfo> callFromOldNames(boolean output, Logger log, Predicate<? super Integer> doOutput)
        throws IOException, ParseException, InterruptedException {
    Map<String, UserInfo> back = new HashMap<>();
    int completed = 0;
    int failed = 0;
    for (String s : names) {
        HttpURLConnection connection = UUIDFetcher.createSingleProfileConnection(s);
        if (connection.getResponseCode() == 429 && this.rateLimiting) {
            log.warning("[UUIDFetcher] Rate limit hit! Waiting 10 minutes until continuing conversion...");
            Thread.sleep(TimeUnit.MINUTES.toMillis(10));
            connection = UUIDFetcher.createSingleProfileConnection(s);
        }
        if (connection.getResponseCode() == 200) {
            JSONObject o = (JSONObject) this.jsonParser
                    .parse(new InputStreamReader(connection.getInputStream()));
            back.put(s, new UserInfo((String) o.get("name"), UUIDFetcher.getUUID((String) o.get("id"))));
            completed++;
        } else { //e.g. 400, 204
            if (output) {
                log.warning(String.format("No profile found for '%s', skipping...", s));
            }
            back.put(s, null);
            failed++;
            continue; //nothing can be done with the return
        }
        if (output) {
            int processed = completed + failed;
            if (doOutput.test(processed) || processed == this.names.size()) {
                log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed,
                        this.names.size(), ((double) processed / this.names.size()) * 100D, failed));
            }
        }
    }
    return back;
}