Example usage for java.util.function BiPredicate test

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

Introduction

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

Prototype

boolean test(T t, U u);

Source Link

Document

Evaluates this predicate on the given arguments.

Usage

From source file:org.codice.ddf.configuration.migration.ExportMigrationContextImpl.java

@Override
public Optional<ExportMigrationEntry> getSystemPropertyReferencedEntry(String name,
        BiPredicate<MigrationReport, String> validator) {
    Validate.notNull(name, "invalid null system property name");
    Validate.notNull(validator, "invalid null validator");
    final ExportMigrationEntry me = systemPropertiesEntries.get(name);

    if (me != null) {
        return Optional.of(me);
    }/*w w  w  .  ja va2 s  .  co m*/
    final String val = System.getProperty(name);

    // must first let the validator deal with it before we check for the value
    // do not check for null first!!!
    if (!validator.test(report, val)) {
        return Optional.empty();
    } else if (val == null) {
        report.record(new MigrationException(Messages.EXPORT_SYSTEM_PROPERTY_NOT_DEFINED_ERROR, name));
        return Optional.empty();
    } else if (val.isEmpty()) {
        report.record(new MigrationException(Messages.EXPORT_SYSTEM_PROPERTY_IS_EMPTY_ERROR, name));
        return Optional.empty();
    }
    final ExportMigrationSystemPropertyReferencedEntryImpl sprop = new ExportMigrationSystemPropertyReferencedEntryImpl(
            this, name, val);

    systemPropertiesEntries.put(name, sprop);
    return Optional.of(sprop);
}

From source file:org.codice.ddf.configuration.migration.ExportMigrationEntryImpl.java

@Override
public Optional<ExportMigrationEntry> getPropertyReferencedEntry(String pname,
        BiPredicate<MigrationReport, String> validator) {
    Validate.notNull(pname, "invalid null java property name");
    Validate.notNull(validator, "invalid null validator");
    final ExportMigrationJavaPropertyReferencedEntryImpl me = properties.get(pname);

    if (me != null) {
        return Optional.of(me);
    }/*from  w  ww.j  a  v  a 2 s . c  o m*/
    try {
        final String val = getJavaPropertyValue(pname);

        if (!validator.test(getReport(), val)) {
            return Optional.empty();
        } else if (val == null) {
            getReport().record(
                    new MigrationException(Messages.EXPORT_JAVA_PROPERTY_NOT_DEFINED_ERROR, pname, path));
            return Optional.empty();
        } else if (val.isEmpty()) {
            getReport()
                    .record(new MigrationException(Messages.EXPORT_JAVA_PROPERTY_IS_EMPTY_ERROR, pname, path));
            return Optional.empty();
        }
        final ExportMigrationJavaPropertyReferencedEntryImpl prop = new ExportMigrationJavaPropertyReferencedEntryImpl(
                context, path, pname, val);

        properties.put(pname, prop);
        return Optional.of(prop);
    } catch (IOException e) {
        getReport().record(new MigrationException(Messages.EXPORT_JAVA_PROPERTY_LOAD_ERROR, pname, path, e));
        return Optional.empty();
    }
}

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

public BooleanArray where(ComplexArray other, BiPredicate<Complex, Complex> predicate) {
    Check.size(this, other);
    BooleanArray bits = factory.newBooleanArray(getShape());
    for (int i = 0; i < size(); i++) {
        bits.set(i, predicate.test(get(i), other.get(i)));
    }/*  w w  w .ja  va 2 s .  c o m*/
    return bits;
}

From source file:org.apache.pulsar.client.impl.RawBatchConverter.java

/**
 * Take a batched message and a filter, and returns a message with the only the sub-messages
 * which match the filter. Returns an empty optional if no messages match.
 *
 * This takes ownership of the passes in message, and if the returned optional is not empty,
 * the ownership of that message is returned also.
 *///from  ww w.  ja  va 2  s  .c o m
public static Optional<RawMessage> rebatchMessage(RawMessage msg, BiPredicate<String, MessageId> filter)
        throws IOException {
    checkArgument(msg.getMessageIdData().getBatchIndex() == -1);

    ByteBuf payload = msg.getHeadersAndPayload();
    MessageMetadata metadata = Commands.parseMessageMetadata(payload);
    ByteBuf batchBuffer = PooledByteBufAllocator.DEFAULT.buffer(payload.capacity());

    CompressionType compressionType = metadata.getCompression();
    CompressionCodec codec = CompressionCodecProvider.getCompressionCodec(compressionType);

    int uncompressedSize = metadata.getUncompressedSize();
    ByteBuf uncompressedPayload = codec.decode(payload, uncompressedSize);
    try {
        int batchSize = metadata.getNumMessagesInBatch();
        int messagesRetained = 0;

        SingleMessageMetadata.Builder emptyMetadataBuilder = SingleMessageMetadata.newBuilder()
                .setCompactedOut(true);
        for (int i = 0; i < batchSize; i++) {
            SingleMessageMetadata.Builder singleMessageMetadataBuilder = SingleMessageMetadata.newBuilder();
            ByteBuf singleMessagePayload = Commands.deSerializeSingleMessageInBatch(uncompressedPayload,
                    singleMessageMetadataBuilder, 0, batchSize);
            MessageId id = new BatchMessageIdImpl(msg.getMessageIdData().getLedgerId(),
                    msg.getMessageIdData().getEntryId(), msg.getMessageIdData().getPartition(), i);
            if (!singleMessageMetadataBuilder.hasPartitionKey()) {
                messagesRetained++;
                Commands.serializeSingleMessageInBatchWithPayload(singleMessageMetadataBuilder,
                        singleMessagePayload, batchBuffer);
            } else if (filter.test(singleMessageMetadataBuilder.getPartitionKey(), id)
                    && singleMessagePayload.readableBytes() > 0) {
                messagesRetained++;
                Commands.serializeSingleMessageInBatchWithPayload(singleMessageMetadataBuilder,
                        singleMessagePayload, batchBuffer);
            } else {
                Commands.serializeSingleMessageInBatchWithPayload(emptyMetadataBuilder, Unpooled.EMPTY_BUFFER,
                        batchBuffer);
            }
            singleMessageMetadataBuilder.recycle();
            singleMessagePayload.release();
        }
        emptyMetadataBuilder.recycle();

        if (messagesRetained > 0) {
            int newUncompressedSize = batchBuffer.readableBytes();
            ByteBuf compressedPayload = codec.encode(batchBuffer);

            MessageMetadata.Builder metadataBuilder = metadata.toBuilder();
            metadataBuilder.setUncompressedSize(newUncompressedSize);
            MessageMetadata newMetadata = metadataBuilder.build();

            ByteBuf metadataAndPayload = Commands.serializeMetadataAndPayload(Commands.ChecksumType.Crc32c,
                    newMetadata, compressedPayload);
            Optional<RawMessage> result = Optional
                    .of(new RawMessageImpl(msg.getMessageIdData(), metadataAndPayload));
            metadataBuilder.recycle();
            newMetadata.recycle();
            metadataAndPayload.release();
            compressedPayload.release();
            return result;
        } else {
            return Optional.empty();
        }
    } finally {
        batchBuffer.release();
        metadata.recycle();
        msg.close();
    }
}

From source file:at.gridtec.lambda4j.predicate.bi.ThrowableBiPredicate.java

/**
 * Returns a composed {@link BiPredicate2} that first applies this predicate to its input, and then applies the
 * {@code recover} operation if a {@link Throwable} is thrown from this one. The {@code recover} operation is
 * represented by a curried operation which is called with throwable information and same arguments of this
 * predicate./*from   w ww. j  a  v  a  2s  . c o m*/
 *
 * @param recover The operation to apply if this predicate throws a {@code Throwable}
 * @return A composed {@link BiPredicate2} that first applies this predicate to its input, and then applies the
 * {@code recover} operation if a {@code Throwable} is thrown from this one.
 * @throws NullPointerException If given argument or the returned enclosing predicate is {@code null}
 * @implSpec The implementation checks that the returned enclosing predicate from {@code recover} operation is not
 * {@code null}. If it is, then a {@link NullPointerException} with appropriate message is thrown.
 * @implNote If thrown {@code Throwable} is of type {@link Error}, it is thrown as-is and thus not passed to {@code
 * recover} operation.
 */
@Nonnull
default BiPredicate2<T, U> recover(
        @Nonnull final Function<? super Throwable, ? extends BiPredicate<? super T, ? super U>> recover) {
    Objects.requireNonNull(recover);
    return (t, u) -> {
        try {
            return this.testThrows(t, u);
        } catch (Error e) {
            throw e;
        } catch (Throwable throwable) {
            final BiPredicate<? super T, ? super U> predicate = recover.apply(throwable);
            Objects.requireNonNull(predicate,
                    () -> "recover returned null for " + throwable.getClass() + ": " + throwable.getMessage());
            return predicate.test(t, u);
        }
    };
}

From source file:com.liferay.exportimport.controller.LayoutImportController.java

protected void validateFile(long companyId, long groupId, Map<String, String[]> parameterMap,
        ZipReader zipReader) throws Exception {

    // XML/*from w  ww .  j  a  va 2  s. c o m*/

    String xml = zipReader.getEntryAsString("/manifest.xml");

    if (xml == null) {
        throw new LARFileException(LARFileException.TYPE_MISSING_MANIFEST);
    }

    Element rootElement = null;

    try {
        Document document = SAXReaderUtil.read(xml);

        rootElement = document.getRootElement();
    } catch (Exception e) {
        throw new LARFileException(LARFileException.TYPE_INVALID_MANIFEST, e);
    }

    // Bundle compatibility

    Element headerElement = rootElement.element("header");

    int importBuildNumber = GetterUtil.getInteger(headerElement.attributeValue("build-number"));

    if (importBuildNumber < ReleaseInfo.RELEASE_7_0_0_BUILD_NUMBER) {
        int buildNumber = ReleaseInfo.getBuildNumber();

        if (buildNumber != importBuildNumber) {
            throw new LayoutImportException(LayoutImportException.TYPE_WRONG_BUILD_NUMBER,
                    new Object[] { importBuildNumber, buildNumber });
        }
    } else {
        BiPredicate<Version, Version> majorVersionBiPredicate = (currentVersion, importVersion) -> Objects
                .equals(currentVersion.getMajor(), importVersion.getMajor());

        BiPredicate<Version, Version> minorVersionBiPredicate = (currentVersion, importVersion) -> {
            int currentMinorVersion = GetterUtil.getInteger(currentVersion.getMinor(), -1);
            int importedMinorVersion = GetterUtil.getInteger(importVersion.getMinor(), -1);

            if (((currentMinorVersion == -1) && (importedMinorVersion == -1))
                    || (currentMinorVersion < importedMinorVersion)) {

                return false;
            }

            return true;
        };

        BiPredicate<Version, Version> manifestVersionBiPredicate = (currentVersion, importVersion) -> {
            BiPredicate<Version, Version> versionBiPredicate = majorVersionBiPredicate
                    .and(minorVersionBiPredicate);

            return versionBiPredicate.test(currentVersion, importVersion);
        };

        String importSchemaVersion = GetterUtil.getString(headerElement.attributeValue("schema-version"),
                "1.0.0");

        if (!manifestVersionBiPredicate.test(
                Version.getInstance(ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION),
                Version.getInstance(importSchemaVersion))) {

            throw new LayoutImportException(LayoutImportException.TYPE_WRONG_LAR_SCHEMA_VERSION,
                    new Object[] { importSchemaVersion, ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION });
        }
    }

    // Type

    String larType = headerElement.attributeValue("type");

    String[] expectedLARTypes = { "layout-prototype", "layout-set", "layout-set-prototype" };

    Stream<String> stream = Stream.of(expectedLARTypes);

    if (stream.noneMatch(lt -> lt.equals(larType))) {
        throw new LARTypeException(larType, expectedLARTypes);
    }

    Group group = _groupLocalService.fetchGroup(groupId);

    String layoutsImportMode = MapUtil.getString(parameterMap, PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE);

    if (larType.equals("layout-prototype") && !group.isLayoutPrototype()
            && !layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

        throw new LARTypeException(LARTypeException.TYPE_LAYOUT_PROTOTYPE);
    }

    if (larType.equals("layout-set")) {
        if (group.isLayoutPrototype() || group.isLayoutSetPrototype()) {
            throw new LARTypeException(LARTypeException.TYPE_LAYOUT_SET);
        }

        long sourceCompanyGroupId = GetterUtil.getLong(headerElement.attributeValue("company-group-id"));
        long sourceGroupId = GetterUtil.getLong(headerElement.attributeValue("group-id"));

        boolean companySourceGroup = false;

        if (sourceCompanyGroupId == sourceGroupId) {
            companySourceGroup = true;
        }

        if (group.isCompany() ^ companySourceGroup) {
            throw new LARTypeException(LARTypeException.TYPE_COMPANY_GROUP);
        }
    }

    if (larType.equals("layout-set-prototype") && !group.isLayoutSetPrototype()
            && !layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

        throw new LARTypeException(LARTypeException.TYPE_LAYOUT_SET_PROTOTYPE);
    }

    // Portlets compatibility

    List<Element> portletElements = fetchPortletElements(rootElement);

    for (Element portletElement : portletElements) {
        String portletId = GetterUtil.getString(portletElement.attributeValue("portlet-id"));

        if (Validator.isNull(portletId)) {
            continue;
        }

        String schemaVersion = GetterUtil.getString(portletElement.attributeValue("schema-version"));

        PortletDataHandler portletDataHandler = _portletDataHandlerProvider.provide(companyId, portletId);

        if (portletDataHandler == null) {
            continue;
        }

        if (!portletDataHandler.validateSchemaVersion(schemaVersion)) {
            throw new LayoutImportException(LayoutImportException.TYPE_WRONG_PORTLET_SCHEMA_VERSION,
                    new Object[] { schemaVersion, portletId, portletDataHandler.getSchemaVersion() });
        }
    }

    // Available locales

    List<Locale> sourceAvailableLocales = Arrays.asList(
            LocaleUtil.fromLanguageIds(StringUtil.split(headerElement.attributeValue("available-locales"))));

    for (Locale sourceAvailableLocale : sourceAvailableLocales) {
        if (!LanguageUtil.isAvailableLocale(groupId, sourceAvailableLocale)) {

            LocaleException le = new LocaleException(LocaleException.TYPE_EXPORT_IMPORT);

            le.setSourceAvailableLocales(sourceAvailableLocales);
            le.setTargetAvailableLocales(LanguageUtil.getAvailableLocales(groupId));

            throw le;
        }
    }

    // Layout prototypes validity

    Element layoutsElement = rootElement.element(Layout.class.getSimpleName());

    validateLayoutPrototypes(companyId, headerElement, layoutsElement);
}

From source file:org.briljantframework.data.vector.AbstractVector.java

@Override
public <T> Vector filterWithIndex(Class<T> cls, BiPredicate<Object, ? super T> predicate) {
    Vector.Builder builder = newBuilder();
    for (Object key : getIndex()) {
        T value = get(cls, key);/*from   ww  w . j ava 2  s. c  o m*/
        if (predicate.test(key, value)) {
            builder.set(key, value);
        }
    }
    return builder.build();
}

From source file:org.ligoj.app.plugin.id.resource.UserOrgResource.java

/**
 * Performs an operation on a group and a user.
 *
 * @param user// w w w.ja v a2 s . com
 *            The user to move.
 * @param group
 *            The group to update.
 * @param updater
 *            The function to execute on computed groups of current user.
 */
private void updateGroupUser(final String user, final String group,
        final BiPredicate<Collection<String>, String> updater) {

    // Get all delegates of current user
    final List<DelegateOrg> delegates = delegateRepository.findAllByUser(securityHelper.getLogin());

    // Get the implied user
    final UserOrg userOrg = getUser().findByIdExpected(user);

    // Check the implied group
    validateWriteGroup(group, delegates);

    // Compute the new groups
    final Set<String> newGroups = new HashSet<>(userOrg.getGroups());
    if (updater.test(newGroups, group)) {

        // Replace the user groups by the normalized groups including the
        // one we have just updated
        final Collection<String> mergedGroups = mergeGroups(delegates, userOrg, newGroups);

        // Update membership
        getUser().updateMembership(new ArrayList<>(mergedGroups), userOrg);
    }
}

From source file:com.liferay.exportimport.controller.PortletImportController.java

protected void validateFile(long companyId, long groupId, String portletId, ZipReader zipReader)
        throws Exception {

    // XML//  w  w w.  j av  a  2 s  .c o m

    String xml = zipReader.getEntryAsString("/manifest.xml");

    if (xml == null) {
        throw new LARFileException(LARFileException.TYPE_MISSING_MANIFEST);
    }

    Element rootElement = null;

    try {
        Document document = SAXReaderUtil.read(xml);

        rootElement = document.getRootElement();
    } catch (Exception e) {
        throw new LARFileException(LARFileException.TYPE_INVALID_MANIFEST, e);
    }

    // Build compatibility

    Element headerElement = rootElement.element("header");
    Element portletElement = rootElement.element("portlet");

    int importBuildNumber = GetterUtil.getInteger(headerElement.attributeValue("build-number"));

    if (importBuildNumber < ReleaseInfo.RELEASE_7_0_0_BUILD_NUMBER) {
        int buildNumber = ReleaseInfo.getBuildNumber();

        throw new LayoutImportException(LayoutImportException.TYPE_WRONG_BUILD_NUMBER,
                new Object[] { importBuildNumber, buildNumber });
    } else {
        BiPredicate<Version, Version> majorVersionBiPredicate = (currentVersion, importVersion) -> Objects
                .equals(currentVersion.getMajor(), importVersion.getMajor());

        BiPredicate<Version, Version> minorVersionBiPredicate = (currentVersion, importVersion) -> {
            int currentMinorVersion = GetterUtil.getInteger(currentVersion.getMinor(), -1);
            int importedMinorVersion = GetterUtil.getInteger(importVersion.getMinor(), -1);

            if (((currentMinorVersion == -1) && (importedMinorVersion == -1))
                    || (currentMinorVersion < importedMinorVersion)) {

                return false;
            }

            return true;
        };

        BiPredicate<Version, Version> manifestVersionBiPredicate = (currentVersion, importVersion) -> {
            BiPredicate<Version, Version> versionBiPredicate = majorVersionBiPredicate
                    .and(minorVersionBiPredicate);

            return versionBiPredicate.test(currentVersion, importVersion);
        };

        String importSchemaVersion = GetterUtil.getString(headerElement.attributeValue("schema-version"),
                "1.0.0");

        if (!manifestVersionBiPredicate.test(
                Version.getInstance(ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION),
                Version.getInstance(importSchemaVersion))) {

            throw new LayoutImportException(LayoutImportException.TYPE_WRONG_LAR_SCHEMA_VERSION,
                    new Object[] { importSchemaVersion, ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION });
        }
    }

    // Type

    String larType = headerElement.attributeValue("type");

    if (!larType.equals("portlet")) {
        throw new LARTypeException(larType, new String[] { "portlet" });
    }

    // Portlet compatibility

    String rootPortletId = headerElement.attributeValue("root-portlet-id");

    String expectedRootPortletId = PortletIdCodec.decodePortletName(portletId);

    if (!expectedRootPortletId.equals(rootPortletId)) {
        throw new PortletIdException(expectedRootPortletId);
    }

    String schemaVersion = GetterUtil.getString(portletElement.attributeValue("schema-version"), "1.0.0");

    PortletDataHandler portletDataHandler = _portletDataHandlerProvider.provide(companyId, portletId);

    if (!portletDataHandler.validateSchemaVersion(schemaVersion)) {
        throw new LayoutImportException(LayoutImportException.TYPE_WRONG_PORTLET_SCHEMA_VERSION,
                new Object[] { schemaVersion, portletId, portletDataHandler.getSchemaVersion() });
    }

    // Available locales

    if (portletDataHandler.isDataLocalized()) {
        List<Locale> sourceAvailableLocales = Arrays.asList(LocaleUtil
                .fromLanguageIds(StringUtil.split(headerElement.attributeValue("available-locales"))));

        for (Locale sourceAvailableLocale : sourceAvailableLocales) {
            if (!LanguageUtil.isAvailableLocale(_portal.getSiteGroupId(groupId), sourceAvailableLocale)) {

                LocaleException le = new LocaleException(LocaleException.TYPE_EXPORT_IMPORT);

                le.setSourceAvailableLocales(sourceAvailableLocales);
                le.setTargetAvailableLocales(LanguageUtil.getAvailableLocales(_portal.getSiteGroupId(groupId)));

                throw le;
            }
        }
    }
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.core.CoarseGrainedOptimizer.java

private List<Triple<Integer, Optional<Double>, Boolean>> alterUntilBreakPoint(SolutionPerJob solPerJob,
        Function<Integer, Integer> updateFunction, Function<Double, Double> fromResult,
        Predicate<Double> feasibilityCheck, Predicate<Double> stoppingCondition,
        BiPredicate<Double, Double> incrementCheck, Predicate<Integer> vmCheck) {
    List<Triple<Integer, Optional<Double>, Boolean>> lst = new ArrayList<>();
    Optional<Double> previous = Optional.empty();
    boolean shouldKeepGoing = true;

    while (shouldKeepGoing) {
        Pair<Optional<Double>, Long> simulatorResult = dataProcessor.simulateClass(solPerJob);
        Optional<Double> maybeResult = simulatorResult.getLeft();
        Optional<Double> interestingMetric = maybeResult.map(fromResult);

        Integer nVM = solPerJob.getNumberVM();
        lst.add(new ImmutableTriple<>(nVM, maybeResult,
                interestingMetric.filter(feasibilityCheck).isPresent()));
        boolean terminationCriterion = !checkState();
        logger.trace("terminationCriterion is " + terminationCriterion + " after checkState()");
        terminationCriterion |= vmCheck.test(nVM);
        logger.trace("terminationCriterion is " + terminationCriterion + " after vmCheck.test()");
        terminationCriterion |= interestingMetric.filter(stoppingCondition).isPresent();
        logger.trace("terminationCriterion is " + terminationCriterion + " after filter");
        if (previous.isPresent() && interestingMetric.isPresent()
                && (dataService.getScenario().getTechnology() != Technology.STORM
                        || interestingMetric.get() == 0.0)) {
            terminationCriterion |= incrementCheck.test(previous.get(), interestingMetric.get());
        }/*from w ww .  j a v a 2 s  .c o m*/
        shouldKeepGoing = !terminationCriterion;
        previous = interestingMetric;
        if (dataService.getScenario().getTechnology() == Technology.STORM) {
            logger.trace(interestingMetric.orElse(Double.NaN) + " vs. " + solPerJob.getJob().getU());
        } else {
            logger.trace(interestingMetric.orElse(Double.NaN) + " vs. " + solPerJob.getJob().getD());
        }
        if (shouldKeepGoing) {
            String message = String.format("class %s -> num VM: %d, simulator result: %f, metric: %f",
                    solPerJob.getId(), nVM, maybeResult.orElse(Double.NaN),
                    interestingMetric.orElse(Double.NaN));
            logger.info(message);
            solPerJob.updateNumberVM(updateFunction.apply(nVM));
        }
    }

    return lst;
}