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

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

Introduction

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

Prototype

public final V get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:org.elasticsearch.smoketest.SmokeTestWatcherWithSecurityIT.java

private ObjectPath getWatchHistoryEntry(String watchId, String state) throws Exception {
    final AtomicReference<ObjectPath> objectPathReference = new AtomicReference<>();
    assertBusy(() -> {//  www  .j  a v a2s. c  o m
        client().performRequest("POST", ".watcher-history-*/_refresh");

        try (XContentBuilder builder = jsonBuilder()) {
            builder.startObject();
            builder.startObject("query").startObject("bool").startArray("must");
            builder.startObject().startObject("term").startObject("watch_id").field("value", watchId)
                    .endObject().endObject().endObject();
            if (Strings.isNullOrEmpty(state) == false) {
                builder.startObject().startObject("term").startObject("state").field("value", state).endObject()
                        .endObject().endObject();
            }
            builder.endArray().endObject().endObject();
            builder.startArray("sort").startObject().startObject("trigger_event.triggered_time")
                    .field("order", "desc").endObject().endObject().endArray();
            builder.endObject();

            StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON);
            Response response = client().performRequest("POST", ".watcher-history-*/_search",
                    Collections.emptyMap(), entity);
            ObjectPath objectPath = ObjectPath.createFromResponse(response);
            int totalHits = objectPath.evaluate("hits.total");
            assertThat(totalHits, is(greaterThanOrEqualTo(1)));
            String watchid = objectPath.evaluate("hits.hits.0._source.watch_id");
            assertThat(watchid, is(watchId));
            objectPathReference.set(objectPath);
        }
    });
    return objectPathReference.get();
}

From source file:org.apache.bookkeeper.client.MetadataUpdateLoopTest.java

/**
 * Test that when 2 update loops conflict when making diffent updates to the metadata,
 * both will eventually succeed, and both updates will be reflected in the final metadata.
 *///from   w w  w .  ja  v  a 2 s .  com
@Test
public void testConflictOnWrite() throws Exception {
    try (BlockableMockLedgerManager lm = spy(new BlockableMockLedgerManager())) {
        lm.blockWrites();

        long ledgerId = 1234L;
        BookieSocketAddress b0 = new BookieSocketAddress("0.0.0.0:3181");
        BookieSocketAddress b1 = new BookieSocketAddress("0.0.0.1:3181");
        BookieSocketAddress b2 = new BookieSocketAddress("0.0.0.2:3181");
        BookieSocketAddress b3 = new BookieSocketAddress("0.0.0.3:3181");

        LedgerMetadata initMeta = LedgerMetadataBuilder.create().withEnsembleSize(2)
                .withDigestType(DigestType.CRC32C).withPassword(new byte[0]).withWriteQuorumSize(2)
                .newEnsembleEntry(0L, Lists.newArrayList(b0, b1)).build();
        Versioned<LedgerMetadata> writtenMetadata = lm.createLedgerMetadata(ledgerId, initMeta).get();

        AtomicReference<Versioned<LedgerMetadata>> reference1 = new AtomicReference<>(writtenMetadata);
        CompletableFuture<Versioned<LedgerMetadata>> loop1 = new MetadataUpdateLoop(lm, ledgerId,
                reference1::get, (currentMetadata) -> currentMetadata.getEnsembleAt(0L).contains(b0),
                (currentMetadata) -> {
                    List<BookieSocketAddress> ensemble = Lists.newArrayList(currentMetadata.getEnsembleAt(0L));
                    ensemble.set(0, b2);
                    return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble)
                            .build();
                }, reference1::compareAndSet).run();

        AtomicReference<Versioned<LedgerMetadata>> reference2 = new AtomicReference<>(writtenMetadata);
        CompletableFuture<Versioned<LedgerMetadata>> loop2 = new MetadataUpdateLoop(lm, ledgerId,
                reference2::get, (currentMetadata) -> currentMetadata.getEnsembleAt(0L).contains(b1),
                (currentMetadata) -> {
                    List<BookieSocketAddress> ensemble = Lists.newArrayList(currentMetadata.getEnsembleAt(0L));
                    ensemble.set(1, b3);
                    return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble)
                            .build();
                }, reference2::compareAndSet).run();

        lm.releaseWrites();

        Versioned<LedgerMetadata> l1meta = loop1.get();
        Versioned<LedgerMetadata> l2meta = loop2.get();

        Assert.assertEquals(l1meta, reference1.get());
        Assert.assertEquals(l2meta, reference2.get());

        Assert.assertEquals(l1meta.getVersion().compare(l2meta.getVersion()), Version.Occurred.BEFORE);

        Assert.assertEquals(l1meta.getValue().getEnsembleAt(0L).get(0), b2);
        Assert.assertEquals(l1meta.getValue().getEnsembleAt(0L).get(1), b1);

        Assert.assertEquals(l2meta.getValue().getEnsembleAt(0L).get(0), b2);
        Assert.assertEquals(l2meta.getValue().getEnsembleAt(0L).get(1), b3);

        verify(lm, times(3)).writeLedgerMetadata(anyLong(), any(), any());
    }
}

From source file:com.facebook.RequestTests.java

@LargeTest
public void testUploadVideoFile() throws IOException, URISyntaxException {
    File tempFile = null;/* w ww .j av  a 2 s  . c  o  m*/
    try {
        tempFile = createTempFileFromAsset("DarkScreen.mov");
        ShareVideo video = new ShareVideo.Builder().setLocalUrl(Uri.fromFile(tempFile)).build();
        ShareVideoContent content = new ShareVideoContent.Builder().setVideo(video).build();
        final ShareApi shareApi = new ShareApi(content);
        final AtomicReference<String> videoId = new AtomicReference<>(null);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                shareApi.share(new FacebookCallback<Sharer.Result>() {
                    @Override
                    public void onSuccess(Sharer.Result result) {
                        videoId.set(result.getPostId());
                        notifyShareFinished();
                    }

                    @Override
                    public void onCancel() {
                        notifyShareFinished();
                    }

                    @Override
                    public void onError(FacebookException error) {
                        notifyShareFinished();
                    }

                    private void notifyShareFinished() {
                        synchronized (shareApi) {
                            shareApi.notifyAll();
                        }
                    }
                });
            }
        });

        synchronized (shareApi) {
            shareApi.wait(REQUEST_TIMEOUT_MILLIS);
        }
        assertNotNull(videoId.get());
    } catch (Exception ex) {
        fail();
    } finally {
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:com.facebook.RequestTests.java

@LargeTest
public void testShareOpenGraphContentWithBadType() throws Exception {
    ShareOpenGraphObject ogObject = new ShareOpenGraphObject.Builder().putString("og:title", "a title")
            .putString("og:type", TEST_OG_OBJECT_TYPE).putString("og:description", "a description").build();

    ShareOpenGraphAction ogAction = new ShareOpenGraphAction.Builder()
            .setActionType(TEST_OG_ACTION_TYPE + "bad").putObject("test", ogObject).build();

    ShareOpenGraphContent content = new ShareOpenGraphContent.Builder().setAction(ogAction)
            .setPreviewPropertyName("test").build();

    final ShareApi shareApi = new ShareApi(content);
    final AtomicReference<String> actionId = new AtomicReference<>(null);
    final AtomicBoolean errorOccurred = new AtomicBoolean(false);

    getActivity().runOnUiThread(new Runnable() {
        @Override/*ww  w  .ja v a2s. com*/
        public void run() {
            shareApi.share(new FacebookCallback<Sharer.Result>() {
                @Override
                public void onSuccess(Sharer.Result result) {
                    actionId.set(result.getPostId());
                    notifyShareFinished();
                }

                @Override
                public void onCancel() {
                    notifyShareFinished();
                }

                @Override
                public void onError(FacebookException error) {
                    errorOccurred.set(true);
                    notifyShareFinished();
                }

                private void notifyShareFinished() {
                    synchronized (shareApi) {
                        shareApi.notifyAll();
                    }
                }
            });
        }
    });

    synchronized (shareApi) {
        shareApi.wait(REQUEST_TIMEOUT_MILLIS);
    }
    assertNull(actionId.get());
    assertTrue(errorOccurred.get());
}

From source file:com.facebook.RequestTests.java

@LargeTest
public void testUploadVideoFileToUserId() throws IOException, URISyntaxException {
    File tempFile = null;//  w  w w.j a va2  s  . c  o m
    try {
        GraphRequest meRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), null);
        GraphResponse meResponse = meRequest.executeAndWait();
        JSONObject meJson = meResponse.getJSONObject();
        assertNotNull(meJson);

        String userId = meJson.optString("id");
        assertNotNull(userId);

        tempFile = createTempFileFromAsset("DarkScreen.mov");
        ShareVideo video = new ShareVideo.Builder().setLocalUrl(Uri.fromFile(tempFile)).build();
        ShareVideoContent content = new ShareVideoContent.Builder().setVideo(video).build();
        final ShareApi shareApi = new ShareApi(content);
        shareApi.setGraphNode(userId);
        final AtomicReference<String> videoId = new AtomicReference<>(null);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                shareApi.share(new FacebookCallback<Sharer.Result>() {
                    @Override
                    public void onSuccess(Sharer.Result result) {
                        videoId.set(result.getPostId());
                        notifyShareFinished();
                    }

                    @Override
                    public void onCancel() {
                        notifyShareFinished();
                    }

                    @Override
                    public void onError(FacebookException error) {
                        notifyShareFinished();
                    }

                    private void notifyShareFinished() {
                        synchronized (shareApi) {
                            shareApi.notifyAll();
                        }
                    }
                });
            }
        });

        synchronized (shareApi) {
            shareApi.wait(REQUEST_TIMEOUT_MILLIS);
        }
        assertNotNull(videoId.get());
    } catch (Exception ex) {
        fail();
    } finally {
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:org.appverse.web.framework.backend.frontfacade.websocket.IntegrationWebsocketTest.java

@Test
public void getPositions() throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> failure = new AtomicReference<>();

    StompSessionHandler handler = new AbstractTestSessionHandler(failure) {

        @Override/*from  ww w . j av  a2 s.c  o m*/
        public void afterConnected(final StompSession session, StompHeaders connectedHeaders) {
            session.subscribe("/app/positions", new StompFrameHandler() {
                @Override
                public Type getPayloadType(StompHeaders headers) {
                    return byte[].class;
                }

                @Override
                public void handleFrame(StompHeaders headers, Object payload) {
                    String json = new String((byte[]) payload);
                    logger.debug("Got " + json);
                    try {
                        new JsonPathExpectationsHelper("$[0].company").assertValue(json,
                                "Citrix Systems, Inc.");
                        new JsonPathExpectationsHelper("$[1].company").assertValue(json, "Dell Inc.");
                        new JsonPathExpectationsHelper("$[2].company").assertValue(json, "Microsoft");
                        new JsonPathExpectationsHelper("$[3].company").assertValue(json, "Oracle");
                    } catch (Throwable t) {
                        failure.set(t);
                    } finally {
                        session.disconnect();
                        latch.countDown();
                    }
                }
            });
        }
    };

    WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
    stompClient.connect("http://localhost:{port}/services/websocket", this.headers, handler, port);

    if (failure.get() != null) {
        throw new AssertionError("", failure.get());
    }

    if (!latch.await(5, TimeUnit.SECONDS)) {
        fail("Portfolio positions not received");
    }
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncQueryIT.java

@Test
public void should_excecute_DML_native_query_with_async_listeners() throws Exception {
    //Given/*from w ww. j a  va2s  .  c  o  m*/
    Long id = RandomUtils.nextLong(0, Long.MAX_VALUE);

    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    final AtomicReference<Throwable> exceptionSpy = new AtomicReference<>();

    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

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

    FutureCallback<Object> exceptionCallBack = new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            exceptionSpy.getAndSet(t);
            latch.countDown();
        }
    };

    final RegularStatement insert = insertInto("completebean").value("id", bindMarker("id"));
    final RegularStatement delete = delete().from("completebean").where(eq("name", "test"));

    //When
    asyncManager.nativeQuery(insert, id).execute(successCallBack);
    asyncManager.nativeQuery(delete).execute(exceptionCallBack);

    latch.await();

    //Then
    assertThat(successSpy.get()).isNotNull().isSameAs(Empty.INSTANCE);
    assertThat(exceptionSpy.get()).isNotNull().isInstanceOf(InvalidQueryException.class);
}

From source file:interactivespaces.service.comm.network.NettyUdpSocketTest.java

/**
 * Test a round trip from a UDP client to a UDP server and back.
 *
 * @throws Exception/* w  w w .ja  va 2s  .c  o  m*/
 *           something bad
 */
@Test
public void testUdpPacketSend() throws Exception {
    final byte[] serverResponseExpectedData = new byte[] { 17, 2, 89, 127 };
    byte[] serverRequestExpectedData = new byte[] { 55, 66, 22, 87 };

    int serverPort = 10000;

    final CountDownLatch serverReceiveLatch = new CountDownLatch(1);
    final AtomicReference<UdpServerRequest> serverRequestActualData = new AtomicReference<UdpServerRequest>();

    final CountDownLatch clientReceiveLatch = new CountDownLatch(1);
    final AtomicReference<byte[]> serverResponseActualData = new AtomicReference<byte[]>();

    UdpServerNetworkCommunicationEndpoint serverEndpoint = serverService.newServer(serverPort, log);
    UdpClientNetworkCommunicationEndpoint clientEndpoint = clientService.newClient(log);

    try {
        serverEndpoint.addListener(new UdpServerNetworkCommunicationEndpointListener() {

            @Override
            public void onUdpRequest(UdpServerNetworkCommunicationEndpoint endpoint, UdpServerRequest request) {
                serverRequestActualData.set(request);

                request.writeResponse(serverResponseExpectedData);

                serverReceiveLatch.countDown();
            }
        });

        serverEndpoint.startup();

        clientEndpoint.addListener(new UdpClientNetworkCommunicationEndpointListener() {

            @Override
            public void onUdpResponse(UdpClientNetworkCommunicationEndpoint endpoint, byte[] response,
                    InetSocketAddress remoteAddress) {
                serverResponseActualData.set(response);

                clientReceiveLatch.countDown();
            }
        });
        clientEndpoint.startup();

        WriteableUdpPacket packet = clientEndpoint.newWriteableUdpPacket(serverRequestExpectedData.length);
        packet.writeBytes(serverRequestExpectedData);

        packet.write(new InetSocketAddress("127.0.0.1", serverPort));

        Assert.assertTrue(clientReceiveLatch.await(5, TimeUnit.SECONDS));
        Assert.assertTrue(serverReceiveLatch.await(5, TimeUnit.SECONDS));
    } finally {
        clientEndpoint.shutdown();
        serverEndpoint.shutdown();
    }

    Assert.assertArrayEquals(serverRequestExpectedData, serverRequestActualData.get().getRequest());
    Assert.assertArrayEquals(serverResponseExpectedData, serverResponseActualData.get());
}

From source file:io.smartspaces.service.comm.network.NettyUdpSocketTest.java

/**
 * Test a round trip from a UDP client to a UDP server and back.
 *
 * @throws Exception//from w w  w.j  ava 2 s . c o  m
 *           something bad
 */
@Test
public void testUdpPacketSend() throws Exception {
    final byte[] serverResponseExpectedData = new byte[] { 17, 2, 89, 127 };
    byte[] serverRequestExpectedData = new byte[] { 55, 66, 22, 87 };

    int serverPort = 8099;

    final CountDownLatch serverReceiveLatch = new CountDownLatch(1);
    final AtomicReference<UdpServerRequest> serverRequestActualData = new AtomicReference<UdpServerRequest>();

    final CountDownLatch clientReceiveLatch = new CountDownLatch(1);
    final AtomicReference<byte[]> serverResponseActualData = new AtomicReference<byte[]>();

    UdpServerNetworkCommunicationEndpoint serverEndpoint = serverService.newServer(serverPort, log);
    UdpClientNetworkCommunicationEndpoint clientEndpoint = clientService.newClient(log);

    try {
        serverEndpoint.addListener(new UdpServerNetworkCommunicationEndpointListener() {

            @Override
            public void onUdpRequest(UdpServerNetworkCommunicationEndpoint endpoint, UdpServerRequest request) {
                serverRequestActualData.set(request);

                request.writeResponse(serverResponseExpectedData);

                serverReceiveLatch.countDown();
            }
        });

        serverEndpoint.startup();

        clientEndpoint.addListener(new UdpClientNetworkCommunicationEndpointListener() {

            @Override
            public void onUdpResponse(UdpClientNetworkCommunicationEndpoint endpoint, byte[] response,
                    InetSocketAddress remoteAddress) {
                serverResponseActualData.set(response);

                clientReceiveLatch.countDown();
            }
        });
        clientEndpoint.startup();

        WriteableUdpPacket packet = clientEndpoint.newWriteableUdpPacket(serverRequestExpectedData.length);
        packet.writeBytes(serverRequestExpectedData);

        packet.write(new InetSocketAddress("127.0.0.1", serverPort));

        Assert.assertTrue(clientReceiveLatch.await(5, TimeUnit.SECONDS));
        Assert.assertTrue(serverReceiveLatch.await(5, TimeUnit.SECONDS));
    } finally {
        clientEndpoint.shutdown();
        serverEndpoint.shutdown();
    }

    Assert.assertArrayEquals(serverRequestExpectedData, serverRequestActualData.get().getRequest());
    Assert.assertArrayEquals(serverResponseExpectedData, serverResponseActualData.get());
}

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

@SuppressWarnings("unchecked")
@Test/*  w w w .  j  a v  a 2 s .  com*/
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);
}