use of java.util.function.BiPredicate in project nifi by apache.
the class ListFile method createFileFilter.
private BiPredicate<Path, BasicFileAttributes> createFileFilter(final ProcessContext context) {
final long minSize = context.getProperty(MIN_SIZE).asDataSize(DataUnit.B).longValue();
final Double maxSize = context.getProperty(MAX_SIZE).asDataSize(DataUnit.B);
final long minAge = context.getProperty(MIN_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
final Long maxAge = context.getProperty(MAX_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
final boolean ignoreHidden = context.getProperty(IGNORE_HIDDEN_FILES).asBoolean();
final Pattern filePattern = Pattern.compile(context.getProperty(FILE_FILTER).getValue());
final String indir = context.getProperty(DIRECTORY).evaluateAttributeExpressions().getValue();
final boolean recurseDirs = context.getProperty(RECURSE).asBoolean();
final String pathPatternStr = context.getProperty(PATH_FILTER).getValue();
final Pattern pathPattern = (!recurseDirs || pathPatternStr == null) ? null : Pattern.compile(pathPatternStr);
return (path, attributes) -> {
if (minSize > attributes.size()) {
return false;
}
if (maxSize != null && maxSize < attributes.size()) {
return false;
}
final long fileAge = System.currentTimeMillis() - attributes.lastModifiedTime().toMillis();
if (minAge > fileAge) {
return false;
}
if (maxAge != null && maxAge < fileAge) {
return false;
}
if (ignoreHidden && path.toFile().isHidden()) {
return false;
}
if (pathPattern != null) {
Path reldir = Paths.get(indir).relativize(path).getParent();
if (reldir != null && !reldir.toString().isEmpty()) {
if (!pathPattern.matcher(reldir.toString()).matches()) {
return false;
}
}
}
// Verify that we have at least read permissions on the file we're considering grabbing
if (!Files.isReadable(path)) {
return false;
}
return filePattern.matcher(path.getFileName().toString()).matches();
};
}
use of java.util.function.BiPredicate in project unipop by unipop-graph.
the class DateFieldPropertySchema method getValues.
@Override
public Set<Object> getValues(PredicatesHolder predicatesHolder) {
Stream<PredicatesHolder> predicates = predicatesHolder.findKey(this.key).map(this::explodeConnective);
Map<String, Date> datePredicates = new HashMap<>();
predicates.flatMap(p -> p.getPredicates().stream()).forEach(has -> {
String biPredicate = has.getBiPredicate().toString();
Object value = has.getValue();
switch(biPredicate) {
case "eq":
datePredicates.put("eq", fromDisplay(value.toString()));
break;
case "gt":
datePredicates.put("gt", fromDisplay(value.toString()));
case "gte":
datePredicates.put("gte", fromDisplay(value.toString()));
break;
case "lt":
datePredicates.put("lt", fromDisplay(value.toString()));
break;
case "lte":
datePredicates.put("lte", fromDisplay(value.toString()));
break;
default:
throw new IllegalArgumentException("cant get value");
}
});
if (datePredicates.size() == 0)
return Collections.emptySet();
if (datePredicates.containsKey("eq"))
return Collections.singleton(toSource(datePredicates.get("eq")));
else if ((datePredicates.containsKey("gt") || datePredicates.containsKey("gte")) && (datePredicates.containsKey("lt") || datePredicates.containsKey("lte"))) {
Date from = datePredicates.containsKey("gt") ? datePredicates.get("gt") : datePredicates.get("gte");
Date to = datePredicates.containsKey("lt") ? datePredicates.get("lt") : datePredicates.get("lte");
List<Date> dates = new ArrayList<>();
long interval = this.interval;
long endTime = to.getTime();
long curTime = from.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
return dates.stream().map(this::toSource).collect(Collectors.toSet());
} else
throw new IllegalArgumentException("cant get only gt or lt value");
}
use of java.util.function.BiPredicate in project pravega by pravega.
the class TableSegmentImplTest method testIterator.
private <T> void testIterator(Function<SegmentIteratorArgs, AsyncIterator<IteratorItem<T>>> newIterator, Supplier<ByteBuf> getLastRequestFromKey, Supplier<ByteBuf> getLastRequestToKey, Function<TableSegmentEntry, T> getItemFromEntry, Consumer<List<T>> sendReply, BiPredicate<T, T> checkItemEquality) throws Exception {
val suggestedKeyCount = 3;
// Generate 100 Entries and split them into batches.
val allEntries = IntStream.range(0, 100).mapToObj(i -> versionedEntry(i * 10L, Integer.toString(i * 10), 1L)).collect(Collectors.toList());
val inputEntries = splitIteratorInputs(allEntries);
// Do an full iteration as well.
inputEntries.add(allEntries);
// Check regular iteration.
for (int i = 0; i < inputEntries.size(); i++) {
val entryList = inputEntries.get(i);
SegmentIteratorArgs args = SegmentIteratorArgs.builder().fromKey(entryList.get(0).getKey().getKey()).toKey(entryList.get(entryList.size() - 1).getKey().getKey()).maxItemsAtOnce(suggestedKeyCount).build();
// We collect iterated items in this list.
val actualItems = new ArrayList<T>();
val itemsToReturn = entryList.iterator();
val tableIterator = newIterator.apply(args);
while (itemsToReturn.hasNext()) {
val iteratorFuture = tableIterator.getNext();
// Verify the wire command got sent as expected.
val requestFromKey = getLastRequestFromKey.get();
Assert.assertEquals("Unexpected fromKey sent.", args.getFromKey(), requestFromKey);
val requestToKey = getLastRequestToKey.get();
Assert.assertEquals("Unexpected toKey sent.", args.getToKey(), requestToKey);
// Send a reply.
val expectedResult = new ArrayList<T>();
int count = suggestedKeyCount;
while (itemsToReturn.hasNext() && count > 0) {
val next = itemsToReturn.next();
expectedResult.add(getItemFromEntry.apply(next));
args = args.next(next.getKey().getKey());
count--;
}
sendReply.accept(expectedResult);
// Check the partial result.
val iteratorResult = iteratorFuture.get(SHORT_TIMEOUT, TimeUnit.MILLISECONDS);
AssertExtensions.assertListEquals("Unexpected partial result.", expectedResult, iteratorResult.getItems(), checkItemEquality);
actualItems.addAll(iteratorResult.getItems());
}
// Then the final result.
val expected = entryList.stream().map(getItemFromEntry).collect(Collectors.toList());
AssertExtensions.assertListEquals("Unexpected result.", expected, actualItems, checkItemEquality);
}
}
use of java.util.function.BiPredicate in project cuba by cuba-platform.
the class AccessConstraintMethodPredicate method createBiPredicate.
private static BiPredicate<AccessGroupDefinition, Entity> createBiPredicate(String className, String methodName, String argClassName) {
Class<?> clazz = ReflectionHelper.getClass(className);
Class<?> argumentClazz = ReflectionHelper.getClass(argClassName);
Method method = Arrays.stream(clazz.getMethods()).filter(m -> Objects.equals(m.getName(), methodName)).filter(m -> m.getParameterCount() == 1 && Objects.equals(m.getParameterTypes()[0], argumentClazz)).findFirst().orElseThrow(() -> new RuntimeException(String.format("Unable to find corresponding in-memory predicate method %s#%s", className, methodName)));
try {
MethodHandles.Lookup caller = MethodHandles.lookup();
CallSite site = LambdaMetafactory.metafactory(caller, "test", MethodType.methodType(BiPredicate.class), MethodType.methodType(boolean.class, Object.class, Object.class), caller.findVirtual(clazz, method.getName(), MethodType.methodType(method.getReturnType(), argumentClazz)), MethodType.methodType(boolean.class, clazz, argumentClazz));
// noinspection unchecked
return (BiPredicate<AccessGroupDefinition, Entity>) site.getTarget().invoke();
} catch (Throwable e) {
throw new IllegalStateException(String.format("Can't create in-memory constraint predicate for method %s#%s", className, methodName), e);
}
}
use of java.util.function.BiPredicate in project ignite by apache.
the class GridSubqueryJoinOptimizer method remapColumns.
/**
* Remap all columns that satisfy the predicate such they be referred to the given table.
*
* @param parent Tree where to search columns.
* @param subSelect Tree where to search column aliases.
* @param colPred Collection predicate.
* @param tbl Table.
*/
private static void remapColumns(GridSqlAst parent, GridSqlAst subSelect, Predicate<GridSqlColumn> colPred, GridSqlAlias tbl) {
ASTNodeFinder colFinder = new ASTNodeFinder(parent, (p, c) -> c instanceof GridSqlColumn && colPred.test((GridSqlColumn) c));
ASTNodeFinder.Result res;
while ((res = colFinder.findNext()) != null) {
GridSqlColumn oldCol = res.getEl().child(res.getIdx());
BiPredicate<GridSqlAst, GridSqlAst> constPred = (p, c) -> c != null && c.getSQL().equals(oldCol.columnName());
BiPredicate<GridSqlAst, GridSqlAst> aliasPred = (p, c) -> c instanceof GridSqlAlias && ((GridSqlAlias) c).alias().equals(oldCol.columnName());
ASTNodeFinder.Result aliasOrPred = findNode(subSelect, constPred.or(aliasPred));
if (aliasOrPred != null)
res.getEl().child(res.getIdx(), GridSqlAlias.unwrap(aliasOrPred.getEl().child(aliasOrPred.getIdx())));
else {
res.getEl().child(res.getIdx(), new GridSqlColumn(oldCol.column(), tbl, oldCol.schema(), tbl.alias(), oldCol.columnName()));
}
}
}
Aggregations