Search in sources :

Example 16 with Supplier

use of java.util.function.Supplier in project javaslang by javaslang.

the class Lazy method val.

/**
     * Creates a real _lazy value_ of type {@code T}, backed by a {@linkplain java.lang.reflect.Proxy} which delegates
     * to a {@code Lazy} instance.
     *
     * @param supplier A supplier
     * @param type     An interface
     * @param <T>      type of the lazy value
     * @return A new instance of T
     */
@GwtIncompatible("reflection is not supported")
@SuppressWarnings("unchecked")
public static <T> T val(Supplier<? extends T> supplier, Class<T> type) {
    Objects.requireNonNull(supplier, "supplier is null");
    Objects.requireNonNull(type, "type is null");
    if (!type.isInterface()) {
        throw new IllegalArgumentException("type has to be an interface");
    }
    final Lazy<T> lazy = Lazy.of(supplier);
    final InvocationHandler handler = (proxy, method, args) -> method.invoke(lazy.get(), args);
    return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] { type }, handler);
}
Also used : Option(javaslang.control.Option) Proxy(java.lang.reflect.Proxy) Predicate(java.util.function.Predicate) Seq(javaslang.collection.Seq) IOException(java.io.IOException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Serializable(java.io.Serializable) Objects(java.util.Objects) Consumer(java.util.function.Consumer) Iterator(javaslang.collection.Iterator) ObjectOutputStream(java.io.ObjectOutputStream) InvocationHandler(java.lang.reflect.InvocationHandler) NoSuchElementException(java.util.NoSuchElementException) Vector(javaslang.collection.Vector) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 17 with Supplier

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

the class StoreStatementTest method shouldCloseOpenedLabelScanReader.

@Test
public void shouldCloseOpenedLabelScanReader() throws Exception {
    // given
    Supplier<LabelScanReader> scanStore = mock(Supplier.class);
    LabelScanReader scanReader = mock(LabelScanReader.class);
    when(scanStore.get()).thenReturn(scanReader);
    StoreStatement statement = new StoreStatement(MockedNeoStores.basicMockedNeoStores(), mock(Supplier.class), scanStore, LockService.NO_LOCK_SERVICE);
    statement.acquire();
    // when
    LabelScanReader actualReader = statement.getLabelScanReader();
    // then
    assertEquals(scanReader, actualReader);
    // when
    statement.close();
    // then
    verify(scanStore).get();
    verifyNoMoreInteractions(scanStore);
    verify(scanReader).close();
    verifyNoMoreInteractions(scanReader);
}
Also used : LabelScanReader(org.neo4j.storageengine.api.schema.LabelScanReader) Supplier(java.util.function.Supplier) Test(org.junit.Test)

Example 18 with Supplier

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

the class DelayedBufferTest method shouldHandleTheWholeWorkloadShebang.

@Test
public void shouldHandleTheWholeWorkloadShebang() throws Throwable {
    // GIVEN
    final int size = 1_000;
    final long bufferTime = 3;
    VerifyingConsumer consumer = new VerifyingConsumer(size);
    final Clock clock = Clocks.systemClock();
    Supplier<Long> chunkThreshold = clock::millis;
    Predicate<Long> safeThreshold = time -> clock.millis() - bufferTime >= time;
    final DelayedBuffer<Long> buffer = new DelayedBuffer<>(chunkThreshold, safeThreshold, 10, consumer);
    MaintenanceThread maintenance = new MaintenanceThread(buffer, 5);
    Race adders = new Race();
    final int numberOfAdders = 20;
    final byte[] offeredIds = new byte[size];
    for (int i = 0; i < numberOfAdders; i++) {
        final int finalI = i;
        adders.addContestant(new Runnable() {

            @Override
            public void run() {
                for (int j = 0; j < size; j++) {
                    if (j % numberOfAdders == finalI) {
                        buffer.offer(j);
                        offeredIds[j] = 1;
                        parkNanos(MILLISECONDS.toNanos(current().nextInt(2)));
                    }
                }
            }
        });
    }
    // WHEN (multi-threadded) offering of ids
    adders.go();
    // ... ensuring the test is sane itself (did we really offer all these IDs?)
    for (int i = 0; i < size; i++) {
        assertEquals("ID " + i, (byte) 1, offeredIds[i]);
    }
    maintenance.halt();
    buffer.close();
    // THEN
    consumer.assertHaveOnlySeenRange(0, size - 1);
}
Also used : Suppliers.singleton(org.neo4j.function.Suppliers.singleton) ThreadLocalRandom.current(java.util.concurrent.ThreadLocalRandom.current) Predicate(java.util.function.Predicate) Predicates(org.neo4j.function.Predicates) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) LockSupport.parkNanos(java.util.concurrent.locks.LockSupport.parkNanos) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Supplier(java.util.function.Supplier) LockSupport(java.util.concurrent.locks.LockSupport) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Utils.safeCastLongToInt(org.neo4j.unsafe.impl.batchimport.Utils.safeCastLongToInt) Assert.assertFalse(org.junit.Assert.assertFalse) Clock(java.time.Clock) Assert.fail(org.junit.Assert.fail) Clocks(org.neo4j.time.Clocks) Race(org.neo4j.test.Race) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) Clock(java.time.Clock) Race(org.neo4j.test.Race) AtomicLong(java.util.concurrent.atomic.AtomicLong) Test(org.junit.Test)

Example 19 with Supplier

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

the class GraphDatabaseFacadeFactoryTest method newFaultyGraphDatabaseFacadeFactory.

private GraphDatabaseFacadeFactory newFaultyGraphDatabaseFacadeFactory(final RuntimeException startupError) {
    return new GraphDatabaseFacadeFactory(DatabaseInfo.UNKNOWN, (p) -> Mockito.mock(EditionModule.class, Mockito.RETURNS_DEEP_STUBS)) {

        @Override
        protected PlatformModule createPlatform(File storeDir, Config config, Dependencies dependencies, GraphDatabaseFacade graphDatabaseFacade) {
            final LifeSupport lifeMock = mock(LifeSupport.class);
            doThrow(startupError).when(lifeMock).start();
            doAnswer(invocation -> invocation.getArguments()[0]).when(lifeMock).add(any(Lifecycle.class));
            return new PlatformModule(storeDir, config, databaseInfo, dependencies, graphDatabaseFacade) {

                @Override
                public LifeSupport createLife() {
                    return lifeMock;
                }
            };
        }

        @Override
        protected DataSourceModule createDataSource(PlatformModule platformModule, EditionModule editionModule, Supplier<QueryExecutionEngine> queryExecutionEngineSupplier) {
            return mock(DataSourceModule.class);
        }
    };
}
Also used : EditionModule(org.neo4j.kernel.impl.factory.EditionModule) Config(org.neo4j.kernel.configuration.Config) GraphDatabaseFacadeFactory(org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory) Lifecycle(org.neo4j.kernel.lifecycle.Lifecycle) LifeSupport(org.neo4j.kernel.lifecycle.LifeSupport) Supplier(java.util.function.Supplier) GraphDatabaseFacade(org.neo4j.kernel.impl.factory.GraphDatabaseFacade) PlatformModule(org.neo4j.kernel.impl.factory.PlatformModule) File(java.io.File)

Example 20 with Supplier

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

the class ConstraintIndexConcurrencyTest method shouldNotAllowConcurrentViolationOfConstraint.

@Test
public void shouldNotAllowConcurrentViolationOfConstraint() throws Exception {
    // Given
    GraphDatabaseAPI graphDb = db.getGraphDatabaseAPI();
    Supplier<Statement> statementSupplier = graphDb.getDependencyResolver().resolveDependency(ThreadToStatementContextBridge.class);
    Label label = label("Foo");
    String propertyKey = "bar";
    String conflictingValue = "baz";
    // a constraint
    try (Transaction tx = graphDb.beginTx()) {
        graphDb.schema().constraintFor(label).assertPropertyIsUnique(propertyKey).create();
        tx.success();
    }
    // When
    try (Transaction tx = graphDb.beginTx()) {
        // create a statement and perform a lookup
        Statement statement = statementSupplier.get();
        int labelId = statement.readOperations().labelGetForName(label.name());
        int propertyKeyId = statement.readOperations().propertyKeyGetForName(propertyKey);
        NewIndexDescriptor index = NewIndexDescriptorFactory.uniqueForLabel(labelId, propertyKeyId);
        statement.readOperations().indexQuery(index, IndexQuery.exact(index.schema().getPropertyId(), "The value is irrelevant, we just want to perform some sort of lookup against this index"));
        // then let another thread come in and create a node
        threads.execute(db -> {
            try (Transaction transaction = db.beginTx()) {
                db.createNode(label).setProperty(propertyKey, conflictingValue);
                transaction.success();
            }
            return null;
        }, graphDb).get();
        // before we create a node with the same property ourselves - using the same statement that we have
        // already used for lookup against that very same index
        long node = statement.dataWriteOperations().nodeCreate();
        statement.dataWriteOperations().nodeAddLabel(node, labelId);
        try {
            statement.dataWriteOperations().nodeSetProperty(node, property(propertyKeyId, conflictingValue));
            fail("exception expected");
        }// Then
         catch (UniquePropertyValueValidationException e) {
            assertEquals(ConstraintDescriptorFactory.uniqueForLabel(labelId, propertyKeyId), e.constraint());
            IndexEntryConflictException conflict = Iterators.single(e.conflicts().iterator());
            assertEquals(conflictingValue, conflict.getSinglePropertyValue());
        }
        tx.success();
    }
}
Also used : ImpermanentDatabaseRule(org.neo4j.test.rule.ImpermanentDatabaseRule) Label(org.neo4j.graphdb.Label) IndexQuery(org.neo4j.kernel.api.schema_new.IndexQuery) ThreadToStatementContextBridge(org.neo4j.kernel.impl.core.ThreadToStatementContextBridge) Iterators(org.neo4j.helpers.collection.Iterators) NewIndexDescriptorFactory(org.neo4j.kernel.api.schema_new.index.NewIndexDescriptorFactory) Test(org.junit.Test) Label.label(org.neo4j.graphdb.Label.label) Statement(org.neo4j.kernel.api.Statement) NewIndexDescriptor(org.neo4j.kernel.api.schema_new.index.NewIndexDescriptor) Property.property(org.neo4j.kernel.api.properties.Property.property) Supplier(java.util.function.Supplier) DatabaseRule(org.neo4j.test.rule.DatabaseRule) GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) Rule(org.junit.Rule) IndexEntryConflictException(org.neo4j.kernel.api.exceptions.index.IndexEntryConflictException) ConstraintDescriptorFactory(org.neo4j.kernel.api.schema_new.constaints.ConstraintDescriptorFactory) UniquePropertyValueValidationException(org.neo4j.kernel.api.exceptions.schema.UniquePropertyValueValidationException) ThreadingRule(org.neo4j.test.rule.concurrent.ThreadingRule) Assert.fail(org.junit.Assert.fail) Transaction(org.neo4j.graphdb.Transaction) Assert.assertEquals(org.junit.Assert.assertEquals) UniquePropertyValueValidationException(org.neo4j.kernel.api.exceptions.schema.UniquePropertyValueValidationException) NewIndexDescriptor(org.neo4j.kernel.api.schema_new.index.NewIndexDescriptor) GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) Transaction(org.neo4j.graphdb.Transaction) Statement(org.neo4j.kernel.api.Statement) Label(org.neo4j.graphdb.Label) IndexEntryConflictException(org.neo4j.kernel.api.exceptions.index.IndexEntryConflictException) Test(org.junit.Test)

Aggregations

Supplier (java.util.function.Supplier)81 List (java.util.List)29 Test (org.junit.Test)28 Map (java.util.Map)16 Collectors (java.util.stream.Collectors)15 Function (java.util.function.Function)13 IOException (java.io.IOException)12 ArrayList (java.util.ArrayList)12 HashMap (java.util.HashMap)12 Arrays (java.util.Arrays)11 Consumer (java.util.function.Consumer)11 Assert.assertEquals (org.junit.Assert.assertEquals)10 Optional (java.util.Optional)9 Mockito.mock (org.mockito.Mockito.mock)6 Collections (java.util.Collections)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 Assert.assertFalse (org.junit.Assert.assertFalse)5 Matchers.any (org.mockito.Matchers.any)5 Mockito.when (org.mockito.Mockito.when)5 Maps (com.google.common.collect.Maps)4