Example usage for java.util.concurrent CountDownLatch countDown

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

Introduction

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

Prototype

public void countDown() 

Source Link

Document

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

Usage

From source file:com.microsoft.office.integration.test.EventsAsyncTestCase.java

@Override
protected void setUp() throws Exception {
    super.setUp();
    final ICalendars cals = Me.getCalendars();
    final CountDownLatch cdl = new CountDownLatch(1);
    // an empty iterator will be returned for any entity set unless you call fetch()
    Futures.addCallback(cals.fetchAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            cdl.countDown();
        }//from w ww .  jav a2  s  . c  om

        public void onSuccess(Void result) {
            Iterator<ICalendar> iterator = cals.iterator();
            if (iterator.hasNext()) {
                calendar = iterator.next();
            }
            cdl.countDown();
        }
    });

    cdl.await(60000, TimeUnit.MILLISECONDS);
    if (calendar == null) {
        fail("No calendar found");
    }
}

From source file:com.github.sardine.AuthenticationTest.java

@Test
public void testBasicPreemptiveAuth() throws Exception {
    final HttpClientBuilder client = HttpClientBuilder.create();
    final CountDownLatch count = new CountDownLatch(1);
    client.setDefaultCredentialsProvider(new BasicCredentialsProvider() {
        @Override//from   w ww  .j a va2s . c  o  m
        public Credentials getCredentials(AuthScope authscope) {
            // Set flag that credentials have been used indicating preemptive authentication
            count.countDown();
            return new Credentials() {
                public Principal getUserPrincipal() {
                    return new BasicUserPrincipal("anonymous");
                }

                public String getPassword() {
                    return "invalid";
                }
            };
        }
    });
    SardineImpl sardine = new SardineImpl(client);
    URI url = URI.create("http://sudo.ch/dav/basic/");
    //Send basic authentication header in initial request
    sardine.enablePreemptiveAuthentication(url.getHost());
    try {
        sardine.list(url.toString());
        fail("Expected authorization failure");
    } catch (SardineException e) {
        // Expect Authorization Failed
        assertEquals(401, e.getStatusCode());
        // Make sure credentials have been queried
        assertEquals("No preemptive authentication attempt", 0, count.getCount());
    }
}

From source file:info.archinnov.achilles.it.TestJSONCall.java

@Test
public void should_insert_json_if_not_exists() throws Exception {
    //Given/* w w  w. ja v  a  2 s. c  o  m*/
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);

    //When
    String json = "{\"id\": " + id + ", \"clust\": 1, \"value\": \"val\", " + "\"liststring\": [\"one\"], "
            + "\"setstring\": [\"two\"], " + "\"mapstring\": {\"3\": \"three\"}" + "}";

    AtomicBoolean success = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    manager.crud().insertJSON(json).ifNotExists().withLwtResultListener(new LWTResultListener() {

        @Override
        public void onSuccess() {
            success.getAndSet(true);
            latch.countDown();
        }

        @Override
        public void onError(LWTResult lwtResult) {
            latch.countDown();
        }
    }).execute();

    //Then
    latch.await();
    assertThat(success.get()).isTrue();
    final Row row = session.execute(
            "SELECT * FROM achilles_embedded.entity_for_json_function_call WHERE id = " + id + "AND clust = 1")
            .one();
    assertThat(row).isNotNull();
    assertThat(row.getString("value")).isEqualTo("val");
    assertThat(row.getList("liststring", String.class)).containsExactly("one");
    assertThat(row.getSet("setstring", String.class)).containsExactly("two");
    assertThat(row.getMap("mapstring", Integer.class, String.class)).hasSize(1).containsEntry(3, "three");
}

From source file:io.smartspaces.util.process.StandardNativeApplicationRunnerCollection.java

@Override
public NativeApplicationRunnerState runNativeApplicationRunner(NativeApplicationDescription description,
        long waitTime) {
    NativeApplicationRunner runner = newNativeApplicationRunner();
    runner.configure(description);/*  www  .  ja  v  a 2  s. c o  m*/

    final CountDownLatch runnerComplete = new CountDownLatch(BLOCKING_RUN_COUNTDOWN_COUNT);
    runner.addNativeApplicationRunnerListener(new BaseNativeApplicationRunnerListener() {

        @Override
        public void onNativeApplicationRunnerStartupFailed(NativeApplicationRunner runner) {
            runnerComplete.countDown();
        }

        @Override
        public void onNativeApplicationRunnerShutdown(NativeApplicationRunner runner) {
            runnerComplete.countDown();
        }
    });

    addNativeApplicationRunner(runner);

    try {
        if (!runnerComplete.await(waitTime, TimeUnit.MILLISECONDS)) {
            SimpleSmartSpacesException.throwFormattedException("The command %s did not complete in %d msec",
                    description, waitTime);
        }
    } catch (SimpleSmartSpacesException e) {
        throw e;
    } catch (InterruptedException e) {
        SimpleSmartSpacesException.throwFormattedException("The command %s wait was interrupted", description);
    }

    return runner.getState();
}

From source file:com.microsoft.office.core.AttachmentsAsyncTestCase.java

private void removeAttachment(final IAttachment attachment) throws Exception {
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(message.getAttachmentsAsync(), new FutureCallback<IAttachments>() {
        public void onSuccess(IAttachments attachments) {
            attachments.delete(attachment.getId());
            Me.flush();//from  www  . j a  va 2  s.c  o  m
            cdl.countDown();
        };

        @Override
        public void onFailure(Throwable err) {
            reportError(err);
            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:com.wso2telco.gsma.authenticators.ussd.SendUSSD.java

/**
 * Post request./*from   w  ww. ja va2  s .  c  o  m*/
 *
 * @param url        the url
 * @param requestStr the request str
 * @param operator   the operator
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void postRequest(String url, String requestStr, String operator) throws IOException {
    final HttpPost postRequest = new HttpPost(url);
    postRequest.addHeader("accept", "application/json");
    postRequest.addHeader("Authorization", "Bearer " + ussdConfig.getAuthToken());

    if (operator != null) {
        postRequest.addHeader("operator", operator);
    }

    StringEntity input = new StringEntity(requestStr);
    input.setContentType("application/json");

    postRequest.setEntity(input);
    final CountDownLatch latch = new CountDownLatch(1);
    FutureCallback<HttpResponse> futureCallback = new FutureCallback<HttpResponse>() {
        @Override
        public void completed(final HttpResponse response) {
            latch.countDown();
            if ((response.getStatusLine().getStatusCode() != 201)) {
                log.error("Error occurred while calling end point - " + response.getStatusLine().getStatusCode()
                        + "; Error - " + response.getStatusLine().getReasonPhrase());
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Success Request - " + postRequest.getURI().getSchemeSpecificPart());
                }
            }
        }

        @Override
        public void failed(final Exception ex) {
            latch.countDown();
            log.error("Error occurred while calling end point - " + postRequest.getURI().getSchemeSpecificPart()
                    + "; Error - " + ex);
        }

        @Override
        public void cancelled() {
            latch.countDown();
            log.warn("Operation cancelled while calling end point - "
                    + postRequest.getURI().getSchemeSpecificPart());
        }
    };
    Util.sendAsyncRequest(postRequest, futureCallback, latch);
}

From source file:com.microsoft.office.integration.test.FoldersAsyncTestCase.java

private void deleteAndCheck() throws Exception {
    removeFolder();/*from  ww  w  .  j av  a 2 s  .  c  o  m*/
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getFolders().getAsync(folder.getId()), new FutureCallback<IFolder>() {
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        public void onSuccess(IFolder result) {
            try {
                assertNull(result);
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

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  w  w .j  av  a2  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. ja  v  a  2  s .  co 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:io.riox.springxd.sinks.websocket.WebsocketSinkTests.java

@Test
public void testMultiplePaths() throws Exception {

    final List<String> messages1 = new ArrayList<String>();
    final List<String> messages2 = new ArrayList<String>();

    Field f1 = WebsocketSink.class.getDeclaredField("port");
    f1.setAccessible(true);/* www  .j a  v a2 s  .  c  o m*/
    Field f2 = WebsocketSink.class.getDeclaredField("path");
    f2.setAccessible(true);

    WebsocketSink sink1 = configs.get(0).sink;
    WebsocketSink sink2 = configs.get(1).sink;

    Method m1 = WebsocketSink.class.getDeclaredMethod("input");
    m1.setAccessible(true);
    final MessageChannel channel1 = (MessageChannel) m1.invoke(sink1);
    final MessageChannel channel2 = (MessageChannel) m1.invoke(sink2);

    URI uri1 = new URI("http://localhost:" + configs.get(0).port + configs.get(0).path);
    URI uri2 = new URI("http://localhost:" + configs.get(1).port + configs.get(1).path);
    URI uri3 = new URI("http://localhost:" + configs.get(1).port + "/invalid_path");

    /* create WS clients */
    final int numMsg1 = 2000;
    final int numMsg2 = 3000;
    final CountDownLatch connectLatch = new CountDownLatch(3);
    final CountDownLatch messagesLatch = new CountDownLatch(numMsg1 + numMsg2);
    WebSocketClient c1 = new WebSocketClient(uri1) {
        public void onMessage(String msg) {
            messages1.add(msg);
            messagesLatch.countDown();
        }

        public void onClose(int arg0, String arg1, boolean arg2) {
        }

        public void onError(Exception e) {
        }

        public void onOpen(ServerHandshake arg0) {
            connectLatch.countDown();
        }
    };
    c1.connect();
    WebSocketClient c2 = new WebSocketClient(uri2) {
        public void onMessage(String msg) {
            messages2.add(msg);
            messagesLatch.countDown();
        }

        public void onClose(int arg0, String arg1, boolean arg2) {
        }

        public void onError(Exception e) {
        }

        public void onOpen(ServerHandshake arg0) {
            connectLatch.countDown();
        }
    };
    c2.connect();
    WebSocketClient c3 = new WebSocketClient(uri3) {
        public void onMessage(String msg) {
            messagesLatch.countDown();
        }

        public void onClose(int arg0, String arg1, boolean arg2) {
        }

        public void onError(Exception e) {
            e.printStackTrace();
        }

        public void onOpen(ServerHandshake arg0) {
            connectLatch.countDown();
        }
    };
    c3.connect();
    connectLatch.await(1, TimeUnit.SECONDS);

    /* send test messages */
    new Thread() {
        public void run() {
            for (int i = 0; i < numMsg1; i++) {
                channel1.send(new GenericMessage<String>("foo"));
            }
        }
    }.start();
    new Thread() {
        public void run() {
            for (int i = 0; i < numMsg2; i++) {
                channel2.send(new GenericMessage<String>("bar"));
            }
        }
    }.start();

    /* assertions */
    assertTrue(messagesLatch.await(5, TimeUnit.SECONDS));
    assertEquals(numMsg1, messages1.size());
    assertEquals(numMsg2, messages2.size());
    for (String m : messages1) {
        assertEquals("foo", m);
    }
    for (String m : messages2) {
        assertEquals("bar", m);
    }

}