Java Code Examples for java.util.function.Predicate

The following are top voted examples for showing how to use java.util.function.Predicate. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: koryphe   File: OrTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldRejectWhenAllFunctionsReject() {
    // Given
    final Predicate<String> func1 = mock(Predicate.class);
    final Predicate<String> func2 = mock(Predicate.class);
    final Predicate<String> func3 = mock(Predicate.class);
    final Or<String> or = new Or<>(func1, func2, func3);

    given(func1.test("value")).willReturn(false);
    given(func2.test("value")).willReturn(false);
    given(func3.test("value")).willReturn(false);

    // When
    boolean accepted = or.test("value");

    // Then
    assertFalse(accepted);
    verify(func1).test("value");
    verify(func2).test("value");
    verify(func3).test("value");
}
 
Example 2
Project: com-liferay-apio-architect   File: FieldsWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Writes a {@code Map<String, S>} returned by a {@link Representor}
 * function. This method uses a consumer so each caller can decide what to
 * do with each entry. Each member of the map is filtered using the {@link
 * Fields} predicate provided by {@link #getFieldsPredicate()}.
 *
 * @param representorFunction the {@code Representor} function that returns
 *        the map being written
 * @param consumer the consumer used to process each filtered entry
 */
public <U> void writeFields(
	Function<Representor<T, S>, Map<String, U>> representorFunction,
	Consumer<Entry<String, U>> consumer) {

	Map<String, U> map = representorFunction.apply(_representor);

	Set<Entry<String, U>> entries = map.entrySet();

	Stream<Entry<String, U>> stream = entries.stream();

	stream.filter(
		entry -> {
			Predicate<String> fieldsPredicate = getFieldsPredicate();

			return fieldsPredicate.test(entry.getKey());
		}
	).forEach(
		consumer
	);
}
 
Example 3
Project: manifold   File: FqnCacheNode.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("UnusedDeclaration")
public final boolean visitNodeBreadthFirst( Predicate<FqnCacheNode> visitor )
{
  if( !visitor.test( this ) )
  {
    return false;
  }
  if( _children != null )
  {
    List<FqnCacheNode<K>> copy = new ArrayList<>( _children.values() );
    for( FqnCacheNode<K> child : copy )
    {
      child.visitNodeBreadthFirst( visitor );
    }
  }
  return true;
}
 
Example 4
Project: keycloak-protocol-cas   File: AbstractUserRoleMappingMapper.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves all roles of the current user based on direct roles set to the user, its groups and their parent groups.
 * Then it recursively expands all composite roles, and restricts according to the given predicate {@code restriction}.
 * If the current client sessions is restricted (i.e. no client found in active user session has full scope allowed),
 * the final list of roles is also restricted by the client scope. Finally, the list is mapped to the token into
 * a claim.
 */
protected void setAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, UserSessionModel userSession,
                                   Predicate<RoleModel> restriction, String prefix) {
    String rolePrefix = prefix == null ? "" : prefix;
    UserModel user = userSession.getUser();

    // get a set of all realm roles assigned to the user or its group
    Stream<RoleModel> clientUserRoles = getAllUserRolesStream(user).filter(restriction);

    boolean dontLimitScope = userSession.getAuthenticatedClientSessions().values().stream().anyMatch(cs -> cs.getClient().isFullScopeAllowed());
    if (! dontLimitScope) {
        Set<RoleModel> clientRoles = userSession.getAuthenticatedClientSessions().values().stream()
          .flatMap(cs -> cs.getClient().getScopeMappings().stream())
          .collect(Collectors.toSet());

        clientUserRoles = clientUserRoles.filter(clientRoles::contains);
    }

    Set<String> realmRoleNames = clientUserRoles
      .map(m -> rolePrefix + m.getName())
      .collect(Collectors.toSet());

    setPlainAttribute(attributes, mappingModel, realmRoleNames);
}
 
Example 5
Project: freecol   File: Colony.java   Source Code and License 6 votes vote down vote up
/**
 * Find a student for the specified teacher.
 * Do not search if ALLOW_STUDENT_SELECTION is true--- its the
 * player's job then.
 *
 * @param teacher The teacher {@code Unit} that needs a student.
 * @return A potential student, or null of none found.
 */
public Unit findStudent(final Unit teacher) {
    if (getSpecification().getBoolean(GameOptions.ALLOW_STUDENT_SELECTION))
        return null; // No automatic assignment
    final GoodsType expertProduction
            = teacher.getType().getExpertProduction();
    final Predicate<Unit> teacherPred = u ->
            u.getTeacher() == null && u.canBeStudent(teacher);
    // Always pick the student with the least skill first.
    // Break ties by favouring the one working in the teacher's trade,
    // otherwise first applicant wins.
    final Comparator<Unit> skillComparator
            = Comparator.comparingInt(Unit::getSkillLevel);
    final Comparator<Unit> tradeComparator
            = Comparator.comparingInt(u ->
            (u.getWorkType() == expertProduction) ? 0 : 1);
    final Comparator<Unit> fullComparator
            = skillComparator.thenComparing(tradeComparator);
    return minimize(getUnits(), teacherPred, fullComparator);
}
 
Example 6
Project: cyberduck   File: ListFilteringFeature.java   Source Code and License 6 votes vote down vote up
protected Path search(final Path file) throws BackgroundException {
    final AttributedList<Path> list;
    if(!cache.isCached(file.getParent())) {
        list = session.list(file.getParent(), new DisabledListProgressListener());
        cache.put(file.getParent(), list);
    }
    else {
        list = cache.get(file.getParent());
    }
    final Predicate<Path> predicate;
    final Predicate<Path> simple = session.getCase() == Session.Case.insensitive ? new CaseInsensitivePathPredicate(file) : new SimplePathPredicate(file);
    if(StringUtils.isNotBlank(file.attributes().getVersionId())) {
        // Look for exact match
        return list.filter(new NullFilter<>()).find(new PredicateChain<Path>(simple, new DefaultPathPredicate(file)));
    }
    else {
        return list.filter(new NullFilter<>()).find(simple);
    }
}
 
Example 7
Project: manifold   File: WeakFqnCache.java   Source Code and License 6 votes vote down vote up
@Override
public boolean visitBreadthFirst( final Predicate<T> visitor )
{
  Predicate<WeakReference<T>> delegate = new Predicate<WeakReference<T>>()
  {
    @Override
    public boolean test( WeakReference<T> node )
    {
      T userData = node == null ? null : node.get();
      return visitor.test( userData );
    }
  };
  List<FqnCacheNode<WeakReference<T>>> copy = new ArrayList<FqnCacheNode<WeakReference<T>>>( _cache.getChildren() );
  for( FqnCacheNode<WeakReference<T>> child : copy )
  {
    child.visitBreadthFirst( delegate );
  }
  return true;
}
 
Example 8
Project: shuffleboard   File: DashboardTab.java   Source Code and License 6 votes vote down vote up
@Override
public boolean hasComponentFor(String sourceId) {
  List<Component> topLevelComponents = getWidgetPane().getTiles().stream()
      .map(Tile::getContent)
      .collect(Collectors.toList());
  Predicate<Sourced> isSameSource = s -> s.getSources().stream()
      .map(DataSource::getId)
      .anyMatch(sourceId::equals);
  Predicate<Sourced> isSubSource = s -> s.getSources().stream()
      .map(i -> i.getId() + "/")
      .anyMatch(sourceId::startsWith);
  Predicate<Sourced> isNotContainer = s -> !(s instanceof ComponentContainer);
  Predicate<Sourced> hasComponent = isSameSource.or(isSubSource.and(isNotContainer));
  return topLevelComponents.stream()
      .flatMap(TypeUtils.castStream(Sourced.class))
      .anyMatch(hasComponent)
      || topLevelComponents.stream()
      .flatMap(TypeUtils.castStream(ComponentContainer.class))
      .flatMap(ComponentContainer::allComponents)
      .flatMap(TypeUtils.castStream(Sourced.class))
      .anyMatch(hasComponent);
}
 
Example 9
Project: trivor-nlp   File: VocabularyGenerator.java   Source Code and License 6 votes vote down vote up
Set<WordUsage> getSentences(List<Sentence> sentences, Function<Token, String> customMapper,
                             Predicate<String> customFilter) {
    final Map<String, Set<String>> words = new HashMap<>();
    for (Sentence sentence: sentences) {
        Stream<String> wordsStream = sentence.getTokens().stream()
                .filter(t -> t.getToken().matches(WORD_REGEX))
                .filter(t -> getTags().contains(t.getTag()))
                .filter(t -> !isUpperCase(t.getToken().charAt(0)))
                .filter(t -> t.getProb() >= config.getVocabularyProb())
                .map(customMapper);

        if (customFilter != null) {
            wordsStream = wordsStream.filter(customFilter);
        }

        wordsStream.forEach(word -> {
            final Set<String> wordSentences = words.getOrDefault(word, new HashSet<>());
            wordSentences.add(sentence.getSentence());
            words.put(word, wordSentences);
        });
    }

    return words.entrySet().stream()
            .sorted(reverseOrder(comparingInt(e -> e.getValue().size())))
            .map(e -> new WordUsage(e.getKey(), e.getValue())).collect(toSet());
}
 
Example 10
Project: openjdk-jdk10   File: ReferencePipeline.java   Source Code and License 6 votes vote down vote up
@Override
public final Stream<P_OUT> filter(Predicate<? super P_OUT> predicate) {
    Objects.requireNonNull(predicate);
    return new StatelessOp<P_OUT, P_OUT>(this, StreamShape.REFERENCE,
                                 StreamOpFlag.NOT_SIZED) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<P_OUT> sink) {
            return new Sink.ChainedReference<P_OUT, P_OUT>(sink) {
                @Override
                public void begin(long size) {
                    downstream.begin(-1);
                }

                @Override
                public void accept(P_OUT u) {
                    if (predicate.test(u))
                        downstream.accept(u);
                }
            };
        }
    };
}
 
Example 11
Project: redirector   File: StaticEngineBuiltFromWSModelTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    urlRules = buildURLRules(buildDefaultStatement(PORT, PROTOCOL, URN, "4"));
    stubNamespacedListsHolder = new StubNamespacedListsHolder();
    Config config = new Config();

    ServiceProviderManagerFactory serviceProviderManagerFactory = new ServiceProviderManagerFactory();
    serviceProviderManagerFactory.setConfig(config);
    serviceProviderManagerFactory.setProviderStrategy(new RoundRobinStrategy<>());

    factory = new RedirectorEngineFactory(serviceProviderManagerFactory);

    ReflectionTestUtils.setField(factory, "config", config);
    ReflectionTestUtils.setField(factory, "isStaticDiscoveryNeededForApp", Predicate.isEqual(APP_NAME));
    ReflectionTestUtils.setField(factory, "serializer", serializer);
}
 
Example 12
Project: openapi-parser   File: BigParseTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test() throws JsonProcessingException, IOException {
	Object parsedYaml = new Yaml().load(modelUrl.openStream());
	JsonNode tree = new YAMLMapper().convertValue(parsedYaml, JsonNode.class);
	final OpenApi3 model = (OpenApi3) new OpenApiParser().parse(modelUrl, false);
	Predicate<JsonNode> valueNodePredicate = n -> n.isValueNode();

	JsonTreeWalker.WalkMethod valueChecker = new JsonTreeWalker.WalkMethod() {
		@Override
		public void run(JsonNode node, JsonPointer path) {
			IJsonOverlay<?> overlay = ((OpenApi3Impl) model).find(path);
			assertNotNull("No overlay object found for path: " + path, overlay);
			Object fromJson = getValue(node);
			String msg = String.format("Wrong overlay value for path '%s': expected '%s', got '%s'", path, fromJson,
					overlay.get());
			assertEquals(msg, fromJson, overlay.get());
		}
	};
	JsonTreeWalker.walkTree(tree, valueNodePredicate, valueChecker);
}
 
Example 13
Project: SoftUni   File: p05_FilterByAge.java   Source Code and License 5 votes vote down vote up
private static Predicate<Integer> createTester(String condition, Integer age) {
    // simple check the according given age
    switch(condition){
        case "younger": return x -> x < age;
        case "older": return x -> x >= age;
    }
    return null;
}
 
Example 14
Project: openjdk-jdk10   File: ElementStructureTest.java   Source Code and License 5 votes vote down vote up
Predicate<String> constructAcceptIgnoreList(String fromFiles) throws IOException {
    StringBuilder acceptPattern = new StringBuilder();
    StringBuilder rejectPattern = new StringBuilder();
    for (String file : fromFiles.split(File.pathSeparator)) {
        try (Stream<String> lines = Files.lines(Paths.get(file))) {
            lines.forEach(line -> {
                if (line.isEmpty())
                    return;
                StringBuilder targetPattern;
                switch (line.charAt(0)) {
                    case '+':
                        targetPattern = acceptPattern;
                        break;
                    case '-':
                        targetPattern = rejectPattern;
                        break;
                    default:
                        return ;
                }
                line = line.substring(1);
                if (line.endsWith("/")) {
                    line += "[^/]*";
                } else {
                    line += "|" + line + "$[^/]*";
                }
                line = line.replace("/", ".");
                if (targetPattern.length() != 0)
                    targetPattern.append("|");
                targetPattern.append(line);
            });
        }
    }
    Pattern accept = Pattern.compile(acceptPattern.toString());
    Pattern reject = Pattern.compile(rejectPattern.toString());

    return clazzName -> accept.matcher(clazzName).matches() && !reject.matcher(clazzName).matches();
}
 
Example 15
Project: SoftUni   File: RepositoryFilters.java   Source Code and License 5 votes vote down vote up
private Predicate<Double> createFilter(String filterType) {
    switch (filterType) {
        case "excellent":
            return mark -> mark >= 5.0;
        case "average":
            return mark -> 3.5 <= mark && mark < 5.0;
        case "poor":
            return mark -> mark < 3.5;
        default:
            return null;
    }
}
 
Example 16
Project: javanalysis   File: CtClassScanner.java   Source Code and License 5 votes vote down vote up
public static void scanDirectory(File directory, Predicate<CtClass> predicate, Consumer<CtMethod> consumer) {
    for (String entry : directory.list()) {
        String path = directory.getPath() + File.separator + entry;
        File file = new File(path);
        if (file.isDirectory()) {
            scanDirectory(file, predicate, consumer);
        } else if (file.isFile() && path.endsWith(".class")) {
            scanClassFile(path, predicate, consumer);
        }
    }
}
 
Example 17
Project: quickmon   File: HealthChecksQuery.java   Source Code and License 5 votes vote down vote up
public Predicate<HealthCheck> asPredicate() {
    Predicate<HealthCheck> predicate = h -> true;
    if (tags != null && !tags.isEmpty()) {
        predicate = predicate.and(h -> h.getTags().containsAll(tags));
    }
    if (status != null) {
        predicate = predicate.and(h -> h.getLastStatus().getHealth() == status);
    }
    if (luceneQuery != null) {
        HealthChecksQueryNodeInterpreter interpreter = new HealthChecksQueryNodeInterpreter();
        Predicate<HealthCheck> luceneQueryPredicate = interpreter.toPredicate(getLuceneQuery());
        predicate = predicate.and(luceneQueryPredicate);
    }
    return predicate;
}
 
Example 18
Project: bird-java   File: ListHelper.java   Source Code and License 5 votes vote down vote up
public T firstOrDefault(Predicate<? super T> filter) {
    int size = this.items.size();
    if (size == 0) return null;

    List list = this.items;
    if (filter == null) return (T) list.get(0);

    for (int i = 0; i <= size - 1; i++) {
        T item = (T) list.get(i);
        if (filter.test(item)) {
            return item;
        }
    }
    return null;
}
 
Example 19
Project: openjdk-jdk10   File: PoolHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Gets all methods from the pool using specified filter
 *
 * @param filter method filter
 * @return pairs of Executable and appropriate Callable
 */
public List<Pair<Executable, Callable<?>>> getAllMethods(
        Predicate<Executable> filter) {
    return getAllMethods().stream()
            .filter(pair -> filter.test(pair.first))
            .collect(Collectors.toList());
}
 
Example 20
Project: esup-ecandidat   File: UserController.java   Source Code and License 5 votes vote down vote up
/**
 * Verifie si le user est gestionnaire de candidat
 * 
 * @return true si le user est gestionnaire
 */
public Boolean isGestionnaireCandidatLS(Authentication auth) {
	if (auth == null) {
		return false;
	}
	return auth.getAuthorities().stream().map(GrantedAuthority::getAuthority)
			.filter(Predicate.isEqual(ConstanteUtils.ROLE_GESTION_CANDIDAT_LS)).findAny().isPresent();
}
 
Example 21
Project: morpheus-core   File: XDataFrame.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor
 * @param from      the from ordinal
 * @param to        the to col ordinal
 * @param predicate the predicate to match columns
 */
SelectColumns(int from, int to, Predicate<DataFrameColumn<R,C>> predicate) {
    this.from = from;
    this.to = to;
    this.predicate = predicate;
    this.threshold = Integer.MAX_VALUE;
    if (isParallel()) {
        this.threshold = DataFrameOptions.getColumnSplitThreshold(XDataFrame.this);
    }
}
 
Example 22
Project: Biliomi   File: FilterDirectiveQueryProcessor.java   Source Code and License 5 votes vote down vote up
/**
 * Use the "filter" query parameter to filter a list of entities.
 * - Chains filter directives in order of appearance
 * - Supports filtering on sub-properties by providing the path as "Property.SubProperty".
 * - Supports basic and/or per directive against previous directives
 *
 * @param entities    The list of entities to filter
 * @param queryParams A map with the value of the "filter" query parameter
 * @return The filtered list of entities
 * @throws IOException When Jackson is unnable to unmarshal the sorting directives
 */
@Override
public List<T> process(List<T> entities, Map<String, Object> queryParams) throws Exception {
  if (entities.size() != 0 && queryParams.containsKey(PARAM_NAME_FILTER)) {
    try {
      String filter = (String) queryParams.get(PARAM_NAME_FILTER);
      Collection<RestFilterDirective> filterDirectives = null;
      // noinspection unchecked This error is inevitable depending on user input
      Class<T> rootClass = (Class<T>) entities.get(0).getClass();

      if (StringUtils.isNotEmpty(filter)) {
        if (filter.startsWith("[") && filter.endsWith("]")) {
          // This looks like a JSON-array, use Jackson to parse it
          filterDirectives = JacksonMarshaller.unmarshalCollection(filter, RestFilterDirective.class);
        } else {
          // Maybe it's a query, parse it to find out
          filterDirectives = RestFilterQueryParser.parseQuery(filter);
        }
      }

      Predicate<T> predicateChain = buildPredicateChain(filterDirectives, rootClass);
      if (predicateChain != null) {
        entities = entities.stream()
            .filter(predicateChain)
            .collect(Collectors.toList());
      }

    } catch (Exception e) {
      LogManager.getLogger(this.getClass()).error(e);
      throw e;
    }
  }

  return entities;
}
 
Example 23
Project: FreeCol   File: DebugUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Debug action to set the amount of goods in a colony.
 *
 * Called from the colony panel.
 *
 * @param freeColClient The {@code FreeColClient} for the game.
 * @param colony The {@code Colony} to set goods amounts in.
 */
public static void setColonyGoods(final FreeColClient freeColClient,
                                  final Colony colony) {
    final Specification spec = colony.getSpecification();
    final Predicate<GoodsType> goodsPred = gt ->
        !gt.isFoodType() || gt == spec.getPrimaryFoodType();
    final Function<GoodsType, ChoiceItem<GoodsType>> mapper = gt ->
        new ChoiceItem<GoodsType>(Messages.getName(gt), gt);

    GoodsType goodsType = freeColClient.getGUI().getChoice(null,
        StringTemplate.template("prompt.selectGoodsType"), "cancel",
        transform(spec.getGoodsTypeList(), goodsPred, mapper,
                  Comparator.naturalOrder()));
    if (goodsType == null) return;

    String response = freeColClient.getGUI().getInput(null,
            StringTemplate.template("prompt.selectGoodsAmount"),
            Integer.toString(colony.getGoodsCount(goodsType)),
            "ok", "cancel");
    if (response == null || response.isEmpty()) return;
    int a;
    try {
        a = Integer.parseInt(response);
    } catch (NumberFormatException nfe) {
        return;
    }

    final FreeColServer server = freeColClient.getFreeColServer();
    final Game sGame = server.getGame();
    final Specification sSpec = server.getSpecification();
    final GoodsType sGoodsType = sSpec.getGoodsType(goodsType.getId());
    GoodsContainer cgc = colony.getGoodsContainer();
    GoodsContainer sgc = sGame.getFreeColGameObject(cgc.getId(),
                                                    GoodsContainer.class);
    cgc.setAmount(goodsType, a);
    sgc.setAmount(sGoodsType, a);
}
 
Example 24
Project: redg   File: ReflectionUtil.java   Source Code and License 5 votes vote down vote up
public static List<Field> findFields(Class<?> clazz, Predicate<Field> predicate) {
	List<Field> matchingFields = new ArrayList<>();
	Class<?> c = clazz;
	while (c != null) {
		for (Field field : c.getDeclaredFields()) {
			if (predicate.test(field)) {
				matchingFields.add(field);
			}
		}
		c = c.getSuperclass();
	}
	return matchingFields;
}
 
Example 25
Project: FreeCol   File: InGameController.java   Source Code and License 5 votes vote down vote up
/**
 * Create the Royal Expeditionary Force player corresponding to
 * a given player that is about to rebel.
 *
 * Public for the test suite.
 *
 * FIXME: this should eventually generate changes for the REF player.
 *
 * @param serverPlayer The {@code ServerPlayer} about to rebel.
 * @return The REF player.
 */
public ServerPlayer createREFPlayer(ServerPlayer serverPlayer) {
    final Nation refNation = serverPlayer.getNation().getREFNation();
    final Monarch monarch = serverPlayer.getMonarch();
    final ServerPlayer refPlayer = getFreeColServer().makeAIPlayer(refNation);
    final Europe europe = refPlayer.getEurope();
    final Predicate<Tile> exploredPred = t ->
        ((!t.isLand() || t.isCoastland() || t.getOwner() == serverPlayer)
            && t.isExploredBy(serverPlayer));
    // Inherit rebel player knowledge of the seas, coasts, claimed
    // land but not full detailed scouting knowledge.
    Set<Tile> explore = new HashSet<>();
    getGame().getMap().forEachTile(exploredPred, t -> explore.add(t));
    refPlayer.exploreTiles(explore);

    // Trigger initial placement routine
    refPlayer.setEntryTile(null);
    // Will change, setup only
    Player.makeContact(serverPlayer, refPlayer);

    // Instantiate the REF in Europe
    Force exf = monarch.getExpeditionaryForce();
    if (!exf.prepareToBoard()) {
        logger.warning("Unable to ensure space for the REF land units.");
        // For now, do not fail completely
    }
    List<Unit> landUnits = refPlayer.createUnits(exf.getLandUnitsList(),
                                                 europe);//-vis: safe!map
    List<Unit> navalUnits = refPlayer.createUnits(exf.getNavalUnitsList(),
                                                  europe);//-vis: safe!map
    List<Unit> leftOver = refPlayer.loadShips(landUnits, navalUnits,
                                              random);//-vis: safe!map
    if (!leftOver.isEmpty()) {
        // Should not happen, make this return null one day
        logger.warning("Failed to board REF units: "
            + join(" ", transform(leftOver, alwaysTrue(),
                                  FreeColObject::getId)));
    }
    return refPlayer;
}
 
Example 26
Project: jdk8u-jdk   File: RegExTest.java   Source Code and License 5 votes vote down vote up
private static void patternAsPredicate() throws Exception {
    Predicate<String> p = Pattern.compile("[a-z]+").asPredicate();

    if (p.test("")) {
        failCount++;
    }
    if (!p.test("word")) {
        failCount++;
    }
    if (p.test("1234")) {
        failCount++;
    }
    report("Pattern.asPredicate");
}
 
Example 27
Project: openjdk-jdk10   File: JMXStatusTest.java   Source Code and License 5 votes vote down vote up
@BeforeMethod
public final void startTestApp() throws Exception {
    testApp = ProcessTools.startProcess(
        TEST_APP_NAME, testAppPb,
        (Predicate<String>)l->l.trim().equals("main enter")
    );
}
 
Example 28
Project: boomer-tuner   File: AlbumsController.java   Source Code and License 5 votes vote down vote up
Predicate<Album> searchFilter(final String searchText) {
	return album -> {
		String search = searchText.toLowerCase();
		String name = album.getName().toLowerCase();
		String artist = album.getArtist().getName().toLowerCase();
		String year = String.valueOf(album.getYear());
		return name.contains(search) || artist.contains(search) || year.contains(search);
	};
}
 
Example 29
Project: Spring-5.0-Cookbook   File: EmployeeScheduledStreamServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Flux<Employee> createPubAndMain() {
	Scheduler pubWorker = Schedulers.newSingle("pub-thread");
	Predicate<Employee> validAge = (e) -> {
		System.out.println("filter thread " +Thread.currentThread().getName());
		return e.getAge() > 25;
	};
	Supplier<Flux<Employee>> deferredTask = ()->{
		System.out.println("defer thread "+Thread.currentThread().getName());
		return Flux.fromIterable(employeeDaoImpl.getEmployees());
	};
	Flux<Employee> deferred = Flux.defer(deferredTask).publishOn(pubWorker).filter(validAge);
	return deferred;
}
 
Example 30
Project: dtmlibs   File: SerializerSet.java   Source Code and License 5 votes vote down vote up
/**
 * Unregisters all {@link Predicate}s that will cause a replacement with the given replacementClass.
 * <br>
 * This may be useful if the order of checks needs to be altered or one of the default predicates needs to be
 * replaced.
 *
 * @param replacementClass The replacement class to unregister all predicates for.
 * @return this builder object.
 */
public Builder unregisterClassReplacement(@NotNull Class replacementClass) {
    Iterator<Entry<Predicate<Class<?>>, Class>> replacementsIterator = classReplacements.entrySet().iterator();
    while (replacementsIterator.hasNext()) {
        if (replacementsIterator.next().getValue().equals(replacementClass)) {
            replacementsIterator.remove();
        }
    }
    return this;
}
 
Example 31
Project: cascade   File: AllOfMatcher.java   Source Code and License 5 votes vote down vote up
public Matcher find(Predicate<Matcher> predicate) {
    for (Matcher matcher: this) {
        if (predicate.test(matcher)) {
            return matcher;
        }
    }
    return null;
}
 
Example 32
Project: morpheus-core   File: DenseArrayOfInts.java   Source Code and License 5 votes vote down vote up
@Override
public final Array<Integer> filter(Predicate<ArrayValue<Integer>> predicate) {
    final ArrayCursor<Integer> cursor = cursor();
    final ArrayBuilder<Integer> builder = ArrayBuilder.of(length(), type());
    for (int i=0; i<values.length; ++i) {
        cursor.moveTo(i);
        final boolean match = predicate.test(cursor);
        if (match) {
            builder.addInt(cursor.getInt());
        }
    }
    return builder.toArray();
}
 
Example 33
Project: limberest   File: RestService.java   Source Code and License 5 votes vote down vote up
@Override
public void initialize(Request<T> request, Principal principal, Predicate<String> roleChecker)
        throws ServiceException {
    if (principal != null)
        request.setUser(principal.getName());
    request.setUserRolePredicate(roleChecker);
}
 
Example 34
Project: NyaaCore   File: Message.java   Source Code and License 5 votes vote down vote up
public Message broadcast(MessageType type, Predicate<Player> playerFilter) {
    for (Player player : Bukkit.getOnlinePlayers()) {
        if (playerFilter.test(player)) {
            this.send(player, type);
        }
    }
    Bukkit.getConsoleSender().sendMessage(inner.toLegacyText());
    Bukkit.getConsoleSender().sendMessage("broadcast with filter:" + playerFilter.toString());
    return this;
}
 
Example 35
Project: creacoinj   File: TextFieldValidator.java   Source Code and License 5 votes vote down vote up
public TextFieldValidator(TextInputControl control, Predicate<String> validator) {
    this.valid.set(validator.test(control.getText()));
    apply(control, valid.get());
    control.textProperty().addListener((observableValue, prev, current) -> {
        boolean nowValid = validator.test(current);
        if (nowValid == valid.get()) return;
        valid.set(nowValid);
    });
    valid.addListener(o -> apply(control, valid.get()));
}
 
Example 36
Project: infxnity   File: MaskBuilder.java   Source Code and License 5 votes vote down vote up
public DefaultMaskCharacter(final Predicate<Character> pAllowed, final UnaryOperator<Character> pTransformation,
        final char pDefaultValue)
{
    allowed = pAllowed;
    defaultValue = pDefaultValue;
    transformation = pTransformation;
}
 
Example 37
Project: swblocks-jbl   File: BuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testBuilderCreatorVerifier() {
    final Supplier mockCreator = mock(Supplier.class);
    final Predicate mockPredicate = mock(Predicate.class);
    final Function mockBuilder = mock(Function.class);
    final ArgumentCaptor intCaptor = ArgumentCaptor.forClass(Integer.class);
    final ArgumentCaptor buildCaptor = ArgumentCaptor.forClass(Integer.class);

    when(mockCreator.get()).thenReturn(1);
    when(mockPredicate.test(intCaptor.capture())).thenReturn(true);
    when(mockBuilder.apply(buildCaptor.capture())).thenReturn(3);

    final Builder testBuilder = Builder.instanceOf(mockCreator, mockPredicate, mockBuilder);
    assertNotNull(testBuilder);

    final ArgumentCaptor consumerCaptor1 = ArgumentCaptor.forClass(Integer.class);
    final ArgumentCaptor consumerCaptor2 = ArgumentCaptor.forClass(Integer.class);

    final BiConsumer mockConsumer = mock(BiConsumer.class);
    doNothing().when(mockConsumer).accept(consumerCaptor1.capture(), consumerCaptor2.capture());

    testBuilder.with(mockConsumer, 2);

    final Object result = testBuilder.build();
    assertNotNull(result);
    assertEquals(Integer.valueOf(3), result);
    assertEquals(1, intCaptor.getValue());
    verify(mockBuilder, times(1)).apply(1);
    assertEquals(1, consumerCaptor1.getValue());
    assertEquals(2, consumerCaptor2.getValue());
}
 
Example 38
Project: redirector   File: AnnotationScanner.java   Source Code and License 5 votes vote down vote up
private static Predicate<ClassPath.ClassInfo> isClassAnnotatedByScannedAnnotations(Set<String> annotationNames) {
    return classInfo -> {
        Set<String> annotationsForClass = getAnnotationNames(classInfo.url());
        annotationsForClass.retainAll(annotationNames);
        return ! annotationsForClass.isEmpty();
    };
}
 
Example 39
Project: SoftUni   File: p05_FilterByAge.java   Source Code and License 5 votes vote down vote up
private static void printFilteredStudents(LinkedHashMap<String, Integer> people, Predicate<Integer> tester, Consumer<Map.Entry<String, Integer>> printer) {
    // iterate all entries in the map 'people'
    for (Map.Entry<String, Integer> person :
            people.entrySet()) {
        // if they meet the criteria 'tester'
        if (tester.test(people.get(person.getKey()))) {
            // send this pair to 'printer'
            printer.accept(person);
        }
    }
}
 
Example 40
Project: monarch   File: MPredicateHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Get the correct predicate for boolean object.
 *
 * @param op the specified predicate operation
 * @param initialValue the initial value, to be checked against, for the predicate
 * @return the predicate with correct operation and specified initial value
 */
public static Predicate getPredicateForBoolean(final TypePredicateOp op,
    final Object initialValue) {
  Predicate predicate = null;
  switch ((CompareOp) op) {
    case EQUAL:
      predicate = isEqual(initialValue);
      break;
    case NOT_EQUAL:
      predicate = isNotEqual(initialValue);
      break;
  }
  return predicate;
}