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.liferay.mobile.android.async.FileUploadAsyncTest.java

@Test
public void uploadPhoto() throws Exception {
    Session session = new SessionImpl(this.session);
    DLAppService service = new DLAppService(session);

    long repositoryId = props.getGroupId();
    long folderId = DLAppServiceTest.PARENT_FOLDER_ID;

    InputStream is = getClass().getResourceAsStream("/" + FileUploadTest.FILE_NAME);

    final int[] size = { 0 };

    FileProgressCallback callback = new FileProgressCallback() {

        @Override/*w ww .  jav a 2s . c  o  m*/
        public void onProgress(int totalBytes) {
            size[0] = totalBytes;
        }

    };

    UploadData data = new UploadData(is, FileUploadTest.MIME_TYPE, FileUploadTest.FILE_NAME, callback);

    final CountDownLatch lock = new CountDownLatch(1);

    session.setCallback(new JSONObjectCallback() {

        @Override
        public void onSuccess(JSONObject file) {
            _file = file;
            lock.countDown();
        }

        @Override
        public void onFailure(Exception exception) {
            fail(exception.getMessage());
            lock.countDown();
        }

    });

    service.addFileEntry(repositoryId, folderId, FileUploadTest.FILE_NAME, FileUploadTest.MIME_TYPE,
            FileUploadTest.FILE_NAME, "", "", data, null);

    lock.await(500, TimeUnit.MILLISECONDS);

    assertEquals(FileUploadTest.FILE_NAME, _file.get(DLAppServiceTest.TITLE));

    assertEquals(372434, size[0]);
}

From source file:com.hpe.application.automation.tools.octane.buildLogs.LogDispatcher.java

@Override
protected void doExecute(TaskListener listener) {
    if (logsQueue.peekFirst() == null) {
        return;//  w w  w  .j av a  2  s. co m
    }

    MqmRestClient mqmRestClient = initMqmRestClient();
    if (mqmRestClient == null) {
        logger.warn(
                "there are pending build logs, but MQM server location is not specified, build logs can't be submitted");
        logsQueue.remove();
        return;
    }

    ResultQueue.QueueItem item;

    while ((item = logsQueue.peekFirst()) != null) {
        if (retryModel.isQuietPeriod()) {
            logger.info("there are pending logs, but we are in quiet period");
            return;
        }

        Run build = getBuildFromQueueItem(item);
        if (build == null) {
            logger.warn("build and/or project [" + item.getProjectName() + " #" + item.getBuildNumber()
                    + "] no longer exists, pending build logs won't be submitted");
            logsQueue.remove();
            continue;
        }

        String jobCiId = BuildHandlerUtils.getJobCiId(build);
        try {
            if (item.getWorkspace() == null) {
                //
                //  initial queue item flow - no workspaces, works with workspaces retrieval and loop ever each of them
                //
                logger.info("retrieving all workspaces that logs of [" + jobCiId + "] are relevant to...");
                List<String> workspaces = mqmRestClient.getJobWorkspaceId(
                        ConfigurationService.getModel().getIdentity(), BuildHandlerUtils.getJobCiId(build));
                if (workspaces.isEmpty()) {
                    logger.info("[" + jobCiId
                            + "] is not part of any Octane pipeline in any workspace, log won't be sent");
                } else {
                    logger.info("logs of [" + jobCiId + "] found to be relevant to " + workspaces.size()
                            + " workspace/s");
                    CountDownLatch latch = new CountDownLatch(workspaces.size());
                    for (String workspaceId : workspaces) {
                        logDispatcherExecutors.execute(new SendLogsExecutor(mqmRestClient, build, item,
                                workspaceId, logsQueue, latch));
                    }

                    boolean completedResult = latch.await(TIMEOUT, TimeUnit.MINUTES);
                    if (!completedResult) {
                        logger.error("timed out sending logs to " + workspaces.size() + " workspace/s");
                    }
                }
                logsQueue.remove();
            } else {
                //
                //  secondary queue item flow - workspace is known, we are in retry flow
                //
                logger.info("");
                transferBuildLogs(build, mqmRestClient, item);
            }
        } catch (Exception e) {
            logger.error("fatally failed to fetch relevant workspaces OR to send log for build "
                    + item.getProjectName() + " #" + item.getBuildNumber() + " to workspace "
                    + item.getWorkspace() + ", will not retry this one", e);
        }
    }
}

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

@Test
public void testGetResourceTicketAsync() throws IOException, InterruptedException {
    final ResourceTicket resourceTicket1 = new ResourceTicket();
    resourceTicket1.setId("resourceTicket1");

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

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ResourceTicketApi resourceTicketApi = new ResourceTicketApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    resourceTicketApi.getResourceTicketAsync("foo", new FutureCallback<ResourceTicket>() {
        @Override//from   w  ww . ja v  a  2 s. c  o  m
        public void onSuccess(@Nullable ResourceTicket result) {
            assertEquals(result, resourceTicket1);
            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.ResourceTicketRestApiTest.java

@Test
public void testGetResourceTicketAsync() throws IOException, InterruptedException {
    final ResourceTicket resourceTicket1 = new ResourceTicket();
    resourceTicket1.setId("resourceTicket1");

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

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ResourceTicketApi resourceTicketApi = new ResourceTicketRestApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    resourceTicketApi.getResourceTicketAsync("foo", new FutureCallback<ResourceTicket>() {
        @Override/*  w w  w. jav  a  2  s.  c  om*/
        public void onSuccess(@Nullable ResourceTicket result) {
            assertEquals(result, resourceTicket1);
            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.liferay.mobile.android.async.GroupServiceAsyncTest.java

@Test
public void getUserSites() throws Exception {
    Session session = new SessionImpl(this.session);

    final JSONArray[] sites = { null };
    final CountDownLatch lock = new CountDownLatch(1);

    session.setCallback(new JSONArrayCallback() {

        @Override//from   w  w  w  .j av  a2 s.co m
        public void onSuccess(JSONArray result) {
            try {
                sites[0] = result;
                lock.countDown();
            } catch (Exception e) {
                onFailure(e);
            }
        }

        @Override
        public void onFailure(Exception exception) {
            fail(exception.getMessage());
            lock.countDown();
        }

    });

    GroupService service = new GroupService(session);
    service.getUserSitesGroups();

    lock.await(500, TimeUnit.MILLISECONDS);
    GroupServiceTest.assertUserSites(sites[0]);
}

From source file:com.liferay.mobile.android.CookieAuthenticationTest.java

@Test
public void signIn() throws Exception {
    Session session = new SessionImpl(this.session);
    final JSONArray[] sites = { null };
    final CountDownLatch lock = new CountDownLatch(1);

    CookieSignIn.signIn(session, new CookieSignIn.CookieCallback() {

        @Override//from www .j  ava  2  s .c  om
        public void onSuccess(Session session) {
            try {
                GroupService service = new GroupService(session);
                sites[0] = service.getUserSitesGroups();
                lock.countDown();
            } catch (Exception e) {
                onFailure(e);
            }
        }

        @Override
        public void onFailure(Exception exception) {
            fail(exception.getMessage());
            lock.countDown();
        }

    });

    lock.await(2000, TimeUnit.MILLISECONDS);
    GroupServiceTest.assertUserSites(sites[0]);
}

From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelector.java

@Test
public void testClosing() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();// w  ww.  j a  va  2s.c o  m
    try {
        final CountDownLatch latch = new CountDownLatch(1);
        LeaderSelector leaderSelector1 = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }

            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                latch.await(10, TimeUnit.SECONDS);
            }
        });

        LeaderSelector leaderSelector2 = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }

            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                latch.await(10, TimeUnit.SECONDS);
            }
        });

        leaderSelector1.start();
        leaderSelector2.start();

        while (!leaderSelector1.hasLeadership() && !leaderSelector2.hasLeadership()) {
            Thread.sleep(1000);
        }

        Assert.assertNotSame(leaderSelector1.hasLeadership(), leaderSelector2.hasLeadership());

        LeaderSelector positiveLeader;
        LeaderSelector negativeLeader;
        if (leaderSelector1.hasLeadership()) {
            positiveLeader = leaderSelector1;
            negativeLeader = leaderSelector2;
        } else {
            positiveLeader = leaderSelector2;
            negativeLeader = leaderSelector1;
        }

        negativeLeader.close();
        Thread.sleep(1000);
        Assert.assertNotSame(positiveLeader.hasLeadership(), negativeLeader.hasLeadership());
        Assert.assertTrue(positiveLeader.hasLeadership());

        positiveLeader.close();
        Thread.sleep(1000);
        Assert.assertFalse(positiveLeader.hasLeadership());
    } finally {
        client.close();
    }
}

From source file:fi.jumi.launcher.remote.ProcessStartingDaemonSummonerTest.java

@Test
public void reports_an_internal_error_if_the_daemon_fails_to_connect_within_a_timeout()
        throws InterruptedException {
    SpyListener<SuiteListener> spy = new SpyListener<>(SuiteListener.class);
    SuiteListener expect = spy.getListener();
    CountDownLatch expectedMessagesArrived = new CountDownLatch(3);

    expect.onSuiteStarted();/*from   ww w  .j  av  a2  s.  co m*/
    expect.onInternalError("Failed to start the test runner daemon process",
            StackTrace.from(new RuntimeException("Could not connect to the daemon: timed out after 0 ms")));
    expect.onSuiteFinished();
    spy.replay();

    daemonSummoner.connectToDaemon(dummySuiteConfig,
            new DaemonConfigurationBuilder().setStartupTimeout(0).freeze(),
            actorRef(new FakeDaemonListener(countMessages(expect, expectedMessagesArrived))));

    expectedMessagesArrived.await(TIMEOUT / 2, TimeUnit.MILLISECONDS);
    spy.verify();
}

From source file:my.adam.smo.client.Client.java

public BlockingRpcChannel blockingConnect(final InetSocketAddress sa) {
    return new BlockingRpcChannel() {
        private int countDownCallTimesToRelease = 1;
        private RpcChannel rpc = connect(sa);

        @Override/*from   w  w w . j  a  v  a2s  .co  m*/
        public Message callBlockingMethod(Descriptors.MethodDescriptor method, RpcController controller,
                Message request, Message responsePrototype) throws ServiceException {
            StopWatch stopWatch = new StopWatch("callBlockingMethod");
            stopWatch.start();

            final CountDownLatch callbackLatch = new CountDownLatch(countDownCallTimesToRelease);

            final AtomicReference<Message> result = new AtomicReference<Message>();

            RpcCallback<Message> done = new RpcCallback<Message>() {
                @Override
                public void run(Message parameter) {
                    result.set(parameter);
                    callbackLatch.countDown();
                }
            };

            rpc.callMethod(method, controller, request, responsePrototype, done);
            try {
                boolean succeededBeforeTimeout = callbackLatch.await(blocking_method_call_timeout,
                        TimeUnit.SECONDS);
                if (!succeededBeforeTimeout) {
                    throw new ServiceException(
                            "blocking method timeout reached for method:" + method.getFullName());
                }
            } catch (InterruptedException e) {
                getLogger().error("call failed", e);
                stopWatch.stop();
            }

            stopWatch.stop();
            getLogger().trace(stopWatch.shortSummary());

            return result.get();
        }
    };
}

From source file:ninja.eivind.hotsreplayuploader.files.tempwatcher.RecursiveTempWatcherTest.java

@Test
public void testCallbackIsInvokedWhenRelevantFileIsDiscovered() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    final File[] fileAccessor = new File[1];
    final File tempWriteReplayFolder = new File(directories.getRemainder(), "TempWriteReplayP99");
    final File target = new File(tempWriteReplayFolder, BattleLobbyWatcher.REPLAY_SERVER_BATTLELOBBY);
    tempWatcher.setCallback(file -> {
        fileAccessor[0] = file;//from   w w  w .  j a v a  2 s  . co  m
        latch.countDown();
    });

    if (!(tempWriteReplayFolder.mkdirs() && target.createNewFile())) {
        fail("Could not create file to drop target " + target + " in");
    }

    if (!latch.await(50000, TimeUnit.MILLISECONDS)) {
        fail("Latch was not tripped.");
    }

    final String expected = target.getName();
    final String actual = fileAccessor[0].getName();

    assertEquals(expected, actual);
}