Search in sources :

Example 11 with Predicate

use of java.util.function.Predicate in project neo4j by neo4j.

the class TestBidirectionalTraversal method mirroredTraversalReversesInitialState.

@Test
public void mirroredTraversalReversesInitialState() throws Exception {
    /*
         * (a)-->(b)-->(c)-->(d)
         */
    createGraph("a TO b", "b TO c", "c TO d");
    BranchCollisionPolicy collisionPolicy = new BranchCollisionPolicy() {

        @Override
        public BranchCollisionDetector create(Evaluator evaluator, Predicate<Path> pathPredicate) {
            return new StandardBranchCollisionDetector(null, null) {

                @Override
                protected boolean includePath(Path path, TraversalBranch startPath, TraversalBranch endPath) {
                    assertEquals(0, startPath.state());
                    assertEquals(10, endPath.state());
                    return true;
                }
            };
        }
    };
    Iterables.count(getGraphDb().bidirectionalTraversalDescription().mirroredSides(getGraphDb().traversalDescription().uniqueness(NODE_PATH).expand(PathExpanders.<Integer>forType(to), new InitialBranchState.State<>(0, 10))).collisionPolicy(collisionPolicy).traverse(getNodeWithName("a"), getNodeWithName("d")));
}
Also used : Path(org.neo4j.graphdb.Path) BranchCollisionPolicy(org.neo4j.graphdb.traversal.BranchCollisionPolicy) InitialBranchState(org.neo4j.graphdb.traversal.InitialBranchState) StandardBranchCollisionDetector(org.neo4j.graphdb.impl.traversal.StandardBranchCollisionDetector) Evaluator(org.neo4j.graphdb.traversal.Evaluator) TraversalBranch(org.neo4j.graphdb.traversal.TraversalBranch) Predicate(java.util.function.Predicate) Test(org.junit.Test)

Example 12 with Predicate

use of java.util.function.Predicate in project neo4j by neo4j.

the class ClusterManager method allSeesAllAsJoined.

public static Predicate<ManagedCluster> allSeesAllAsJoined() {
    return new Predicate<ManagedCluster>() {

        @Override
        public boolean test(ManagedCluster cluster) {
            int clusterSize = cluster.size();
            int clusterMembersChecked = 0;
            for (HighlyAvailableGraphDatabase database : cluster.getAllMembers()) {
                clusterMembersChecked++;
                ClusterMembers members = database.getDependencyResolver().resolveDependency(ClusterMembers.class);
                if (count(members.getMembers()) < clusterSize) {
                    return false;
                }
            }
            for (ObservedClusterMembers arbiter : cluster.getArbiters()) {
                clusterMembersChecked++;
                if (count(arbiter.getMembers()) < clusterSize) {
                    return false;
                }
            }
            // Everyone sees everyone else as joined!
            return clusterMembersChecked > 0;
        }

        @Override
        public String toString() {
            return "All instances should see all others as joined";
        }
    };
}
Also used : ObservedClusterMembers(org.neo4j.kernel.ha.cluster.member.ObservedClusterMembers) HighlyAvailableGraphDatabase(org.neo4j.kernel.ha.HighlyAvailableGraphDatabase) ClusterMembers(org.neo4j.kernel.ha.cluster.member.ClusterMembers) ObservedClusterMembers(org.neo4j.kernel.ha.cluster.member.ObservedClusterMembers) Predicate(java.util.function.Predicate)

Example 13 with Predicate

use of java.util.function.Predicate in project helios by spotify.

the class HostsResource method list.

/**
   * Returns the list of hostnames of known hosts/agents.
   * @return The list of hostnames.
   */
@GET
@Produces(APPLICATION_JSON)
@Timed
@ExceptionMetered
public List<String> list(@QueryParam("namePattern") final String namePattern, @QueryParam("selector") final List<String> hostSelectors) {
    List<String> hosts = model.listHosts();
    if (namePattern != null) {
        final Predicate<String> matchesPattern = Pattern.compile(namePattern).asPredicate();
        hosts = hosts.stream().filter(matchesPattern).collect(Collectors.toList());
    }
    if (!hostSelectors.isEmpty()) {
        // check that all supplied selectors are parseable/valid
        final List<HostSelector> selectors = hostSelectors.stream().map(selectorStr -> {
            final HostSelector parsed = HostSelector.parse(selectorStr);
            if (parsed == null) {
                throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Invalid host selector: " + selectorStr).build());
            }
            return parsed;
        }).collect(Collectors.toList());
        final Map<String, Map<String, String>> hostsAndLabels = getLabels(hosts);
        final HostMatcher matcher = new HostMatcher(hostsAndLabels);
        hosts = matcher.getMatchingHosts(selectors);
    }
    return hosts;
}
Also used : Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) SetGoalResponse(com.spotify.helios.common.protocol.SetGoalResponse) HostRegisterResponse(com.spotify.helios.common.protocol.HostRegisterResponse) Valid(javax.validation.Valid) QueryParam(javax.ws.rs.QueryParam) Optional(com.google.common.base.Optional) JobUndeployResponse(com.spotify.helios.common.protocol.JobUndeployResponse) Map(java.util.Map) INVALID_ID(com.spotify.helios.common.protocol.JobUndeployResponse.Status.INVALID_ID) Deployment(com.spotify.helios.common.descriptors.Deployment) DefaultValue(javax.ws.rs.DefaultValue) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) HostStillInUseException(com.spotify.helios.master.HostStillInUseException) JobDeployResponse(com.spotify.helios.common.protocol.JobDeployResponse) DELETE(javax.ws.rs.DELETE) HostMatcher(com.spotify.helios.master.HostMatcher) Responses.notFound(com.spotify.helios.master.http.Responses.notFound) JobDoesNotExistException(com.spotify.helios.master.JobDoesNotExistException) FORBIDDEN(com.spotify.helios.common.protocol.JobUndeployResponse.Status.FORBIDDEN) Predicate(java.util.function.Predicate) JOB_NOT_FOUND(com.spotify.helios.common.protocol.JobUndeployResponse.Status.JOB_NOT_FOUND) Collectors(java.util.stream.Collectors) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) JobPortAllocationConflictException(com.spotify.helios.master.JobPortAllocationConflictException) WebApplicationException(javax.ws.rs.WebApplicationException) Responses.badRequest(com.spotify.helios.master.http.Responses.badRequest) Pattern(java.util.regex.Pattern) JobId(com.spotify.helios.common.descriptors.JobId) PathParam(javax.ws.rs.PathParam) HOST_NOT_FOUND(com.spotify.helios.common.protocol.JobUndeployResponse.Status.HOST_NOT_FOUND) GET(javax.ws.rs.GET) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) OK(com.spotify.helios.common.protocol.JobUndeployResponse.Status.OK) PATCH(com.spotify.helios.master.http.PATCH) Function(java.util.function.Function) Responses.forbidden(com.spotify.helios.master.http.Responses.forbidden) HostSelector(com.spotify.helios.common.descriptors.HostSelector) EMPTY_TOKEN(com.spotify.helios.common.descriptors.Job.EMPTY_TOKEN) HostStatus(com.spotify.helios.common.descriptors.HostStatus) HostNotFoundException(com.spotify.helios.master.HostNotFoundException) JobAlreadyDeployedException(com.spotify.helios.master.JobAlreadyDeployedException) MasterModel(com.spotify.helios.master.MasterModel) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) HostDeregisterResponse(com.spotify.helios.common.protocol.HostDeregisterResponse) Maps(com.google.common.collect.Maps) TokenVerificationException(com.spotify.helios.master.TokenVerificationException) PUT(javax.ws.rs.PUT) JobNotDeployedException(com.spotify.helios.master.JobNotDeployedException) WebApplicationException(javax.ws.rs.WebApplicationException) HostSelector(com.spotify.helios.common.descriptors.HostSelector) Map(java.util.Map) HostMatcher(com.spotify.helios.master.HostMatcher) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 14 with Predicate

use of java.util.function.Predicate in project platform_frameworks_base by android.

the class RecentsProvider method call.

@Override
public Bundle call(String method, String arg, Bundle extras) {
    if (METHOD_PURGE.equals(method)) {
        // Purge references to unknown authorities
        final Intent intent = new Intent(DocumentsContract.PROVIDER_INTERFACE);
        final Set<String> knownAuth = Sets.newHashSet();
        for (ResolveInfo info : getContext().getPackageManager().queryIntentContentProviders(intent, 0)) {
            knownAuth.add(info.providerInfo.authority);
        }
        purgeByAuthority(new Predicate<String>() {

            @Override
            public boolean test(String authority) {
                // Purge unknown authorities
                return !knownAuth.contains(authority);
            }
        });
        return null;
    } else if (METHOD_PURGE_PACKAGE.equals(method)) {
        // Purge references to authorities in given package
        final Intent intent = new Intent(DocumentsContract.PROVIDER_INTERFACE);
        intent.setPackage(arg);
        final Set<String> packageAuth = Sets.newHashSet();
        for (ResolveInfo info : getContext().getPackageManager().queryIntentContentProviders(intent, 0)) {
            packageAuth.add(info.providerInfo.authority);
        }
        if (!packageAuth.isEmpty()) {
            purgeByAuthority(new Predicate<String>() {

                @Override
                public boolean test(String authority) {
                    // Purge authority matches
                    return packageAuth.contains(authority);
                }
            });
        }
        return null;
    } else {
        return super.call(method, arg, extras);
    }
}
Also used : ResolveInfo(android.content.pm.ResolveInfo) Set(java.util.Set) Intent(android.content.Intent) DocumentInfo.getCursorString(com.android.documentsui.model.DocumentInfo.getCursorString) Predicate(java.util.function.Predicate)

Example 15 with Predicate

use of java.util.function.Predicate in project cassandra by apache.

the class CompactionController method getPurgeEvaluator.

/**
     * @param key
     * @return a predicate for whether tombstones marked for deletion at the given time for the given partition are
     * purgeable; we calculate this by checking whether the deletion time is less than the min timestamp of all SSTables
     * containing his partition and not participating in the compaction. This means there isn't any data in those
     * sstables that might still need to be suppressed by a tombstone at this timestamp.
     */
public Predicate<Long> getPurgeEvaluator(DecoratedKey key) {
    if (NEVER_PURGE_TOMBSTONES || !compactingRepaired())
        return time -> false;
    overlapIterator.update(key);
    Set<SSTableReader> filteredSSTables = overlapIterator.overlaps();
    Iterable<Memtable> memtables = cfs.getTracker().getView().getAllMemtables();
    long minTimestampSeen = Long.MAX_VALUE;
    boolean hasTimestamp = false;
    for (SSTableReader sstable : filteredSSTables) {
        // we check index file instead.
        if (sstable.getBloomFilter() instanceof AlwaysPresentFilter && sstable.getPosition(key, SSTableReader.Operator.EQ, false) != null || sstable.getBloomFilter().isPresent(key)) {
            minTimestampSeen = Math.min(minTimestampSeen, sstable.getMinTimestamp());
            hasTimestamp = true;
        }
    }
    for (Memtable memtable : memtables) {
        Partition partition = memtable.getPartition(key);
        if (partition != null) {
            minTimestampSeen = Math.min(minTimestampSeen, partition.stats().minTimestamp);
            hasTimestamp = true;
        }
    }
    if (!hasTimestamp)
        return time -> true;
    else {
        final long finalTimestamp = minTimestampSeen;
        return time -> time < finalTimestamp;
    }
}
Also used : java.util(java.util) Iterables(com.google.common.collect.Iterables) Logger(org.slf4j.Logger) OverlapIterator(org.apache.cassandra.utils.OverlapIterator) Predicate(java.util.function.Predicate) TombstoneOption(org.apache.cassandra.schema.CompactionParams.TombstoneOption) LoggerFactory(org.slf4j.LoggerFactory) org.apache.cassandra.db(org.apache.cassandra.db) RateLimiter(com.google.common.util.concurrent.RateLimiter) SSTableReader(org.apache.cassandra.io.sstable.format.SSTableReader) Partition(org.apache.cassandra.db.partitions.Partition) FileDataInput(org.apache.cassandra.io.util.FileDataInput) UnfilteredRowIterator(org.apache.cassandra.db.rows.UnfilteredRowIterator) FileUtils(org.apache.cassandra.io.util.FileUtils) SSTableIntervalTree.buildIntervals(org.apache.cassandra.db.lifecycle.SSTableIntervalTree.buildIntervals) Memtable(org.apache.cassandra.db.Memtable) Predicates(com.google.common.base.Predicates) Refs(org.apache.cassandra.utils.concurrent.Refs) AlwaysPresentFilter(org.apache.cassandra.utils.AlwaysPresentFilter) Partition(org.apache.cassandra.db.partitions.Partition) SSTableReader(org.apache.cassandra.io.sstable.format.SSTableReader) AlwaysPresentFilter(org.apache.cassandra.utils.AlwaysPresentFilter) Memtable(org.apache.cassandra.db.Memtable)

Aggregations

Predicate (java.util.function.Predicate)76 List (java.util.List)34 Map (java.util.Map)21 Arrays (java.util.Arrays)19 IOException (java.io.IOException)18 Collections (java.util.Collections)16 Collectors (java.util.stream.Collectors)16 Test (org.junit.Test)14 ArrayList (java.util.ArrayList)13 Assert.assertEquals (org.junit.Assert.assertEquals)10 Mockito.mock (org.mockito.Mockito.mock)9 InputStream (java.io.InputStream)7 HashMap (java.util.HashMap)7 Optional (java.util.Optional)7 ImmutableList (com.google.common.collect.ImmutableList)6 ImmutableSet (com.google.common.collect.ImmutableSet)6 BufferedReader (java.io.BufferedReader)6 Set (java.util.Set)6 SortedSet (java.util.SortedSet)6 Before (org.junit.Before)6