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.hawkular.listener.cache.InventoryHelperTest.java

@Test
public void shouldListNoMetricsForTypeWhenChunksAreIncomplete() {
    // Data & mocks
    String tenant = "tenant";
    String feed = "feed";
    Metric<String> r1 = new Metric<>("inventory.123.r.r1", null, 7, MetricType.STRING, null);
    long currentTime = System.currentTimeMillis();
    when(metricsService.findMetricsWithFilters(anyString(), anyObject(), anyString()))
            .thenAnswer(invocationOnMock -> Observable.just(r1));
    DataPoint<String> tempDataPoint = buildRootResourceDatapointWithMetrics(tenant, feed, currentTime - 500,
            "r1");
    DataPoint<String> dataPoint = new DataPoint<>(tempDataPoint.getTimestamp(), tempDataPoint.getValue(),
            ImmutableMap.<String, String>builder().put("chunks", "3").put("size", "1000").build());
    when(metricsService.findStringData(r1.getMetricId(), 0, currentTime, false, 0, Order.DESC))
            .thenReturn(Observable.just(dataPoint));
    org.hawkular.inventory.api.model.MetricType.Blueprint bp = org.hawkular.inventory.api.model.MetricType.Blueprint
            .builder(MetricDataType.GAUGE).withId("metricType1").withName("Metric type 1").withInterval(60L)
            .withUnit(MetricUnit.BYTES).build();

    // Test & assertions
    AtomicReference<Throwable> refException = new AtomicReference<>();
    InventoryHelper.listMetricsForType(metricsService, tenant, feed, bp, currentTime).toList().subscribe(a -> {
    }, refException::set);//from   ww w. j  a v  a 2  s. c  o m
    Assert.assertEquals(InvalidInventoryChunksException.class, refException.get().getCause().getClass());
    Assert.assertTrue("Unexpected message: " + refException.get().getCause().getMessage(),
            refException.get().getCause().getMessage()
                    .contains("Inventory sanity check failure: 3 chunks expected, only 1 are available"));
}

From source file:com.networknt.client.oauth.OauthHelper.java

/**
 * Get the certificate from key distribution service of OAuth 2.0 provider with the kid.
 *
 * @param keyRequest One of the sub classes to get the key for access token or sign token.
 * @param envTag the environment tag from the server.yml for the cluster lookup.
 * @return String of the certificate/*from   ww  w .j  a v  a  2 s  .  c om*/
 * @throws ClientException throw exception if communication with the service fails.
 */
public static String getKey(KeyRequest keyRequest, String envTag) throws ClientException {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        if (keyRequest.getServerUrl() != null) {
            connection = client.connect(new URI(keyRequest.getServerUrl()), Http2Client.WORKER, Http2Client.SSL,
                    Http2Client.BUFFER_POOL,
                    keyRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                            : OptionMap.EMPTY)
                    .get();
        } else if (keyRequest.getServiceId() != null) {
            Cluster cluster = SingletonServiceFactory.getBean(Cluster.class);
            String url = cluster.serviceToUrl("https", keyRequest.getServiceId(), envTag, null);
            connection = client
                    .connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL,
                            keyRequest.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 "
                    + keyRequest.getClass());
            throw new ClientException("both server_url and serviceId are not configured in client.yml for "
                    + keyRequest.getClass());
        }
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath(keyRequest.getUri()).setMethod(Methods.GET);

        if (keyRequest.getClientId() != null) {
            request.getRequestHeaders().put(Headers.AUTHORIZATION,
                    getBasicAuthHeader(keyRequest.getClientId(), keyRequest.getClientSecret()));
        }
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        adjustNoChunkedEncoding(request, "");
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    return reference.get().getAttachment(Http2Client.RESPONSE_BODY);
}

From source file:com.netflix.curator.ensemble.exhibitor.TestExhibitorEnsembleProvider.java

@Test
public void testExhibitorFailures() throws Exception {
    final AtomicReference<String> backupConnectionString = new AtomicReference<String>("backup1:1");
    final AtomicReference<String> connectionString = new AtomicReference<String>(
            "count=1&port=2&server0=localhost");
    Exhibitors exhibitors = new Exhibitors(Lists.newArrayList("foo", "bar"), 1000,
            new Exhibitors.BackupConnectionStringProvider() {
                @Override/*from   w  ww  .  j a  v  a  2  s  .co  m*/
                public String getBackupConnectionString() {
                    return backupConnectionString.get();
                }
            });
    ExhibitorRestClient mockRestClient = new ExhibitorRestClient() {
        @Override
        public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception {
            String localConnectionString = connectionString.get();
            if (localConnectionString == null) {
                throw new IOException();
            }
            return localConnectionString;
        }
    };

    final Semaphore semaphore = new Semaphore(0);
    ExhibitorEnsembleProvider provider = new ExhibitorEnsembleProvider(exhibitors, mockRestClient, "/foo", 10,
            new RetryOneTime(1)) {
        @Override
        protected void poll() {
            super.poll();
            semaphore.release();
        }
    };
    provider.pollForInitialEnsemble();
    try {
        provider.start();

        Assert.assertEquals(provider.getConnectionString(), "localhost:2");

        connectionString.set(null);
        semaphore.drainPermits();
        semaphore.acquire(); // wait for next poll
        Assert.assertEquals(provider.getConnectionString(), "backup1:1");

        backupConnectionString.set("backup2:2");
        semaphore.drainPermits();
        semaphore.acquire(); // wait for next poll
        Assert.assertEquals(provider.getConnectionString(), "backup2:2");

        connectionString.set("count=1&port=3&server0=localhost3");
        semaphore.drainPermits();
        semaphore.acquire(); // wait for next poll
        Assert.assertEquals(provider.getConnectionString(), "localhost3:3");
    } finally {
        IOUtils.closeQuietly(provider);
    }
}

From source file:com.github.jdye64.processors.provenance.ProvenanceEventsToPhoenix.java

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {

    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;/* ww w .  j a  v a2s.  c  o m*/
    }

    String tableName = context.getProperty(PHOENIX_TABLE_NAME).evaluateAttributeExpressions(flowFile)
            .getValue();

    StringBuffer buffer = new StringBuffer();
    buffer.append(PREPEND_UPSERT);
    buffer.append(tableName);
    buffer.append(PROV_UPSERT_PREDICATES);
    buffer.append(PROV_PREP_VALUES);

    try {

        AtomicReference<JSONArray> provEvents = new AtomicReference<>();

        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream in) throws IOException {
                StringWriter writer = new StringWriter();
                IOUtils.copy(in, writer, "UTF-8");
                provEvents.set(new JSONArray(writer.toString()));
            }
        });

        JSONArray events = provEvents.get();

        for (int i = 0; i < events.length(); i++) {
            JSONObject obj = events.getJSONObject(i);
            Map<String, String> attributes = generateAttributes(obj, tableName);

            FlowFile ff = session.write(session.clone(flowFile), new OutputStreamCallback() {
                @Override
                public void process(OutputStream out) throws IOException {
                    out.write(buffer.toString().getBytes());
                }
            });

            ff = session.putAllAttributes(ff, attributes);
            session.transfer(ff, REL_SUCCESS);
        }

        session.remove(flowFile);

    } catch (Exception ex) {
        getLogger().error("Error converting provenance event into Phoenix prepared statement {}",
                new Object[] { ex.getMessage() }, ex);
        session.transfer(flowFile, REL_FAILURE);
    }
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.egit.dialogs.GitBuildDefinitionDialog.java

private GitRepository getBuildProjectRepository() {
    final GitRepositoriesMap repositoriesMap = getRepositoriesMap();
    final List<GitRepository> repositories = repositoriesMap.getServerRepositories();

    final AtomicReference<String> repositoryName = new AtomicReference<String>();

    final String buildFileLocation = buildDefinition.getConfigurationFolderPath();

    if (GitProperties.parseGitItemUrl(buildFileLocation, null, repositoryName, null, null)) {

        for (final GitRepository repository : repositories) {
            if (repository.getName().equalsIgnoreCase(repositoryName.get())) {
                return repository;
            }//from  w w w . j a  v  a 2 s.  c o  m
        }
    }

    return null;
}

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  a  v a  2 s  .c  o m*/

    return connection;
}

From source file:com.netflix.curator.ensemble.exhibitor.TestExhibitorEnsembleProvider.java

@Test
public void testChanging() throws Exception {
    TestingServer secondServer = new TestingServer();
    try {//ww w. j  av  a 2 s  . c o  m
        String mainConnectionString = "count=1&port=" + server.getPort() + "&server0=localhost";
        String secondConnectionString = "count=1&port=" + secondServer.getPort() + "&server0=localhost";

        final Semaphore semaphore = new Semaphore(0);
        final AtomicReference<String> connectionString = new AtomicReference<String>(mainConnectionString);
        Exhibitors exhibitors = new Exhibitors(Lists.newArrayList("foo", "bar"), 1000,
                dummyConnectionStringProvider);
        ExhibitorRestClient mockRestClient = new ExhibitorRestClient() {
            @Override
            public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception {
                semaphore.release();
                return connectionString.get();
            }
        };
        ExhibitorEnsembleProvider provider = new ExhibitorEnsembleProvider(exhibitors, mockRestClient, "/foo",
                10, new RetryOneTime(1));
        provider.pollForInitialEnsemble();

        Timing timing = new Timing().multiple(4);
        final CuratorZookeeperClient client = new CuratorZookeeperClient(provider, timing.session(),
                timing.connection(), null, new RetryOneTime(2));
        client.start();
        try {
            RetryLoop.callWithRetry(client, new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    client.getZooKeeper().create("/test", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
                            CreateMode.PERSISTENT);
                    return null;
                }
            });

            connectionString.set(secondConnectionString);
            semaphore.drainPermits();
            semaphore.acquire();

            server.stop(); // create situation where the current zookeeper gets a sys-disconnected

            Stat stat = RetryLoop.callWithRetry(client, new Callable<Stat>() {
                @Override
                public Stat call() throws Exception {
                    return client.getZooKeeper().exists("/test", false);
                }
            });
            Assert.assertNull(stat); // it's a different server so should be null
        } finally {
            client.close();
        }
    } finally {
        IOUtils.closeQuietly(secondServer);
    }
}

From source file:io.fabric8.agent.download.DownloadManagerTest.java

private StreamProvider download(DownloadManager manager, String url) throws Exception {
    final AtomicReference<StreamProvider> ref = new AtomicReference<>();
    Downloader downloader = manager.createDownloader();
    downloader.download(url, new DownloadCallback() {
        @Override//  ww  w.ja  va  2  s .c  o  m
        public void downloaded(StreamProvider provider) throws Exception {
            synchronized (ref) {
                ref.set(provider);
                ref.notifyAll();
            }
        }
    });
    synchronized (ref) {
        ref.wait(30000);
        return ref.get();
    }
}

From source file:org.bpmscript.process.hibernate.SpringHibernateInstanceManagerTest.java

public void testInstanceManagerLocking() throws Exception {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/endtoend/spring.xml");

    try {/*from ww w.jav  a  2s .co m*/

        final IInstanceManager instanceManager = (IInstanceManager) context.getBean("instanceManager");

        final String pid1 = instanceManager.createInstance("parentVersion", "definitionId", "test",
                IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "one");
        IInstance instance = instanceManager.getInstance(pid1);
        assertNotNull(instance);

        instanceManager.createInstance("parentVersion", "definitionId", "test",
                IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "two");
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        final AtomicReference<Queue<String>> results = new AtomicReference<Queue<String>>(
                new LinkedList<String>());
        executorService.submit(new Callable<Object>() {

            public Object call() throws Exception {
                return instanceManager.doWithInstance(pid1, new IInstanceCallback() {
                    public IExecutorResult execute(IInstance instance) throws Exception {
                        log.info("locking one");
                        Thread.sleep(2000);
                        results.get().add("one");
                        return new IgnoredResult("", "", "");
                    }
                });
            }

        });
        Thread.sleep(100);
        Future<Object> future2 = executorService.submit(new Callable<Object>() {

            public Object call() throws Exception {
                return instanceManager.doWithInstance(pid1, new IInstanceCallback() {
                    public IExecutorResult execute(IInstance instance) throws Exception {
                        log.info("locking two");
                        results.get().add("two");
                        return new IgnoredResult("", "", "");
                    }
                });
            }

        });
        future2.get();
        assertEquals(2, results.get().size());
        assertEquals("one", results.get().poll());
        assertEquals("two", results.get().poll());

    } finally {
        context.destroy();
    }
}