Java Code Examples for java.util.function.Predicate#or()

The following examples show how to use java.util.function.Predicate#or() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AlexaPlatformService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public ListenableFuture<PlatformMessage> request(PlatformMessage msg, Predicate<PlatformMessage> matcher, int timeoutSecs) {
   if(timeoutSecs < 0) {
      timeoutSecs = defaultTimeoutSecs;
   }

   final Address addr = msg.getDestination();
   final SettableFuture<PlatformMessage> future = SettableFuture.create();
   future.addListener(() -> { futures.remove(addr); }, workerPool);

   Predicate<PlatformMessage> pred = (pm) -> { return Objects.equals(msg.getCorrelationId(), pm.getCorrelationId()) && msg.isError(); };
   pred = matcher.or(pred);

   Pair<Predicate<PlatformMessage>, SettableFuture<PlatformMessage>> pair = new ImmutablePair<>(matcher, future);
   futures.put(addr, pair);
   bus.send(msg);
   timeoutPool.newTimeout((timer) -> {
      if(!future.isDone()) {
         future.setException(new TimeoutException("future timed out"));
      }
   }, timeoutSecs, TimeUnit.SECONDS);
   return future;
}
 
Example 2
Source File: TestStandardProcessorTestRunner.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllConditionsMetComplex() {
    TestRunner runner = new StandardProcessorTestRunner(new GoodProcessor());

    final Map<String, String> attributes = new HashMap<>();
    attributes.put("GROUP_ATTRIBUTE_KEY", "1");
    attributes.put("KeyB", "hihii");
    runner.enqueue("1,hello\n1,good-bye".getBytes(), attributes);

    attributes.clear();
    attributes.put("age", "34");
    runner.enqueue("May Andersson".getBytes(), attributes);

    runner.run();
    runner.assertAllFlowFilesTransferred(GoodProcessor.REL_SUCCESS, 2);

    Predicate<MockFlowFile> firstPredicate = mff -> mff.isAttributeEqual("GROUP_ATTRIBUTE_KEY", "1");
    Predicate<MockFlowFile> either = firstPredicate.or(mff -> mff.isAttributeEqual("age", "34"));

    runner.assertAllConditionsMet("success", either);
}
 
Example 3
Source File: TestStandardProcessorTestRunner.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllConditionsMetComplex() {
    TestRunner runner = new StandardProcessorTestRunner(new GoodProcessor());

    final Map<String, String> attributes = new HashMap<>();
    attributes.put("GROUP_ATTRIBUTE_KEY", "1");
    attributes.put("KeyB", "hihii");
    runner.enqueue("1,hello\n1,good-bye".getBytes(), attributes);

    attributes.clear();
    attributes.put("age", "34");
    runner.enqueue("May Andersson".getBytes(), attributes);

    runner.run();
    runner.assertAllFlowFilesTransferred(GoodProcessor.REL_SUCCESS, 2);

    Predicate<MockFlowFile> firstPredicate = mff -> mff.isAttributeEqual("GROUP_ATTRIBUTE_KEY", "1");
    Predicate<MockFlowFile> either = firstPredicate.or(mff -> mff.isAttributeEqual("age", "34"));

    runner.assertAllConditionsMet("success", either);
}
 
Example 4
Source File: AutoConfiguredSslIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void deleteKeyStoreFilesInCurrentWorkingDirectory() {

	Predicate<File> keystorePredicate = file -> file.getAbsolutePath().endsWith(".jks");

	keystorePredicate.or(file -> file.getAbsolutePath().endsWith(".keystore"));
	keystorePredicate.or(file -> file.getAbsolutePath().endsWith(".truststore"));

	File currentWorkingDirectory = new File(System.getProperty("user.dir"));

	if (currentWorkingDirectory.isDirectory()) {

		Arrays.stream(nullSafeArray(currentWorkingDirectory.listFiles(keystorePredicate::test), File.class))
			.filter(Objects::nonNull)
			.filter(File::isFile)
			.forEach(File::delete);
	}
}
 
Example 5
Source File: AppQuestCondition.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * 条件(論理演算)
 *
 * @param ships 艦隊
 * @return 条件に一致する場合true
 */
private boolean testOperator(List<ShipMst> ships) {
    Predicate<List<ShipMst>> predicate = null;
    for (FleetCondition condition : this.conditions) {
        if (predicate == null) {
            predicate = condition;
        } else {
            predicate = this.operator.endsWith("AND")
                    ? predicate.and(condition)
                    : predicate.or(condition);
        }
    }
    if ("NAND".equals(this.operator) || "NOR".equals(this.operator)) {
        predicate = predicate.negate();
    }
    return predicate.test(new ArrayList<>(ships));
}
 
Example 6
Source File: Predicates.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@SafeVarargs
public static <T1> Predicate<? super T1> anyOf(final Predicate<? super T1>... preds) {
    Predicate<T1> current =  (Predicate<T1>)preds[0];
    for(int i=1;i<preds.length;i++){
        current = current.or((Predicate<T1>)preds[i]);
    }
    return current;
}
 
Example 7
Source File: ProMatches.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
public static Predicate<Territory> territoryIsOrAdjacentToEnemyNotNeutralLand(
    final GamePlayer player, final GameData data) {
  final Predicate<Territory> isMatch =
      territoryIsEnemyLand(player, data)
          .and(Matches.territoryIsNeutralButNotWater().negate())
          .and(t -> !ProUtils.isPassiveNeutralPlayer(t.getOwner()));
  final Predicate<Territory> adjacentMatch =
      territoryCanMoveLandUnits(player, data, false)
          .and(Matches.territoryHasNeighborMatching(data, isMatch));
  return isMatch.or(adjacentMatch);
}
 
Example 8
Source File: ProMatches.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
public static Predicate<Territory> territoryCanMoveLandUnitsThrough(
    final GamePlayer player,
    final GameData data,
    final Unit u,
    final Territory startTerritory,
    final boolean isCombatMove,
    final List<Territory> enemyTerritories) {
  return t -> {
    if (isCombatMove
        && Matches.unitCanBlitz().test(u)
        && TerritoryEffectHelper.unitKeepsBlitz(u, startTerritory)) {
      final Predicate<Territory> alliedWithNoEnemiesMatch =
          Matches.isTerritoryAllied(player, data)
              .and(Matches.territoryHasNoEnemyUnits(player, data));
      final Predicate<Territory> alliedOrBlitzableMatch =
          alliedWithNoEnemiesMatch.or(territoryIsBlitzable(player, data, u));
      return ProMatches.territoryCanMoveSpecificLandUnit(player, data, isCombatMove, u)
          .and(alliedOrBlitzableMatch)
          .and(Matches.territoryIsInList(enemyTerritories).negate())
          .test(t);
    }
    return ProMatches.territoryCanMoveSpecificLandUnit(player, data, isCombatMove, u)
        .and(Matches.isTerritoryAllied(player, data))
        .and(Matches.territoryHasNoEnemyUnits(player, data))
        .and(Matches.territoryIsInList(enemyTerritories).negate())
        .test(t);
  };
}
 
Example 9
Source File: ProTechAi.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Finds list of territories at exactly distance from the start.
 *
 * @param endCondition condition that all end points must satisfy
 * @param routeCondition condition that all traversed internal territories must satisfied
 */
private static List<Territory> findFrontier(
    final Territory start,
    final Predicate<Territory> endCondition,
    final Predicate<Territory> routeCondition,
    final GameData data) {
  final Predicate<Territory> canGo = endCondition.or(routeCondition);
  final IntegerMap<Territory> visited = new IntegerMap<>();
  final List<Territory> frontier = new ArrayList<>();
  final Queue<Territory> q = new ArrayDeque<>(data.getMap().getNeighbors(start, canGo));
  Territory current;
  visited.put(start, 0);
  for (final Territory t : q) {
    visited.put(t, 1);
    if (endCondition.test(t)) {
      frontier.add(t);
    }
  }
  while (!q.isEmpty()) {
    current = q.remove();
    if (visited.getInt(current) == 1) {
      break;
    }

    for (final Territory neighbor : data.getMap().getNeighbors(current, canGo)) {
      if (!visited.keySet().contains(neighbor)) {
        q.add(neighbor);
        final int dist = visited.getInt(current) + 1;
        visited.put(neighbor, dist);
        if (dist == 1 && endCondition.test(neighbor)) {
          frontier.add(neighbor);
        }
      }
    }
  }
  return frontier;
}
 
Example 10
Source File: ShardingUpsertExecutor.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<? extends Iterable<Row>> apply(BatchIterator<Row> batchIterator) {
    var reqBatchIterator = BatchIterators.partition(
        batchIterator,
        bulkSize,
        () -> new ShardedRequests<>(requestFactory),
        grouper,
        bulkShardCreationLimiter.or(isUsedBytesOverThreshold)
    );

    // If IO is involved the source iterator should pause when the target node reaches a concurrent job counter limit.
    // Without IO, we assume that the source iterates over in-memory structures which should be processed as
    // fast as possible to free resources.
    Predicate<ShardedRequests<ShardUpsertRequest, ShardUpsertRequest.Item>> shouldPause =
        this::shouldPauseOnPartitionCreation;
    if (batchIterator.hasLazyResultSet()) {
        shouldPause = shouldPause.or(this::shouldPauseOnTargetNodeJobsCounter);
    }

    BatchIteratorBackpressureExecutor<ShardedRequests<ShardUpsertRequest, ShardUpsertRequest.Item>, UpsertResults> executor =
        new BatchIteratorBackpressureExecutor<>(
            scheduler,
            this.executor,
            reqBatchIterator,
            this::execute,
            resultCollector.combiner(),
            resultCollector.supplier().get(),
            shouldPause,
            BACKOFF_POLICY
        );
    return executor.consumeIteratorAndExecute()
        .thenApply(upsertResults -> resultCollector.finisher().apply(upsertResults));
}
 
Example 11
Source File: OrPredicate.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test( Composite item )
{
    Predicate<Composite> master = t -> false;
    for( Predicate<Composite> p : operands )
    {
        master = master.or( p );
    }
    return master.test( item );
}
 
Example 12
Source File: MoveValidator.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks that there only transports, subs and/or allies on the route except at the end. AA and
 * factory dont count as enemy.
 */
public boolean onlyIgnoredUnitsOnPath(
    final Route route, final GamePlayer player, final boolean ignoreRouteEnd) {
  final Predicate<Unit> transportOnly =
      Matches.unitIsInfrastructure()
          .or(Matches.unitIsTransportButNotCombatTransport())
          .or(Matches.unitIsLand())
          .or(Matches.enemyUnit(player, data).negate());
  final Predicate<Unit> subOnly =
      Matches.unitIsInfrastructure()
          .or(Matches.unitCanBeMovedThroughByEnemies())
          .or(Matches.enemyUnit(player, data).negate());
  final Predicate<Unit> transportOrSubOnly = transportOnly.or(subOnly);
  final boolean getIgnoreTransportInMovement = Properties.getIgnoreTransportInMovement(data);
  final List<Territory> steps;
  if (ignoreRouteEnd) {
    steps = route.getMiddleSteps();
  } else {
    steps = route.getSteps();
  }
  // if there are no steps, then we began in this sea zone, so see if there are ignored units in
  // this sea zone (not sure if we need !ignoreRouteEnd here).
  if (steps.isEmpty() && !ignoreRouteEnd) {
    steps.add(route.getStart());
  }
  boolean validMove = false;
  for (final Territory current : steps) {
    if (current.isWater()) {
      if ((getIgnoreTransportInMovement
              && current.getUnitCollection().allMatch(transportOrSubOnly))
          || current.getUnitCollection().allMatch(subOnly)) {
        validMove = true;
        continue;
      }
      return false;
    }
  }
  return validMove;
}
 
Example 13
Source File: PredicateTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testOr_null() throws Exception {
  Predicate<Object> alwaysTrue = x -> true;
  try {
    alwaysTrue.or(null);
    fail();
  } catch (NullPointerException expected) {}
}
 
Example 14
Source File: Validator.java    From bullet-core with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link Predicate} that is true if any of the provided predicates are true and false otherwise.
 *
 * @param predicates The predicates to be ORed.
 * @return A predicate that is the OR of all the given predicates.
 */
@SafeVarargs
public static Predicate<Object> or(Predicate<Object>... predicates) {
    Predicate<Object> ored = not(UNARY_IDENTITY);
    for (Predicate<Object> predicate : predicates) {
        ored = ored.or(predicate);
    }
    return ored;
}
 
Example 15
Source File: Predicates.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@SafeVarargs
public static <T> Predicate<T> or(Predicate<T>... predicates) {
    Predicate<T> predicate = predicates[0];

    for (int i = 1; i < predicates.length; i++) {
        predicate = predicate.or(predicates[i]);
    }

    return predicate;
}
 
Example 16
Source File: CentralDogmaConfig.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static Predicate<InetAddress> toTrustedProxyAddressPredicate(List<String> trustedProxyAddresses) {
    final String first = trustedProxyAddresses.get(0);
    Predicate<InetAddress> predicate = first.indexOf('/') < 0 ? ofExact(first) : ofCidr(first);
    for (int i = 1; i < trustedProxyAddresses.size(); i++) {
        final String next = trustedProxyAddresses.get(i);
        predicate = predicate.or(next.indexOf('/') < 0 ? ofExact(next) : ofCidr(next));
    }
    return predicate;
}
 
Example 17
Source File: ProMatches.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
public static Predicate<Unit> unitCantBeMovedAndIsAlliedDefender(
    final GamePlayer player, final GameData data, final Territory t) {
  final Predicate<Unit> myUnitHasNoMovementMatch =
      Matches.unitIsOwnedBy(player).and(Matches.unitHasMovementLeft().negate());
  final Predicate<Unit> alliedUnitMatch =
      Matches.unitIsOwnedBy(player)
          .negate()
          .and(Matches.isUnitAllied(player, data))
          .and(
              Matches.unitIsBeingTransportedByOrIsDependentOfSomeUnitInThisList(
                      t.getUnits(), player, data, false)
                  .negate());
  return myUnitHasNoMovementMatch.or(alliedUnitMatch);
}
 
Example 18
Source File: StandardFunctionalInterfaces.java    From Learn-Java-12-Programming with MIT License 5 votes vote down vote up
private static void predicate(){
    Predicate<Integer> isLessThan10 = i -> i < 10;

    System.out.println(isLessThan10.test(7));  //prints: true
    System.out.println(isLessThan10.test(12)); //prints: false

    int val = 7;
    Consumer<String> printIsSmallerThan10 =
            printWithPrefixAndPostfix("Is " + val + " smaller than 10? ", " Great!");
    printIsSmallerThan10.accept(String.valueOf(isLessThan10.test(val)));         //prints: Is 7 smaller than 10? true Great!

    Predicate<Integer> isEqualOrGreaterThan10 = isLessThan10.negate();
    System.out.println(isEqualOrGreaterThan10.test(7));   //prints: false
    System.out.println(isEqualOrGreaterThan10.test(12));  //prints: true

    isEqualOrGreaterThan10 = Predicate.not(isLessThan10);
    System.out.println(isEqualOrGreaterThan10.test(7));   //prints: false
    System.out.println(isEqualOrGreaterThan10.test(12));  //prints: true

    Predicate<Integer> isGreaterThan10 = i -> i > 10;
    Predicate<Integer> is_lessThan10_OR_greaterThan10 = isLessThan10.or(isGreaterThan10);
    System.out.println(is_lessThan10_OR_greaterThan10.test(20));   //prints: true
    System.out.println(is_lessThan10_OR_greaterThan10.test(10));   //prints: false

    Predicate<Integer> isGreaterThan5 = i -> i > 5;
    Predicate<Integer> is_lessThan10_AND_greaterThan5 = isLessThan10.and(isGreaterThan5);
    System.out.println(is_lessThan10_AND_greaterThan5.test(3));  //prints: false
    System.out.println(is_lessThan10_AND_greaterThan5.test(7));  //prints: true

    Person nick = new Person(42, "Nick", "Samoylov");
    Predicate<Person> isItNick = Predicate.isEqual(nick);
    Person john = new Person(42, "John", "Smith");
    Person person = new Person(42, "Nick", "Samoylov");
    System.out.println(isItNick.test(john));      //prints: false
    System.out.println(isItNick.test(person));    //prints: true
}
 
Example 19
Source File: MorePredicates.java    From presto with Apache License 2.0 5 votes vote down vote up
public static <T> Predicate<T> isInstanceOfAny(Class<?>... classes)
{
    Predicate<T> predicate = alwaysFalse();
    for (Class<?> clazz : classes) {
        predicate = predicate.or(clazz::isInstance);
    }
    return predicate;
}
 
Example 20
Source File: PessoaApp.java    From acelera-dev-brasil-2019-01 with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {


        Pessoa ada = Pessoa.builder()
                .withNome("Ada")
                .withCidade("Salvador")
                .withPais("Pais")
                .withRg("rg")
                .withCpf("cpf")
                .withEmail("meu-email")
                .build();

        List<Pessoa> pessoas = new ArrayList<>();
        pessoas.add(ada);
        pessoas.add(ada);
        pessoas.add(ada);
        pessoas.add(ada);


        Predicate<Pessoa> fromSalvador = p -> "Salvador".equals(p.getCidade());
        Predicate<Pessoa> nomeComecaComA = p -> p.getNome().startsWith("A");
        Predicate<Pessoa> naoDeSalvador = fromSalvador.negate();

        Predicate<Pessoa> deSalvadorEnomeComecaComA = fromSalvador.and(nomeComecaComA);
        Predicate<Pessoa> deSalvadorOunomeComecaComA = fromSalvador.or(nomeComecaComA);


        List<Pessoa> salvador = pessoas.stream()
                .filter(fromSalvador)
                .collect(Collectors.toList());

        Set<Pessoa> nomesA = pessoas.stream()
                .filter(nomeComecaComA)
                .collect(Collectors.toSet());

        Queue<Pessoa> fila = pessoas.stream()
                .filter(deSalvadorEnomeComecaComA)
                .collect(Collectors.toCollection(LinkedList::new));

        String nomes = pessoas.stream()
                .map(p -> p.getNome())
                .collect(Collectors.joining(","));

        Optional<Integer> reduce = pessoas.stream()
                .map(Pessoa::getIdade)
                .reduce(Integer::sum);

        IntSummaryStatistics statistics = pessoas.stream()
                .mapToInt(Pessoa::getIdade)
                .summaryStatistics();

        System.out.println(" " + statistics.getAverage());
        System.out.println(" " + statistics.getCount());
        System.out.println(" " + statistics.getMax());
        System.out.println(" " + statistics.getMin());
        System.out.println(" " + statistics.getSum());


        Map<String, List<Pessoa>> pessoasAgrupadasPorCidade =
                pessoas.stream().collect(Collectors.groupingBy(Pessoa::getCidade));

        List<Pessoa> salvador1 = pessoasAgrupadasPorCidade.get("Salvador");
        System.out.println("pessoas de salvador "+ salvador1);

        List<Pessoa> saoPaulo = pessoasAgrupadasPorCidade
                .getOrDefault("Sao Paulo", Collections.emptyList());


    }