use of java.util.function.BiPredicate in project GDSC-SMLM by aherbert.
the class TcPalmAnalysis method createSelectionFilter.
/**
* Creates the selection filter to identify all cluster groups using a custom filter.
*
* @param roi the roi
* @param settings the settings
* @return the bi predicate
*/
private BiPredicate<ClusterData, Rectangle2D> createSelectionFilter(final Roi roi, final TcPalmAnalysisSettings settings) {
// Filter on time first as this is simple.
BiPredicate<ClusterData, Rectangle2D> test = null;
if (settings.getMinFrame() > minT) {
final int min = settings.getMinFrame();
test = (c, r) -> c.start >= min;
}
if (settings.getMaxFrame() < maxT) {
final int max = settings.getMaxFrame();
test = and(test, (c, r) -> c.end <= max);
}
// Add square bounds check
test = and(test, settings.getIntersects() ? ClusterData::intersects : ClusterData::isWithin);
// -- Check if the cluster is inside the ROI using a CoordinatePredicate
if (roi.getType() != Roi.RECTANGLE || roi.getCornerDiameter() != 0) {
final CoordinatePredicate pred = CoordinatePredicateUtils.createContainsPredicate(roi);
if (settings.getIntersects()) {
test = and(test, (c, r) -> c.intersects(pred, image::mapX, image::mapY));
} else {
test = and(test, (c, r) -> c.isWithin(pred, image::mapX, image::mapY));
}
}
return test;
}
use of java.util.function.BiPredicate in project ignite by apache.
the class SnapshotRestoreProcess method snapshotAffinity.
/**
* @param metas Map of snapshot metadata distribution across the cluster.
* @return Map of cache partitions per each node.
*/
private static Map<UUID, Map<Integer, Set<Integer>>> snapshotAffinity(Map<UUID, List<SnapshotMetadata>> metas, BiPredicate<Integer, Integer> filter) {
Map<UUID, Map<Integer, Set<Integer>>> nodeToSnp = new HashMap<>();
List<UUID> nodes = new ArrayList<>(metas.keySet());
Collections.shuffle(nodes);
Map<UUID, List<SnapshotMetadata>> shuffleMetas = new LinkedHashMap<>();
nodes.forEach(k -> shuffleMetas.put(k, metas.get(k)));
for (Map.Entry<UUID, List<SnapshotMetadata>> e : shuffleMetas.entrySet()) {
UUID nodeId = e.getKey();
for (SnapshotMetadata meta : ofNullable(e.getValue()).orElse(Collections.emptyList())) {
Map<Integer, Set<Integer>> parts = ofNullable(meta.partitions()).orElse(Collections.emptyMap());
for (Map.Entry<Integer, Set<Integer>> metaParts : parts.entrySet()) {
for (Integer partId : metaParts.getValue()) {
if (filter.test(metaParts.getKey(), partId)) {
nodeToSnp.computeIfAbsent(nodeId, n -> new HashMap<>()).computeIfAbsent(metaParts.getKey(), k -> new HashSet<>()).add(partId);
}
}
}
}
}
return nodeToSnp;
}
use of java.util.function.BiPredicate in project suite by stupidsing.
the class HttpHandleSessionAuth method getHandler.
public Handler getHandler(BiPredicate<String, String> authenticate, Handler protectedHandler) {
return new Handler() {
public Response handle(Request request) {
var current = System.currentTimeMillis();
var sessionIdOpt = //
request.headers.getOpt(//
"Cookie").map(cookie -> HttpHeaderUtil.getCookieAttrs(cookie).get("session"));
var session = sessionIdOpt.map(sm::get).or(null);
Response response;
if (Equals.ab(request.paths, PerList.of("login"))) {
var attrs = HttpHeaderUtil.getPostedAttrs(request.in);
var username = attrs.get("username");
var password = attrs.get("password");
var paths = HttpHeaderUtil.getPaths(attrs.get("path"));
if (authenticate.test(username, password)) {
var sessionId = getRandomSessionId();
sm.put(sessionId, session = new Session(username, current));
var request1 = new //
Request(//
request.method, //
request.server, //
paths, //
request.query, //
request.headers, request.in);
response = showProtectedPage(request1, sessionId);
} else
response = showLoginPage(paths, true);
} else if (Equals.ab(request.paths, PerList.of("logout"))) {
sessionIdOpt.sink(sm::remove);
response = showLoginPage(PerList.end(), false);
} else if (session != null && current < session.lastRequestDt.value() + timeoutDuration) {
session.lastRequestDt.update(current);
response = showProtectedPage(request, sessionIdOpt.g());
} else
response = showLoginPage(request.paths, false);
return response;
}
private Response showProtectedPage(Request request, String sessionId) {
var r = protectedHandler.handle(request);
var headers1 = r.headers.put("Set-Cookie", "session=" + sessionId + "; Path=/site");
return new Response(r.status, headers1, r.body);
}
private Response showLoginPage(PerList<String> redirectPath, boolean isLoginFailed) {
var redirectPath1 = redirectPath.streamlet().map(p -> "/" + p).toJoinedString();
return Response.of(Pull.from(//
"<html>" + //
"<head><title>Login</title></head>" + //
"<body>" + //
"<font face=\"Monospac821 BT,Monaco,Consolas\">" + //
(isLoginFailed ? "<b>LOGIN FAILED</b><p/>" : "") + //
"<form name=\"login\" action=\"login\" method=\"post\">" + //
"Username <input type=\"text\" name=\"username\" autofocus /><br/>" + //
"Password <input type=\"password\" name=\"password\" /><br/>" + "<input type=\"hidden\" name=\"path\" value=\"" + htmlUtil.encode(redirectPath1) + //
"\" />" + //
"<input type=\"submit\" value=\"Login\">" + //
"</form>" + //
"</font>" + //
"</body>" + "</html>"));
}
private String getRandomSessionId() {
var bytes = new byte[16];
random.nextBytes(bytes);
return Build.string(sb -> {
for (var b : bytes) sb.append(String.format("%02x", b));
});
}
};
}
use of java.util.function.BiPredicate in project pravega by pravega.
the class StreamSegmentMetadataTests method testAttributes.
/**
* Tests that Attributes are properly recorded and updated
*/
@Test
public void testAttributes() {
StreamSegmentMetadata metadata = new StreamSegmentMetadata(SEGMENT_NAME, SEGMENT_ID, CONTAINER_ID);
// Step 1: initial set of attributes.
Random rnd = new Random(0);
val expectedAttributes = generateAttributes(rnd);
metadata.updateAttributes(expectedAttributes);
SegmentMetadataComparer.assertSameAttributes("Unexpected attributes after initial set.", expectedAttributes, metadata);
// Step 2: Update half of attributes and add 50% more.
int count = 0;
val keyIterator = expectedAttributes.keySet().iterator();
val attributeUpdates = new HashMap<AttributeId, Long>();
// Update
while (count < ATTRIBUTE_COUNT / 2 && keyIterator.hasNext()) {
attributeUpdates.put(keyIterator.next(), rnd.nextLong());
count++;
}
// Now add a few more.
while (attributeUpdates.size() < ATTRIBUTE_COUNT) {
attributeUpdates.put(AttributeId.randomUUID(), rnd.nextLong());
}
attributeUpdates.forEach(expectedAttributes::put);
metadata.updateAttributes(attributeUpdates);
SegmentMetadataComparer.assertSameAttributes("Unexpected attributes after update.", expectedAttributes, metadata);
// Check getAttributes(filter).
BiPredicate<AttributeId, Long> filter = (key, value) -> key.getBitGroup(1) % 2 == 0;
val expectedFilteredAttributes = expectedAttributes.entrySet().stream().filter(e -> filter.test(e.getKey(), e.getValue())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
val actualFilteredAttributes = metadata.getAttributes(filter);
AssertExtensions.assertMapEquals("Unexpected result from getAttributes(Filter).", expectedFilteredAttributes, actualFilteredAttributes);
// Step 3: Remove all attributes (Note that attributes are not actually removed; they're set to the NULL_ATTRIBUTE_VALUE).
expectedAttributes.entrySet().forEach(e -> e.setValue(Attributes.NULL_ATTRIBUTE_VALUE));
metadata.updateAttributes(expectedAttributes);
SegmentMetadataComparer.assertSameAttributes("Unexpected attributes after removal.", expectedAttributes, metadata);
}
use of java.util.function.BiPredicate in project jersey by jersey.
the class ApplicationHandler method bindProvidersAndResources.
private void bindProvidersAndResources(final Iterable<ComponentProvider> componentProviders, final ComponentBag componentBag, final Collection<Class<?>> resourceClasses, final Collection<Object> resourceInstances) {
JerseyResourceContext resourceContext = injectionManager.getInstance(JerseyResourceContext.class);
Set<Class<?>> registeredClasses = runtimeConfig.getRegisteredClasses();
/*
* Check the {@code component} whether it is correctly configured for client or server {@link RuntimeType runtime}.
*/
java.util.function.Predicate<Class<?>> correctlyConfigured = componentClass -> Providers.checkProviderRuntime(componentClass, componentBag.getModel(componentClass), RuntimeType.SERVER, !registeredClasses.contains(componentClass), resourceClasses.contains(componentClass));
/*
* Check the {@code resource class} whether it is correctly configured for client or server {@link RuntimeType runtime}.
*/
BiPredicate<Class<?>, ContractProvider> correctlyConfiguredResource = (resourceClass, model) -> Providers.checkProviderRuntime(resourceClass, model, RuntimeType.SERVER, !registeredClasses.contains(resourceClass), true);
Set<Class<?>> componentClassses = componentBag.getClasses(ComponentBag.excludeMetaProviders(injectionManager)).stream().filter(correctlyConfigured).collect(Collectors.toSet());
// Merge programmatic resource classes with component classes.
Set<Class<?>> classes = Collections.newSetFromMap(new IdentityHashMap<>());
classes.addAll(componentClassses);
classes.addAll(resourceClasses);
// Bind classes.
for (final Class<?> componentClass : classes) {
ContractProvider model = componentBag.getModel(componentClass);
if (bindWithComponentProvider(componentClass, model, componentProviders)) {
continue;
}
if (resourceClasses.contains(componentClass)) {
if (!Resource.isAcceptable(componentClass)) {
LOGGER.warning(LocalizationMessages.NON_INSTANTIABLE_COMPONENT(componentClass));
continue;
}
if (model != null && !correctlyConfiguredResource.test(componentClass, model)) {
model = null;
}
resourceContext.unsafeBindResource(componentClass, model, injectionManager);
} else {
ProviderBinder.bindProvider(componentClass, model, injectionManager);
}
}
// Merge programmatic resource instances with other component instances.
Set<Object> instances = componentBag.getInstances(ComponentBag.excludeMetaProviders(injectionManager)).stream().filter(instance -> correctlyConfigured.test(instance.getClass())).collect(Collectors.toSet());
instances.addAll(resourceInstances);
// Bind instances.
for (Object component : instances) {
ContractProvider model = componentBag.getModel(component.getClass());
if (resourceInstances.contains(component)) {
if (model != null && !correctlyConfiguredResource.test(component.getClass(), model)) {
model = null;
}
resourceContext.unsafeBindResource(component, model, injectionManager);
} else {
ProviderBinder.bindProvider(component, model, injectionManager);
}
}
}
Aggregations