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.apache.accumulo.core.conf.PropertyType.java

private static Predicate<String> boundedUnits(final long lowerBound, final long upperBound,
        final boolean caseSensitive, final String... suffixes) {
    Predicate<String> suffixCheck = new HasSuffix(caseSensitive, suffixes);
    return x -> x == null
            || (suffixCheck.test(x) && new Bounds(lowerBound, upperBound).test(stripUnits.apply(x)));
}

From source file:ambroafb.general.AnnotiationUtils.java

private static boolean getPredicateValue(Class predicateClass, String fieldName) {
    try {//  w  ww  .  j a v a2s  .co m
        if (predicateClass != Annotations.ContentNotEmpty.DEFAULT.class) {
            Predicate<String> p = (Predicate<String>) predicateClass.getConstructor().newInstance();
            return p.test(fieldName);
        }
    } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
            | IllegalArgumentException | InvocationTargetException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return true;
}

From source file:Main.java

@Nullable
public static <ELEMENTTYPE> ELEMENTTYPE getAtIndex(@Nullable final Iterable<? extends ELEMENTTYPE> aCollection,
        @Nullable final Predicate<? super ELEMENTTYPE> aFilter, @Nonnegative final int nIndex,
        @Nullable final ELEMENTTYPE aDefault) {
    if (aFilter == null)
        return getAtIndex(aCollection, nIndex, aDefault);

    if (nIndex >= 0) {
        int nCurIndex = 0;
        for (final ELEMENTTYPE aElement : aCollection)
            if (aFilter.test(aElement)) {
                if (nCurIndex == nIndex)
                    return aElement;
                ++nCurIndex;/*from ww  w  . ja va  2  s . co m*/
            }
    }
    return aDefault;
}

From source file:org.opensingular.form.SFormUtil.java

/**
 * Retorna o nome do filho atual indo em direo ao raiz mas parando segundo
 * a condico de parada informada.// w  ww. j a  v  a 2 s.  c o  m
 */
public static String generatePath(SInstance instance, Predicate<SInstance> stopCondition) {
    SInstance current = instance;
    List<SInstance> sequencia = null;
    while (!stopCondition.test(current)) {
        if (sequencia == null) {
            sequencia = new ArrayList<>();
        }
        sequencia.add(current);
        current = current.getParent();
    }
    if (sequencia == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    for (int i = sequencia.size() - 1; i != -1; i--) {
        current = sequencia.get(i);
        if (current.getParent() instanceof SIList) {
            int pos = ((SIList<?>) current.getParent()).indexOf(current);
            if (pos == -1) {
                throw new SingularFormException(
                        current.getName() + " no  mais filho de " + current.getParent().getName());
            }
            sb.append('[').append(pos).append(']');
        } else {
            if (current.getParent() != null && sb.length() != 0) {
                sb.append('.');
            }
            sb.append(current.getName());
        }
    }
    return sb.toString();
}

From source file:de.bluepair.sci.client.SHAUtils.java

public static <T> Map<String, String> sha512(Path path, Predicate<T> gard, T testValue, long blockSizePref,
        boolean forceBlockSize) {

    if (Files.notExists(path)) {
        return null;
    }/*from  ww w.  ja v a  2s  .  co m*/
    MessageDigest md = getDigest();
    MessageDigest md1 = getDigest();

    if (!gard.test(testValue)) {
        return null;
    }
    long blockSize = blockSizePref;
    long size = -1;
    try {
        size = Files.size(path);
        if (!forceBlockSize) {// maximal 10 hashsummen
            // sonst hab ich zu viele in der datei
            // stehen!
            while (size / blockSize > 10) {
                blockSize += blockSizePref;
            }
        }

    } catch (IOException e) {
        blockSize = blockSizePref;
        return null;
    }

    Map<String, String> map = new HashMap<>();

    long lastStart = 0;

    long stepDown = blockSize;

    try (final SeekableByteChannel fileChannel = Files.newByteChannel(path, StandardOpenOption.READ);) {

        final ByteBuffer buffer = ByteBuffer.allocateDirect(8192);
        int last;
        do {
            if (!gard.test(testValue) || Files.notExists(path)) {
                return null;
            }
            buffer.clear();
            last = fileChannel.read(buffer);

            buffer.flip();
            md.update(buffer);

            // calc 2checksups
            buffer.flip();
            md1.update(buffer);

            if (last > 0) {
                stepDown -= last;
            }

            // wenn ich ein 100mb netzwerk habe
            // ~ca. 5MB bertragung
            // also bei abbruch kann wiederaufgesetzt werden wenn die summen
            // bekannt sind.
            // ~hnlich Blcke berechen also
            // 0-5 c1
            // 0-10 c2
            // 5-10 c3 ...

            if (stepDown <= 0 || (last <= 0)) {
                long len = (blockSize + Math.abs(stepDown));
                if (stepDown > 0) {
                    // kottektur wenn last <0
                    len = blockSize - stepDown;
                }
                stepDown = blockSize;
                map.put("sha512_" + lastStart + "_" + len, Hex.encodeHexString(md1.digest()));
                lastStart += len;
                md1.reset();
            }

        } while (last > 0);

    } catch (IOException ex) {
        Logger.getLogger(FileAnalysis.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

    final byte[] sha1hash = md.digest();
    map.put("sha512", Hex.encodeHexString(sha1hash));
    return map;

}

From source file:fr.landel.utils.commons.exception.ExceptionUtils.java

/**
 * Throws an exception if the predicate doesn't match
 * /* w  w  w  .j a  v  a  2s.c  o  m*/
 * <pre>
 * String key = "test";
 * // ...
 * ExceptionUtils.throwsException(key, StringUils::isNotEmpty, IllegalArgumentException::new, null, "error on key");
 * </pre>
 * 
 * @param object
 *            the object to check
 * @param predicate
 *            the predicate that validates the object
 * @param supplier
 *            the exception supplier
 * @param locale
 *            the message locale (optional)
 * @param message
 *            the error message (required)
 * @param arguments
 *            the message arguments
 * @param <T>
 *            the object type
 * @param <E>
 *            the exception type
 * @throws E
 *             if predicate doesn't match
 */
public static <T, E extends Throwable> void throwsException(final T object, final Predicate<T> predicate,
        final Function<String, E> supplier, final Locale locale, final String message,
        final Object... arguments) throws E {
    Objects.requireNonNull(predicate, "predicate");
    Objects.requireNonNull(supplier, "supplier");
    Objects.requireNonNull(message, "message");

    if (!predicate.test(object)) {
        throw supplier.apply(StringUtils.format(locale, message, new Object[] { object }, arguments));
    }
}

From source file:org.briljantframework.data.Collectors.java

/**
 * Returns an aggregator that filter values.
 *
 * @param supplier the vector builder/*from  w  w  w .j  av  a 2  s . c om*/
 * @param predicate the predicate. If {@code true} include value.
 * @param <T> the input type
 * @return a filtering aggregator
 */
public static <T> Collector<T, ?, Vector> filter(Supplier<Vector.Builder> supplier, Predicate<T> predicate) {
    return Collector.of(supplier, (acc, v) -> {
        if (predicate.test(v)) {
            acc.add(v);
        }
    }, (Vector.Builder left, Vector.Builder right) -> {
        left.addAll(right);
        return left;
    }, Vector.Builder::build);
}

From source file:io.github.jeddict.jcode.util.StringHelper.java

public static String getNext(String name, Predicate<String> checkExist, boolean increment) {
    int index = 0;
    String nextName;/*from   w ww.j  av a 2 s .c om*/
    if (increment) {
        nextName = name + ++index;
    } else {
        nextName = name;
    }
    boolean isExist = true;
    while (isExist) {
        if (checkExist.test(nextName)) {
            isExist = true;
            nextName = name + ++index;
        } else {
            return nextName;
        }
    }
    return nextName;
}

From source file:org.diorite.config.impl.actions.ActionsRegistry.java

@Nullable
public static Pair<ConfigPropertyAction, ActionMatcherResult> findMethod(Method method,
        Predicate<String> propertyNameChecker) {
    Pair<ConfigPropertyAction, ActionMatcherResult> lastMatching = null;
    for (ConfigPropertyActionEntry actionEntry : actions) {
        ConfigPropertyAction action = actionEntry.action;
        ActionMatcherResult actionMatcherResult = action.matchesAction(method);
        if (actionMatcherResult.isMatching()) {
            actionMatcherResult.setValidatedName(action.declaresProperty()
                    || propertyNameChecker.test(actionMatcherResult.getPropertyName()));
            lastMatching = new ImmutablePair<>(action, actionMatcherResult);
            if (actionMatcherResult.isValidatedName()) {
                return lastMatching;
            }/*from  ww  w.j a  va  2 s .co  m*/
        }
    }
    return lastMatching;
}

From source file:org.apache.accumulo.core.client.impl.ClientContext.java

/**
 * A utility method for converting client configuration to a standard configuration object for use internally.
 *
 * @param config/*from   w ww. ja  va2 s.c  om*/
 *          the original {@link ClientConfiguration}
 * @return the client configuration presented in the form of an {@link AccumuloConfiguration}
 */
public static AccumuloConfiguration convertClientConfig(final Configuration config) {

    final AccumuloConfiguration defaults = DefaultConfiguration.getInstance();

    return new AccumuloConfiguration() {
        @Override
        public String get(Property property) {
            final String key = property.getKey();

            // Attempt to load sensitive properties from a CredentialProvider, if configured
            if (property.isSensitive()) {
                org.apache.hadoop.conf.Configuration hadoopConf = getHadoopConfiguration();
                if (null != hadoopConf) {
                    try {
                        char[] value = CredentialProviderFactoryShim.getValueFromCredentialProvider(hadoopConf,
                                key);
                        if (null != value) {
                            log.trace("Loaded sensitive value for {} from CredentialProvider", key);
                            return new String(value);
                        } else {
                            log.trace(
                                    "Tried to load sensitive value for {} from CredentialProvider, but none was found",
                                    key);
                        }
                    } catch (IOException e) {
                        log.warn(
                                "Failed to extract sensitive property ({}) from Hadoop CredentialProvider, falling back to base AccumuloConfiguration",
                                key, e);
                    }
                }
            }

            if (config.containsKey(key))
                return config.getString(key);
            else {
                // Reconstitute the server kerberos property from the client config
                if (Property.GENERAL_KERBEROS_PRINCIPAL == property) {
                    if (config.containsKey(ClientProperty.KERBEROS_SERVER_PRIMARY.getKey())) {
                        // Avoid providing a realm since we don't know what it is...
                        return config.getString(ClientProperty.KERBEROS_SERVER_PRIMARY.getKey()) + "/_HOST@"
                                + SaslConnectionParams.getDefaultRealm();
                    }
                }
                return defaults.get(property);
            }
        }

        @Override
        public void getProperties(Map<String, String> props, Predicate<String> filter) {
            defaults.getProperties(props, filter);

            Iterator<?> keyIter = config.getKeys();
            while (keyIter.hasNext()) {
                String key = keyIter.next().toString();
                if (filter.test(key))
                    props.put(key, config.getString(key));
            }

            // Two client props that don't exist on the server config. Client doesn't need to know about the Kerberos instance from the principle, but servers do
            // Automatically reconstruct the server property when converting a client config.
            if (props.containsKey(ClientProperty.KERBEROS_SERVER_PRIMARY.getKey())) {
                final String serverPrimary = props.remove(ClientProperty.KERBEROS_SERVER_PRIMARY.getKey());
                if (filter.test(Property.GENERAL_KERBEROS_PRINCIPAL.getKey())) {
                    // Use the _HOST expansion. It should be unnecessary in "client land".
                    props.put(Property.GENERAL_KERBEROS_PRINCIPAL.getKey(),
                            serverPrimary + "/_HOST@" + SaslConnectionParams.getDefaultRealm());
                }
            }

            // Attempt to load sensitive properties from a CredentialProvider, if configured
            org.apache.hadoop.conf.Configuration hadoopConf = getHadoopConfiguration();
            if (null != hadoopConf) {
                try {
                    for (String key : CredentialProviderFactoryShim.getKeys(hadoopConf)) {
                        if (!Property.isValidPropertyKey(key) || !Property.isSensitive(key)) {
                            continue;
                        }

                        if (filter.test(key)) {
                            char[] value = CredentialProviderFactoryShim
                                    .getValueFromCredentialProvider(hadoopConf, key);
                            if (null != value) {
                                props.put(key, new String(value));
                            }
                        }
                    }
                } catch (IOException e) {
                    log.warn(
                            "Failed to extract sensitive properties from Hadoop CredentialProvider, falling back to accumulo-site.xml",
                            e);
                }
            }
        }

        private org.apache.hadoop.conf.Configuration getHadoopConfiguration() {
            String credProviderPaths = config
                    .getString(Property.GENERAL_SECURITY_CREDENTIAL_PROVIDER_PATHS.getKey());
            if (null != credProviderPaths && !credProviderPaths.isEmpty()) {
                org.apache.hadoop.conf.Configuration hadoopConf = new org.apache.hadoop.conf.Configuration();
                hadoopConf.set(CredentialProviderFactoryShim.CREDENTIAL_PROVIDER_PATH, credProviderPaths);
                return hadoopConf;
            }

            log.trace("Did not find credential provider configuration in ClientConfiguration");

            return null;
        }
    };

}