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.diorite.impl.entity.diorite.EntityImpl.java

@Override
public <T extends Entity> Collection<? extends T> getNearbyEntities(final double x, final double y,
        final double z, final Predicate<Entity> predicate) {
    final Vector3f entitySize = this.aabb.getEntitySize();
    final Set<T> entities = new HashSet<>(25);

    final int cx = this.getChunk().getX(); // Chunk X location
    final int cz = this.getChunk().getZ(); // Chunk Z location

    final int chunkScanSizeX = 1 + DioriteMathUtils.ceil((x + entitySize.x) / Chunk.CHUNK_SIZE);
    final int chunkScanSizeZ = 1 + DioriteMathUtils.ceil((z + entitySize.z) / Chunk.CHUNK_SIZE);

    final int cxBeginScan = cx - chunkScanSizeX;
    final int czBeginScan = cz - chunkScanSizeZ;

    final int cxEndScan = cx + chunkScanSizeX;
    final int czEndScan = cz + chunkScanSizeZ;

    for (int i = cxBeginScan; i <= cxEndScan; i++) {
        for (int j = czBeginScan; j <= czEndScan; j++) {
            final ChunkImpl chunk = this.world.getChunkAt(i, j);
            if (!chunk.isLoaded()) {
                continue;
            }// w w w . j  a va2 s .c o m

            //noinspection unchecked,ObjectEquality
            chunk.getEntities().stream().filter(e -> (e != this) && predicate.test(e))
                    .forEach(e -> entities.add((T) e));
        }
    }

    return entities;
}

From source file:org.diorite.cfg.messages.MessageLoader.java

/**
 * Load messages from given folder with language files, each file means one language so they need contains language code at the end, like: <br>
 * myLangFile_pl-PL.yml<br>/*from  ww  w  . ja  v a  2  s  .  c o m*/
 * myLangFile_en-US.yml<br>
 * etc... <br>
 *
 * @param predicate             files need match this predictate to be loaded.
 * @param func                  this function should get {@link Locale} in which are messages in file written.
 * @param node                  messages node to use, usefull when you want load messages to one of subnodes.
 * @param folder                folder where language files will be created/loaded
 * @param defaultValuesFunction function that returns Reader with default values for given language.
 *
 * @return this same messages instance as given after loading messages.
 */
public Messages loadMessages(final Predicate<File> predicate, final Function<File, Locale> func,
        final Messages node, final File folder, final Function<Locale, Reader> defaultValuesFunction) {
    final DataTree result = new DataTree("");
    if (!folder.exists()) {
        folder.mkdirs();
    } else if (!folder.isDirectory()) {
        throw new IllegalArgumentException(
                "Given file isn't a folder, can't load language files from: " + folder.toPath());
    }
    final File[] files = folder.listFiles();
    assert files != null;
    final DataTree masterDefault = new DataTree("");
    final Map<Locale, DataTree> defaults = new HashMap<>(files.length + 1);
    {
        for (final Locale locale : this.languages) {
            try (final Reader reader = defaultValuesFunction.apply(locale)) {
                if (reader != null) {
                    result.putDefaults(
                            this.toTree(locale, "", this.yaml.load(Map.class, reader), new DataTree("")));
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
            defaults.put(locale, masterDefault);
        }
    }
    for (final File file : files) {
        if (!predicate.test(file)) {
            continue;
        }
        Locale locale = func.apply(file);
        if (locale == null) {
            locale = this.languages[0];
        }
        {
            final DataTree dataTree = defaults.get(locale);
            if (dataTree == null) {
                continue;
            }
        }
        final Map<?, ?> loaded;
        try {
            loaded = this.yaml.load(Map.class, new FileInputStream(file));
        } catch (final IOException e) {
            e.printStackTrace();
            continue;
        }
        this.toTree(locale, "", loaded, result);
    }
    return result.construct(node);
}

From source file:org.jactr.io.resolver.ASTResolver.java

/**
 * create a version of the model.with the option to generate just the model
 * header (fullResoltuion), or to filter out content when generating a full
 * dump/*from  ww w.j ava 2s  .  c  om*/
 * 
 * @param model
 * @param fullResolution
 *          if false, just the model & parameters is generated. filters are
 *          ignored.
 * @param productionFilter
 * @param chunkTypeFilter
 * @param chunkFilter
 * @return
 */
static public CommonTree toAST(IModel model, boolean fullResolution, Predicate<IProduction> productionFilter,
        Predicate<IChunkType> chunkTypeFilter, Predicate<IChunk> chunkFilter) {
    if (productionFilter == null)
        productionFilter = p -> true;
    if (chunkTypeFilter == null)
        chunkTypeFilter = c -> true;
    if (chunkFilter == null)
        chunkFilter = c -> true;

    /**
     * lock so that we are the only one right now
     */
    ReadWriteLock lock = model.getLock();

    lock.readLock().lock();
    try {
        CommonTree md = _support.createModelTree(model.getName());

        // insert all the parameters
        setParameters(ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.PARAMETERS), model);

        if (fullResolution) {
            CommonTree modules = ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.MODULES);
            for (IModule module : model.getModules()) {
                CommonTree modDesc = toAST(module);
                modules.addChild(modDesc);
            }

            // if full we add extensions, buffers, chunks, chunktype, and
            // productions
            CommonTree extensions = ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.EXTENSIONS);

            for (IExtension extension : model.getExtensions()) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Generating AST for extension " + extension.getClass().getName());

                CommonTree ed = toAST(extension);

                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Returned ast " + ed.toStringTree());

                extensions.addChild(ed);
            }
            // chunktypes will add the chunks for us
            CommonTree decWrapper = ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.DECLARATIVE_MEMORY);
            Set<IChunkType> resolved = new HashSet<IChunkType>();
            List<CommonTree> chunkTypes = new ArrayList<CommonTree>();
            try {
                for (IChunkType ct : model.getDeclarativeModule().getChunkTypes().get())
                    if (chunkTypeFilter.test(ct)) {
                        List<CommonTree> chunkTypesList = toOrderedAST(ct, resolved, chunkTypeFilter,
                                chunkFilter);
                        chunkTypes.addAll(chunkTypesList);
                    }
            } catch (InterruptedException ie) {
                LOGGER.error("Interrupted ", ie);
            } catch (ExecutionException e) {
                LOGGER.error("Execution ", e);
            }

            // now we can dump them
            for (CommonTree ctNode : chunkTypes)
                decWrapper.addChild(ctNode);

            chunkTypes.clear();

            // productions
            CommonTree proWrapper = ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.PROCEDURAL_MEMORY);
            try {
                for (IProduction p : model.getProceduralModule().getProductions().get()) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("generating AST for production " + p);
                    CommonTree pd = toAST(p);
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("returned ast " + pd.toStringTree());
                    proWrapper.addChild(pd);
                }
            } catch (InterruptedException ie) {
                LOGGER.error("Interrupted ", ie);
            } catch (ExecutionException e) {
                LOGGER.error("Execution ", e);
            }

            // buffers
            CommonTree buffersWrapper = ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.BUFFERS);
            Map<String, CommonTree> chunkTypeNodes = ASTSupport.getMapOfTrees(decWrapper,
                    JACTRBuilder.CHUNK_TYPE);
            for (IActivationBuffer buffer : model.getActivationBuffers()) {
                buffersWrapper.addChild(toAST(buffer));
                /*
                 * since the chunks in the buffer aren't in the model, they won't be
                 * serialized correctly, so we grab them now and stick them under
                 * their respective chunktype
                 */
                for (IChunk source : buffer.getSourceChunks()) {
                    CommonTree sourceChunk = toAST(source, false);
                    CommonTree chunkType = chunkTypeNodes.get(source.getSymbolicChunk().getChunkType()
                            .getSymbolicChunkType().getName().toLowerCase());

                    if (chunkType != null)
                        ASTSupport.getFirstDescendantWithType(chunkType, JACTRBuilder.CHUNKS)
                                .addChild(sourceChunk);
                }
            }
        }
        return md;
    } finally {
        lock.readLock().unlock();
    }
}

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

/**
 * Makes a request to mojang's servers of a sublist of at most 100 player's
 * names. Additionally can provide progress outputs
 * //from ww w  . j  a  v a 2  s  .c o m
 * @since 0.0.1
 * @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 player names to their {@link UUID}s
 * @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, UUID> callWithProgessOutput(boolean output, Logger log, Predicate<? super Integer> doOutput)
        throws IOException, ParseException, InterruptedException {
    //Method start
    Map<String, UUID> uuidMap = new HashMap<>();
    int totalNames = this.names.size();
    int completed = 0;
    int failed = 0;
    int requests = (int) Math.ceil(this.names.size() / UUIDFetcher.PROFILES_PER_REQUEST);
    for (int i = 0; i < requests; i++) {
        List<String> request = names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()));
        String body = JSONArray.toJSONString(request);
        HttpURLConnection connection = UUIDFetcher.createConnection();
        UUIDFetcher.writeBody(connection, body);
        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.createConnection();
            UUIDFetcher.writeBody(connection, body);
        }
        JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
        completed += array.size();
        failed += request.size() - array.size();
        for (Object profile : array) {
            JSONObject jsonProfile = (JSONObject) profile;
            UUID uuid = UUIDFetcher.getUUID((String) jsonProfile.get("id"));
            uuidMap.put((String) jsonProfile.get("name"), uuid);
        }
        if (output) {
            int processed = completed + failed;
            if (doOutput.test(processed) || processed == totalNames) {
                log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed,
                        totalNames, ((double) processed / totalNames) * 100D, failed));
            }
        }
    }
    return uuidMap;
}

From source file:org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptorTest.java

private long countScore(String source, QueryResult<Variant> variantQueryResult,
        Predicate<Double> doublePredicate, Function<VariantAnnotation, List<Score>> mapper) {
    long c = 0;/*ww  w.  j a v  a 2  s . c  o m*/
    for (Variant variant : variantQueryResult.getResult()) {
        List<Score> list = mapper.apply(variant.getAnnotation());
        if (list != null) {
            for (Score score : list) {
                if (score.getSource().equalsIgnoreCase(source)) {
                    if (doublePredicate.test(score.getScore())) {
                        c++;
                    }
                }
            }
        }
    }
    return c;
}

From source file:org.finra.herd.service.impl.BusinessObjectDefinitionServiceImpl.java

/**
 * A helper method that will validate a list of business object definitions
 *
 * @param businessObjectDefinitionEntityList the list of business object definitions that will be validated
 *
 * @return true all of the business object definitions are valid in the index
 *///from  w w  w  . j  a va2s  .c  o  m
private boolean indexValidateBusinessObjectDefinitionsList(
        final List<BusinessObjectDefinitionEntity> businessObjectDefinitionEntityList, String indexName) {
    final String documentType = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_DOCUMENT_TYPE, String.class);

    Predicate<BusinessObjectDefinitionEntity> validInIndexPredicate = businessObjectDefinitionEntity -> {
        // Fetch Join with .size()
        businessObjectDefinitionEntity.getAttributes().size();
        businessObjectDefinitionEntity.getBusinessObjectDefinitionTags().size();
        businessObjectDefinitionEntity.getBusinessObjectFormats().size();
        businessObjectDefinitionEntity.getColumns().size();
        businessObjectDefinitionEntity.getSampleDataFiles().size();

        // Convert the business object definition entity to a JSON string
        final String jsonString = businessObjectDefinitionHelper
                .safeObjectMapperWriteValueAsString(businessObjectDefinitionEntity);

        return indexFunctionsDao.isValidDocumentIndex(indexName, documentType,
                businessObjectDefinitionEntity.getId().toString(), jsonString);
    };

    boolean isValid = true;
    for (BusinessObjectDefinitionEntity businessObjectDefinitionEntity : businessObjectDefinitionEntityList) {
        if (!validInIndexPredicate.test(businessObjectDefinitionEntity)) {
            isValid = false;
        }
    }

    return isValid;
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** Utility to get the vertices in the DB matching the specified keys TODO: move to intermediate utils  
 * @param keys// ww  w . j a  va 2s .c  o  m
 * @param bucket_filter
 * @return
 */
@SuppressWarnings("unchecked")
public static final Map<JsonNode, List<Vertex>> getGroupedVertices(final Collection<ObjectNode> keys,
        final TitanTransaction tx, final List<String> key_fields, final Predicate<Vertex> vertex_filter) {
    final Stream<TitanVertex> dups = Lambdas.get(() -> {
        final Map<String, Set<Object>> dedup_query_builder = keys.stream()
                .flatMap(j -> Optionals.streamOf(j.fields(), false))
                .collect(Collectors.groupingBy(kv -> kv.getKey(),
                        Collectors.mapping(kv -> jsonNodeToObject(kv.getValue()), Collectors.toSet())));
        ;

        //TODO (ALEPH-15): would be nice to support custom "fuzzier" queries, since we're doing a dedup stage to pick the actual winning vertices anyway
        // that way you could say query on tokenized-version of name and get anyone with the same first or last name (say) and then pick the most likely
        // one based on the graph ... of course you'd probably want the full graph for that, so it might end up being better served as a "self-analytic" to do is part
        // of post processing?
        // (NOTE: same remarks apply for edges)
        // (NOTE: currently I've been going in the opposite direction, ie enforcing only one vertex per keyset per bucket ... otherwise it's going to get really 
        //  confusing when you try to merge all the different versions that Titan creates because of the lack of an upsert function....)

        final TitanGraphQuery<?> matching_nodes_query = dedup_query_builder.entrySet().stream().reduce(
                tx.query(), (query, kv) -> query.has(kv.getKey(), Contain.IN, kv.getValue()),
                (query1, query2) -> query1 // (can't occur since reduce not parallel)
        );

        return Optionals.streamOf(matching_nodes_query.vertices(), false);
    });

    // Remove false positives, un-authorized nodes, and group by key

    final Map<JsonNode, List<Vertex>> grouped_vertices = dups
            .map(vertex -> Tuples._2T((Vertex) vertex, getElementProperties(vertex, key_fields)))
            .filter(vertex_key -> keys.contains(vertex_key._2())) // (remove false positives)
            .filter(vertex_key -> vertex_filter.test(vertex_key._1())) // (remove un-authorized nodes)
            .collect(Collectors.groupingBy(t2 -> (JsonNode) t2._2(), // (group by key)
                    Collectors.mapping(t2 -> t2._1(), Collectors.toList())));

    return grouped_vertices;
}

From source file:enumj.Enumerator.java

/**
 * Returns whether any elements of the current enumerator match the
 * provided predicate.//ww w.j a  v a  2 s.c  om
 *
 * @param predicate state-less predicate to apply to the enumerated
 * elements.
 * @return true if some elements satisfy
 * {@code predicate}, false otherwise.
 * @see #allMatch(java.util.function.Predicate)
 * @see #noneMatch(java.util.function.Predicate)
 * @exception IllegalArgumentException {@code predicate} is null.
 */
public default boolean anyMatch(Predicate<? super E> predicate) {
    Checks.ensureNotNull(predicate, Messages.NULL_ENUMERATOR_PREDICATE);
    while (hasNext()) {
        if (predicate.test(next())) {
            return true;
        }
    }
    return false;
}

From source file:enumj.Enumerator.java

/**
 * Returns whether no enumerated element matches the provided predicate.
 *
 * @param predicate state-less {@link Predicate} instance to apply
 * to enumerated elements./*from   ww  w.  j a v a2s . c o  m*/
 * @return true if no enumerated element matches
 * <code>predicate</code>, false otherwise.
 * @exception IllegalArgumentException <code>predicate</code> is null.
 * @see #allMatch(java.util.function.Predicate)
 * @see #anyMatch(java.util.function.Predicate)
 */
public default boolean noneMatch(Predicate<? super E> predicate) {
    Checks.ensureNotNull(predicate, Messages.NULL_ENUMERATOR_PREDICATE);
    while (hasNext()) {
        if (predicate.test(next())) {
            return false;
        }
    }
    return true;
}

From source file:enumj.Enumerator.java

/**
 * Returns whether all the elements of the current enumerator match the
 * provided predicate.//  w w w. ja v  a2 s.  co  m
 *
 * @param predicate state-less predicate to apply to the enumerated
 * elements.
 * @return true if all the elements satisfy.
 * {@code predicate}, false otherwise
 * @see #anyMatch(java.util.function.Predicate)
 * @see #noneMatch(java.util.function.Predicate)
 * @exception IllegalArgumentException {@code predicate} is null.
 */
public default boolean allMatch(Predicate<? super E> predicate) {
    Checks.ensureNotNull(predicate, Messages.NULL_ENUMERATOR_PREDICATE);
    while (hasNext()) {
        if (!predicate.test(next())) {
            return false;
        }
    }
    return true;
}