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:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java

@Test
public void should_notify_listener_when_LWT_error_on_native_query() throws Exception {
    //Given//from  ww  w.  j  av  a 2  s .c om
    final AtomicReference<LWTResultListener.LWTResult> atomicLWTResult = new AtomicReference(null);
    LWTResultListener listener = new LWTResultListener() {
        @Override
        public void onSuccess() {
        }

        @Override
        public void onError(LWTResult lwtResult) {
            atomicLWTResult.compareAndSet(null, lwtResult);
        }
    };
    Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("[applied]", false, "name",
            "John");

    CompleteBean entity = builder().randomId().name("John").buid();
    manager.insert(entity);

    final RegularStatement statement = update("CompleteBean").with(set("name", "Helen"))
            .where(eq("id", entity.getId())).onlyIf(eq("name", "Andrew"));

    //When
    final NativeQuery nativeQuery = manager.nativeQuery(statement, lwtResultListener(listener));
    nativeQuery.execute();

    //Then
    final LWTResultListener.LWTResult LWTResult = atomicLWTResult.get();

    assertThat(LWTResult).isNotNull();
    assertThat(LWTResult.operation()).isEqualTo(UPDATE);
    assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues);
}

From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java

private void verifyAuthorizationPage(OAuth2RestTemplate restTemplate, String location) {
    final AtomicReference<String> confirmationPage = new AtomicReference<String>();
    AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider() {
        @Override/*from w  w  w  . java2 s .c om*/
        protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() {
            return new ResponseExtractor<ResponseEntity<Void>>() {
                public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
                    confirmationPage
                            .set(StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")));
                    return new ResponseEntity<Void>(response.getHeaders(), response.getStatusCode());
                }
            };
        }
    };
    try {
        provider.obtainAuthorizationCode(restTemplate.getResource(),
                restTemplate.getOAuth2ClientContext().getAccessTokenRequest());
    } catch (UserApprovalRequiredException e) {
        // ignore
    }
    String page = confirmationPage.get();
    verifyAuthorizationPage(page);
}

From source file:com.springsource.insight.plugin.apache.http.hc4.HttpClientExecutionCollectionAspectTest.java

private void runResponseHandlerTest(String testName, HttpHost host, HttpContext context) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    String uri = createTestUri(testName);
    HttpGet request = new HttpGet(uri);
    // must be final or the anonymous class cannot reference it...
    final AtomicReference<HttpResponse> rspRef = new AtomicReference<HttpResponse>(null);
    ResponseHandler<HttpResponse> handler = new ResponseHandler<HttpResponse>() {
        public HttpResponse handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            HttpResponse prevValue = rspRef.getAndSet(response);
            assertNull("Duplicate response handling", prevValue);
            return response;
        }//w  ww  .j a  va2  s.  c  o m
    };

    HttpResponse response;
    if (host == null) {
        response = (context == null) ? httpClient.execute(request, handler)
                : httpClient.execute(request, handler, context);
    } else {
        response = (context == null) ? httpClient.execute(host, request, handler)
                : httpClient.execute(host, request, handler, context);
    }

    assertSame("Mismatched reference and return value", response, rspRef.get());
    handleResponse(testName, uri, request, response, true);
}

From source file:com.networknt.graphql.security.JwtVerifyHandlerTest.java

@Test
public void testWithRightScopeInIdToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from w w  w  . j  a va2 s . c o  m
        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("/v2/pet/111").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTgwNTEzNjU1MSwianRpIjoiV0Z1VVZneE83dmxKUm5XUlllMjE1dyIsImlhdCI6MTQ4OTc3NjU1MSwibmJmIjoxNDg5Nzc2NDMxLCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6InN0ZXZlIiwidXNlcl90eXBlIjoiRU1QTE9ZRUUiLCJjbGllbnRfaWQiOiJmN2Q0MjM0OC1jNjQ3LTRlZmItYTUyZC00YzU3ODc0MjFlNzIiLCJzY29wZSI6WyJ3cml0ZTpwZXRzIiwicmVhZDpwZXRzIl19.ZDlD_JbtHMqfx8EWOlOXI0zFGjB_pJ6yXWpxoE03o2yQnCUq1zypaDTJWSiy-BPIiQAxwDV09L3SN7RsOcgJ3y2LLFhgqIXhcHoePxoz52LPOeeiihG2kcrgBm-_VMq0uUykLrD-ljSmmSm1Hai_dx0WiYGAEJf-TiD1mgzIUTlhogYrjFKlp2NaYHxr7yjzEGefKv4DWdjtlEMmX_cXkqPgxra_omzyxeWE-n0b7f_r7Hr5HkxnmZ23gkZcvFXfVWKEp2t0_dYmNCbSVDavAjNanvmWsNThYNglFRvF0lm8kl7jkfMO1pTa0WLcBLvOO2y_jRWjieFCrc0ksbIrXA");
        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(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(body);
    }
}

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

@Test
public void should_batch_with_custom_consistency_level_async() throws Exception {
    Tweet tweet1 = TweetTestBuilder.tweet().randomId().content("simple_tweet1").buid();
    Tweet tweet2 = TweetTestBuilder.tweet().randomId().content("simple_tweet2").buid();
    Tweet tweet3 = TweetTestBuilder.tweet().randomId().content("simple_tweet3").buid();

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override/*from   w  w w.j a v  a2  s.  c  o m*/
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

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

    asyncManager.insert(tweet1).getImmediately();

    // Start batch
    AsyncBatch batch = asyncManager.createBatch();

    batch.startBatch(QUORUM);

    logAsserter.prepareLogLevelForDriverConnection();

    Tweet foundTweet1 = asyncManager.find(Tweet.class, tweet1.getId()).getImmediately();

    assertThat(foundTweet1.getContent()).isEqualTo(tweet1.getContent());

    batch.insert(tweet2);
    batch.insert(tweet3);

    batch.asyncEndBatch(successCallBack);

    latch.await();

    logAsserter.assertConsistencyLevels(QUORUM);
    assertThatBatchContextHasBeenReset(batch);

    assertThat(successSpy.get()).isSameAs(Empty.INSTANCE);
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void rootServletContextResource() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    final AtomicReference<URL> rootResource = new AtomicReference<>();
    this.webServer = factory.getWebServer((servletContext) -> {
        try {//from  w  ww. j a  v  a  2  s.  c  om
            rootResource.set(servletContext.getResource("/"));
        } catch (MalformedURLException ex) {
            throw new ServletException(ex);
        }
    });
    this.webServer.start();
    assertThat(rootResource.get()).isNotNull();
}

From source file:com.microsoft.tfs.client.common.ui.teamexplorer.internal.pendingchanges.PendingChangesViewModel.java

private void loadPendingChangesAndCandidates() {
    if (workspace == null) {
        allPendingChanges = new PendingChange[0];
        updateCandidates(new PendingChange[0]);
        // Also updates checkin note field definitions
        updateIncludedExcludedAndAffected();
        return;/*from   w  w w  . ja v  a  2  s.c om*/
    }

    final long start = System.currentTimeMillis();

    final ItemSpec[] itemSpecs = new ItemSpec[1];
    itemSpecs[0] = new ItemSpec(ServerPath.ROOT, RecursionType.FULL);
    final AtomicReference<PendingChange[]> outCandidateChanges = new AtomicReference<PendingChange[]>();

    allPendingChanges = workspace.getPendingChangesWithCandidates(itemSpecs, false, outCandidateChanges);
    updateCandidates(outCandidateChanges.get());

    updateIncludedExcludedAndAffected();

    log.debug(MessageFormat.format("Load changes including candidates took {0} ms", //$NON-NLS-1$
            (System.currentTimeMillis() - start)));
}

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

@Test
public void testWithRightScopeInIdToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from ww w  .j  a  va2  s .  c o m*/
        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.GET);
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTgwNTEzNjU1MSwianRpIjoiV0Z1VVZneE83dmxKUm5XUlllMjE1dyIsImlhdCI6MTQ4OTc3NjU1MSwibmJmIjoxNDg5Nzc2NDMxLCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6InN0ZXZlIiwidXNlcl90eXBlIjoiRU1QTE9ZRUUiLCJjbGllbnRfaWQiOiJmN2Q0MjM0OC1jNjQ3LTRlZmItYTUyZC00YzU3ODc0MjFlNzIiLCJzY29wZSI6WyJ3cml0ZTpwZXRzIiwicmVhZDpwZXRzIl19.ZDlD_JbtHMqfx8EWOlOXI0zFGjB_pJ6yXWpxoE03o2yQnCUq1zypaDTJWSiy-BPIiQAxwDV09L3SN7RsOcgJ3y2LLFhgqIXhcHoePxoz52LPOeeiihG2kcrgBm-_VMq0uUykLrD-ljSmmSm1Hai_dx0WiYGAEJf-TiD1mgzIUTlhogYrjFKlp2NaYHxr7yjzEGefKv4DWdjtlEMmX_cXkqPgxra_omzyxeWE-n0b7f_r7Hr5HkxnmZ23gkZcvFXfVWKEp2t0_dYmNCbSVDavAjNanvmWsNThYNglFRvF0lm8kl7jkfMO1pTa0WLcBLvOO2y_jRWjieFCrc0ksbIrXA");
        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(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
    }
}

From source file:com.networknt.security.JwtVerifyHandlerTest.java

@Test
public void testWithRightScopeInIdToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {// w ww . ja  v a  2  s .c o  m
        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("/v2/pet/111").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTgwNTEzNjU1MSwianRpIjoiV0Z1VVZneE83dmxKUm5XUlllMjE1dyIsImlhdCI6MTQ4OTc3NjU1MSwibmJmIjoxNDg5Nzc2NDMxLCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6InN0ZXZlIiwidXNlcl90eXBlIjoiRU1QTE9ZRUUiLCJjbGllbnRfaWQiOiJmN2Q0MjM0OC1jNjQ3LTRlZmItYTUyZC00YzU3ODc0MjFlNzIiLCJzY29wZSI6WyJ3cml0ZTpwZXRzIiwicmVhZDpwZXRzIl19.ZDlD_JbtHMqfx8EWOlOXI0zFGjB_pJ6yXWpxoE03o2yQnCUq1zypaDTJWSiy-BPIiQAxwDV09L3SN7RsOcgJ3y2LLFhgqIXhcHoePxoz52LPOeeiihG2kcrgBm-_VMq0uUykLrD-ljSmmSm1Hai_dx0WiYGAEJf-TiD1mgzIUTlhogYrjFKlp2NaYHxr7yjzEGefKv4DWdjtlEMmX_cXkqPgxra_omzyxeWE-n0b7f_r7Hr5HkxnmZ23gkZcvFXfVWKEp2t0_dYmNCbSVDavAjNanvmWsNThYNglFRvF0lm8kl7jkfMO1pTa0WLcBLvOO2y_jRWjieFCrc0ksbIrXA");
        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(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
    }
}

From source file:gda.util.persistence.LocalParametersTest.java

public void testThreadSafety() throws Exception {
    final File testScratchDir = TestUtils.createClassScratchDirectory(LocalParametersTest.class);
    final String configDir = testScratchDir.getAbsolutePath();

    final String configName = "threadsafety";

    // Delete config from disk, if it exists
    final File configFile = new File(configDir, configName + ".xml");
    configFile.delete();/*  www .  j  a  v a2s. c o  m*/

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

    final int numThreads = 4;
    final long threadRunTimeInMs = 5000;
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch finishLatch = new CountDownLatch(numThreads);

    for (int i = 0; i < numThreads; i++) {
        Thread t = new Thread() {
            @Override
            public void run() {

                try {
                    final FileConfiguration config = LocalParameters.getThreadSafeXmlConfiguration(configDir,
                            configName, true);

                    // Wait for signal to start
                    startLatch.await();

                    final String propertyName = Thread.currentThread().getName();

                    final long startTime = System.currentTimeMillis();
                    while (true) {

                        // Finish if we've exceeded the run time
                        long elapsedTime = System.currentTimeMillis() - startTime;
                        if (elapsedTime >= threadRunTimeInMs) {
                            break;
                        }

                        // Finish if another thread has generated an exception
                        if (error.get() != null) {
                            break;
                        }

                        config.setProperty(propertyName, System.currentTimeMillis());
                        config.save();
                    }
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                    error.set(e);
                }

                finishLatch.countDown();
            }
        };
        t.start();
    }

    // Start all threads
    final long startTime = System.currentTimeMillis();
    startLatch.countDown();

    // Wait for all threads to finish
    finishLatch.await();
    final long endTime = System.currentTimeMillis();
    final long elapsedTime = (endTime - startTime);
    System.out.printf("Finished after %dms%n", elapsedTime);

    // No error should have been thrown
    assertNull("An exception was thrown by one of the threads", error.get());
}