Search in sources :

Example 16 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 17 with Predicate

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

the class TestShortestPath method withFilters.

@Test
public void withFilters() throws Exception {
    // Layout:
    //
    // (a)-->(b)-->(c)-->(d)
    //   \               ^
    //    -->(g)-->(h)--/
    //
    graph.makeEdgeChain("a,b,c,d");
    graph.makeEdgeChain("a,g,h,d");
    final Node a = graph.getNode("a");
    final Node d = graph.getNode("d");
    final Node b = graph.getNode("b");
    b.setProperty("skip", true);
    final Predicate<Node> filter = item -> {
        final boolean skip = (Boolean) item.getProperty("skip", false);
        return !skip;
    };
    testShortestPathFinder(finder -> assertPaths(finder.findAllPaths(a, d), "a,g,h,d"), ((StandardExpander) PathExpanders.allTypesAndDirections()).addNodeFilter(filter), 10);
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) Arrays(java.util.Arrays) ResourceIterator(org.neo4j.graphdb.ResourceIterator) MutableInt(org.apache.commons.lang3.mutable.MutableInt) Label(org.neo4j.graphdb.Label) Direction(org.neo4j.graphdb.Direction) PathFinder(org.neo4j.graphalgo.PathFinder) OUTGOING(org.neo4j.graphdb.Direction.OUTGOING) GraphAlgoFactory.shortestPath(org.neo4j.graphalgo.GraphAlgoFactory.shortestPath) PathExpanders(org.neo4j.graphdb.PathExpanders) Node(org.neo4j.graphdb.Node) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Assert.assertThat(org.junit.Assert.assertThat) BOTH(org.neo4j.graphdb.Direction.BOTH) PathExpander(org.neo4j.graphdb.PathExpander) Arrays.asList(java.util.Arrays.asList) R1(common.Neo4jAlgoTestCase.MyRelTypes.R1) StandardExpander(org.neo4j.graphdb.impl.StandardExpander) Iterator(java.util.Iterator) Predicate(java.util.function.Predicate) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Neo4jAlgoTestCase(common.Neo4jAlgoTestCase) INCOMING(org.neo4j.graphdb.Direction.INCOMING) BranchState(org.neo4j.graphdb.traversal.BranchState) Path(org.neo4j.graphdb.Path) List(java.util.List) Relationship(org.neo4j.graphdb.Relationship) Iterables(org.neo4j.helpers.collection.Iterables) Assert.assertFalse(org.junit.Assert.assertFalse) PathExpanders.allTypesAndDirections(org.neo4j.graphdb.PathExpanders.allTypesAndDirections) RelationshipType(org.neo4j.graphdb.RelationshipType) Assert.assertEquals(org.junit.Assert.assertEquals) Node(org.neo4j.graphdb.Node) Test(org.junit.Test)

Example 18 with Predicate

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

the class StoreMigrator method moveMigratedFiles.

@Override
public void moveMigratedFiles(File migrationDir, File storeDir, String versionToUpgradeFrom, String versionToUpgradeTo) throws IOException {
    // Move the migrated ones into the store directory
    StoreFile.fileOperation(MOVE, fileSystem, migrationDir, storeDir, StoreFile.currentStoreFiles(), // allow to skip non existent source files
    true, // allow to overwrite target files
    ExistingTargetStrategy.OVERWRITE, StoreFileType.values());
    // move the files with the page cache.
    try {
        Iterable<FileHandle> fileHandles = pageCache.streamFilesRecursive(migrationDir)::iterator;
        for (FileHandle fh : fileHandles) {
            Predicate<StoreFile> predicate = storeFile -> storeFile.fileName(StoreFileType.STORE).equals(fh.getFile().getName());
            if (StreamSupport.stream(StoreFile.currentStoreFiles().spliterator(), false).anyMatch(predicate)) {
                final Optional<PagedFile> optionalPagedFile = pageCache.getExistingMapping(fh.getFile());
                if (optionalPagedFile.isPresent()) {
                    optionalPagedFile.get().close();
                }
                fh.rename(new File(storeDir, fh.getFile().getName()), StandardCopyOption.REPLACE_EXISTING);
            }
        }
    } catch (NoSuchFileException e) {
    //This means that we had no files only present in the page cache, this is fine.
    }
    RecordFormats oldFormat = selectForVersion(versionToUpgradeFrom);
    RecordFormats newFormat = selectForVersion(versionToUpgradeTo);
    boolean movingAwayFromVersionTrailers = oldFormat.hasCapability(VERSION_TRAILERS) && !newFormat.hasCapability(VERSION_TRAILERS);
    if (movingAwayFromVersionTrailers) {
        StoreFile.removeTrailers(versionToUpgradeFrom, fileSystem, storeDir, pageCache.pageSize());
    }
    File neoStore = new File(storeDir, MetaDataStore.DEFAULT_NAME);
    long logVersion = MetaDataStore.getRecord(pageCache, neoStore, Position.LOG_VERSION);
    long lastCommittedTx = MetaDataStore.getRecord(pageCache, neoStore, Position.LAST_TRANSACTION_ID);
    // update or add upgrade id and time and other necessary neostore records
    updateOrAddNeoStoreFieldsAsPartOfMigration(migrationDir, storeDir, versionToUpgradeTo);
    // delete old logs
    legacyLogs.deleteUnusedLogFiles(storeDir);
    if (movingAwayFromVersionTrailers) {
        // write a check point in the log in order to make recovery work in the newer version
        new StoreMigratorCheckPointer(storeDir, fileSystem).checkPoint(logVersion, lastCommittedTx);
    }
}
Also used : PropertyDeduplicator(org.neo4j.kernel.impl.storemigration.legacystore.v21.propertydeduplication.PropertyDeduplicator) Arrays(java.util.Arrays) PageCursor(org.neo4j.io.pagecache.PageCursor) NullLogProvider(org.neo4j.logging.NullLogProvider) StringUtils(org.apache.commons.lang3.StringUtils) UNKNOWN_TX_COMMIT_TIMESTAMP(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.UNKNOWN_TX_COMMIT_TIMESTAMP) COPY(org.neo4j.kernel.impl.storemigration.FileOperation.COPY) SchemaIndexProvider(org.neo4j.kernel.api.index.SchemaIndexProvider) CountsComputer(org.neo4j.kernel.impl.store.CountsComputer) Arrays.asList(java.util.Arrays.asList) BASE_TX_COMMIT_TIMESTAMP(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.BASE_TX_COMMIT_TIMESTAMP) Position(org.neo4j.kernel.impl.store.MetaDataStore.Position) Lifespan(org.neo4j.kernel.lifecycle.Lifespan) RecordCursors(org.neo4j.kernel.impl.store.RecordCursors) SilentMigrationProgressMonitor(org.neo4j.kernel.impl.storemigration.monitoring.SilentMigrationProgressMonitor) StandardCharsets(java.nio.charset.StandardCharsets) MetaDataRecordFormat(org.neo4j.kernel.impl.store.format.standard.MetaDataRecordFormat) DELETE(org.neo4j.kernel.impl.storemigration.FileOperation.DELETE) Stream(java.util.stream.Stream) ExecutionSupervisors.withDynamicProcessorAssignment(org.neo4j.unsafe.impl.batchimport.staging.ExecutionSupervisors.withDynamicProcessorAssignment) StoreType(org.neo4j.kernel.impl.store.StoreType) BatchImporter(org.neo4j.unsafe.impl.batchimport.BatchImporter) NodeStore(org.neo4j.kernel.impl.store.NodeStore) StoreFactory(org.neo4j.kernel.impl.store.StoreFactory) Collectors(org.neo4j.unsafe.impl.batchimport.input.Collectors) PagedFile(org.neo4j.io.pagecache.PagedFile) VERSION_TRAILERS(org.neo4j.kernel.impl.store.format.Capability.VERSION_TRAILERS) FormatFamily(org.neo4j.kernel.impl.store.format.FormatFamily) Supplier(java.util.function.Supplier) UNKNOWN_TX_CHECKSUM(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.UNKNOWN_TX_CHECKSUM) BufferedOutputStream(java.io.BufferedOutputStream) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) TransactionId(org.neo4j.kernel.impl.store.TransactionId) StandardV2_2(org.neo4j.kernel.impl.store.format.standard.StandardV2_2) LogPosition(org.neo4j.kernel.impl.transaction.log.LogPosition) StandardV2_1(org.neo4j.kernel.impl.store.format.standard.StandardV2_1) RelationshipStore(org.neo4j.kernel.impl.store.RelationshipStore) StandardV2_0(org.neo4j.kernel.impl.store.format.standard.StandardV2_0) IdMappers(org.neo4j.unsafe.impl.batchimport.cache.idmapping.IdMappers) BiConsumer(java.util.function.BiConsumer) IdGenerators(org.neo4j.unsafe.impl.batchimport.cache.idmapping.IdGenerators) StreamSupport(java.util.stream.StreamSupport) DirectRecordStoreMigrator(org.neo4j.kernel.impl.storemigration.DirectRecordStoreMigrator) CoarseBoundedProgressExecutionMonitor(org.neo4j.unsafe.impl.batchimport.staging.CoarseBoundedProgressExecutionMonitor) StoreFile(org.neo4j.kernel.impl.storemigration.StoreFile) FileOutputStream(java.io.FileOutputStream) RecordFormatSelector.selectForVersion(org.neo4j.kernel.impl.store.format.RecordFormatSelector.selectForVersion) IOException(java.io.IOException) NodeRecordFormat(org.neo4j.kernel.impl.store.format.standard.NodeRecordFormat) LegacyLogs(org.neo4j.kernel.impl.storemigration.legacylogs.LegacyLogs) File(java.io.File) Iterables(org.neo4j.helpers.collection.Iterables) ParallelBatchImporter(org.neo4j.unsafe.impl.batchimport.ParallelBatchImporter) NodeRecord(org.neo4j.kernel.impl.store.record.NodeRecord) Configuration(org.neo4j.unsafe.impl.batchimport.Configuration) BufferedReader(java.io.BufferedReader) MigrationProgressMonitor(org.neo4j.kernel.impl.storemigration.monitoring.MigrationProgressMonitor) RelationshipRecord(org.neo4j.kernel.impl.store.record.RelationshipRecord) StoreUpgrader(org.neo4j.kernel.impl.storemigration.StoreUpgrader) NoSuchFileException(java.nio.file.NoSuchFileException) BASE_TX_LOG_VERSION(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.BASE_TX_LOG_VERSION) BASE_TX_CHECKSUM(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.BASE_TX_CHECKSUM) PageCache(org.neo4j.io.pagecache.PageCache) InputNode(org.neo4j.unsafe.impl.batchimport.input.InputNode) Predicate(java.util.function.Predicate) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) MOVE(org.neo4j.kernel.impl.storemigration.FileOperation.MOVE) LogService(org.neo4j.kernel.impl.logging.LogService) List(java.util.List) StoreFileType(org.neo4j.kernel.impl.storemigration.StoreFileType) MetaDataStore(org.neo4j.kernel.impl.store.MetaDataStore) Writer(java.io.Writer) Optional(java.util.Optional) Inputs(org.neo4j.unsafe.impl.batchimport.input.Inputs) InputIterable(org.neo4j.unsafe.impl.batchimport.InputIterable) InputRelationship(org.neo4j.unsafe.impl.batchimport.input.InputRelationship) TransactionIdStore(org.neo4j.kernel.impl.transaction.log.TransactionIdStore) InputEntity(org.neo4j.unsafe.impl.batchimport.input.InputEntity) DEFAULT_NAME(org.neo4j.kernel.impl.store.MetaDataStore.DEFAULT_NAME) RecordFormats(org.neo4j.kernel.impl.store.format.RecordFormats) CustomIOConfigValidator(org.neo4j.kernel.impl.util.CustomIOConfigValidator) AdditionalInitialIds(org.neo4j.unsafe.impl.batchimport.AdditionalInitialIds) NeoStores(org.neo4j.kernel.impl.store.NeoStores) StorePropertyCursor(org.neo4j.kernel.impl.api.store.StorePropertyCursor) CountsTracker(org.neo4j.kernel.impl.store.counts.CountsTracker) ExistingTargetStrategy(org.neo4j.kernel.impl.storemigration.ExistingTargetStrategy) PhysicalLogFiles(org.neo4j.kernel.impl.transaction.log.PhysicalLogFiles) RelationshipRecordFormat(org.neo4j.kernel.impl.store.format.standard.RelationshipRecordFormat) OutputStream(java.io.OutputStream) Config(org.neo4j.kernel.configuration.Config) ReadOnlyIdGeneratorFactory(org.neo4j.kernel.impl.store.id.ReadOnlyIdGeneratorFactory) LockService(org.neo4j.kernel.impl.locking.LockService) FileHandle(org.neo4j.io.pagecache.FileHandle) CapabilityType(org.neo4j.kernel.impl.store.format.CapabilityType) PrimitiveRecord(org.neo4j.kernel.impl.store.record.PrimitiveRecord) FIELD_NOT_PRESENT(org.neo4j.kernel.impl.store.format.standard.MetaDataRecordFormat.FIELD_NOT_PRESENT) StoreMigratorCheckPointer(org.neo4j.kernel.impl.storemigration.StoreMigratorCheckPointer) ExecutionMonitor(org.neo4j.unsafe.impl.batchimport.staging.ExecutionMonitor) BASE_TX_LOG_BYTE_OFFSET(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.BASE_TX_LOG_BYTE_OFFSET) FileSystemAbstraction(org.neo4j.io.fs.FileSystemAbstraction) PagedFile(org.neo4j.io.pagecache.PagedFile) FileHandle(org.neo4j.io.pagecache.FileHandle) NoSuchFileException(java.nio.file.NoSuchFileException) RecordFormats(org.neo4j.kernel.impl.store.format.RecordFormats) StoreFile(org.neo4j.kernel.impl.storemigration.StoreFile) PagedFile(org.neo4j.io.pagecache.PagedFile) StoreFile(org.neo4j.kernel.impl.storemigration.StoreFile) File(java.io.File) StoreMigratorCheckPointer(org.neo4j.kernel.impl.storemigration.StoreMigratorCheckPointer)

Example 19 with Predicate

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

the class ProviderBinder method bindProviders.

/**
     * Bind all providers contained in {@code p roviderBag} (classes and instances) using injection manager. Configuration is
     * also committed.
     *
     * @param componentBag      bag of provider classes and instances.
     * @param constrainedTo     current runtime (client or server).
     * @param registeredClasses classes which are manually registered by the user (not found by the classpath scanning).
     * @param injectionManager  injection manager the binder will use to bind the providers into.
     */
public static void bindProviders(ComponentBag componentBag, RuntimeType constrainedTo, Set<Class<?>> registeredClasses, InjectionManager injectionManager) {
    Predicate<ContractProvider> filter = ComponentBag.EXCLUDE_EMPTY.and(ComponentBag.excludeMetaProviders(injectionManager));
    /*
         * Check the {@code component} whether it is correctly configured for client or server {@link RuntimeType runtime}.
         */
    Predicate<Class<?>> correctlyConfigured = componentClass -> Providers.checkProviderRuntime(componentClass, componentBag.getModel(componentClass), constrainedTo, registeredClasses == null || !registeredClasses.contains(componentClass), false);
    /*
         * These binder will be register to Bean Manager at the and of method because of a bulk registration to avoid register
         * each binder alone.
         */
    Collection<Binder> binderToRegister = new ArrayList<>();
    // Bind provider classes except for pure meta-providers and providers with empty contract models (e.g. resources)
    Set<Class<?>> classes = new LinkedHashSet<>(componentBag.getClasses(filter));
    if (constrainedTo != null) {
        classes = classes.stream().filter(correctlyConfigured).collect(Collectors.toSet());
    }
    for (final Class<?> providerClass : classes) {
        final ContractProvider model = componentBag.getModel(providerClass);
        binderToRegister.addAll(createProviderBinders(providerClass, model));
    }
    // Bind pure provider instances except for pure meta-providers and providers with empty contract models (e.g. resources)
    Set<Object> instances = componentBag.getInstances(filter);
    if (constrainedTo != null) {
        instances = instances.stream().filter(component -> correctlyConfigured.test(component.getClass())).collect(Collectors.toSet());
    }
    for (final Object provider : instances) {
        final ContractProvider model = componentBag.getModel(provider.getClass());
        binderToRegister.addAll(createProviderBinders(provider, model));
    }
    injectionManager.register(CompositeBinder.wrap(binderToRegister));
}
Also used : Arrays(java.util.Arrays) RuntimeType(javax.ws.rs.RuntimeType) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ComponentBag(org.glassfish.jersey.model.internal.ComponentBag) Set(java.util.Set) ContractProvider(org.glassfish.jersey.model.ContractProvider) Singleton(javax.inject.Singleton) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) List(java.util.List) Annotation(java.lang.annotation.Annotation) Collections(java.util.Collections) LinkedHashSet(java.util.LinkedHashSet) LinkedHashSet(java.util.LinkedHashSet) ContractProvider(org.glassfish.jersey.model.ContractProvider) ArrayList(java.util.ArrayList)

Example 20 with Predicate

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

the class GeneratorMine method getGen.

@Nullable
private static WorldGenerator getGen(@Nullable IBlockState ore, int density) {
    Predicate<IBlockState> genCheck = state -> RailcraftConfig.isWorldGenEnabled("sky") ? GenTools.AIR_STONE.test(state) : GenTools.STONE.test(state);
    WorldGenerator gen;
    if (ore == null)
        gen = null;
    else if (density >= 4)
        gen = new WorldGenMinable(ore, density, genCheck::test);
    else
        gen = new WorldGenSmallDeposits(ore, density, genCheck);
    return gen;
}
Also used : java.util(java.util) NoiseGenSimplex(mods.railcraft.common.worldgen.NoiseGen.NoiseGenSimplex) World(net.minecraft.world.World) Predicate(java.util.function.Predicate) EventType(net.minecraftforge.event.terraingen.OreGenEvent.GenerateMinable.EventType) Metal(mods.railcraft.common.items.Metal) BlockPos(net.minecraft.util.math.BlockPos) WorldGenMinable(net.minecraft.world.gen.feature.WorldGenMinable) IBlockState(net.minecraft.block.state.IBlockState) WorldGenerator(net.minecraft.world.gen.feature.WorldGenerator) BiomeDictionary(net.minecraftforge.common.BiomeDictionary) Type(net.minecraftforge.common.BiomeDictionary.Type) RailcraftConfig(mods.railcraft.common.core.RailcraftConfig) TerrainGen(net.minecraftforge.event.terraingen.TerrainGen) MapMaker(com.google.common.collect.MapMaker) Biome(net.minecraft.world.biome.Biome) Nullable(javax.annotation.Nullable) WorldGenerator(net.minecraft.world.gen.feature.WorldGenerator) IBlockState(net.minecraft.block.state.IBlockState) WorldGenMinable(net.minecraft.world.gen.feature.WorldGenMinable) Nullable(javax.annotation.Nullable)

Aggregations

Predicate (java.util.function.Predicate)120 List (java.util.List)49 Map (java.util.Map)34 Collectors (java.util.stream.Collectors)31 Test (org.junit.Test)30 IOException (java.io.IOException)28 ArrayList (java.util.ArrayList)26 Arrays (java.util.Arrays)25 Collections (java.util.Collections)23 Set (java.util.Set)15 Function (java.util.function.Function)14 Assert.assertEquals (org.junit.Assert.assertEquals)14 java.util (java.util)13 Optional (java.util.Optional)13 Supplier (java.util.function.Supplier)13 HashMap (java.util.HashMap)12 Before (org.junit.Before)12 Objects (java.util.Objects)11 InputStream (java.io.InputStream)10 AssertExtensions (io.pravega.test.common.AssertExtensions)9