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:eu.eubrazilcc.lvl.storage.TokenCollectionTest.java

@Test
public void test() {
    System.out.println("TokenCollectionTest.test()");
    try {/*  ww  w .j  ava 2 s  .  c o m*/
        final Collection<String> scopes = newArrayList("scope1", "scope2", "scope2/username1", "scope3,a");
        // insert
        final AccessToken accessToken = AccessToken.builder().token("1234567890abcdEFGhiJKlMnOpqrstUVWxyZ")
                .issuedAt(currentTimeMillis() / 1000l).expiresIn(23l).ownerId("username1").scope(scopes)
                .build();
        TOKEN_DAO.insert(accessToken);

        // find
        AccessToken accessToken2 = TOKEN_DAO.find(accessToken.getToken());
        assertThat("access token is not null", accessToken2, notNullValue());
        assertThat("access token coincides with original", accessToken2, equalTo(accessToken));
        System.out.println(accessToken2.toString());

        // update
        accessToken.setExpiresIn(604800l);
        TOKEN_DAO.update(accessToken);

        // find after update
        accessToken2 = TOKEN_DAO.find(accessToken.getToken());
        assertThat("access token is not null", accessToken2, notNullValue());
        assertThat("access token coincides with original", accessToken2, equalTo(accessToken));
        System.out.println(accessToken2.toString());

        // list by owner Id
        List<AccessToken> accessTokens = TOKEN_DAO.listByOwnerId(accessToken.getOwnerId());
        assertThat("access tokens are not null", accessTokens, notNullValue());
        assertThat("access tokens are not empty", !accessTokens.isEmpty(), equalTo(true));
        assertThat("number of access tokens coincides with expected", accessTokens.size(), equalTo(1));
        assertThat("access tokens coincide with original", accessTokens.get(0), equalTo(accessToken));

        // check validity         
        boolean validity = TOKEN_DAO.isValid(accessToken.getToken());
        assertThat("access token is valid", validity, equalTo(true));

        final AtomicReference<String> ownerIdRef = new AtomicReference<String>();
        validity = TOKEN_DAO.isValid(accessToken.getToken(), ownerIdRef);
        assertThat("access token is valid using target scope", validity, equalTo(true));
        assertThat("owner id coincides is not null", ownerIdRef.get(), notNullValue());
        assertThat("owner id coincides with expected", ownerIdRef.get(), equalTo(accessToken.getOwnerId()));

        // remove
        TOKEN_DAO.delete(accessToken.getToken());
        final long numRecords = TOKEN_DAO.count();
        assertThat("number of access tokens stored in the database coincides with expected", numRecords,
                equalTo(0l));

        // pagination
        final List<String> ids = newArrayList();
        for (int i = 0; i < 11; i++) {
            final AccessToken accessToken3 = AccessToken.builder().token(Integer.toString(i)).build();
            ids.add(accessToken3.getToken());
            TOKEN_DAO.insert(accessToken3);
        }
        final int size = 3;
        int start = 0;
        accessTokens = null;
        final MutableLong count = new MutableLong(0l);
        do {
            accessTokens = TOKEN_DAO.list(start, size, null, null, null, count);
            if (accessTokens.size() != 0) {
                System.out.println("Paging: first item " + start + ", showing " + accessTokens.size() + " of "
                        + count.getValue() + " items");
            }
            start += accessTokens.size();
        } while (!accessTokens.isEmpty());
        for (final String id2 : ids) {
            TOKEN_DAO.delete(id2);
        }
        TOKEN_DAO.stats(System.out);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("TokenCollectionTest.test() failed: " + e.getMessage());
    } finally {
        System.out.println("TokenCollectionTest.test() has finished");
    }
}

From source file:org.cerberus.launchcampaign.checkcampaign.CheckCampaignStatus.java

/**
 * Check all 5 seconds the status of campaign's execution. 
 * @param checkCampaign call method checkCampaign() all 5 seconds with parameter {@link ResultCIDto}.  
 *                   {@link ResultCIDto} contains all information of execution of campaing at the instant t
 * @param result call method result() when campaign execution is finish.
 *             {@link ResultCIDto} contains all information of execution at finish time
 * @throws Exception //w ww .  ja v  a  2s .  co  m
 */
public void execute(final CheckCampaignEvent checkCampaign, final ResultEvent result, final LogEvent logEvent)
        throws Exception {
    final ScheduledThreadPoolExecutor sch = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);

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

    sch.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            try {
                URL resultURL = new URL(urlCerberus + "/" + Constantes.URL_RESULT_CI + "?tag=" + tagCerberus);
                ResultCIDto resultDto = new ObjectMapper().readValue(resultURL, ResultCIDto.class);

                // condition to finish task
                if (!"PE".equals(resultDto.getResult())) {
                    result.result(resultDto);
                    sch.shutdown(); // when campaign is finish, we shutdown the schedule thread
                }

                if (!checkCampaign.checkCampaign(resultDto)) {
                    sch.shutdown();
                }
            } catch (SocketException e) {
                // do nothing during network problem. Wait the timeout to shutdown, and notify the error to logEvent
                logEvent.log("", e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e));
            } catch (Exception e) {
                exceptionOnThread.set(e);
                sch.shutdown();
            }
        }
    }, 0, this.timeToRefreshCampaignStatus, TimeUnit.SECONDS);

    sch.awaitTermination(this.timeoutForCampaignExecution, TimeUnit.SECONDS);

    // pass exeption of thread to called method
    if (exceptionOnThread.get() != null) {
        throw exceptionOnThread.get();
    }
}

From source file:de.hybris.platform.test.ThreadPoolTest.java

@Test
public void testTransactionCleanUpSimple()
        throws InterruptedException, BrokenBarrierException, TimeoutException {
    final boolean flagBefore = Config.getBoolean("transaction.monitor.begin", false);
    Config.setParameter("transaction.monitor.begin", "true");
    ThreadPool pool = null;//from   w w  w  .j a v a  2 s.  c o m
    try {
        pool = new ThreadPool(Registry.getCurrentTenantNoFallback().getTenantID(), 1);

        final GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.maxActive = 1;
        config.maxIdle = 1;
        config.maxWait = -1;
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        config.testOnBorrow = true;
        config.testOnReturn = true;
        config.timeBetweenEvictionRunsMillis = 30 * 1000; // keep idle threads for at most 30 sec
        pool.setConfig(config);

        final CyclicBarrier gate = new CyclicBarrier(2);
        final AtomicReference<Throwable> threadError = new AtomicReference<Throwable>();
        final AtomicReference<RecordingTransaction> threadTransaction = new AtomicReference<ThreadPoolTest.RecordingTransaction>();
        final PoolableThread thread1 = pool.borrowThread();
        thread1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final Transaction tx = new RecordingTransaction();
                    tx.activateAsCurrentTransaction();
                    tx.begin();
                    tx.begin(); // second time
                    tx.begin(); // third time
                    assertTrue(tx.isRunning());
                    assertEquals(3, tx.getOpenTransactionCount());
                    threadTransaction.set((RecordingTransaction) tx);
                    gate.await(10, TimeUnit.SECONDS);
                } catch (final Throwable t) {
                    threadError.set(t);
                }
            }
        });
        gate.await(10, TimeUnit.SECONDS);
        assertNull(threadError.get());
        // busy waiting for correct number of rollbacks - at the moment there is no hook for a better solution
        final RecordingTransaction tx = threadTransaction.get();
        final long maxWait = System.currentTimeMillis() + (15 * 1000);
        while (tx.rollbackCounter.get() < 3 && System.currentTimeMillis() < maxWait) {
            Thread.sleep(100);
        }
        assertEquals(3, tx.rollbackCounter.get());

        final PoolableThread thread2 = pool.borrowThread();
        assertNotSame(thread1, thread2);
    } finally {
        if (pool != null) {
            try {
                pool.close();
            } catch (final Exception e) {
                // can't help it
            }
        }
        Config.setParameter("transaction.monitor.begin", BooleanUtils.toStringTrueFalse(flagBefore));
    }
}

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();//from   ww w.  j ava2  s.  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());
}

From source file:com.hubrick.vertx.rest.converter.JacksonJsonHttpMessageConverter.java

@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
    if (!jackson23Available) {
        return (this.objectMapper.canSerialize(clazz) && canWrite(mediaType));
    }//w w  w.j  av  a 2 s .  c  o m
    AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
    if (this.objectMapper.canSerialize(clazz, causeRef) && canWrite(mediaType)) {
        return true;
    }
    Throwable cause = causeRef.get();
    if (cause != null) {
        log.warn("Failed to evaluate serialization for type [{}]", clazz, cause);
    }
    return false;
}

From source file:com.twitter.hbc.httpclient.ClientBase.java

ClientBase(String name, HttpClient client, Hosts hosts, StreamingEndpoint endpoint, Authentication auth,
        HosebirdMessageProcessor processor, ReconnectionManager manager, RateTracker rateTracker,
        @Nullable BlockingQueue<Event> eventsQueue) {
    this.client = Preconditions.checkNotNull(client);
    this.name = Preconditions.checkNotNull(name);

    this.endpoint = Preconditions.checkNotNull(endpoint);
    this.hosts = Preconditions.checkNotNull(hosts);
    this.auth = Preconditions.checkNotNull(auth);

    this.processor = Preconditions.checkNotNull(processor);
    this.reconnectionManager = Preconditions.checkNotNull(manager);
    this.rateTracker = Preconditions.checkNotNull(rateTracker);

    this.eventsQueue = eventsQueue;

    this.exitEvent = new AtomicReference<Event>();

    this.isRunning = new CountDownLatch(1);
    this.statsReporter = new StatsReporter();

    this.connectionEstablished = new AtomicBoolean(false);
    this.reconnect = new AtomicBoolean(false);
}

From source file:org.zalando.riptide.OAuth2CompatibilityTest.java

@Test
public void dispatchesConsumedAsyncResponseAgain() throws IOException {
    final AsyncRestTemplate template = new AsyncRestTemplate();
    final MockRestServiceServer server = MockRestServiceServer.createServer(template);

    server.expect(requestTo(url)).andRespond(withUnauthorizedRequest().body(new byte[] { 0x13, 0x37 }));

    template.setErrorHandler(new OAuth2ErrorHandler(new OAuth2CompatibilityResponseErrorHandler(), null));
    final AsyncRest rest = AsyncRest.create(template);

    final AtomicReference<ClientHttpResponse> reference = new AtomicReference<>();

    rest.execute(GET, url).dispatch(status(), on(UNAUTHORIZED).call(reference::set));

    assertThat(reference.get().getBody().available(), is(2));
}

From source file:io.undertow.server.handlers.ChunkedResponseTrailersTestCase.java

@Test
public void sendHttpRequest() throws Exception {
    Assume.assumeFalse(DefaultServer.isH2()); //this test will still run under h2-upgrade, but will fail

    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
    TestHttpClient client = new TestHttpClient();
    final AtomicReference<ChunkedInputStream> stream = new AtomicReference<>();
    client.addResponseInterceptor(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context) throws IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                if (instream instanceof ChunkedInputStream) {
                    stream.set(((ChunkedInputStream) instream));
                }//from w  ww  .j  a v  a 2  s . c  o m
            }
        }
    });
    try {
        generateMessage(1);
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

        Assert.assertEquals(message, HttpClientUtils.readResponse(result));

        Header[] footers = stream.get().getFooters();
        Assert.assertEquals(2, footers.length);
        for (final Header header : footers) {
            if (header.getName().equals("foo")) {
                Assert.assertEquals("fooVal", header.getValue());
            } else if (header.getName().equals("bar")) {
                Assert.assertEquals("barVal", header.getValue());
            } else {
                Assert.fail("Unknown header" + header);
            }
        }

        generateMessage(1000);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals(message, HttpClientUtils.readResponse(result));
        footers = stream.get().getFooters();
        Assert.assertEquals(2, footers.length);
        for (final Header header : footers) {
            if (header.getName().equals("foo")) {
                Assert.assertEquals("fooVal", header.getValue());
            } else if (header.getName().equals("bar")) {
                Assert.assertEquals("barVal", header.getValue());
            } else {
                Assert.fail("Unknown header" + header);
            }
        }
    } finally {
        client.getConnectionManager().shutdown();
    }

}

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

@Test
public void testWithRightCredentials() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from w  w w  .  ja  va  2 s  . c  om
        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("user1", "user1pass"));
        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.client.oauth.OauthHelper.java

/**
 * Get an access token from the token service. A Result of TokenResponse will be returned if the invocation is successfully.
 * Otherwise, a Result of Status will be returned.
 *
 * @param tokenRequest token request constructed from the client.yml token section.
 * @param envTag the environment tag from the server.yml for service lookup.
 * @return Result of TokenResponse or error Status.
 *//*from w  ww .  j a  va 2s . c  o m*/
public static Result<TokenResponse> getTokenResult(TokenRequest tokenRequest, String envTag) {
    final AtomicReference<Result<TokenResponse>> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        if (tokenRequest.getServerUrl() != null) {
            connection = client.connect(new URI(tokenRequest.getServerUrl()), Http2Client.WORKER,
                    Http2Client.SSL, Http2Client.BUFFER_POOL,
                    tokenRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                            : OptionMap.EMPTY)
                    .get();
        } else if (tokenRequest.getServiceId() != null) {
            Cluster cluster = SingletonServiceFactory.getBean(Cluster.class);
            String url = cluster.serviceToUrl("https", tokenRequest.getServiceId(), envTag, null);
            connection = client
                    .connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL,
                            tokenRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                                    : OptionMap.EMPTY)
                    .get();
        } else {
            // both server_url and serviceId are empty in the config.
            logger.error("Error: both server_url and serviceId are not configured in client.yml for "
                    + tokenRequest.getClass());
            throw new ClientException("both server_url and serviceId are not configured in client.yml for "
                    + tokenRequest.getClass());
        }
    } catch (Exception e) {
        logger.error("cannot establish connection:", e);
        return Failure.of(new Status(ESTABLISH_CONNECTION_ERROR,
                tokenRequest.getServerUrl() != null ? tokenRequest.getServerUrl()
                        : tokenRequest.getServiceId()));
    }

    try {
        IClientRequestComposable requestComposer = ClientRequestComposerProvider.getInstance().getComposer(
                ClientRequestComposerProvider.ClientRequestComposers.CLIENT_CREDENTIAL_REQUEST_COMPOSER);

        connection.getIoThread()
                .execute(new TokenRequestAction(tokenRequest, requestComposer, connection, reference, latch));

        latch.await(4, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        return Failure.of(new Status(FAIL_TO_SEND_REQUEST));
    } finally {
        IoUtils.safeClose(connection);
    }

    //if reference.get() is null at this point, mostly likely couldn't get token within latch.await() timeout.
    return reference.get() == null ? Failure.of(new Status(GET_TOKEN_TIMEOUT)) : reference.get();
}