List of usage examples for java.util.function Predicate test
boolean test(T t);
From source file:org.fenixedu.academic.domain.ExecutionCourse.java
public void searchAttends(SearchExecutionCourseAttendsBean attendsBean) { check(this, ExecutionCoursePredicates.executionCourseLecturingTeacherOrDegreeCoordinator); final Predicate<Attends> filter = attendsBean.getFilters(); final Collection<Attends> validAttends = new HashSet<Attends>(); final Map<Integer, Integer> enrolmentNumberMap = new HashMap<Integer, Integer>(); for (final Attends attends : getAttendsSet()) { if (filter.test(attends)) { validAttends.add(attends);/* www . ja v a 2 s . c o m*/ addAttendsToEnrolmentNumberMap(attends, enrolmentNumberMap); } } attendsBean.setAttendsResult(validAttends); attendsBean.setEnrolmentsNumberMap(enrolmentNumberMap); }
From source file:org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptorTest.java
public long filterPopulation(QueryResult<Variant> queryResult, Predicate<Variant> filterVariants, Predicate<Map<String, PopulationFrequency>> predicate) { queryResult.getResult().forEach(variant -> { assertNotNull(variant);/*from w ww.j a v a 2s. c o m*/ assertNotNull("In " + variant, variant.getAnnotation()); // assertNotNull("In " + variant, variant.getAnnotation().getPopulationFrequencies()); }); Set<String> expectedVariants = allVariants.getResult().stream() .filter(filterVariants.and(variant -> variant.getAnnotation() != null)).filter(variant -> { Map<String, PopulationFrequency> map; if (variant.getAnnotation().getPopulationFrequencies() == null) { map = Collections.emptyMap(); } else { map = new HashMap<>(); for (PopulationFrequency p : variant.getAnnotation().getPopulationFrequencies()) { map.put(p.getStudy() + ":" + p.getPopulation(), p); } } return predicate.test(map); }).map(Variant::toString).collect(Collectors.toSet()); assertTrue("Expect to get at least one result", expectedVariants.size() > 0); for (String variant : expectedVariants) { Set<String> result = queryResult.getResult().stream().map(Variant::toString) .collect(Collectors.toSet()); if (!result.contains(variant)) { System.out.println("variant missing = " + variant); } } for (Variant variant : queryResult.getResult()) { if (!expectedVariants.contains(variant.toString())) { System.out.println("variant not suppose to be = " + variant); } } assertEquals(expectedVariants.size(), queryResult.getNumResults()); long count = queryResult.getResult().stream().map(variant -> { Map<String, PopulationFrequency> map; if (variant.getAnnotation().getPopulationFrequencies() == null) { map = Collections.emptyMap(); } else { map = new HashMap<>(); for (PopulationFrequency p : variant.getAnnotation().getPopulationFrequencies()) { map.put(p.getStudy() + ":" + p.getPopulation(), p); } } return map; }).filter(predicate.negate()).count(); assertEquals(0, count); return count; }
From source file:blusunrize.immersiveengineering.api.ApiUtils.java
public static boolean raytraceAlongCatenaryRelative(Connection conn, Predicate<Triple<BlockPos, Vec3d, Vec3d>> shouldStop, Consumer<Triple<BlockPos, Vec3d, Vec3d>> close, Vec3d vStart, Vec3d vEnd) {//w ww .ja v a 2s .c o m conn.getSubVertices(vStart, vEnd); HashMap<BlockPos, Vec3d> halfScanned = new HashMap<>(); HashSet<BlockPos> done = new HashSet<>(); HashSet<Triple<BlockPos, Vec3d, Vec3d>> near = new HashSet<>(); Vec3d across = vEnd.subtract(vStart); across = new Vec3d(across.x, 0, across.z); double lengthHor = across.length(); halfScanned.put(conn.start, vStart); halfScanned.put(conn.end, vEnd); //Raytrace X&Z for (int dim = 0; dim <= 2; dim += 2) { int start = (int) Math.ceil(Math.min(getDim(vStart, dim), getDim(vEnd, dim))); int end = (int) Math.ceil(Math.max(getDim(vStart, dim), getDim(vEnd, dim))); for (int i = start; i < end; i++) { double factor = (i - getDim(vStart, dim)) / getDim(across, dim); Vec3d pos = conn.getVecAt(factor); if (handleVec(pos, pos, 0, halfScanned, done, shouldStop, near, conn.start)) return false; } } //Raytrace Y boolean vertical = vStart.x == vEnd.x && vStart.z == vEnd.z; if (vertical) { for (int y = (int) Math.ceil(Math.min(vStart.y, vEnd.y)); y <= Math .floor(Math.max(vStart.y, vEnd.y)); y++) { Vec3d pos = new Vec3d(vStart.x, y, vStart.z); if (handleVec(pos, pos, 0, halfScanned, done, shouldStop, near, conn.start)) return false; } } else { double min = conn.catA + conn.catOffsetY + vStart.y; for (int i = 0; i < 2; i++) { double factor = i == 0 ? 1 : -1; double max = i == 0 ? vEnd.y : vStart.y; for (int y = (int) Math.ceil(min); y <= Math.floor(max); y++) { double yReal = y - vStart.y; double posRel; Vec3d pos; posRel = (factor * acosh((yReal - conn.catOffsetY) / conn.catA) * conn.catA + conn.catOffsetX) / lengthHor; pos = new Vec3d(vStart.x + across.x * posRel, y, vStart.z + across.z * posRel); if (posRel >= 0 && posRel <= 1 && handleVec(pos, pos, 0, halfScanned, done, shouldStop, near, conn.start)) return false; } } } for (Triple<BlockPos, Vec3d, Vec3d> p : near) close.accept(p); for (Map.Entry<BlockPos, Vec3d> p : halfScanned.entrySet()) if (shouldStop.test(new ImmutableTriple<>(p.getKey(), p.getValue(), p.getValue()))) return false; return true; }
From source file:org.exoplatform.outlook.OutlookServiceImpl.java
/** * Fetch query./*from w ww . ja v a2 s.c om*/ * * @param qr the qr * @param limit the limit * @param res the res * @param acceptNode the accept node * @throws RepositoryException the repository exception * @throws OutlookException the outlook exception */ protected void fetchQuery(QueryResult qr, int limit, Set<File> res, Predicate<Node> acceptNode) throws RepositoryException, OutlookException { SpaceService spaceService = spaceService(); for (NodeIterator niter = qr.getNodes(); niter.getPosition() < limit && niter.hasNext();) { Node node = niter.nextNode(); try { if (acceptNode.test(node)) { // detect is it space and then check if space member String path = node.getPath(); Space space; if (path.startsWith(SPACES_HOME)) { try { String groupId = path.substring(7, path.indexOf("/", SPACES_HOME.length() + 1)); space = spaceService.getSpaceByGroupId(groupId); if (space != null) { Set<String> allMemembers = new HashSet<String>(); for (String s : space.getManagers()) { allMemembers.add(s); } for (String s : space.getMembers()) { allMemembers.add(s); } if (!allMemembers.contains(currentUserId())) { // when not a space member - skip this file (but user still may be an owner of it!) limit++; continue; } } } catch (IndexOutOfBoundsException e) { // XXX something not clear with space path, will use portal page path as for Personal // Documents (it works well in PLF 4.3) space = null; } } else { space = null; } UserFile file = new UserFile(node.getParent().getPath(), node); if (space != null) { initDocumentLink(SiteType.GROUP, // GROUP space.getGroupId().replace("/", "."), space.getGroupId(), // /spaces/product_team space.getShortName() + "/documents", // product_team/documents file); } else { initDocumentLink(SiteType.PORTAL, // PORTAL PERSONAL_DOCUMENTS, "intranet", // intranet "documents", // documents file); } res.add(file); } else { limit++; } } catch (RepositoryException e) { LOG.warn("Error read queried node " + e.getMessage() + ". Node skipped: " + node); limit++; } } }
From source file:com.joyent.manta.client.MantaClient.java
/** * <p>Finds all directories and files recursively under a given path. Since * this method returns a {@link Stream}, consumers can add their own * additional filtering based on path, object type or other criteria.</p> * * <p>This method will make each request to each subdirectory in parallel. * Parallelism settings are set by JDK system property: * <code>java.util.concurrent.ForkJoinPool.common.parallelism</code></p> * * <p>When using a filter with this method, if the filter matches a directory, * then all subdirectory results for that directory will be excluded. If you * want to perform a match against all results, then use {@link #find(String)} * and then filter on the stream returned.</p> * * <p><strong>WARNING:</strong> this method is not atomic and thereby not * safe if other operations are performed on the directory structure while * it is running.</p>/*from w ww .j a v a2s . c o m*/ * * @param path directory path * @param filter predicate class used to filter all results returned * @return A recursive unsorted {@link Stream} of {@link MantaObject} * instances representing the contents of all subdirectories. */ public Stream<MantaObject> find(final String path, final Predicate<? super MantaObject> filter) { /* We read directly from the iterator here to reduce the total stack * frames and to reduce the amount of abstraction to a minimum. * * Within this loop, we store all of the objects found in memory so * that we can later query find() methods for the directory objects * in parallel. */ final Stream.Builder<MantaObject> objectBuilder = Stream.builder(); final Stream.Builder<MantaObject> dirBuilder = Stream.builder(); try (MantaDirectoryListingIterator itr = streamingIterator(path)) { while (itr.hasNext()) { final Map<String, Object> item = itr.next(); final MantaObject obj = MantaObjectConversionFunction.INSTANCE.apply(item); /* We take a predicate as a method parameter because it allows * us to filter at the highest level within this iterator. If * we just passed the stream as is back to the user, then * they would have to filter the results *after* all of the * HTTP requests were made. This way the filter can help limit * the total number of HTTP requests made to Manta. */ if (filter == null || filter.test(obj)) { objectBuilder.accept(obj); if (obj.isDirectory()) { dirBuilder.accept(obj); } } } } /* All objects within this directory should be included in the results, * so we have a stream stored here that will later be concatenated. */ final Stream<MantaObject> objectStream = objectBuilder.build(); /* Directories are processed in parallel because it is the only unit * within our abstractions that can be properly done in parallel. * MantaDirectoryListingIterator forces all paging of directory * listings to be sequential requests. However, it works fine to * run multiple MantaDirectoryListingIterator instances per request. * That is exactly what we are doing here using streams which is * allowing us to do the recursive calls in a lazy fashion. * * From a HTTP request perspective, this means that only the listing for * this current highly directory is performed and no other listing * will be performed until the stream is read. */ try { final Stream<MantaObject> dirStream = findForkJoinPool .submit(() -> dirBuilder.build().parallel().flatMap(obj -> find(obj.getPath(), filter))).get(); /* Due to the way we concatenate the results will be quite out of order * if a consumer needs sorted results that is their responsibility. */ final Stream<MantaObject> stream = Stream.concat(objectStream, dirStream); danglingStreams.add(stream); return stream; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return Stream.empty(); } catch (ExecutionException e) { throw new MantaException(e.getCause()); } }
From source file:gedi.util.ArrayUtils.java
public static <T> int count(T[] a, Predicate<T> pred) { int re = 0;//from w w w . j a va 2 s .co m for (T c : a) if (pred.test(c)) re++; return re; }
From source file:gedi.util.ArrayUtils.java
/** * Searches the array from the beginning to the end until an element matching * the predicate is found.//ww w. j a v a 2 s .c om * Returns -1 if the element could not be found. * @param <T> * @param array the array * @param item the item to search for * @return */ public static <T> int linearSearch(T[] array, Predicate<T> predicate) { for (int i = 0; i < array.length; i++) if (predicate.test(array[i])) return i; return -1; }
From source file:gedi.util.ArrayUtils.java
public static <T> int remove(T[] a, Predicate<T> retain) { int index = 0; for (int i = 0; i < a.length; i++) { if (retain.test(a[i])) a[index++] = a[i];/* w ww . jav a 2 s . co m*/ } return index; }
From source file:gedi.util.ArrayUtils.java
public static <T> int find(T[] a, int start, int stop, Predicate<T> predicate) { start = Math.max(start, 0);//from w w w. ja va2s .co m stop = Math.min(stop, a.length); for (int i = start; i < stop; i++) if (predicate.test(a[i])) return i; return -1; }