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:com.netflix.curator.framework.recipes.cache.TestPathChildrenCacheInCluster.java

@Test
public void testServerLoss() throws Exception {
    Timing timing = new Timing();

    CuratorFramework client = null;//w  ww  .  j  a  v  a 2 s .  c  om
    PathChildrenCache cache = null;
    TestingCluster cluster = new TestingCluster(3);
    try {
        cluster.start();

        client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(),
                timing.connection(), new RetryOneTime(1));
        client.start();
        client.create().creatingParentsIfNeeded().forPath("/test");

        cache = new PathChildrenCache(client, "/test", false);
        cache.start();

        final CountDownLatch resetLatch = new CountDownLatch(1);
        final CountDownLatch reconnectLatch = new CountDownLatch(1);
        final AtomicReference<CountDownLatch> latch = new AtomicReference<CountDownLatch>(
                new CountDownLatch(3));
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED) {
                    resetLatch.countDown();
                } else if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED) {
                    reconnectLatch.countDown();
                } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
                    latch.get().countDown();
                }
            }
        });

        client.create().forPath("/test/one");
        client.create().forPath("/test/two");
        client.create().forPath("/test/three");

        Assert.assertTrue(latch.get().await(10, TimeUnit.SECONDS));

        InstanceSpec connectionInstance = cluster
                .findConnectionInstance(client.getZookeeperClient().getZooKeeper());
        cluster.killServer(connectionInstance);

        Assert.assertTrue(timing.awaitLatch(reconnectLatch));

        Assert.assertEquals(cache.getCurrentData().size(), 3);
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
        IOUtils.closeQuietly(cluster);
    }
}

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

@Test
public void testInvalidRequstPath() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from   www.j ava 2 s.  com*/
        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("/api").setMethod(Methods.GET);
        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(404, statusCode);
    if (statusCode == 404) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10007", status.getCode());
    }
}

From source file:com.jayway.restassured.itest.java.FilterITest.java

@Test
public void content_type_in_filter_contains_charset_by_default() {
    final AtomicReference<String> contentType = new AtomicReference<String>();

    given().filter(new Filter() {
        public Response filter(FilterableRequestSpecification requestSpec,
                FilterableResponseSpecification responseSpec, FilterContext ctx) {
            contentType.set(requestSpec.getRequestContentType());
            return ctx.next(requestSpec, responseSpec);
        }//ww w .j a  va 2s  .co m
    }).formParam("firstName", "John").formParam("lastName", "Doe").when().post("/greet").then().statusCode(200);

    assertThat(contentType.get(), equalTo("application/x-www-form-urlencoded; charset=ISO-8859-1"));
}

From source file:eu.eubrazilcc.lvl.storage.ResourceOwnerCollectionTest.java

@Test
public void test() {
    System.out.println("ResourceOwnerCollectionTest.test()");
    try {//  ww  w.j a v  a  2 s .co m
        final Collection<String> roles = newArrayList("role1", "role2");
        final Collection<String> permissions = newArrayList("sequences:leishmania:public:*:view",
                "sequences:sandflies:public:*:view");
        // insert (no salt)
        final ResourceOwner resourceOwner = ResourceOwner.builder()
                .user(User.builder().userid("username").password("password").email("username@example.com")
                        .firstname("firstname").lastname("lastname").roles(roles).permissions(permissions)
                        .build())
                .build();
        WriteResult<ResourceOwner> result = RESOURCE_OWNER_DAO.insert(resourceOwner);
        assertThat("insert resource owner result is not null", result, notNullValue());
        assertThat("insert resource owner result id is not null", result.getId(), notNullValue());
        assertThat("insert resource owner result id is not empty", isNotBlank(result.getId()), equalTo(true));
        assertThat("insert resource owner result element is not null", result.getElement(), notNullValue());
        assertThat("insert resource owner result user is not null", result.getElement().getUser(),
                notNullValue());
        assertThat("insert resource owner result hashed password", result.getElement().getUser().getPassword(),
                notNullValue());
        assertThat("insert resource owner result hashed password",
                isNotBlank(result.getElement().getUser().getPassword()), equalTo(true));
        assertThat("insert resource owner result salt", result.getElement().getUser().getSalt(),
                notNullValue());
        assertThat("insert resource owner result salt", isNotBlank(result.getElement().getUser().getSalt()),
                equalTo(true));
        assertThat("inserted resource owner coincides with original (ignoring password & salt)",
                resourceOwner.equalsToUnprotected(result.getElement()), equalTo(true));
        final ResourceOwner hashed = result.getElement();

        // find (no salt)
        ResourceOwner resourceOwner2 = RESOURCE_OWNER_DAO.find(resourceOwner.getOwnerId());
        assertThat("resource owner is not null", resourceOwner2, notNullValue());
        assertThat("resource owner coincides with original", resourceOwner2, equalTo(hashed));
        System.out.println(resourceOwner2.toString());

        // find (no salt) with volatile values
        resourceOwner2 = RESOURCE_OWNER_DAO.useGravatar(true).find(resourceOwner.getOwnerId());
        assertThat("resource owner with volatile values is not null", resourceOwner2, notNullValue());
        assertThat("resource owner links are null", resourceOwner2.getUser().getLinks(), nullValue());
        assertThat("resource owner picture URL is not null", resourceOwner2.getUser().getPictureUrl(),
                notNullValue());
        assertThat("resource owner picture URL is not empty",
                isNotBlank(resourceOwner2.getUser().getPictureUrl()));
        assertThat("resource owner with volatile values coincides with original",
                resourceOwner2.getUser().equalsIgnoringVolatile(hashed.getUser()));
        System.out.println(resourceOwner2.toString());

        // insert element with hard link
        final ResourceOwner resourceOwner1 = ResourceOwner.builder()
                .user(User.builder()
                        .links(newArrayList(Link.fromUri("http://example.com/users/username1").rel(SELF)
                                .type(APPLICATION_JSON).build()))
                        .userid("username1").password("password1").email("username1@example.com")
                        .firstname("Firstname 1").lastname("Lastname 1").roles(roles).permissions(permissions)
                        .build())
                .build();

        result = RESOURCE_OWNER_DAO.insert(resourceOwner1);
        resourceOwner1.getUser().setLinks(null);
        assertThat("resource owner result inserted with hard link is not null", result, notNullValue());
        assertThat("resource owner inserted with hard link is not null", result.getElement(), notNullValue());
        assertThat("resource owner inserted with hard link coincides with original (ignoring password & salt)",
                resourceOwner1.equalsToUnprotected(result.getElement()), equalTo(true));
        System.out.println(resourceOwner2.toString());

        RESOURCE_OWNER_DAO.delete(resourceOwner1.getOwnerId());

        // update
        final String plainPassword = "new_password";
        updatePassword(hashed, plainPassword);
        RESOURCE_OWNER_DAO.update(hashed);

        // find after update
        resourceOwner2 = RESOURCE_OWNER_DAO.reset().find(resourceOwner.getOwnerId());
        assertThat("resource owner is not null", resourceOwner2, notNullValue());
        assertThat("resource owner coincides with original", resourceOwner2, equalTo(hashed));
        System.out.println(resourceOwner2.toString());

        // check validity using owner Id and username
        AtomicReference<String> ownerIdRef = new AtomicReference<String>();
        boolean validity = RESOURCE_OWNER_DAO.isValid(hashed.getOwnerId(), hashed.getUser().getUserid(),
                plainPassword, false, null, ownerIdRef);
        assertThat("resource owner is valid (using owner Id & username)", validity, equalTo(true));
        assertThat("resource owner Id passed as reference coincides with expected", ownerIdRef.get(),
                equalTo(hashed.getOwnerId()));

        // check validity using email address
        ownerIdRef = new AtomicReference<String>();
        validity = RESOURCE_OWNER_DAO.isValid(null, hashed.getUser().getEmail(), plainPassword, true, null,
                ownerIdRef);
        assertThat("resource owner is valid (using email)", validity, equalTo(true));
        assertThat("resource owner Id passed as reference coincides with expected", ownerIdRef.get(),
                equalTo(hashed.getOwnerId()));

        // add roles
        RESOURCE_OWNER_DAO.addRoles(resourceOwner.getOwnerId(), "role3");

        // remove roles
        RESOURCE_OWNER_DAO.removeRoles(resourceOwner.getOwnerId(), "role2");

        // test listing unexisting shared datasets
        List<DatasetShare> shares = RESOURCE_OWNER_DAO.listDatashares("otheruser@lvl", "mysequences.xml", 0,
                Integer.MAX_VALUE, null, null, null);
        assertThat("dataset shares is null", shares, notNullValue());
        assertThat("dataset shares is empty", shares.isEmpty(), equalTo(true));
        // uncomment for additional output
        System.out.println(" >> Dataset shares (before permissions are granted): " + shares.toString());

        // share dataset by adding permissions to resource owner
        RESOURCE_OWNER_DAO.addPermissions(resourceOwner.getOwnerId(),
                "datasets:files:otheruser@lvl:mysequences.xml:view");
        resourceOwner2 = RESOURCE_OWNER_DAO.reset().find(resourceOwner.getOwnerId());
        assertThat("resource owner is not null", resourceOwner2, notNullValue());
        // uncomment for additional output
        System.out.println(" >> Owner with permissions to view shared dataset: " + resourceOwner2.toString());

        // test listing shared datasets
        shares = RESOURCE_OWNER_DAO.listDatashares("otheruser@lvl", "mysequences.xml", 0, Integer.MAX_VALUE,
                null, null, null);
        assertThat("dataset shares is not null", shares, notNullValue());
        assertThat("number of dataset shares coincides with expected", shares.size(), equalTo(1));
        // uncomment for additional output
        System.out.println(" >> Dataset shares (after permissions are granted): " + shares.toString());

        // insert redundant permissions
        RESOURCE_OWNER_DAO.addPermissions(resourceOwner.getOwnerId(),
                "datasets:files:otheruser@lvl:mysequences.xml:view,edit");

        // test getting information about a specific share
        DatasetShare share = RESOURCE_OWNER_DAO.findDatashare("otheruser@lvl", "mysequences.xml",
                resourceOwner.getOwnerId());
        assertThat("dataset share is not null", share, notNullValue());
        // uncomment for additional output
        System.out.println(" >> Dataset share (after adding redundant permissions): " + share.toString());

        // test modifying a share
        // not available

        // remove all permissions and stop sharing
        RESOURCE_OWNER_DAO.removePermissions(resourceOwner.getOwnerId(),
                "datasets:files:otheruser@lvl:mysequences.xml:view",
                "datasets:files:otheruser@lvl:mysequences.xml:view,edit");
        shares = RESOURCE_OWNER_DAO.listDatashares("otheruser@lvl", "mysequences.xml", 0, Integer.MAX_VALUE,
                null, null, null);
        assertThat("dataset shares is null", shares, notNullValue());
        assertThat("dataset shares is empty", shares.isEmpty(), equalTo(true));
        // uncomment for additional output
        System.out.println(" >> Dataset shares (after permissions are removed): " + shares.toString());

        // get OAuth scope
        resourceOwner2 = RESOURCE_OWNER_DAO.find(resourceOwner.getOwnerId());
        final String oauthScope = ResourceOwnerDAO.oauthScope(resourceOwner2, true);
        assertThat("resource owner OAuth scope is not null", oauthScope, notNullValue());
        assertThat("resource owner OAuth scope is not blank", isNotBlank(oauthScope));
        assertThat("resource owner OAuth scope coincided with expected", oauthScope, equalTo("role1 role3"));
        System.out.println("OAuth scope: '" + oauthScope + "'");

        // remove (default LVL administrator is not removed)
        RESOURCE_OWNER_DAO.delete(resourceOwner.getOwnerId());
        final long numRecords = RESOURCE_OWNER_DAO.count();
        assertThat("number of resource owners stored in the database coincides with expected", numRecords,
                equalTo(1l));

        // insert (with salt)
        result = RESOURCE_OWNER_DAO.insert(hashed);
        assertThat("insert resource owner result (with salt) is not null", result, notNullValue());
        assertThat("insert resource owner result (with salt) id is not null", result.getId(), notNullValue());
        assertThat("insert resource owner result (with salt) id is not empty", isNotBlank(result.getId()),
                equalTo(true));

        // find (with salt)
        resourceOwner2 = RESOURCE_OWNER_DAO.find(hashed.getOwnerId());
        assertThat("resource owner (with salt) is not null", resourceOwner2, notNullValue());
        assertThat("resource owner (with salt) coincides with original", resourceOwner2, equalTo(hashed));
        System.out.println(resourceOwner2.toString());

        // pagination
        final List<String> ids = newArrayList();
        for (int i = 0; i < 11; i++) {
            final ResourceOwner resourceOwner3 = ResourceOwner.builder()
                    .user(User.builder().userid(Integer.toString(i)).password("password")
                            .email("username" + i + "@example.com").firstname("Firstname").lastname("Lastname")
                            .roles(roles).permissions(permissions).build())
                    .build();
            ids.add(resourceOwner3.getOwnerId());
            RESOURCE_OWNER_DAO.insert(resourceOwner3);
        }
        final int size = 3;
        int start = 0;
        List<ResourceOwner> resourceOwners = null;
        final MutableLong count = new MutableLong(0l);
        do {
            resourceOwners = RESOURCE_OWNER_DAO.list(start, size, null, null, null, count);
            if (resourceOwners.size() != 0) {
                System.out.println("Paging: first item " + start + ", showing " + resourceOwners.size() + " of "
                        + count.getValue() + " items");
            }
            start += resourceOwners.size();
        } while (!resourceOwners.isEmpty());
        for (final String id2 : ids) {
            RESOURCE_OWNER_DAO.delete(id2);
        }
        RESOURCE_OWNER_DAO.stats(System.out);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("ResourceOwnerCollectionTest.test() failed: " + e.getMessage());
    } finally {
        System.out.println("ResourceOwnerCollectionTest.test() has finished");
    }
}

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

@Test
public void testInvalidMethod() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*w w w  .  j a  v a 2  s . co  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").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();
    Assert.assertEquals(405, statusCode);
    if (statusCode == 405) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10008", status.getCode());
    }
}

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

@Test
public void testGetParam() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from   ww w.j av  a  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.GET);
        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);
        Assert.assertEquals("getPetById", body);
    }
}

From source file:org.apache.solr.servlet.SolrDispatchFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain, boolean retry)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest))
        return;/*from   ww  w  . j a  v a2  s .c o  m*/
    try {

        if (cores == null || cores.isShutDown()) {
            log.error(
                    "Error processing the request. CoreContainer is either not initialized or shutting down.");
            throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE,
                    "Error processing the request. CoreContainer is either not initialized or shutting down.");
        }

        AtomicReference<ServletRequest> wrappedRequest = new AtomicReference<>();
        if (!authenticateRequest(request, response, wrappedRequest)) { // the response and status code have already been
                                                                       // sent
            return;
        }
        if (wrappedRequest.get() != null) {
            request = wrappedRequest.get();
        }

        request = closeShield(request, retry);
        response = closeShield(response, retry);

        if (cores.getAuthenticationPlugin() != null) {
            log.debug("User principal: {}", ((HttpServletRequest) request).getUserPrincipal());
        }

        // No need to even create the HttpSolrCall object if this path is excluded.
        if (excludePatterns != null) {
            String requestPath = ((HttpServletRequest) request).getServletPath();
            String extraPath = ((HttpServletRequest) request).getPathInfo();
            if (extraPath != null) { // In embedded mode, servlet path is empty - include all post-context path here for
                                     // testing
                requestPath += extraPath;
            }
            for (Pattern p : excludePatterns) {
                Matcher matcher = p.matcher(requestPath);
                if (matcher.lookingAt()) {
                    chain.doFilter(request, response);
                    return;
                }
            }
        }

        HttpSolrCall call = getHttpSolrCall((HttpServletRequest) request, (HttpServletResponse) response,
                retry);
        ExecutorUtil.setServerThreadFlag(Boolean.TRUE);
        try {
            Action result = call.call();
            switch (result) {
            case PASSTHROUGH:
                chain.doFilter(request, response);
                break;
            case RETRY:
                doFilter(request, response, chain, true);
                break;
            case FORWARD:
                request.getRequestDispatcher(call.getPath()).forward(request, response);
                break;
            }
        } finally {
            call.destroy();
            ExecutorUtil.setServerThreadFlag(null);
        }
    } finally {
        consumeInputFully((HttpServletRequest) request);
    }
}

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 {/*from  ww  w. ja  v a 2  s  .  co  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.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:it.anyplace.sync.bep.IndexFinder.java

public SearchCompletedEvent doSearch(final String term) throws InterruptedException {
    final Object lock = new Object();
    final AtomicReference<SearchCompletedEvent> reference = new AtomicReference<>();
    final Object eventListener = new Object() {
        @Subscribe//  w w w  .ja va2s .  com
        public void handleSearchCompletedEvent(SearchCompletedEvent event) {
            if (equal(event.getQuery(), term)) {
                synchronized (lock) {
                    reference.set(event);
                    lock.notify();
                }
            }
        }
    };
    synchronized (lock) {
        eventBus.register(eventListener);
        submitSearch(term);
        try {
            while (!Thread.currentThread().isInterrupted() && reference.get() == null) {
                lock.wait();
            }
            checkNotNull(reference.get());
            return reference.get();
        } finally {
            eventBus.unregister(eventListener);
        }
    }
}

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

@Test
public void testMissingToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*w  w  w. j  av a  2  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");
        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("ERR10002", status.getCode());
    }
}