Example usage for java.util.concurrent.atomic AtomicInteger incrementAndGet

List of usage examples for java.util.concurrent.atomic AtomicInteger incrementAndGet

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicInteger incrementAndGet.

Prototype

public final int incrementAndGet() 

Source Link

Document

Atomically increments the current value, with memory effects as specified by VarHandle#getAndAdd .

Usage

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

@Test
public void shouldDecodeSimpleStringAsSignature() throws Exception {
    String response = Resources.read("signature_simple_string.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    queue.add(requestMock);/* w  ww.jav  a2 s .c o m*/
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0);

    final AtomicInteger invokeCounter1 = new AtomicInteger();
    assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, FAKE_CLIENTID, "success", "\"json\"",
            new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    invokeCounter1.incrementAndGet();
                    String item = buf.toString(CharsetUtil.UTF_8);
                    buf.release();
                    fail("no result expected, got " + item);
                }
            }, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    buf.release();
                    fail("no error expected");
                }
            },
            //no metrics in this json sample
            expectedMetricsCounts(0, 1));
    assertEquals(0, invokeCounter1.get());
}

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

@Test
public void shouldDecodeNRowResponse() throws Exception {
    String response = Resources.read("success_5.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    queue.add(requestMock);/*from ww  w  .j a  v  a 2  s .  co  m*/
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0);

    final AtomicInteger found = new AtomicInteger(0);
    assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, FAKE_CLIENTID, "success",
            FAKE_SIGNATURE, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf row) {
                    found.incrementAndGet();
                    String content = row.toString(CharsetUtil.UTF_8);
                    row.release();
                    assertNotNull(content);
                    assertTrue(!content.isEmpty());
                    try {
                        Map decoded = mapper.readValue(content, Map.class);
                        assertTrue(decoded.size() > 0);
                        assertTrue(decoded.containsKey("name"));
                    } catch (Exception e) {
                        assertTrue(false);
                    }
                }
            }, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    fail("no error expected");
                }
            }, expectedMetricsCounts(0, 5));
    assertEquals(5, found.get());
}

From source file:org.elasticsearch.client.sniff.SnifferTests.java

/**
 * Test that {@link Sniffer#close()} shuts down the underlying {@link Scheduler}, and that such calls are idempotent.
 * Also verifies that the next scheduled round gets cancelled.
 *///from  www. j av a 2  s .  c o m
public void testClose() {
    final Future<?> future = mock(Future.class);
    long sniffInterval = randomLongBetween(1, Long.MAX_VALUE);
    long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE);
    RestClient restClient = mock(RestClient.class);
    final AtomicInteger shutdown = new AtomicInteger(0);
    final AtomicBoolean initialized = new AtomicBoolean(false);
    Scheduler scheduler = new Scheduler() {
        @Override
        public Future<?> schedule(Sniffer.Task task, long delayMillis) {
            if (initialized.compareAndSet(false, true)) {
                //run from the same thread so the sniffer gets for sure initialized and the scheduled task gets cancelled on close
                task.run();
            }
            return future;
        }

        @Override
        public void shutdown() {
            shutdown.incrementAndGet();
        }
    };

    Sniffer sniffer = new Sniffer(restClient, new MockHostsSniffer(), scheduler, sniffInterval,
            sniffAfterFailureDelay);
    assertEquals(0, shutdown.get());
    int iters = randomIntBetween(3, 10);
    for (int i = 1; i <= iters; i++) {
        sniffer.close();
        verify(future, times(i)).cancel(false);
        assertEquals(i, shutdown.get());
    }
}

From source file:com.chessix.vas.web.AccountController.java

@RequestMapping(value = "/{clasId}/range/from/{start}/count/{count}", method = RequestMethod.POST)
public DeferredResult<Object> createAccounts(@PathVariable final String clasId,
        @PathVariable final String start, @PathVariable final String count) {
    log.info("createAccounts({},{},{})", clasId, start, count);
    final ActorRef clas = clasService.getClas(clasId);
    final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
    final int countValue = Integer.parseInt(count);

    if (countValue > MAX_ACCOUNTS_IN_BATCH) {
        deferredResult/*from www .j ava 2  s .co m*/
                .setErrorResult(String.format("count %s is to large (> %d)", count, MAX_ACCOUNTS_IN_BATCH));
        return deferredResult;
    }

    if (clas != null) {
        final List<AccountCreated> results = Collections.synchronizedList(new LinkedList<AccountCreated>());
        final AtomicInteger resultsCounter = new AtomicInteger(0);

        for (int i = Integer.parseInt(start); i < Integer.parseInt(start) + countValue; i++) {
            final String accountId = Integer.toString(i);
            log.debug("createAccounts() : create {}", accountId);
            final Future<Object> future = Patterns.ask(clas,
                    new CreateAccount.RequestBuilder(clasId).accountId(accountId).build(),
                    timeout * countValue);
            future.onSuccess(new OnSuccess<Object>() {
                @Override
                public void onSuccess(final Object result) {
                    log.info("createAccount({}) : result: {}", clasId, result);
                    final CreateAccount.Response response = (CreateAccount.Response) result;
                    results.add(new AccountCreated(clasId, response.getAccountId(), true,
                            String.format("Account %s created", accountId)));

                    // check if all values are received
                    if (resultsCounter.incrementAndGet() >= countValue) {
                        deferredResult.setResult(results);
                    }

                }
            }, system.dispatcher());
            future.onFailure(new OnFailure() {
                @Override
                public void onFailure(final Throwable arg) throws Throwable {
                    log.error("onFailure", arg);
                    deferredResult
                            .setErrorResult(new AccountCreated(clasId, null, false, arg.getLocalizedMessage()));
                }
            }, system.dispatcher());
        }
    } else {
        deferredResult.setErrorResult(new AccountCreated(clasId, null, false, "CLAS does not exist"));
    }
    return deferredResult;
}

From source file:org.apache.tinkerpop.gremlin.server.GremlinDriverIntegrateTest.java

@Test
public void shouldStream() throws Exception {
    final Cluster cluster = Cluster.open();
    final Client client = cluster.connect();

    final ResultSet results = client.submit("[1,2,3,4,5,6,7,8,9]");
    final AtomicInteger counter = new AtomicInteger(0);
    results.stream().map(i -> i.get(Integer.class) * 2)
            .forEach(i -> assertEquals(counter.incrementAndGet() * 2, Integer.parseInt(i.toString())));
    assertEquals(9, counter.get());//from w  ww .  j  av a2 s. c  o  m
    assertThat(results.allItemsAvailable(), is(true));

    // cant stream it again
    assertThat(results.stream().iterator().hasNext(), is(false));

    cluster.close();
}

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

@Test
public void shouldDecodeOneRowResponseWithShortClientID() throws Exception {
    String response = Resources.read("short_client_id.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    queue.add(requestMock);/*from  w  ww.  j a v a 2 s.  c om*/
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0);

    final AtomicInteger invokeCounter1 = new AtomicInteger();
    assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, "123456789", "success",
            FAKE_SIGNATURE, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    invokeCounter1.incrementAndGet();
                    String response = buf.toString(CharsetUtil.UTF_8);
                    try {
                        Map found = mapper.readValue(response, Map.class);
                        assertEquals(12, found.size());
                        assertEquals("San Francisco", found.get("city"));
                        assertEquals("United States", found.get("country"));
                        Map geo = (Map) found.get("geo");
                        assertNotNull(geo);
                        assertEquals(3, geo.size());
                        assertEquals("ROOFTOP", geo.get("accuracy"));
                    } catch (IOException e) {
                        assertFalse(true);
                    }
                }
            }, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    fail("no error expected");
                }
            }, expectedMetricsCounts(0, 1));
    assertEquals(1, invokeCounter1.get());
}

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

@Test
public void shouldDecodeOneRowResponse() throws Exception {
    String response = Resources.read("success_1.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    queue.add(requestMock);//from   w w w.  j a  va2s  .  c o m
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0);

    final AtomicInteger invokeCounter1 = new AtomicInteger();
    assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, FAKE_CLIENTID, "success",
            FAKE_SIGNATURE, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    invokeCounter1.incrementAndGet();
                    String response = buf.toString(CharsetUtil.UTF_8);
                    try {
                        Map found = mapper.readValue(response, Map.class);
                        assertEquals(12, found.size());
                        assertEquals("San Francisco", found.get("city"));
                        assertEquals("United States", found.get("country"));
                        Map geo = (Map) found.get("geo");
                        assertNotNull(geo);
                        assertEquals(3, geo.size());
                        assertEquals("ROOFTOP", geo.get("accuracy"));
                    } catch (IOException e) {
                        fail("no result expected");
                    }
                }
            }, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    fail("no error expected");
                }
            }, expectedMetricsCounts(0, 1));
    assertEquals(1, invokeCounter1.get());
}

From source file:cc.gospy.example.google.GoogleSpider.java

public Collection<String> getResultLinks(final String keyword, final int pageFrom, final int pageTo) {
    if (pageFrom < 1)
        throw new IllegalArgumentException(pageFrom + "<" + 1);
    if (pageFrom >= pageTo)
        throw new IllegalArgumentException(pageFrom + ">=" + pageTo);

    final AtomicInteger currentPage = new AtomicInteger(pageFrom);
    final AtomicBoolean returned = new AtomicBoolean(false);
    final Collection<String> links = new LinkedHashSet<>();
    Gospy googleSpider = Gospy.custom()/*from  w w  w.j a v a 2 s.co  m*/
            .setScheduler(
                    Schedulers.VerifiableScheduler.custom().setExitCallback(() -> returned.set(true)).build())
            .addFetcher(Fetchers.HttpFetcher.custom()
                    .before(request -> request.setConfig(
                            RequestConfig.custom().setProxy(new HttpHost("127.0.0.1", 8118)).build()))
                    .build())
            .addProcessor(Processors.XPathProcessor.custom()
                    .extract("//*[@id='ires']/ol/div/h3/a/@href", (task, resultList, returnedData) -> {
                        resultList.forEach(a -> {
                            if (a.startsWith("/url?q=")) {
                                String link = a.substring(7);
                                int end = link.indexOf("&sa=");
                                links.add(link.substring(0, end != -1 ? end : link.length()));
                            }
                        });
                        currentPage.incrementAndGet();
                        if (pageFrom <= currentPage.get() && currentPage.get() < pageTo) {
                            return Arrays.asList(
                                    new Task(String.format("http://www.google.com/search?q=%s&start=%d&*",
                                            keyword, (currentPage.get() - 1) * 10)));
                        } else {
                            return Arrays.asList();
                        }
                    }).build())
            .build().addTask(String.format("http://www.google.com/search?q=%s&start=%d&*", keyword, pageFrom));
    googleSpider.start();
    while (!returned.get())
        ; // block until spider returned
    googleSpider.stop();
    return links;
}

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

@Test
public void shouldDecodeOneRowResponseWithoutPrettyPrint() throws Exception {
    String response = Resources.read("no_pretty.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    queue.add(requestMock);//ww w .  j  a v a  2s .c o m
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0);

    final AtomicInteger invokeCounter1 = new AtomicInteger();
    assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, FAKE_CLIENTID, "success",
            FAKE_SIGNATURE, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    invokeCounter1.incrementAndGet();
                    String response = buf.toString(CharsetUtil.UTF_8);
                    buf.release();
                    try {
                        Map found = mapper.readValue(response, Map.class);
                        assertEquals(12, found.size());
                        assertEquals("San Francisco", found.get("city"));
                        assertEquals("United States", found.get("country"));
                        Map geo = (Map) found.get("geo");
                        assertNotNull(geo);
                        assertEquals(3, geo.size());
                        assertEquals("ROOFTOP", geo.get("accuracy"));
                    } catch (IOException e) {
                        assertFalse(true);
                    }
                }
            }, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    fail("no error expected");
                }
            }, expectedMetricsCounts(0, 1));
    assertEquals(1, invokeCounter1.get());
}

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

@Test
public void shouldDecodeNRowResponseChunked() throws Exception {
    String response = Resources.read("success_5.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultLastHttpContent(
            Unpooled.copiedBuffer(response.substring(0, 300), CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultLastHttpContent(
            Unpooled.copiedBuffer(response.substring(300, 950), CharsetUtil.UTF_8));
    HttpContent responseChunk3 = new DefaultLastHttpContent(
            Unpooled.copiedBuffer(response.substring(950, 1345), CharsetUtil.UTF_8));
    HttpContent responseChunk4 = new DefaultLastHttpContent(
            Unpooled.copiedBuffer(response.substring(1345, 3000), CharsetUtil.UTF_8));
    HttpContent responseChunk5 = new DefaultLastHttpContent(
            Unpooled.copiedBuffer(response.substring(3000), CharsetUtil.UTF_8));

    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    queue.add(requestMock);//from   w  w w. j  a  va2 s  . c o  m
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2, responseChunk3, responseChunk4,
            responseChunk5);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0);

    final AtomicInteger found = new AtomicInteger(0);
    assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, FAKE_CLIENTID, "success",
            FAKE_SIGNATURE, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf byteBuf) {
                    found.incrementAndGet();
                    String content = byteBuf.toString(CharsetUtil.UTF_8);
                    byteBuf.release();
                    assertNotNull(content);
                    assertTrue(!content.isEmpty());
                    try {
                        Map decoded = mapper.readValue(content, Map.class);
                        assertTrue(decoded.size() > 0);
                        assertTrue(decoded.containsKey("name"));
                    } catch (Exception e) {
                        assertTrue(false);
                    }
                }
            }, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    fail("no error expected");
                }
            }, expectedMetricsCounts(0, 5));
    assertEquals(5, found.get());
}