Search in sources :

Example 6 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project jackrabbit-oak by apache.

the class UploadStagingCacheTest method testPutMoveFileError.

/**
 * Error in putting file to stage.
 * @throws Exception
 */
@Test
public void testPutMoveFileError() throws Exception {
    File empty = new File(folder.getRoot(), String.valueOf(System.currentTimeMillis()));
    assertFalse(empty.exists());
    Optional<SettableFuture<Integer>> future = stagingCache.put(ID_PREFIX + 0, empty);
    // assert no file
    assertFalse(future.isPresent());
    assertEquals(1, stagingCache.getStats().getMissCount());
    assertCacheStats(stagingCache, 0, 0, 0, 1);
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) File(java.io.File) Test(org.junit.Test)

Example 7 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project jackrabbit-oak by apache.

the class UploadStagingCacheTest method testDefaultStatsProvider.

@Test
public void testDefaultStatsProvider() throws Exception {
    stagingCache = UploadStagingCache.build(root, null, 1, /*threads*/
    8 * 1024, /* bytes */
    uploader, null, /*cache*/
    null, executor, null, 3000, 6000);
    // add load
    File f = copyToFile(randomStream(0, 4 * 1024), folder.newFile());
    Optional<SettableFuture<Integer>> future = stagingCache.put(ID_PREFIX + 0, f);
    assertTrue(future.isPresent());
    assertNotNull(stagingCache.getIfPresent(ID_PREFIX + 0));
    assertCacheStats(stagingCache, 1, 4 * 1024, 1, 1);
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) File(java.io.File) Test(org.junit.Test)

Example 8 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project controller by opendaylight.

the class ConcurrentDOMDataBrokerTest method testSuccessfulSubmit.

private void testSuccessfulSubmit(final boolean doAsync) throws InterruptedException {
    final CountDownLatch asyncCanCommitContinue = new CountDownLatch(1);
    Answer<ListenableFuture<Boolean>> asyncCanCommit = invocation -> {
        final SettableFuture<Boolean> future = SettableFuture.create();
        if (doAsync) {
            new Thread(() -> {
                Uninterruptibles.awaitUninterruptibly(asyncCanCommitContinue, 10, TimeUnit.SECONDS);
                future.set(true);
            }).start();
        } else {
            future.set(true);
        }
        return future;
    };
    doAnswer(asyncCanCommit).when(mockCohort1).canCommit();
    doReturn(Futures.immediateFuture(null)).when(mockCohort1).preCommit();
    doReturn(Futures.immediateFuture(null)).when(mockCohort1).commit();
    doReturn(Futures.immediateFuture(true)).when(mockCohort2).canCommit();
    doReturn(Futures.immediateFuture(null)).when(mockCohort2).preCommit();
    doReturn(Futures.immediateFuture(null)).when(mockCohort2).commit();
    ListenableFuture<Void> future = coordinator.submit(transaction, Arrays.asList(mockCohort1, mockCohort2));
    final CountDownLatch doneLatch = new CountDownLatch(1);
    final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
    Futures.addCallback(future, new FutureCallback<Void>() {

        @Override
        public void onSuccess(final Void result) {
            doneLatch.countDown();
        }

        @Override
        public void onFailure(final Throwable failure) {
            caughtEx.set(failure);
            doneLatch.countDown();
        }
    }, MoreExecutors.directExecutor());
    asyncCanCommitContinue.countDown();
    assertEquals("Submit complete", true, doneLatch.await(5, TimeUnit.SECONDS));
    if (caughtEx.get() != null) {
        Throwables.throwIfUnchecked(caughtEx.get());
        throw new RuntimeException(caughtEx.get());
    }
    assertEquals("Task count", doAsync ? 1 : 0, futureExecutor.getTaskCount());
    InOrder inOrder = inOrder(mockCohort1, mockCohort2);
    inOrder.verify(mockCohort1).canCommit();
    inOrder.verify(mockCohort2).canCommit();
    inOrder.verify(mockCohort1).preCommit();
    inOrder.verify(mockCohort2).preCommit();
    inOrder.verify(mockCohort1).commit();
    inOrder.verify(mockCohort2).commit();
}
Also used : DOMDataTreeWriteTransaction(org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction) Arrays(java.util.Arrays) CheckedFuture(com.google.common.util.concurrent.CheckedFuture) TimeoutException(java.util.concurrent.TimeoutException) SettableFuture(com.google.common.util.concurrent.SettableFuture) DataStoreUnavailableException(org.opendaylight.mdsal.common.api.DataStoreUnavailableException) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) After(org.junit.After) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) Assert.fail(org.junit.Assert.fail) InMemoryDOMDataStore(org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataStore) DOMStoreTransactionChain(org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain) DOMDataTreeReadWriteTransaction(org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction) Mockito.doReturn(org.mockito.Mockito.doReturn) DOMStore(org.opendaylight.mdsal.dom.spi.store.DOMStore) DOMStoreThreePhaseCommitCohort(org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort) DOMDataTreeIdentifier(org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier) ImmutableMap(com.google.common.collect.ImmutableMap) SynchronousQueue(java.util.concurrent.SynchronousQueue) Collection(java.util.Collection) DOMDataTreeReadTransaction(org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) DOMDataTreeCommitCohort(org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort) Mockito.inOrder(org.mockito.Mockito.inOrder) DOMTransactionChain(org.opendaylight.mdsal.dom.api.DOMTransactionChain) Mockito.mock(org.mockito.Mockito.mock) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) TransactionChainListener(org.opendaylight.mdsal.common.api.TransactionChainListener) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) Assert.assertSame(org.junit.Assert.assertSame) Answer(org.mockito.stubbing.Answer) DOMDataTreeCommitCohortRegistry(org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry) DOMStoreWriteTransaction(org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction) DOMStoreReadWriteTransaction(org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction) NoShardLeaderException(org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException) Before(org.junit.Before) DistributedDataStore(org.opendaylight.controller.cluster.datastore.DistributedDataStore) Uninterruptibles(com.google.common.util.concurrent.Uninterruptibles) InOrder(org.mockito.InOrder) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Throwables(com.google.common.base.Throwables) DOMStoreReadTransaction(org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) TransactionCommitFailedException(org.opendaylight.mdsal.common.api.TransactionCommitFailedException) FutureCallback(com.google.common.util.concurrent.FutureCallback) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) DOMDataTreeChangeService(org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService) Mockito.never(org.mockito.Mockito.never) Futures(com.google.common.util.concurrent.Futures) LogicalDatastoreType(org.opendaylight.mdsal.common.api.LogicalDatastoreType) DOMDataBrokerExtension(org.opendaylight.mdsal.dom.api.DOMDataBrokerExtension) Assert.assertEquals(org.junit.Assert.assertEquals) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) SettableFuture(com.google.common.util.concurrent.SettableFuture) InOrder(org.mockito.InOrder) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ListenableFuture(com.google.common.util.concurrent.ListenableFuture)

Example 9 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project closure-templates by google.

the class DetachStateTest method testDetachOnEachIteration.

@Test
public void testDetachOnEachIteration() throws IOException {
    CompiledTemplates templates = TemplateTester.compileTemplateBody("{@param list : list<string>}", "prefix{\\n}", "{for $item in $list}", "  loop-prefix{\\n}", "  {$item}{\\n}", "  loop-suffix{\\n}", "{/for}", "suffix");
    CompiledTemplate.Factory factory = templates.getTemplateFactory("ns.foo");
    RenderContext context = getDefaultContext(templates);
    List<SettableFuture<String>> futures = ImmutableList.of(SettableFuture.<String>create(), SettableFuture.<String>create(), SettableFuture.<String>create());
    CompiledTemplate template = factory.create(asRecord(ImmutableMap.of("list", futures)), EMPTY_DICT);
    BufferingAppendable output = LoggingAdvisingAppendable.buffering();
    RenderResult result = template.render(output, context);
    assertThat(result.type()).isEqualTo(RenderResult.Type.DETACH);
    assertThat(result.future()).isEqualTo(futures.get(0));
    assertThat(output.getAndClearBuffer()).isEqualTo("prefix\nloop-prefix\n");
    futures.get(0).set("first");
    result = template.render(output, context);
    assertThat(result.type()).isEqualTo(RenderResult.Type.DETACH);
    assertThat(result.future()).isEqualTo(futures.get(1));
    assertThat(output.getAndClearBuffer()).isEqualTo("first\nloop-suffix\nloop-prefix\n");
    futures.get(1).set("second");
    result = template.render(output, context);
    assertThat(result.type()).isEqualTo(RenderResult.Type.DETACH);
    assertThat(result.future()).isEqualTo(futures.get(2));
    assertThat(output.getAndClearBuffer()).isEqualTo("second\nloop-suffix\nloop-prefix\n");
    futures.get(2).set("third");
    result = template.render(output, context);
    assertThat(result).isEqualTo(RenderResult.done());
    assertThat(output.toString()).isEqualTo("third\nloop-suffix\nsuffix");
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) RenderContext(com.google.template.soy.jbcsrc.shared.RenderContext) BufferingAppendable(com.google.template.soy.data.LoggingAdvisingAppendable.BufferingAppendable) RenderResult(com.google.template.soy.jbcsrc.api.RenderResult) CompiledTemplates(com.google.template.soy.jbcsrc.shared.CompiledTemplates) CompiledTemplate(com.google.template.soy.jbcsrc.shared.CompiledTemplate) Test(org.junit.Test)

Example 10 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project cdap by caskdata.

the class WorkflowTest method testOneActionWorkflow.

@Test(timeout = 120 * 1000L)
public void testOneActionWorkflow() throws Exception {
    final ApplicationWithPrograms app = AppFabricTestHelper.deployApplicationWithManager(OneActionWorkflowApp.class, TEMP_FOLDER_SUPPLIER);
    final Injector injector = AppFabricTestHelper.getInjector();
    final ProgramDescriptor programDescriptor = Iterators.filter(app.getPrograms().iterator(), input -> input.getProgramId().getType() == ProgramType.WORKFLOW).next();
    final SettableFuture<String> completion = SettableFuture.create();
    final ProgramController controller = AppFabricTestHelper.submit(app, programDescriptor.getSpecification().getClassName(), new BasicArguments(), TEMP_FOLDER_SUPPLIER);
    controller.addListener(new AbstractListener() {

        @Override
        public void init(ProgramController.State currentState, @Nullable Throwable cause) {
            LOG.info("Initializing");
            long nowSecs = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
            setStartAndRunning(injector.getInstance(Store.class), controller.getProgramRunId().getParent(), controller.getProgramRunId().getRun(), nowSecs);
        }

        @Override
        public void completed() {
            LOG.info("Completed");
            completion.set("Completed");
        }

        @Override
        public void error(Throwable cause) {
            LOG.info("Error", cause);
            completion.setException(cause);
        }
    }, Threads.SAME_THREAD_EXECUTOR);
    String run = completion.get();
    Assert.assertEquals("Completed", run);
}
Also used : ProgramDescriptor(co.cask.cdap.app.program.ProgramDescriptor) ProgramController(co.cask.cdap.app.runtime.ProgramController) Supplier(com.google.common.base.Supplier) LoggerFactory(org.slf4j.LoggerFactory) SettableFuture(com.google.common.util.concurrent.SettableFuture) Iterators(com.google.common.collect.Iterators) ProgramType(co.cask.cdap.proto.ProgramType) WorkflowApp(co.cask.cdap.WorkflowApp) Store(co.cask.cdap.app.store.Store) ProgramId(co.cask.cdap.proto.id.ProgramId) MissingMapReduceWorkflowApp(co.cask.cdap.MissingMapReduceWorkflowApp) ClassRule(org.junit.ClassRule) Nullable(javax.annotation.Nullable) Threads(org.apache.twill.common.Threads) NonUniqueProgramsInWorkflowWithForkApp(co.cask.cdap.NonUniqueProgramsInWorkflowWithForkApp) AbstractListener(co.cask.cdap.internal.app.runtime.AbstractListener) Logger(org.slf4j.Logger) OneActionWorkflowApp(co.cask.cdap.OneActionWorkflowApp) ImmutableMap(com.google.common.collect.ImmutableMap) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) Throwables(com.google.common.base.Throwables) Test(org.junit.Test) IOException(java.io.IOException) Category(org.junit.experimental.categories.Category) File(java.io.File) NonUniqueProgramsInWorkflowApp(co.cask.cdap.NonUniqueProgramsInWorkflowApp) ApplicationWithPrograms(co.cask.cdap.internal.app.deploy.pipeline.ApplicationWithPrograms) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) BasicArguments(co.cask.cdap.internal.app.runtime.BasicArguments) ScheduleAppWithMissingWorkflow(co.cask.cdap.ScheduleAppWithMissingWorkflow) XSlowTests(co.cask.cdap.test.XSlowTests) AppWithAnonymousWorkflow(co.cask.cdap.AppWithAnonymousWorkflow) AppFabricTestHelper(co.cask.cdap.internal.AppFabricTestHelper) MissingSparkWorkflowApp(co.cask.cdap.MissingSparkWorkflowApp) Assert(org.junit.Assert) WorkflowSchedulesWithSameNameApp(co.cask.cdap.WorkflowSchedulesWithSameNameApp) TemporaryFolder(org.junit.rules.TemporaryFolder) ProgramController(co.cask.cdap.app.runtime.ProgramController) ApplicationWithPrograms(co.cask.cdap.internal.app.deploy.pipeline.ApplicationWithPrograms) Injector(com.google.inject.Injector) AbstractListener(co.cask.cdap.internal.app.runtime.AbstractListener) ProgramDescriptor(co.cask.cdap.app.program.ProgramDescriptor) BasicArguments(co.cask.cdap.internal.app.runtime.BasicArguments) Test(org.junit.Test)

Aggregations

SettableFuture (com.google.common.util.concurrent.SettableFuture)46 Test (org.junit.Test)25 ArrayList (java.util.ArrayList)15 List (java.util.List)15 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)14 File (java.io.File)12 IOException (java.io.IOException)10 TimeUnit (java.util.concurrent.TimeUnit)10 Futures (com.google.common.util.concurrent.Futures)9 ImmutableMap (com.google.common.collect.ImmutableMap)8 ExecutionException (java.util.concurrent.ExecutionException)8 FutureCallback (com.google.common.util.concurrent.FutureCallback)7 Before (org.junit.Before)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 Throwables (com.google.common.base.Throwables)5 ImmutableList (com.google.common.collect.ImmutableList)5 Assert.assertSame (org.junit.Assert.assertSame)5 Mock (org.mockito.Mock)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5