Search in sources :

Example 11 with BiPredicate

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;
}
Also used : Color(java.awt.Color) Arrays(java.util.Arrays) Calibration(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration) IntUnaryOperator(java.util.function.IntUnaryOperator) Rectangle2D(java.awt.geom.Rectangle2D) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) IdFramePeakResultComparator(uk.ac.sussex.gdsc.smlm.results.sort.IdFramePeakResultComparator) UnaryOperator(java.util.function.UnaryOperator) Hull(uk.ac.sussex.gdsc.core.math.hull.Hull) TableCellRenderer(javax.swing.table.TableCellRenderer) ResultsSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsSettings) FloatUnaryOperator(uk.ac.sussex.gdsc.core.utils.function.FloatUnaryOperator) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) RoiManager(ij.plugin.frame.RoiManager) RowSorter(javax.swing.RowSorter) SoftLock(uk.ac.sussex.gdsc.core.utils.SoftLock) JFrame(javax.swing.JFrame) LutHelper(uk.ac.sussex.gdsc.core.ij.process.LutHelper) KeyStroke(javax.swing.KeyStroke) TableModelEvent(javax.swing.event.TableModelEvent) InputSource(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsManager.InputSource) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) KeyEvent(java.awt.event.KeyEvent) WindowAdapter(java.awt.event.WindowAdapter) ConcurrencyUtils(uk.ac.sussex.gdsc.core.utils.concurrent.ConcurrencyUtils) Component(java.awt.Component) Hull2d(uk.ac.sussex.gdsc.core.math.hull.Hull2d) TextUtils(uk.ac.sussex.gdsc.core.utils.TextUtils) Plot(ij.gui.Plot) Executors(java.util.concurrent.Executors) CalibrationHelper(uk.ac.sussex.gdsc.smlm.data.config.CalibrationHelper) ImagePlus(ij.ImagePlus) DefaultTableCellRenderer(javax.swing.table.DefaultTableCellRenderer) ToDoubleFunction(java.util.function.ToDoubleFunction) TcPalmAnalysisSettings(uk.ac.sussex.gdsc.smlm.ij.settings.GUIProtos.TcPalmAnalysisSettings) FileUtils(uk.ac.sussex.gdsc.core.utils.FileUtils) PlugIn(ij.plugin.PlugIn) ListSelectionModel(javax.swing.ListSelectionModel) ActionListener(java.awt.event.ActionListener) PolygonRoi(ij.gui.PolygonRoi) StoredData(uk.ac.sussex.gdsc.core.utils.StoredData) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) WindowManager(ij.WindowManager) ConvexHull2d(uk.ac.sussex.gdsc.core.math.hull.ConvexHull2d) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) PointRoi(ij.gui.PointRoi) Trace(uk.ac.sussex.gdsc.smlm.results.Trace) GenericDialog(ij.gui.GenericDialog) AbstractTableModel(javax.swing.table.AbstractTableModel) SortUtils(uk.ac.sussex.gdsc.core.utils.SortUtils) RounderUtils(uk.ac.sussex.gdsc.core.data.utils.RounderUtils) Overlay(ij.gui.Overlay) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) Window(java.awt.Window) IOException(java.io.IOException) JScrollPane(javax.swing.JScrollPane) RoiListener(ij.gui.RoiListener) Paths(java.nio.file.Paths) ConcurrentMonoStack(uk.ac.sussex.gdsc.core.utils.concurrent.ConcurrentMonoStack) ListSelectionListener(javax.swing.event.ListSelectionListener) TIntArrayList(gnu.trove.list.array.TIntArrayList) IdentityTypeConverter(uk.ac.sussex.gdsc.core.data.utils.IdentityTypeConverter) Point(java.awt.Point) CoordinatePredicateUtils(uk.ac.sussex.gdsc.core.ij.roi.CoordinatePredicateUtils) ResultsImageSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageSettings) ImageJPluginLoggerHelper(uk.ac.sussex.gdsc.core.ij.ImageJPluginLoggerHelper) LocalCollectors(uk.ac.sussex.gdsc.core.utils.LocalCollectors) ImageJImagePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJImagePeakResults) NonBlockingExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.NonBlockingExtendedGenericDialog) ScreenDimensionHelper(uk.ac.sussex.gdsc.core.ij.gui.ScreenDimensionHelper) PlotWindow(ij.gui.PlotWindow) ListSelectionEvent(javax.swing.event.ListSelectionEvent) SettingsManager(uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager) JMenuBar(javax.swing.JMenuBar) CoordinatePredicate(uk.ac.sussex.gdsc.core.ij.roi.CoordinatePredicate) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) PeakResultsList(uk.ac.sussex.gdsc.smlm.results.PeakResultsList) JMenu(javax.swing.JMenu) TIntIntHashMap(gnu.trove.map.hash.TIntIntHashMap) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) WindowEvent(java.awt.event.WindowEvent) DoubleStream(java.util.stream.DoubleStream) Objects(java.util.Objects) List(java.util.List) SimpleArrayUtils(uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils) JTable(javax.swing.JTable) LUT(ij.process.LUT) TypeConverter(uk.ac.sussex.gdsc.core.data.utils.TypeConverter) Roi(ij.gui.Roi) Rectangle(java.awt.Rectangle) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) AtomicReference(java.util.concurrent.atomic.AtomicReference) SwingConstants(javax.swing.SwingConstants) TextField(java.awt.TextField) Level(java.util.logging.Level) AWTEvent(java.awt.AWTEvent) BiPredicate(java.util.function.BiPredicate) SwingUtilities(javax.swing.SwingUtilities) JMenuItem(javax.swing.JMenuItem) ImagePeakResultsFactory(uk.ac.sussex.gdsc.smlm.ij.results.ImagePeakResultsFactory) UnitHelper(uk.ac.sussex.gdsc.smlm.data.config.UnitHelper) ExecutorService(java.util.concurrent.ExecutorService) LutColour(uk.ac.sussex.gdsc.core.ij.process.LutHelper.LutColour) ActionEvent(java.awt.event.ActionEvent) Rounder(uk.ac.sussex.gdsc.core.data.utils.Rounder) TimeUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.TimeUnit) Consumer(java.util.function.Consumer) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) TableColumnAdjuster(uk.ac.sussex.gdsc.smlm.ij.gui.TableColumnAdjuster) IJ(ij.IJ) DoublePredicate(java.util.function.DoublePredicate) Collections(java.util.Collections) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) Rectangle2D(java.awt.geom.Rectangle2D) Point(java.awt.Point) CoordinatePredicate(uk.ac.sussex.gdsc.core.ij.roi.CoordinatePredicate)

Example 12 with BiPredicate

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;
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) StoredCacheData(org.apache.ignite.internal.processors.cache.StoredCacheData) CacheObjectBinaryProcessorImpl.binaryWorkDir(org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl.binaryWorkDir) RESTORE_CACHE_GROUP_SNAPSHOT_ROLLBACK(org.apache.ignite.internal.util.distributed.DistributedProcess.DistributedProcessType.RESTORE_CACHE_GROUP_SNAPSHOT_ROLLBACK) BooleanSupplier(java.util.function.BooleanSupplier) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Path(java.nio.file.Path) IgniteFuture(org.apache.ignite.lang.IgniteFuture) FilePageStoreManager.cacheGroupName(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.cacheGroupName) EventType(org.apache.ignite.events.EventType) Collection(java.util.Collection) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) Set(java.util.Set) FilePageStoreManager(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) FilePageStoreManager.partId(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.partId) Serializable(java.io.Serializable) INDEX_PARTITION(org.apache.ignite.internal.pagemem.PageIdAllocator.INDEX_PARTITION) Objects(java.util.Objects) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) CU(org.apache.ignite.internal.util.typedef.internal.CU) Optional(java.util.Optional) SNAPSHOT_RESTORE_CACHE_GROUP(org.apache.ignite.internal.IgniteFeatures.SNAPSHOT_RESTORE_CACHE_GROUP) IgniteFutureImpl(org.apache.ignite.internal.util.future.IgniteFutureImpl) CACHE_GRP_DIR_PREFIX(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.CACHE_GRP_DIR_PREFIX) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) ClusterSnapshotFuture(org.apache.ignite.internal.processors.cache.persistence.snapshot.IgniteSnapshotManager.ClusterSnapshotFuture) ClusterState(org.apache.ignite.cluster.ClusterState) U(org.apache.ignite.internal.util.typedef.internal.U) IgniteSnapshotManager.databaseRelativePath(org.apache.ignite.internal.processors.cache.persistence.snapshot.IgniteSnapshotManager.databaseRelativePath) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) IgniteLogger(org.apache.ignite.IgniteLogger) IgniteFeatures(org.apache.ignite.internal.IgniteFeatures) DiscoCache(org.apache.ignite.internal.managers.discovery.DiscoCache) AtomicReference(java.util.concurrent.atomic.AtomicReference) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) GridKernalContext(org.apache.ignite.internal.GridKernalContext) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) BiPredicate(java.util.function.BiPredicate) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgnitePredicate(org.apache.ignite.lang.IgnitePredicate) IgniteIllegalStateException(org.apache.ignite.IgniteIllegalStateException) S(org.apache.ignite.internal.util.typedef.internal.S) METASTORAGE_CACHE_NAME(org.apache.ignite.internal.processors.cache.persistence.metastorage.MetaStorage.METASTORAGE_CACHE_NAME) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) RESTORE_CACHE_GROUP_SNAPSHOT_PREPARE(org.apache.ignite.internal.util.distributed.DistributedProcess.DistributedProcessType.RESTORE_CACHE_GROUP_SNAPSHOT_PREPARE) RESTORE_CACHE_GROUP_SNAPSHOT_PRELOAD(org.apache.ignite.internal.util.distributed.DistributedProcess.DistributedProcessType.RESTORE_CACHE_GROUP_SNAPSHOT_PRELOAD) DistributedProcess(org.apache.ignite.internal.util.distributed.DistributedProcess) F(org.apache.ignite.internal.util.typedef.F) Files(java.nio.file.Files) Optional.ofNullable(java.util.Optional.ofNullable) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) IOException(java.io.IOException) GridAffinityAssignmentCache(org.apache.ignite.internal.processors.affinity.GridAffinityAssignmentCache) MetricRegistry(org.apache.ignite.internal.processors.metric.MetricRegistry) File(java.io.File) Consumer(java.util.function.Consumer) GridCacheSharedContext(org.apache.ignite.internal.processors.cache.GridCacheSharedContext) RESTORE_CACHE_GROUP_SNAPSHOT_START(org.apache.ignite.internal.util.distributed.DistributedProcess.DistributedProcessType.RESTORE_CACHE_GROUP_SNAPSHOT_START) DiscoveryDataClusterState(org.apache.ignite.internal.processors.cluster.DiscoveryDataClusterState) Paths(java.nio.file.Paths) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) IgniteFinishedFutureImpl(org.apache.ignite.internal.util.future.IgniteFinishedFutureImpl) Collections(java.util.Collections) IgniteUuid(org.apache.ignite.lang.IgniteUuid) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) List(java.util.List) ArrayList(java.util.ArrayList) UUID(java.util.UUID) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet)

Example 13 with BiPredicate

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));
            });
        }
    };
}
Also used : Response(suite.http.Http.Response) Build(primal.Verbs.Build) Random(java.util.Random) Session(suite.http.Http.Session) SecureRandom(java.security.SecureRandom) BiPredicate(java.util.function.BiPredicate) Response(suite.http.Http.Response) Request(suite.http.Http.Request) SessionManager(suite.http.Http.SessionManager) Pull(primal.MoreVerbs.Pull) Equals(primal.Verbs.Equals) PerList(primal.persistent.PerList) Handler(suite.http.Http.Handler) HtmlUtil(suite.util.HtmlUtil) Request(suite.http.Http.Request) Handler(suite.http.Http.Handler) PerList(primal.persistent.PerList) Session(suite.http.Http.Session)

Example 14 with BiPredicate

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);
}
Also used : lombok.val(lombok.val) TableAttributes(io.pravega.segmentstore.contracts.tables.TableAttributes) Attributes(io.pravega.segmentstore.contracts.Attributes) Iterator(java.util.Iterator) AssertExtensions(io.pravega.test.common.AssertExtensions) AttributeId(io.pravega.segmentstore.contracts.AttributeId) lombok.val(lombok.val) HashMap(java.util.HashMap) Random(java.util.Random) Test(org.junit.Test) Collectors(java.util.stream.Collectors) SegmentMetadataComparer(io.pravega.segmentstore.server.SegmentMetadataComparer) ImmutableDate(io.pravega.common.util.ImmutableDate) UpdateableSegmentMetadata(io.pravega.segmentstore.server.UpdateableSegmentMetadata) ArrayList(java.util.ArrayList) Consumer(java.util.function.Consumer) BiPredicate(java.util.function.BiPredicate) SegmentType(io.pravega.segmentstore.contracts.SegmentType) Stream(java.util.stream.Stream) Rule(org.junit.Rule) Map(java.util.Map) Timeout(org.junit.rules.Timeout) Assert(org.junit.Assert) Collections(java.util.Collections) Random(java.util.Random) HashMap(java.util.HashMap) AttributeId(io.pravega.segmentstore.contracts.AttributeId) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 15 with BiPredicate

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);
        }
    }
}
Also used : JerseyResourceContext(org.glassfish.jersey.server.internal.JerseyResourceContext) ComponentBag(org.glassfish.jersey.model.internal.ComponentBag) RankedComparator(org.glassfish.jersey.model.internal.RankedComparator) SecurityContext(javax.ws.rs.core.SecurityContext) Errors(org.glassfish.jersey.internal.Errors) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ModelProcessor(org.glassfish.jersey.server.model.ModelProcessor) ComponentProvider(org.glassfish.jersey.server.spi.ComponentProvider) Application(javax.ws.rs.core.Application) JerseyResourceContext(org.glassfish.jersey.server.internal.JerseyResourceContext) ContainerLifecycleListener(org.glassfish.jersey.server.spi.ContainerLifecycleListener) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) ContainerResponseFilter(javax.ws.rs.container.ContainerResponseFilter) RankedProvider(org.glassfish.jersey.model.internal.RankedProvider) JerseyRequestTimeoutHandler(org.glassfish.jersey.server.internal.JerseyRequestTimeoutHandler) ExecutorProviders(org.glassfish.jersey.process.internal.ExecutorProviders) Stages(org.glassfish.jersey.process.internal.Stages) Future(java.util.concurrent.Future) Ref(org.glassfish.jersey.internal.util.collection.Ref) ReaderInterceptor(javax.ws.rs.ext.ReaderInterceptor) Map(java.util.Map) ProviderBinder(org.glassfish.jersey.internal.inject.ProviderBinder) RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) ModelErrors(org.glassfish.jersey.server.model.internal.ModelErrors) ApplicationEvent(org.glassfish.jersey.server.monitoring.ApplicationEvent) Values(org.glassfish.jersey.internal.util.collection.Values) ContainerResponseWriter(org.glassfish.jersey.server.spi.ContainerResponseWriter) LocalizationMessages(org.glassfish.jersey.server.internal.LocalizationMessages) IdentityHashMap(java.util.IdentityHashMap) RuntimeType(javax.ws.rs.RuntimeType) Collection(java.util.Collection) Version(org.glassfish.jersey.internal.Version) MessageBodyWorkers(org.glassfish.jersey.message.MessageBodyWorkers) Container(org.glassfish.jersey.server.spi.Container) Set(java.util.Set) ContractProvider(org.glassfish.jersey.model.ContractProvider) ResourceModel(org.glassfish.jersey.server.model.ResourceModel) Providers(org.glassfish.jersey.internal.inject.Providers) Logger(java.util.logging.Logger) ModelValidationException(org.glassfish.jersey.server.model.ModelValidationException) Collectors(java.util.stream.Collectors) ChainableStage(org.glassfish.jersey.process.internal.ChainableStage) PreMatching(javax.ws.rs.container.PreMatching) GenericType(javax.ws.rs.core.GenericType) DynamicFeature(javax.ws.rs.container.DynamicFeature) List(java.util.List) Principal(java.security.Principal) HttpHeaders(javax.ws.rs.core.HttpHeaders) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) MonitoringContainerListener(org.glassfish.jersey.server.internal.monitoring.MonitoringContainerListener) Spliterator(java.util.Spliterator) Resource(org.glassfish.jersey.server.model.Resource) CommonProperties(org.glassfish.jersey.CommonProperties) Configuration(javax.ws.rs.core.Configuration) Order(org.glassfish.jersey.model.internal.RankedComparator.Order) CompletableFuture(java.util.concurrent.CompletableFuture) AbstractBinder(org.glassfish.jersey.internal.inject.AbstractBinder) Singleton(javax.inject.Singleton) Binder(org.glassfish.jersey.internal.inject.Binder) Function(java.util.function.Function) Supplier(java.util.function.Supplier) HttpMethod(javax.ws.rs.HttpMethod) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) ApplicationEventListener(org.glassfish.jersey.server.monitoring.ApplicationEventListener) BiPredicate(java.util.function.BiPredicate) ReferencesInitializer(org.glassfish.jersey.server.internal.process.ReferencesInitializer) Value(org.glassfish.jersey.internal.util.collection.Value) ApplicationEventImpl(org.glassfish.jersey.server.internal.monitoring.ApplicationEventImpl) ExternalRequestScope(org.glassfish.jersey.server.spi.ExternalRequestScope) Routing(org.glassfish.jersey.server.internal.routing.Routing) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) LazyValue(org.glassfish.jersey.internal.util.collection.LazyValue) StreamSupport(java.util.stream.StreamSupport) WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) Injections(org.glassfish.jersey.internal.inject.Injections) LinkedList(java.util.LinkedList) OutputStream(java.io.OutputStream) CompositeApplicationEventListener(org.glassfish.jersey.server.internal.monitoring.CompositeApplicationEventListener) Iterator(java.util.Iterator) ServiceConfigurationError(org.glassfish.jersey.internal.ServiceConfigurationError) ProcessingProviders(org.glassfish.jersey.server.internal.ProcessingProviders) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ReflectionHelper(org.glassfish.jersey.internal.util.ReflectionHelper) TimeUnit(java.util.concurrent.TimeUnit) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ComponentModelValidator(org.glassfish.jersey.server.model.ComponentModelValidator) NameBinding(javax.ws.rs.NameBinding) CompositeBinder(org.glassfish.jersey.internal.inject.CompositeBinder) Stage(org.glassfish.jersey.process.internal.Stage) ServiceFinder(org.glassfish.jersey.internal.ServiceFinder) NullOutputStream(org.glassfish.jersey.message.internal.NullOutputStream) Collections(java.util.Collections) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) ContractProvider(org.glassfish.jersey.model.ContractProvider)

Aggregations

BiPredicate (java.util.function.BiPredicate)36 List (java.util.List)17 Collectors (java.util.stream.Collectors)16 ArrayList (java.util.ArrayList)14 IOException (java.io.IOException)12 Collections (java.util.Collections)12 Map (java.util.Map)11 Files (java.nio.file.Files)10 Objects (java.util.Objects)8 Set (java.util.Set)8 HashMap (java.util.HashMap)7 Paths (java.nio.file.Paths)6 Arrays (java.util.Arrays)6 HashSet (java.util.HashSet)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 HasContainer (org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer)6 Path (java.nio.file.Path)5 java.util (java.util)5 Collection (java.util.Collection)5 Function (java.util.function.Function)5