Exemple #1
0
 /** Process objects with specific tag. */
 public void byTag(
     String tagName, Predicate<IOsmObject> predicate, Consumer<IOsmObject> consumer) {
   short tagKey = tagsPack.getTagCode(tagName);
   for (int i = 0; i < nodes.size(); i++) {
     IOsmNode n = nodes.get(i);
     if (n.hasTag(tagKey)) {
       if (predicate.test(n)) {
         consumer.accept(n);
       }
     }
   }
   for (int i = 0; i < ways.size(); i++) {
     IOsmWay w = ways.get(i);
     if (w.hasTag(tagKey)) {
       if (predicate.test(w)) {
         consumer.accept(w);
       }
     }
   }
   for (int i = 0; i < relations.size(); i++) {
     IOsmRelation r = relations.get(i);
     if (r.hasTag(tagKey)) {
       if (predicate.test(r)) {
         consumer.accept(r);
       }
     }
   }
 }
  @Override
  public boolean rejectedByFilter(AisMessage message) {
    if (geomtries.size() == 0) {
      return false;
    }

    if (message instanceof IPositionMessage) {
      Position pos = ((IPositionMessage) message).getPos().getGeoLocation();
      if (pos != null) {
        posMap.put(message.getUserId(), pos);
      }
    }

    // Get location
    Position loc = posMap.get(message.getUserId());
    if (loc == null) {
      return true;
    }

    for (Predicate<? super Position> geometry : geomtries) {
      if (geometry.test(loc)) {
        return false;
      }
    }

    return true;
  }
  @Test
  public void nodematch() {
    Predicate<Node> nodeMatch = FileContentReplace.nodeMatch(2, "add", "/somepath/is/here.txt");
    {
      Node ourNode = new NodeImpl(new RevisionImpl(2));
      ourNode.getHeaders().put(NodeHeader.ACTION, "add");
      ourNode.getHeaders().put(NodeHeader.PATH, "/somepath/is/here.txt");

      assertTrue(nodeMatch.test(ourNode));
    }
    {
      Node ourNode = new NodeImpl(new RevisionImpl(2));
      ourNode.getHeaders().put(NodeHeader.ACTION, "add");
      ourNode.getHeaders().put(NodeHeader.PATH, "/somepath/is/here1.txt");

      assertFalse(nodeMatch.test(ourNode));
    }
    {
      Node ourNode = new NodeImpl(new RevisionImpl(2));
      ourNode.getHeaders().put(NodeHeader.ACTION, "remove");
      ourNode.getHeaders().put(NodeHeader.PATH, "/somepath/is/here.txt");

      assertFalse(nodeMatch.test(ourNode));
    }
    {
      Node ourNode = new NodeImpl(new RevisionImpl(3));
      ourNode.getHeaders().put(NodeHeader.ACTION, "add");
      ourNode.getHeaders().put(NodeHeader.PATH, "/somepath/is/here.txt");

      assertFalse(nodeMatch.test(ourNode));
    }
  }
Exemple #4
0
  @Override
  public void readValue(Object data, Tagable tagabale) {
    if (data instanceof MacroSeqData) {
      MacroSeqData macro = (MacroSeqData) data;
      Object val = getValue(macro.getAttributes());
      if (val instanceof Sequence) {
        Sequence seq = (Sequence) val;
        if (!seq.isEmpty()) {
          val = seq.get(0);
        }
      }

      if (val instanceof Attributes) {
        Attributes dataset = (Attributes) val;
        Predicate<? super Attributes> predicate = macro.getApplicable();
        if (predicate == null || predicate.test(dataset)) {
          for (TagW tag : macro.getTags()) {
            if (tag != null) {
              tag.readValue(dataset, tagabale);
            }
          }
        }
      }
    }
  }
  @Test
  public void ChainHandler_is_NOT_called() {

    // given:

    Predicate<Integer> filter = Mockito.mock(UberClasses.cast(Predicate.class));
    EventHandler<Integer> handler = Mockito.mock(UberClasses.cast(EventHandler.class));

    Mockito.when(filter.test(Matchers.any())).thenReturn(false);
    Mockito.when(handler.test(Matchers.any())).thenReturn(true);

    EventCollector<Listener, Integer> collector =
        EventCollector.create(
            Listener.class, Listener::event, EventHandlers.chain(filter, handler));

    Listener target = collector.getTarget();

    // when

    target.event(100);

    // then

    InOrder order = Mockito.inOrder(filter, handler);
    order.verify(filter, Mockito.times(1)).test(100);
    order.verifyNoMoreInteractions();
  }
  @Test
  public void eventCollected_is_not_called() {

    // given:

    Predicate<Integer> filter = Mockito.mock(UberClasses.cast(Predicate.class));
    EventHandler<Integer> filterEH = Mockito.mock(UberClasses.cast(EventHandler.class));

    Mockito.when(filter.test(Matchers.any())).thenReturn(false);
    Mockito.when(filterEH.test(Matchers.any())).thenReturn(true);

    EventCollector<Listener, Integer> collector = createCollector(filter, filterEH);
    Listener target = collector.getTarget();

    // when:

    target.event(100);
    target.event(200);

    // then:

    Mockito.verify(filter, Mockito.times(2)).test(Matchers.any());
    Mockito.verify(filterEH, Mockito.times(2)).test(Matchers.any());

    // and:

    Mockito.verifyNoMoreInteractions(filterEH);
  }
  @Test
  public void events_are_collected() {

    // given:

    Predicate<Integer> filter = Mockito.mock(UberClasses.cast(Predicate.class));
    EventHandler<Integer> filterEH = Mockito.mock(UberClasses.cast(EventHandler.class));

    Mockito.when(filter.test(Matchers.any())).thenReturn(true);
    Mockito.when(filterEH.test(Matchers.any())).thenReturn(true);

    Mockito.when(filter.test(200)).thenReturn(false);

    EventCollector<Listener, Integer> collector = createCollector(filter, filterEH);
    Listener target = collector.getTarget();

    // when:

    target.event(100);
    target.event(200);
    target.event(300);

    // then:

    Mockito.verify(filter, Mockito.times(3)).test(Matchers.any());
    Mockito.verify(filterEH, Mockito.times(3)).test(Matchers.any());

    // and:

    List<Integer> events = collector.getEvents();
    Assert.assertThat(events, contains(100, 300));
    Assert.assertThat(collector.getLastEvent(), equalTo(300));
  }
 private void find(MessageContext context, String args) {
   DiscordApiClient apiClient = context.getApiClient();
   Channel channel = context.getChannel();
   Pattern pattern;
   try {
     pattern = Pattern.compile(args);
   } catch (PatternSyntaxException pse) {
     apiClient.sendMessage(loc.localize("commands.admin.find.response.invalid"), channel);
     return;
   }
   Predicate<String> matcher = pattern.asPredicate();
   List<User> results =
       context
           .getServer()
           .getMembers()
           .stream()
           .map(Member::getUser)
           .filter(u -> matcher.test(u.getUsername()))
           .collect(Collectors.toList());
   int size = results.size();
   if (size > 20) {
     apiClient.sendMessage(loc.localize("commands.admin.find.response.oversize", size), channel);
     return;
   }
   StringJoiner resultJoiner = new StringJoiner(", ");
   results.stream().map(this::userToResult).forEach(resultJoiner::add);
   apiClient.sendMessage(
       loc.localize("commands.admin.find.response.format", size, resultJoiner.toString()),
       channel);
 }
  public void waitForFeature(String featureName, Predicate<FeatureState> predicate)
      throws Exception {
    boolean ready = false;

    long timeoutLimit = System.currentTimeMillis() + REQUIRED_BUNDLES_TIMEOUT;
    while (!ready) {
      FeaturesService featuresService = getFeaturesService();
      if (featuresService != null) {
        Feature feature = featuresService.getFeature(featureName);
        FeatureState state =
            featuresService.getState(feature.getName() + "/" + feature.getVersion());
        if (state == null) {
          LOGGER.warn("No Feature found for featureName: {}", featureName);
          return;
        } else if (predicate.test(state)) {
          ready = true;
        }
      }

      if (!ready) {
        if (System.currentTimeMillis() > timeoutLimit) {
          printInactiveBundles();
          fail(
              String.format(
                  "Feature did not change to State ["
                      + predicate.toString()
                      + "] within %d minutes.",
                  TimeUnit.MILLISECONDS.toMinutes(REQUIRED_BUNDLES_TIMEOUT)));
        }
        LOGGER.info("Feature [{}] not [{}], sleeping...", featureName, predicate.toString());
        Thread.sleep(1000);
      }
    }
  }
Exemple #10
0
  @Test
  public void constraintTest() {
    Debug.testStart("Constraint");

    final int COUNT = 100;

    final TestMonitorable mon = new TestMonitorable();

    final Random rand = new Random();

    final Predicate<TestMonitorable> pred1 = m -> m.get() < COUNT;
    final Predicate<TestMonitorable> pred2 = m -> m.get() % 2 == 0;

    final Monitor<TestMonitorable> monitor1 = new ConstraintMonitor<>(pred1);
    mon.addChangeMonitor(monitor1);
    final Monitor<TestMonitorable> monitor2 = Monitors.monitor(mon).constraint(pred2);

    for (int i = 0; i < COUNT; i++) {
      boolean failed = false;
      try {
        mon.increment();
      } catch (final UnprotectedMonitorException cve) {
        failed = true;
      }
      final boolean shouldFail = !pred1.test(mon) || !pred2.test(mon);

      if (failed) {
        if (!shouldFail) throw new Error("False negative at " + mon.get());
      } else if (shouldFail) throw new Error("False positive at " + mon.get());
    }

    Debug.testEnd("Constraint");
  }
 /**
  * Returns a composed {@link ToFloatBiFunction} that first applies the {@code before} predicates
  * to its input, and then applies this function to the result. If evaluation of either operation
  * throws an exception, it is relayed to the caller of the composed operation.
  *
  * @param <A> The type of the argument to the first given predicate, and of composed function
  * @param <B> The type of the argument to the second given predicate, and of composed function
  * @param before1 The first predicate to apply before this function is applied
  * @param before2 The second predicate to apply before this function is applied
  * @return A composed {@code ToFloatBiFunction} that first applies the {@code before} predicates
  *     to its input, and then applies this function to the result.
  * @throws NullPointerException If given argument is {@code null}
  * @implSpec The input argument of this method is able to handle every type.
  */
 @Nonnull
 default <A, B> ToFloatBiFunction<A, B> compose(
     @Nonnull final Predicate<? super A> before1, @Nonnull final Predicate<? super B> before2) {
   Objects.requireNonNull(before1);
   Objects.requireNonNull(before2);
   return (a, b) -> applyAsFloat(before1.test(a), before2.test(b));
 }
  private static void exampleOfPredicate() {

    Predicate<String> p = text -> text.equals("Some text");
    print("Predicate 1: " + p.test("Another text"));

    p = LambdaAPI::isThisTextGreaterThan10;
    System.out.println("Predicate 2: " + p.test("ABCDEFGHIJKLMN"));
  }
Exemple #13
0
 /**
  * Combines expected packet type and given filter.
  *
  * @see Connection#sendSynchronous(Packet, Predicate, long)
  */
 @SuppressWarnings("unchecked")
 public <R extends Packet> R sendSynchronous(
     Packet request, Class<R> expectedPacketType, Predicate<R> filter, long timeout)
     throws IOException {
   Predicate<Packet> typeFilter = new TypeFilter<>(expectedPacketType);
   Predicate<Packet> composed = p -> typeFilter.test(p) && filter.test((R) p);
   return (R) sendSynchronous(request, composed, timeout);
 }
  public void resolve(
      String identifier,
      TableReference container,
      EReference reference,
      int position,
      boolean resolveFuzzy,
      final ISqlReferenceResolveResult<TableDefinition> result) {

    SQLScript sqlScript = (SQLScript) EcoreUtil.getRootContainer(container);

    String catalogName = container.getCatalogName();
    Predicate<TableDefinition> filter =
        !Helper.isEmpty(catalogName)
            ? table -> catalogName.equals(table.getSchemaQualifiedName().getCatalogName())
            : table -> true;

    String schemaName = container.getSchemaName();
    Predicate<TableDefinition> filter2 =
        !Helper.isEmpty(schemaName)
            ? table -> schemaName.equals(table.getSchemaQualifiedName().getSchemaName())
            : table -> true;

    Stream<TableDefinition> tables =
        sqlScript
            .getStatements()
            .stream()
            .filter(stmt -> stmt instanceof TableDefinition)
            .map(table -> (TableDefinition) table)
            .filter(filter.and(filter2));

    Consumer<TableDefinition> addMapping =
        table -> result.addMapping(table.getSchemaQualifiedName().getName(), table);

    if (resolveFuzzy) {
      tables
          .filter(
              table ->
                  table.getSchemaQualifiedName() != null
                      && table.getSchemaQualifiedName().getName() != null
                      && table
                          .getSchemaQualifiedName()
                          .getName()
                          .toUpperCase()
                          .startsWith(identifier.toUpperCase()))
          .forEach(addMapping);
    } else {
      tables
          .filter(
              table ->
                  table.getSchemaQualifiedName() != null
                      && table.getSchemaQualifiedName().getName() != null
                      && table.getSchemaQualifiedName().getName().equals(identifier))
          .findFirst()
          .ifPresent(addMapping);
    }
  }
  @Override
  public List<Contact> searchContacts(Map<SearchTerm, String> criteria) {

    String firstNameCriteria = criteria.get(SearchTerm.FIRST_NAME);
    String lastNameCriteria = criteria.get(SearchTerm.LAST_NAME);
    String companyCriteria = criteria.get(SearchTerm.COMPANY);
    String phoneCriteria = criteria.get(SearchTerm.PHONE);
    String emailCriteria = criteria.get(SearchTerm.EMAIL);

    Predicate<Contact> firstNameMatches;
    Predicate<Contact> lastNameMatches;
    Predicate<Contact> companyMatches;
    Predicate<Contact> phoneMatches;
    Predicate<Contact> emailMatches;

    Predicate<Contact> truePredicate =
        (c) -> {
          return true;
        };

    firstNameMatches =
        (firstNameCriteria == null) || (firstNameCriteria.isEmpty())
            ? truePredicate
            : (c) -> c.getFirstName().equalsIgnoreCase(firstNameCriteria);

    lastNameMatches =
        (lastNameCriteria == null) || (lastNameCriteria.isEmpty())
            ? truePredicate
            : (c) -> c.getLastName().equalsIgnoreCase(lastNameCriteria);

    companyMatches =
        (companyCriteria == null) || (companyCriteria.isEmpty())
            ? truePredicate
            : (c) -> c.getCompany().equalsIgnoreCase(companyCriteria);

    phoneMatches =
        (phoneCriteria == null) || (phoneCriteria.isEmpty())
            ? truePredicate
            : (c) -> c.getPhone().equalsIgnoreCase(phoneCriteria);

    emailMatches =
        (emailCriteria == null) || (emailCriteria.isEmpty())
            ? truePredicate
            : (c) -> c.getEmail().equalsIgnoreCase(emailCriteria);

    return contactMap
        .values()
        .stream()
        .filter(
            firstNameMatches
                .and(lastNameMatches)
                .and(companyMatches)
                .and(phoneMatches)
                .and(emailMatches))
        .collect(Collectors.toList());
  }
Exemple #16
0
    @Override
    protected void realRun() {
      try {
        foundMatches = 0;
        SearchCompiler.Match matcher = SearchCompiler.compile(setting);

        if (setting.mode == SearchMode.replace) {
          selection.clear();
        } else if (setting.mode == SearchMode.in_selection) {
          foundMatches = selection.size();
        }

        Collection<OsmPrimitive> all;
        if (setting.allElements) {
          all = ds.allPrimitives();
        } else {
          all = ds.getPrimitives(OsmPrimitive::isSelectable);
        }
        final ProgressMonitor subMonitor =
            getProgressMonitor().createSubTaskMonitor(all.size(), false);
        subMonitor.beginTask(
            trn("Searching in {0} object", "Searching in {0} objects", all.size(), all.size()));

        for (OsmPrimitive osm : all) {
          if (canceled) {
            return;
          }
          if (setting.mode == SearchMode.replace) {
            if (matcher.match(osm)) {
              selection.add(osm);
              ++foundMatches;
            }
          } else if (setting.mode == SearchMode.add && !predicate.test(osm) && matcher.match(osm)) {
            selection.add(osm);
            ++foundMatches;
          } else if (setting.mode == SearchMode.remove
              && predicate.test(osm)
              && matcher.match(osm)) {
            selection.remove(osm);
            ++foundMatches;
          } else if (setting.mode == SearchMode.in_selection
              && predicate.test(osm)
              && !matcher.match(osm)) {
            selection.remove(osm);
            --foundMatches;
          }
          subMonitor.worked(1);
        }
        subMonitor.finishTask();
      } catch (ParseError e) {
        Main.debug(e);
        JOptionPane.showMessageDialog(
            Main.parent, e.getMessage(), tr("Error"), JOptionPane.ERROR_MESSAGE);
      }
    }
 private boolean retry(Exception e) {
   if (retryPredicates.isEmpty()) {
     return true;
   }
   for (Predicate<Exception> retryPredicate : retryPredicates) {
     if (retryPredicate.test(e)) {
       return true;
     }
   }
   return false;
 }
Exemple #18
0
  private void predicate() {
    Predicate<String> p1 = s -> s.length() < 20;
    Predicate<String> p2 = s -> s.length() > 10;

    Predicate<String> p3 = p1.and(p2);

    Predicate<String> id = Predicate.isEqual(p1);

    //        List<String>

  }
Exemple #19
0
  /**
   * Creates a {@link BodyFilter} that replaces the properties in the json response with the
   * replacement passed as argument. This {@link BodyFilter} works on all levels inside the json
   * tree and it only works with string values<br>
   * <br>
   * Example from {@link #accessToken} method:<br>
   *
   * <pre>
   * Set<String> properties = new HashSet<>();
   * properties.add("access_token");
   * properties.add("open_id");
   * properties.add("id_token");
   * return replaceJsonStringProperty(properties, "XXX");
   * </pre>
   *
   * @param properties JSON properties to replace
   * @param replacement String to replace the properties values
   * @return BodyFilter generated
   */
  public static BodyFilter replaceJsonStringProperty(Set<String> properties, String replacement) {
    String regex = properties.stream().map(Pattern::quote).collect(joining("|"));

    final Predicate<String> json = MediaTypeQuery.compile("application/json", "application/*+json");
    final Pattern pattern = Pattern.compile("(\"(?:" + regex + ")\"\\s*\\:\\s*)\".+?\"");

    return (contentType, body) ->
        json.test(contentType)
            ? pattern.matcher(body).replaceAll("$1\"" + replacement + "\"")
            : body;
  }
  @Override
  public boolean test(final T object) {
    for (final Predicate<T> predicate : this.predicates) {
      final boolean test = predicate.test(object);
      if (!test) {

        return false;
      }
    }
    return true;
  }
Exemple #21
0
 @SafeVarargs
 public static <A> Predicate<A> or(final Predicate<A>... predicates) {
   return a -> {
     for (Predicate<A> predicate : predicates) {
       if (predicate.test(a)) {
         return true;
       }
     }
     return false;
   };
 }
 private <T extends PlanNode> void findAllRecursive(
     PlanNode node, ImmutableList.Builder<T> nodes) {
   if (where.test(node)) {
     nodes.add((T) node);
   }
   if (skipOnly.test(node)) {
     for (PlanNode source : node.getSources()) {
       findAllRecursive(source, nodes);
     }
   }
 }
Exemple #23
0
 private void awaitCond(java.util.function.Predicate<Void> predicate, long duration, long steps) {
   if (!predicate.test(null)) {
     final long currentTimeMillis = System.currentTimeMillis();
     while (!predicate.test(null) && System.currentTimeMillis() - currentTimeMillis > duration) {
       try {
         Thread.sleep(steps);
       } catch (InterruptedException e) {
         // ignore
       }
     }
   }
 }
  public static void main(String[] args) {
    List<Person> people = new TestDataFixture().getFakePeople();

    // Print males above 60
    System.out.println(filter(people, isMale.and(isOlderThan60)));

    // Print males OR person above 60
    System.out.println(filter(people, isMale.or(isOlderThan60)));

    // Print not males
    System.out.println(filter(people, isMale.negate()));
  }
 private <T extends PlanNode> Optional<T> findFirstRecursive(PlanNode node) {
   if (where.test(node)) {
     return Optional.of((T) node);
   }
   if (skipOnly.test(node)) {
     for (PlanNode source : node.getSources()) {
       Optional<T> found = findFirstRecursive(source);
       if (found.isPresent()) {
         return found;
       }
     }
   }
   return Optional.empty();
 }
 private PlanNode replaceAllRecursive(PlanNode node, PlanNode nodeToReplace) {
   if (where.test(node)) {
     return nodeToReplace;
   }
   if (skipOnly.test(node)) {
     List<PlanNode> sources =
         node.getSources()
             .stream()
             .map(source -> replaceAllRecursive(source, nodeToReplace))
             .collect(toImmutableList());
     return replaceChildren(node, sources);
   }
   return node;
 }
Exemple #27
0
/** Created by vishn_000 on 20.03.2014. */
public class Pred {

  // instead of TextUtils...
  public static Predicate<String> nonNull = s -> s != null;
  public static Predicate<String> emptyString = String::isEmpty;

  public static Predicate<String> combinePredicates = nonNull.and(emptyString.negate());

  public static void main(String[] args) {
    System.out.println(combinePredicates.test("test"));
    System.out.println(combinePredicates.test(""));
    System.out.println(combinePredicates.test(null));
  }
}
Exemple #28
0
  /**
   * Asserts that arguments can be resolved from method references for simple functional interfaces.
   */
  public void shouldResolveArgumentsFromMethodRefs() {
    Baz baz = new Baz();
    Predicate<String> p1 = baz::evaluate;
    Predicate<String> p2 = Baz::eval;
    BiPredicate<Baz, String> p3 = Baz::evaluate;
    Comparator<String> c = String::compareToIgnoreCase;

    assertEquals(TypeResolver.resolveRawArgument(Predicate.class, p1.getClass()), String.class);
    assertEquals(TypeResolver.resolveRawArgument(Predicate.class, p2.getClass()), String.class);
    assertEquals(
        TypeResolver.resolveRawArguments(BiPredicate.class, p3.getClass()),
        new Class<?>[] {Baz.class, String.class});
    assertEquals(TypeResolver.resolveRawArgument(Comparator.class, c.getClass()), String.class);
  }
Exemple #29
0
 @Override
 default int indexWhere(Predicate<? super T> predicate, int from) {
   Objects.requireNonNull(predicate, "predicate is null");
   int start = Math.max(from, 0);
   int n = start + segmentLength(predicate.negate(), start);
   return (n >= length()) ? -1 : n;
 }
Exemple #30
0
  public static <T, U> Function<T, U> ternaryOperator(
      Predicate<? super T> condition,
      Function<? super T, ? extends U> ifTrue,
      Function<? super T, ? extends U> ifFalse) {

    return (x -> condition.test(x) ? ifTrue.apply(x) : ifFalse.apply(x));
  }