Example usage for java.util.concurrent CountDownLatch await

List of usage examples for java.util.concurrent CountDownLatch await

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch await.

Prototype

public boolean await(long timeout, TimeUnit unit) throws InterruptedException 

Source Link

Document

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted , or the specified waiting time elapses.

Usage

From source file:com.vmware.photon.controller.api.client.resource.FlavorRestApiTest.java

@Test
public void testCreateAsync() throws Exception {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    FlavorApi flavorApi = new FlavorRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.createAsync(new FlavorCreateSpec(), new FutureCallback<Task>() {
        @Override/*from   www. j  a va2s . co  m*/
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:org.wisdom.framework.vertx.CookiesTest.java

@Test
public void testThatCookiesCanBeReplaced() throws InterruptedException, IOException {
    Router router = prepareServer();//from w  ww  . j  av a  2s .c  o  m

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            if (context().parameter("id") == null) {
                return badRequest("'id' parameter required");
            }
            return ok("Alright").with(Cookie.builder("my-cookie", context().parameter("id")).setMaxAge(3600)
                    .setSecure(false).build());
        }

        @SuppressWarnings("unused")
        public Result logged() {
            String id = context().cookieValue("my-cookie");
            if (id == null) {
                return badRequest("no cookie");
            } else {
                return ok(id).with(Cookie.cookie("my-cookie", id + "_").build());
            }
        }
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    final Route route2 = new RouteBuilder().route(HttpMethod.GET).on("/logged").to(controller, "logged");
    configureRouter(router, route1, route2);

    server.start();
    waitForStart(server);

    // Now start bunch of clients
    int num = NUMBER_OF_CLIENTS;
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(num);

    int port = server.httpPort();

    createAndSubmitClients(num, startSignal, doneSignal, port);

    startSignal.countDown(); // let all threads proceed
    assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue(); // wait for all to finish

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(num);

}

From source file:org.wisdom.framework.vertx.CookiesTest.java

@Test
public void testThatCookiesCanBeWithdrawnAndReplaced() throws InterruptedException, IOException {
    Router router = prepareServer();//from   www. j a  va 2s.  co  m

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            if (context().parameter("id") == null) {
                return badRequest("'id' parameter required");
            }
            return ok("Alright").with(Cookie.builder("my-cookie", context().parameter("id")).setMaxAge(3600)
                    .setSecure(false).build());
        }

        @SuppressWarnings("unused")
        public Result logged() {
            String id = context().cookieValue("my-cookie");
            if (id == null) {
                return badRequest("no cookie");
            } else {
                return ok(id).without("my-cookie").with(Cookie.cookie("my-cookie", id + "_").build());
            }
        }
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    final Route route2 = new RouteBuilder().route(HttpMethod.GET).on("/logged").to(controller, "logged");
    configureRouter(router, route1, route2);

    server.start();
    waitForStart(server);

    // Now start bunch of clients
    int num = NUMBER_OF_CLIENTS;
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(num);

    int port = server.httpPort();

    createAndSubmitClients(num, startSignal, doneSignal, port);

    startSignal.countDown(); // let all threads proceed
    assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue(); // wait for all to finish

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(num);

}

From source file:com.vmware.photon.controller.deployer.xenon.DeployerServiceGroupTest.java

private void waitForServicesStartup(PhotonControllerXenonHost host)
        throws TimeoutException, InterruptedException, NoSuchFieldException, IllegalAccessException {

    serviceSelfLinks = ServiceHostUtils.getServiceSelfLinks(
            DeployerServiceGroup.FACTORY_SERVICE_FIELD_NAME_SELF_LINK, DeployerServiceGroup.FACTORY_SERVICES);
    serviceSelfLinks.add(DeployerServiceGroup.UPLOAD_VIB_WORK_QUEUE_SELF_LINK);

    final CountDownLatch latch = new CountDownLatch(serviceSelfLinks.size());
    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override/* ww w  . j ava  2s  . c  o m*/
        public void handle(Operation completedOp, Throwable failure) {
            latch.countDown();
        }
    };

    String[] links = new String[serviceSelfLinks.size()];
    host.registerForServiceAvailability(handler, serviceSelfLinks.toArray(links));
    if (!latch.await(10, TimeUnit.SECONDS)) {
        throw new TimeoutException();
    }
}

From source file:com.vmware.photon.controller.api.client.resource.DeploymentApiTest.java

@Test
public void testGetVmsAsync() throws IOException, InterruptedException {
    Vm vm1 = new Vm();
    vm1.setId("vm1");

    Vm vm2 = new Vm();
    vm2.setId("vm2");

    final ResourceList<Vm> vmList = new ResourceList<>(Arrays.asList(vm1, vm2));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(vmList);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    DeploymentApi deploymentApi = new DeploymentApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    deploymentApi.getAllDeploymentVmsAsync("foo", new FutureCallback<ResourceList<Vm>>() {
        @Override/* w w w  .  j  a  v  a 2  s  .c  om*/
        public void onSuccess(ResourceList<Vm> result) {
            assertEquals(result.getItems(), vmList.getItems());
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.vmware.photon.controller.api.client.resource.DeploymentRestApiTest.java

@Test
public void testGetVmsAsync() throws IOException, InterruptedException {
    Vm vm1 = new Vm();
    vm1.setId("vm1");

    Vm vm2 = new Vm();
    vm2.setId("vm2");

    final ResourceList<Vm> vmList = new ResourceList<>(Arrays.asList(vm1, vm2));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(vmList);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    DeploymentApi deploymentApi = new DeploymentRestApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    deploymentApi.getAllDeploymentVmsAsync("foo", new FutureCallback<ResourceList<Vm>>() {
        @Override/*www .  j  av a  2 s  . c  o m*/
        public void onSuccess(ResourceList<Vm> result) {
            assertEquals(result.getItems(), vmList.getItems());
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:co.cask.cdap.data2.datafabric.dataset.service.DatasetServiceTestBase.java

@Before
public void before() throws Exception {
    CConfiguration cConf = CConfiguration.create();
    File dataDir = new File(tmpFolder.newFolder(), "data");
    cConf.set(Constants.CFG_LOCAL_DATA_DIR, dataDir.getAbsolutePath());
    if (!DirUtils.mkdirs(dataDir)) {
        throw new RuntimeException(String.format("Could not create DatasetFramework output dir %s", dataDir));
    }// w  w  w  .ja  va  2s  .  c om
    cConf.set(Constants.Dataset.Manager.OUTPUT_DIR, dataDir.getAbsolutePath());
    cConf.set(Constants.Dataset.Manager.ADDRESS, "localhost");
    cConf.setBoolean(Constants.Dangerous.UNRECOVERABLE_RESET, true);

    // Starting DatasetService service
    discoveryService = new InMemoryDiscoveryService();
    MetricsCollectionService metricsCollectionService = new NoOpMetricsCollectionService();

    // Tx Manager to support working with datasets
    Configuration txConf = HBaseConfiguration.create();
    CConfigurationUtil.copyTxProperties(cConf, txConf);
    txManager = new TransactionManager(txConf);
    txManager.startAndWait();
    InMemoryTxSystemClient txSystemClient = new InMemoryTxSystemClient(txManager);
    TransactionSystemClientService txSystemClientService = new DelegatingTransactionSystemClientService(
            txSystemClient);

    final Injector injector = Guice.createInjector(new ConfigModule(cConf),
            new LocationRuntimeModule().getInMemoryModules(),
            new SystemDatasetRuntimeModule().getInMemoryModules(), new TransactionInMemoryModule());

    DatasetDefinitionRegistryFactory registryFactory = new DatasetDefinitionRegistryFactory() {
        @Override
        public DatasetDefinitionRegistry create() {
            DefaultDatasetDefinitionRegistry registry = new DefaultDatasetDefinitionRegistry();
            injector.injectMembers(registry);
            return registry;
        }
    };

    locationFactory = injector.getInstance(LocationFactory.class);
    NamespacedLocationFactory namespacedLocationFactory = injector.getInstance(NamespacedLocationFactory.class);
    dsFramework = new RemoteDatasetFramework(cConf, discoveryService, registryFactory);
    SystemDatasetInstantiatorFactory datasetInstantiatorFactory = new SystemDatasetInstantiatorFactory(
            locationFactory, dsFramework, cConf);

    DatasetAdminService datasetAdminService = new DatasetAdminService(dsFramework, cConf, locationFactory,
            datasetInstantiatorFactory, new NoOpMetadataStore());
    ImmutableSet<HttpHandler> handlers = ImmutableSet
            .<HttpHandler>of(new DatasetAdminOpHTTPHandler(datasetAdminService));
    opExecutorService = new DatasetOpExecutorService(cConf, discoveryService, metricsCollectionService,
            handlers);

    opExecutorService.startAndWait();

    ImmutableMap<String, DatasetModule> modules = ImmutableMap.<String, DatasetModule>builder()
            .putAll(injector.getInstance(Key.get(new TypeLiteral<Map<String, DatasetModule>>() {
            }, Names.named("defaultDatasetModules")))).putAll(DatasetMetaTableUtil.getModules()).build();

    TransactionExecutorFactory txExecutorFactory = injector.getInstance(TransactionExecutorFactory.class);

    inMemoryDatasetFramework = new InMemoryDatasetFramework(registryFactory, modules, cConf);
    MDSDatasetsRegistry mdsDatasetsRegistry = new MDSDatasetsRegistry(txSystemClientService,
            inMemoryDatasetFramework);

    ExploreFacade exploreFacade = new ExploreFacade(new DiscoveryExploreClient(cConf, discoveryService), cConf);
    namespaceStore = new InMemoryNamespaceStore();
    namespaceStore.create(NamespaceMeta.DEFAULT);
    DatasetInstanceService instanceService = new DatasetInstanceService(
            new DatasetTypeManager(cConf, mdsDatasetsRegistry, locationFactory,
                    // we don't need any default modules in this test
                    Collections.<String, DatasetModule>emptyMap()),
            new DatasetInstanceManager(mdsDatasetsRegistry), new InMemoryDatasetOpExecutor(dsFramework),
            exploreFacade, cConf, txExecutorFactory, registryFactory, namespaceStore);

    service = new DatasetService(cConf, namespacedLocationFactory, discoveryService, discoveryService,
            new DatasetTypeManager(cConf, mdsDatasetsRegistry, locationFactory,
                    // we don't need any default modules in this test
                    Collections.<String, DatasetModule>emptyMap()),
            metricsCollectionService, new InMemoryDatasetOpExecutor(dsFramework), mdsDatasetsRegistry,
            new HashSet<DatasetMetricsReporter>(), instanceService,
            new LocalStorageProviderNamespaceAdmin(cConf, namespacedLocationFactory, exploreFacade),
            namespaceStore);

    // Start dataset service, wait for it to be discoverable
    service.start();
    final CountDownLatch startLatch = new CountDownLatch(1);
    discoveryService.discover(Constants.Service.DATASET_MANAGER)
            .watchChanges(new ServiceDiscovered.ChangeListener() {
                @Override
                public void onChange(ServiceDiscovered serviceDiscovered) {
                    if (!Iterables.isEmpty(serviceDiscovered)) {
                        startLatch.countDown();
                    }
                }
            }, Threads.SAME_THREAD_EXECUTOR);

    startLatch.await(5, TimeUnit.SECONDS);
    // this usually happens while creating a namespace, however not doing that in data fabric tests
    Locations.mkdirsIfNotExists(namespacedLocationFactory.get(Id.Namespace.DEFAULT));
}

From source file:com.vmware.photon.controller.api.client.resource.DeploymentApiTest.java

@Test
public void testListAllAsync() throws Exception {
    Deployment deployment = getNewDeployment();

    ResourceList<Deployment> deploymentResourceList = new ResourceList<>(Arrays.asList(deployment));

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(deploymentResourceList);

    setupMocks(serializedResponse, HttpStatus.SC_OK);

    DeploymentApi deploymentApi = new DeploymentApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    deploymentApi.listAllAsync(new FutureCallback<ResourceList<Deployment>>() {
        @Override//from w  ww . j a  va  2 s.  c om
        public void onSuccess(@Nullable ResourceList<Deployment> result) {
            assertEquals(result.getItems(), deploymentResourceList.getItems());
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.vmware.photon.controller.api.client.resource.DeploymentRestApiTest.java

@Test
public void testListAllAsync() throws Exception {
    Deployment deployment = getNewDeployment();

    ResourceList<Deployment> deploymentResourceList = new ResourceList<>(Arrays.asList(deployment));

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(deploymentResourceList);

    setupMocks(serializedResponse, HttpStatus.SC_OK);

    DeploymentApi deploymentApi = new DeploymentRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    deploymentApi.listAllAsync(new FutureCallback<ResourceList<Deployment>>() {
        @Override/*  w ww . j ava 2s  . com*/
        public void onSuccess(@Nullable ResourceList<Deployment> result) {
            assertEquals(result.getItems(), deploymentResourceList.getItems());
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:de.taimos.httputils.Tester1.java

/**
 * // w w  w. j av a 2  s .  c om
 */
@Test
public void testGetAsyncStringCB() throws InterruptedException {
    final CountDownLatch cdl = new CountDownLatch(1);
    WS.url("http://www.heise.de").getAsync(new HTTPStringCallback() {

        @Override
        public void fail(Exception e) {
            System.out.println(e);
            Assert.fail();
            cdl.countDown();
        }

        @Override
        protected void invalidStatus(int status, HttpResponse response) {
            System.out.println("Invalid status: " + status);
            Assert.fail();
            cdl.countDown();
        }

        @Override
        protected void stringResponse(String body, HttpResponse response) {
            Assert.assertNotNull(body);
            Assert.assertFalse(body.isEmpty());
            cdl.countDown();
        }

    });
    Assert.assertTrue(cdl.await(10, TimeUnit.SECONDS));
}