Example usage for java.util.concurrent.atomic AtomicReference AtomicReference

List of usage examples for java.util.concurrent.atomic AtomicReference AtomicReference

Introduction

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

Prototype

public AtomicReference() 

Source Link

Document

Creates a new AtomicReference with null initial value.

Usage

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void relativeRedirect() throws Exception {
    int code = 200;
    statusCode.set(code);//from  w ww.ja v  a  2s .c om
    redirects.set(2);
    AtomicIntegerArray expected = copy(statusCounts);
    expected.addAndGet(302, 2);
    expected.addAndGet(code, 1);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get(uri("/relativeRedirect")).subscribe(Actions.empty(), new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            latch.countDown();
            throwable.set(t);
        }
    }, new Action0() {
        @Override
        public void call() {
            latch.countDown();
        }
    });

    latch.await();
    assertEquals(expected, statusCounts);
}

From source file:com.networknt.basic.BasicAuthHandlerTest.java

@Test
public void testInvalidPassword() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from  www.  j av  a2 s  .co m*/
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        request.getRequestHeaders().put(Headers.AUTHORIZATION, "BASIC " + encodeCredentials("user2", "ppp"));
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(401, statusCode);
    if (statusCode == 401) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10047", status.getCode());
    }
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java

@Test
public void test2Clients() throws Exception {
    CuratorFramework client1 = null;/*from ww  w .j av  a 2  s . c  o m*/
    CuratorFramework client2 = null;
    try {
        client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        client1.start();
        client2.start();

        final InterProcessLock mutexForClient1 = makeLock(client1);
        final InterProcessLock mutexForClient2 = makeLock(client2);

        final CountDownLatch latchForClient1 = new CountDownLatch(1);
        final CountDownLatch latchForClient2 = new CountDownLatch(1);
        final CountDownLatch acquiredLatchForClient1 = new CountDownLatch(1);
        final CountDownLatch acquiredLatchForClient2 = new CountDownLatch(1);

        final AtomicReference<Exception> exceptionRef = new AtomicReference<Exception>();

        ExecutorService service = Executors.newCachedThreadPool();
        Future<Object> future1 = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    mutexForClient1.acquire(10, TimeUnit.SECONDS);
                    acquiredLatchForClient1.countDown();
                    latchForClient1.await(10, TimeUnit.SECONDS);
                    mutexForClient1.release();
                } catch (Exception e) {
                    exceptionRef.set(e);
                }
                return null;
            }
        });
        Future<Object> future2 = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    mutexForClient2.acquire(10, TimeUnit.SECONDS);
                    acquiredLatchForClient2.countDown();
                    latchForClient2.await(10, TimeUnit.SECONDS);
                    mutexForClient2.release();
                } catch (Exception e) {
                    exceptionRef.set(e);
                }
                return null;
            }
        });

        while (!mutexForClient1.isAcquiredInThisProcess() && !mutexForClient2.isAcquiredInThisProcess()) {
            Thread.sleep(1000);
            Assert.assertFalse(future1.isDone() && future2.isDone());
        }

        Assert.assertTrue(
                mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess());
        Thread.sleep(1000);
        Assert.assertTrue(
                mutexForClient1.isAcquiredInThisProcess() || mutexForClient2.isAcquiredInThisProcess());
        Assert.assertTrue(
                mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess());

        Exception exception = exceptionRef.get();
        if (exception != null) {
            throw exception;
        }

        if (mutexForClient1.isAcquiredInThisProcess()) {
            latchForClient1.countDown();
            Assert.assertTrue(acquiredLatchForClient2.await(10, TimeUnit.SECONDS));
            Assert.assertTrue(mutexForClient2.isAcquiredInThisProcess());
        } else {
            latchForClient2.countDown();
            Assert.assertTrue(acquiredLatchForClient1.await(10, TimeUnit.SECONDS));
            Assert.assertTrue(mutexForClient1.isAcquiredInThisProcess());
        }
    } finally {
        IOUtils.closeQuietly(client1);
        IOUtils.closeQuietly(client2);
    }
}

From source file:fr.pilato.elasticsearch.crawler.fs.test.integration.ElasticsearchClientIT.java

@Test
public void testBulkWithErrors() throws IOException, InterruptedException {
    // Create the index first
    elasticsearchClient.createIndex(getCrawlerName());
    elasticsearchClient.waitForHealthyIndex(getCrawlerName());

    AtomicReference<BulkResponse> bulkResponse = new AtomicReference<>();

    BulkProcessor bulkProcessor = new BulkProcessor.Builder(elasticsearchClient, new BulkProcessor.Listener() {
        @Override//from w  w w  . java 2s. c  o m
        public void beforeBulk(long executionId, BulkRequest request) {
        }

        @Override
        public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
            bulkResponse.set(response);
        }

        @Override
        public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
        }
    }).setBulkActions(100).setFlushInterval(TimeValue.timeValueMillis(200)).build();
    bulkProcessor.add(
            new IndexRequest(getCrawlerName(), FsCrawlerUtil.INDEX_TYPE_DOC, "id").source("{\"foo\":\"bar\""));
    bulkProcessor.close();

    BulkResponse response = bulkResponse.get();
    Throwable message = response.buildFailureMessage();

    assertThat(message.getMessage(), containsString("1 failures"));

    // If we run the test with a TRACE level, we can check more things
    if (LogManager.getLogger(BulkResponse.class).isTraceEnabled()) {
        assertThat(message.getMessage(), containsString("failed to parse"));
    }
}

From source file:com.quartercode.eventbridge.test.def.extra.extension.DefaultReturnEventExtensionReturnerTest.java

@SuppressWarnings("unchecked")
@Test/*from   www  . jav  a 2s .c  om*/
public void testCallRequestHandler() {

    final BridgeConnector source = context.mock(BridgeConnector.class);

    final EmptyEvent1 regularEvent = new EmptyEvent1();
    final EmptyEvent2 otherEvent = new EmptyEvent2();

    final RequestEventHandler<Event> handler = context.mock(RequestEventHandler.class, "handler");
    final EventPredicate<Event> predicate = context.mock(EventPredicate.class, "predicate");
    final EventPredicate<?> wrapperPredicate = new ReturnEventExtensionWrapperPredicate(predicate);

    final RequestHandleInterceptor interceptor = context.mock(RequestHandleInterceptor.class);
    extension.getRequestHandleChannel().addInterceptor(new DummyRequestHandleInterceptor(interceptor), 1);

    final AtomicReference<LowLevelHandler> lowLevelHandler = new AtomicReference<>();

    // @formatter:off
    context.checking(new Expectations() {
        {

            allowing(predicate).test(regularEvent);
            will(returnValue(true));
            allowing(predicate).test(otherEvent);
            will(returnValue(false));

            oneOf(lowLevelHandlerModule).addHandler(with(aLowLevelHandlerWithThePredicate(wrapperPredicate)));
            will(storeArgument(0).in(lowLevelHandler));

            final Sequence handleChain = context.sequence("handleChain");
            // Regular event
            oneOf(interceptor).handleRequest(with(any(ChannelInvocation.class)), with(regularEvent),
                    with(source), with(handler), with(any(ReturnEventSender.class)));
            inSequence(handleChain);
            oneOf(handler).handle(with(regularEvent), with(any(ReturnEventSender.class)));
            inSequence(handleChain);
            // Other event
            // Expect the unwanted event to be invoked since the predicate is not tested by the StandardHandlerModule
            // In fact, the predicate is tested by the LowLevelHandlerModule
            oneOf(interceptor).handleRequest(with(any(ChannelInvocation.class)), with(otherEvent), with(source),
                    with(handler), with(any(ReturnEventSender.class)));
            inSequence(handleChain);
            oneOf(handler).handle(with(otherEvent), with(any(ReturnEventSender.class)));
            inSequence(handleChain);

        }
    });
    // @formatter:on

    extension.addRequestHandler(handler, predicate);

    lowLevelHandler.get().handle(new ReturnEventExtensionWrapper(regularEvent, 0, true), source);
    lowLevelHandler.get().handle(new ReturnEventExtensionWrapper(otherEvent, 0, true), source);
}

From source file:com.microsoft.gittf.client.clc.commands.framework.Command.java

protected TFSTeamProjectCollection getConnection(final URI serverURI, final Repository repository)
        throws Exception {
    if (connection == null) {
        AtomicReference<Credentials> credentials = new AtomicReference<Credentials>();
        credentials.set(getCredentials(repository));

        connection = getConnection(serverURI, credentials);

        userCredentials = credentials.get();
    }/*from w  ww .  j  av a  2s .c om*/

    return connection;
}

From source file:com.networknt.openapi.ValidatorHandlerTest.java

@Test
public void testDeleteWithoutHeader() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//w  ww . j ava 2 s.  c om
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v1/pets/111").setMethod(Methods.DELETE);
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(400, statusCode);
    if (statusCode == 400) {
        Status status = Config.getInstance().getMapper().readValue(body, Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR11017", status.getCode());
    }
}

From source file:com.quartercode.eventbridge.test.def.bridge.module.DefaultStandardHandlerModuleTest.java

@SuppressWarnings("unchecked")
@Test/*from w w  w  .  j a  va2 s  .  c o m*/
public void testCallHandlerWrongTypeInPredicate() {

    final EventPredicate<Event> predicate = context.mock(EventPredicate.class);
    final EventHandler<CallableEvent> handler = new EventHandler<CallableEvent>() {

        @Override
        public void handle(CallableEvent event) {

            // Provoke a ClassCastException
            event.call();
        }

    };

    final AtomicReference<LowLevelHandler> lowLevelHandler = new AtomicReference<>();

    // @formatter:off
    context.checking(new Expectations() {
        {

            oneOf(lowLevelHandlerModule).addHandler(with(aLowLevelHandlerWithThePredicate(predicate)));
            will(storeArgument(0).in(lowLevelHandler));

        }
    });
    // @formatter:on

    module.addHandler(handler, predicate);

    lowLevelHandler.get().handle(new EmptyEvent1(), null);
}

From source file:io.vertx.camel.OutboundEndpointTest.java

@Test
public void testWithRouteWithFailure() throws Exception {
    AtomicReference<String> calledSpy = new AtomicReference<>();

    camel.addRoutes(new RouteBuilder() {
        @Override/*from   www.  j a  va  2s.  co m*/
        public void configure() throws Exception {
            from("direct:my-route").to("http://localhost:8081");
        }
    });

    bridge = CamelBridge.create(vertx, new CamelBridgeOptions(camel)
            .addOutboundMapping(fromVertx("camel-route").toCamel("direct:my-route")));

    camel.start();
    BridgeHelper.startBlocking(bridge);

    vertx.eventBus().send("camel-route", "hello", reply -> {
        calledSpy.set(reply.cause().getMessage());
    });

    await().atMost(DEFAULT_TIMEOUT).untilAtomic(calledSpy, is("Connection refused"));
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

@Override
public V put(K key, V value) {
    checkState(!closed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);/*from  w w  w  .ja va 2s .co  m*/
    checkNotNull(value, ERROR_NULL_VALUE);

    String encodedKey = encodeKey(key);
    byte[] encodedValue = encodeValue(value);

    MapValue newValue = new MapValue(encodedValue, timestampProvider.get(Maps.immutableEntry(key, value)));

    counter.incrementCount();
    AtomicReference<byte[]> oldValue = new AtomicReference<>();
    AtomicBoolean updated = new AtomicBoolean(false);
    items.compute(encodedKey, (k, existing) -> {
        if (existing == null || newValue.isNewerThan(existing)) {
            updated.set(true);
            oldValue.set(existing != null ? existing.get() : null);
            return newValue;
        }
        return existing;
    });

    if (updated.get()) {
        notifyPeers(new UpdateEntry(encodedKey, newValue),
                peerUpdateFunction.select(Maps.immutableEntry(key, value), membershipService));
        if (oldValue.get() == null) {
            notifyListeners(new MapDelegateEvent<>(INSERT, key, value));
        } else {
            notifyListeners(new MapDelegateEvent<>(UPDATE, key, value));
        }
        return decodeValue(oldValue.get());
    }
    return value;
}