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:com.chiorichan.updater.Download.java

protected InputStream getConnectionInputStream(final URLConnection urlconnection) throws DownloadException {
    final AtomicReference<InputStream> is = new AtomicReference<InputStream>();

    for (int j = 0; j < 3 && is.get() == null; j++) {
        StreamThread stream = new StreamThread(urlconnection, is);
        stream.start();/*from   w ww  .  ja  v a 2s.  co  m*/
        int iterationCount = 0;
        while (is.get() == null && iterationCount++ < 5)
            try {
                stream.join(1000L);
            } catch (InterruptedException ignore) {
            }

        if (stream.permDenied.get())
            throw new DownloadDeniedException("Permission denied!");

        if (is.get() != null)
            break;
        try {
            stream.interrupt();
            stream.join();
        } catch (InterruptedException ignore) {
        }
    }

    if (is.get() == null)
        throw new DownloadException("Unable to download file from " + urlconnection.getURL());
    return new BufferedInputStream(is.get());
}

From source file:org.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java

@Test
public void concurrentLoginSingleUser() throws Throwable {
    log.info("*********************************************");
    long start = System.currentTimeMillis();

    AtomicReference<String> userSessionId = new AtomicReference<>();
    LoginTask loginTask = null;//from   w  ww.j  a  v a2s .com

    try (CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setRedirectStrategy(new LaxRedirectStrategy()).build()) {
        loginTask = new LoginTask(httpClient, userSessionId, 100, 1, false,
                Arrays.asList(createHttpClientContextForUser(httpClient, "test-user@localhost", "password")));
        run(DEFAULT_THREADS, DEFAULT_CLIENTS_COUNT, loginTask);
        int clientSessionsCount = testingClient.testing().getClientSessionsCountInUserSession("test",
                userSessionId.get());
        Assert.assertEquals(1 + DEFAULT_CLIENTS_COUNT, clientSessionsCount);
    } finally {
        long end = System.currentTimeMillis() - start;
        log.infof("Statistics: %s", loginTask == null ? "??" : loginTask.getHistogram());
        log.info("concurrentLoginSingleUser took " + (end / 1000) + "s");
        log.info("*********************************************");
    }
}

From source file:io.termd.core.telnet.TelnetHandlerTest.java

@Test
public void testAcceptSGA() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    SuppressGAOptionHandler optionHandler = new SuppressGAOptionHandler(false, false, false, true);
    testOptionValue(() -> new TelnetHandler() {
        @Override/*from w ww .j a v a  2  s . com*/
        protected void onOpen(TelnetConnection conn) {
            conn.writeWillOption(Option.SGA);
        }

        @Override
        protected void onSGA(boolean sga) {
            serverValue.set(sga);
            testComplete();
        }
    }, optionHandler);
    assertEquals(true, serverValue.get());
    assertEquals(true, optionHandler.getAcceptRemote());
}

From source file:com.dgtlrepublic.anitomyj.Tokenizer.java

/** Tokenize by bracket. */
private void tokenizeByBrackets() {
    /** a ref to the closing brace of a found opening brace. (e.g "}" if we found an "}") */
    AtomicReference<String> matchingBracket = new AtomicReference<>();

    /** function to find an opening brace */
    BiFunction<Integer, Integer, Integer> findFirstBracket = (start, end) -> {
        for (int i = start; i < end; i++) {
            for (Pair<String, String> bracket : brackets) {
                if (String.valueOf(filename.charAt(i)).equals(bracket.getLeft())) {
                    matchingBracket.set(bracket.getRight());
                    return i;
                }/*from w w w.ja  v a2  s.  co m*/
            }
        }

        return -1;
    };

    boolean isBracketOpen = false;
    for (int i = 0; i < filename.length();) {
        int foundIdx;
        if (!isBracketOpen) {
            /** look for opening brace */
            foundIdx = findFirstBracket.apply(i, filename.length());
        } else {
            /** look for closing brace */
            foundIdx = filename.indexOf(matchingBracket.get(), i);
        }

        TokenRange range = new TokenRange(i, foundIdx == -1 ? filename.length() : foundIdx - i);
        if (range.getSize() > 0) {
            /** check if our range contains any known anime identifies */
            tokenizeByPreidentified(isBracketOpen, range);
        }

        if (foundIdx != -1) {
            /** mark as bracket */
            addToken(TokenCategory.kBracket, true, new TokenRange(range.getOffset() + range.getSize(), 1));
            isBracketOpen = !isBracketOpen;
            i = foundIdx + 1;
        } else {
            break;
        }
    }
}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupport.java

/**
 * Creates a new {@link GenericObjectPool} using the {@link Supplier}.
 *
 * @param connectionSupplier must not be {@literal null}.
 * @param config must not be {@literal null}.
 * @param wrapConnections {@literal false} to return direct connections that need to be returned to the pool using
 *        {@link ObjectPool#returnObject(Object)}. {@literal true} to return wrapped connection that are returned to the
 *        pool when invoking {@link StatefulConnection#close()}.
 * @param <T> connection type./*from   ww  w  .j  av a2s.  co m*/
 * @return the connection pool.
 */
@SuppressWarnings("unchecked")
public static <T extends StatefulConnection<?, ?>> GenericObjectPool<T> createGenericObjectPool(
        Supplier<T> connectionSupplier, GenericObjectPoolConfig config, boolean wrapConnections) {

    LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null");
    LettuceAssert.notNull(config, "GenericObjectPoolConfig must not be null");

    AtomicReference<ObjectPool<T>> poolRef = new AtomicReference<>();

    GenericObjectPool<T> pool = new GenericObjectPool<T>(new RedisPooledObjectFactory<>(connectionSupplier),
            config) {

        @Override
        public synchronized T borrowObject() throws Exception {
            return wrapConnections ? wrapConnection(super.borrowObject(), this) : super.borrowObject();
        }

        @Override
        public synchronized void returnObject(T obj) {

            if (wrapConnections && obj instanceof HasTargetConnection) {
                super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection());
                return;
            }
            super.returnObject(obj);
        }
    };

    poolRef.set(pool);

    return pool;
}

From source file:com.splout.db.common.TestUtils.java

/**
 * Returns a QNode instance if, after a maximum of X trials, we can find a port to bind it to.
 * The configuration passed by instance might have been modified accordingly.
 *//*from  ww w.  j a v  a2 s .  c  o  m*/
public static QNode getTestQNode(final SploutConfiguration testConfig, final IQNodeHandler handler)
        throws Throwable {
    final AtomicReference<QNode> reference = new AtomicReference<QNode>();
    CatchAndRetry qNodeInit = new CatchAndRetry(java.net.BindException.class, 50) {

        @Override
        public void businessLogic() throws Throwable {
            QNode qNode = new QNode();
            qNode.start(testConfig, handler);
            reference.set(qNode);
        }

        @Override
        public void retryLogic() {
            testConfig.setProperty(QNodeProperties.PORT, testConfig.getInt(QNodeProperties.PORT) + 1);
        }
    };
    qNodeInit.catchAndRetry();
    return reference.get();
}

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 ww. java 2s  .  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("/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:io.pravega.segmentstore.server.host.ZKSegmentContainerMonitor.java

/**
 * Creates an instance of ZKSegmentContainerMonitor.
 *
 * @param containerRegistry      The registry used to control the container state.
 * @param zkClient               The curator client.
 * @param pravegaServiceEndpoint The pravega endpoint for which we need to fetch the container assignment.
 *///from  w w w.j a  va2s  .  c  o m
ZKSegmentContainerMonitor(SegmentContainerRegistry containerRegistry, CuratorFramework zkClient,
        Host pravegaServiceEndpoint, ScheduledExecutorService executor) {
    Preconditions.checkNotNull(zkClient, "zkClient");

    this.registry = Preconditions.checkNotNull(containerRegistry, "containerRegistry");
    this.host = Preconditions.checkNotNull(pravegaServiceEndpoint, "pravegaServiceEndpoint");
    this.executor = Preconditions.checkNotNull(executor, "executor");
    this.handles = new ConcurrentHashMap<>();
    this.pendingTasks = new ConcurrentSkipListSet<>();
    String clusterPath = ZKPaths.makePath("cluster", "segmentContainerHostMapping");
    this.hostContainerMapNode = new NodeCache(zkClient, clusterPath);
    this.assigmentTask = new AtomicReference<>();
}

From source file:com.cloudera.livy.rsc.driver.RSCDriver.java

public RSCDriver(SparkConf conf, RSCConf livyConf) throws Exception {
    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwx------");
    this.localTmpDir = Files.createTempDirectory("rsc-tmp", PosixFilePermissions.asFileAttribute(perms))
            .toFile();/*from  w  w  w . j  a v a  2 s .c  o  m*/
    this.executor = Executors.newCachedThreadPool();
    this.jobQueue = new LinkedList<>();
    this.clients = new ConcurrentLinkedDeque<>();
    this.serializer = new Serializer();

    this.conf = conf;
    this.livyConf = livyConf;
    this.jcLock = new Object();
    this.shutdownLock = new Object();

    this.activeJobs = new ConcurrentHashMap<>();
    this.bypassJobs = new ConcurrentLinkedDeque<>();
    this.idleTimeout = new AtomicReference<>();
}

From source file:com.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java

/**
 * Retrieves certificate chain of specified host:port using https protocol.
 *
 * @param host to get certificate chain from (cannot be null)
 * @param port of host to connect to//from   w  w  w . ja  v  a2 s .co  m
 * @return certificate chain
 * @throws Exception Re-thrown from accessing the remote host
 */
public Certificate[] retrieveCertificatesFromHttpsServer(final String host, final int port) throws Exception {
    checkNotNull(host);

    log.info("Retrieving certificate from https://{}:{}", host, port);

    // setup custom connection manager so we can configure SSL to trust-all
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null);
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sc,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HttpSchemes.HTTP, PlainConnectionSocketFactory.getSocketFactory())
            .register(HttpSchemes.HTTPS, sslSocketFactory).build();
    final HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);

    try {
        final AtomicReference<Certificate[]> certificates = new AtomicReference<>();

        HttpClient httpClient = httpClientManager.create(new Customizer() {
            @Override
            public void customize(final HttpClientPlan plan) {
                // replace connection-manager with customized version needed to fetch SSL certificates
                plan.getClient().setConnectionManager(connectionManager);

                // add interceptor to grab peer-certificates
                plan.getClient().addInterceptorFirst(new HttpResponseInterceptor() {
                    @Override
                    public void process(final HttpResponse response, final HttpContext context)
                            throws HttpException, IOException {
                        ManagedHttpClientConnection connection = HttpCoreContext.adapt(context)
                                .getConnection(ManagedHttpClientConnection.class);

                        // grab the peer-certificates from the session
                        if (connection != null) {
                            SSLSession session = connection.getSSLSession();
                            if (session != null) {
                                certificates.set(session.getPeerCertificates());
                            }
                        }
                    }
                });
            }
        });

        httpClient.execute(new HttpGet("https://" + host + ":" + port));

        return certificates.get();
    } finally {
        // shutdown single-use connection manager
        connectionManager.shutdown();
    }
}