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:io.termd.core.telnet.TelnetHandlerTest.java

@Test
public void testAcceptNAWS() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    final AtomicReference<int[]> size = new AtomicReference<>();
    WindowSizeOptionHandler optionHandler = new WindowSizeOptionHandler(20, 10, false, false, true, false);
    testOptionValue(() -> new TelnetHandler() {
        @Override/* w  w  w . j a  v a  2  s . c  om*/
        protected void onOpen(TelnetConnection conn) {
            conn.writeDoOption(Option.NAWS);
        }

        @Override
        protected void onNAWS(boolean naws) {
            serverValue.set(naws);
        }

        @Override
        protected void onSize(int width, int height) {
            size.set(new int[] { width, height });
            testComplete();
        }
    }, optionHandler);
    assertEquals(true, serverValue.get());
    assertEquals(true, optionHandler.getAcceptLocal());
    assertEquals(2, size.get().length);
    assertEquals(20, size.get()[0]);
    assertEquals(10, size.get()[1]);
}

From source file:fi.solita.phantomrunner.jetty.PhantomWebSocketHandler.java

public JsonNode sendMessageToConnections(String msg) {
    try {/*from   w w  w  . ja v  a 2s . c  om*/
        final Object requestLock = new Object();
        final AtomicReference<JsonNode> result = new AtomicReference<JsonNode>();

        synchronized (socketLock) {
            if (socket.get() == null) {
                // wait for 10 secs for the socket to open
                socketLock.wait(TimeUnit.SECONDS.toMillis(10));
            }
        }

        if (socket.get() == null) {
            throw new PhantomWebSocketException("No open websocket connection available, cannot send message");
        }

        try {
            socket.get().send(msg, new PhantomMessageListener() {
                @Override
                public void message(JsonNode readTree) {
                    synchronized (requestLock) {
                        result.set(readTree);
                        requestLock.notifyAll();
                    }
                }
            });
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        synchronized (requestLock) {
            requestLock.wait(10000);
        }

        return result.get();
    } catch (InterruptedException ie) {
        throw new RuntimeException(ie);
    }
}

From source file:org.keycloak.testsuite.crossdc.ConcurrentLoginCrossDCTest.java

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

    AtomicReference<String> userSessionId = new AtomicReference<>();
    LoginTask loginTask = null;/*from   w w  w  .ja  v  a 2  s. c  om*/

    try (CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setRedirectStrategy(new LaxRedirectStrategy()).build()) {
        loginTask = new LoginTask(httpClient, userSessionId, LOGIN_TASK_DELAY_MS, LOGIN_TASK_RETRIES, false,
                Arrays.asList(createHttpClientContextForUser(httpClient, "test-user@localhost", "password")));
        HttpUriRequest request = handleLogin(
                getPageContent(oauth.getLoginFormUrl(), httpClient, HttpClientContext.create()),
                "test-user@localhost", "password");
        log.debug("Executing login request");
        org.junit.Assert.assertTrue(
                parseAndCloseResponse(httpClient.execute(request)).contains("<title>AUTH_RESPONSE</title>"));

        run(DEFAULT_THREADS, DEFAULT_CLIENTS_COUNT, loginTask, new SwapDcAvailability());
        int clientSessionsCount = testingClient.testing().getClientSessionsCountInUserSession("test",
                userSessionId.get());
        org.junit.Assert.assertEquals(1 + DEFAULT_CLIENTS_COUNT, clientSessionsCount);
    } finally {
        long end = System.currentTimeMillis() - start;
        log.infof("Statistics: %s", loginTask == null ? "??" : loginTask.getHistogram());
        log.info("concurrentLoginWithRandomDcFailures took " + (end / 1000) + "s");
        log.info("*********************************************");
    }
}

From source file:edu.rit.flick.genetics.FastFileInflator.java

@Override
public synchronized File inflate(final Configuration configuration, final File fileIn, final File fileOut) {
    assert fileIn.exists();

    try {/*from w  w  w  .j av a 2s  .c o  m*/
        // Inflate to Directory
        final String outputDirectoryPath = fileOut.getPath()
                .replaceAll("." + Files.getFileExtension(fileOut.getPath()), FLICK_FAST_FILE_TMP_DIR_SUFFIX);

        final File tmpOutputDirectory = new File(outputDirectoryPath);
        if (tmpOutputDirectory.exists())
            FileUtils.deleteDirectory(tmpOutputDirectory);

        final AtomicReference<Thread> cleanHookAtomic = new AtomicReference<Thread>();

        final Thread inflateToDirectoryThread = new Thread(() -> {
            try {
                // Inflate Fast file to a temporary directory
                inflateFromFile(fileIn, tmpOutputDirectory);

                // Inflate Directory to a zip file
                inflateFromDirectory(tmpOutputDirectory, fileOut);

                // Clean up IO
                close();
                System.gc();
                Thread.sleep(100);

                // Clean up temporary directory
                FileUtils.deleteDirectory(tmpOutputDirectory);

                Runtime.getRuntime().removeShutdownHook(cleanHookAtomic.get());
            } catch (final Exception e) {
                if (!interrupted)
                    System.err.println(e.getMessage());
            }
        }, "Default_Inflation_Thread");

        // Make cleaning hook
        final Thread cleanHook = new Thread(() -> {
            interrupted = true;
            configuration.setFlag(VERBOSE_FLAG, false);
            configuration.setFlag(DELETE_FLAG, false);
            try {
                if (inflateToDirectoryThread.isAlive())
                    inflateToDirectoryThread.interrupt();

                // Clean up IO
                close();
                System.gc();
                Thread.sleep(100);

                synchronized (this) {
                    while (inflateToDirectoryThread.isAlive())
                        this.wait();
                }

            } catch (final IOException | InterruptedException e) {
                e.printStackTrace();
            } finally {
                // Clean up temporary directory
                FileUtils.deleteQuietly(tmpOutputDirectory);
                // Clean up INCOMPLETE output file
                FileUtils.deleteQuietly(fileOut);
                System.out.println();
            }

        }, "Inflation_Cleaning_Thread");

        cleanHookAtomic.set(cleanHook);

        Runtime.getRuntime().addShutdownHook(cleanHook);

        inflateToDirectoryThread.start();
        inflateToDirectoryThread.join();

    } catch (final IOException | InterruptedException e) {
        e.printStackTrace();
    }

    return fileOut;
}

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void notModified() throws Exception {
    int code = 304;
    statusCode.set(code);//from   www.j a  v  a  2s. c  o m
    redirects.set(2);
    AtomicIntegerArray expected = copy(statusCounts);
    expected.addAndGet(code, 1);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get(uri("/notModified")).subscribe(Actions.empty(), new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            latch.countDown();
            throwable.set(t);
        }
    }, new Action0() {
        @Override
        public void call() {
            latch.countDown();
        }
    });

    latch.await();
    assertEquals(expected, statusCounts);
    Assert.assertNull(throwable.get());
}

From source file:it.ecubecenter.processors.sentiment.SentimentAnalyzer.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ComponentLog log = getLogger();
    final AtomicReference<String> atomicStringToAnalyze = new AtomicReference<>();

    FlowFile flowFile = session.get();//w  ww  . ja  v  a2s.  com
    if (flowFile == null) {
        return;
    }
    String attributeToBeUsed = context.getProperty(ATTRIBUTE_TO_ANALYZE_PROPERTY).getValue();
    if (attributeToBeUsed == null || attributeToBeUsed.equals("")) {
        attributeToBeUsed = "";
        log.info("Start reading the flow file content in order to perform the sentiment analysis.");
        session.read(flowFile, new InputStreamCallback() {

            @Override
            public void process(InputStream in) throws IOException {
                atomicStringToAnalyze.set(IOUtils.toString(in));
            }
        });
    } else {
        log.info("Getting the content of attribute " + attributeToBeUsed
                + "in order to perform the sentiment analysis.");
        atomicStringToAnalyze.set(flowFile.getAttribute(attributeToBeUsed));
    }
    String stringToAnalyze = atomicStringToAnalyze.get();
    if (stringToAnalyze == null || stringToAnalyze.equals("")) {
        log.warn("The attribute to be analyzed doesn't exist or it is empty.");
        session.transfer(flowFile, FAILURE_RELATIONSHIP);
        return;
    }

    SentimentModel model = SentimentModel.getInstance();

    List<double[]> sentiments = model.getSentencesSentiment(stringToAnalyze);
    flowFile = session.putAttribute(flowFile, attributeToBeUsed + ".sentiment.category",
            SentimentModel.getOverallSentiment(sentiments));
    flowFile = session.putAttribute(flowFile, attributeToBeUsed + ".sentiment.sentences.scores",
            stringifyListOfSentiments(sentiments));

    session.transfer(flowFile, SUCCESS_RELATIONSHIP);
}

From source file:org.apache.bookkeeper.client.MetadataUpdateLoopTest.java

/**
 * Test that we can update the metadata using the update loop.
 *//*from   w w w  . j  av a  2 s.c o m*/
@Test
public void testBasicUpdate() throws Exception {
    try (LedgerManager lm = new MockLedgerManager()) {
        LedgerMetadata initMeta = LedgerMetadataBuilder.create().withEnsembleSize(5)
                .withDigestType(DigestType.CRC32C).withPassword(new byte[0])
                .newEnsembleEntry(0L, Lists.newArrayList(new BookieSocketAddress("0.0.0.0:3181"),
                        new BookieSocketAddress("0.0.0.1:3181"), new BookieSocketAddress("0.0.0.2:3181"),
                        new BookieSocketAddress("0.0.0.3:3181"), new BookieSocketAddress("0.0.0.4:3181")))
                .build();
        long ledgerId = 1234L;
        Versioned<LedgerMetadata> writtenMetadata = lm.createLedgerMetadata(ledgerId, initMeta).get();

        AtomicReference<Versioned<LedgerMetadata>> reference = new AtomicReference<>(writtenMetadata);

        BookieSocketAddress newAddress = new BookieSocketAddress("0.0.0.5:3181");
        MetadataUpdateLoop loop = new MetadataUpdateLoop(lm, ledgerId, reference::get,
                (currentMetadata) -> true, (currentMetadata) -> {
                    List<BookieSocketAddress> ensemble = Lists.newArrayList(currentMetadata.getEnsembleAt(0L));
                    ensemble.set(0, newAddress);
                    return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble)
                            .build();
                }, reference::compareAndSet);
        loop.run().get();

        Assert.assertNotEquals(reference.get(), writtenMetadata);
        Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(0), newAddress);
    }
}

From source file:org.springframework.cloud.sleuth.instrument.web.client.TraceWebClientAutoConfiguration.java

Mono<HttpClientResponse> wrapHttpClientRequestSending(ProceedingJoinPoint pjp,
        BiFunction<? super HttpClientRequest, ? super NettyOutbound, ? extends Publisher<Void>> function)
        throws Throwable {
    // add headers and set CS
    final Span currentSpan = this.tracer.currentSpan();
    final AtomicReference<Span> span = new AtomicReference<>();
    BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> combinedFunction = (req, nettyOutbound) -> {
        try (Tracer.SpanInScope spanInScope = this.tracer.withSpanInScope(currentSpan)) {
            io.netty.handler.codec.http.HttpHeaders originalHeaders = req.requestHeaders().copy();
            io.netty.handler.codec.http.HttpHeaders tracedHeaders = req.requestHeaders();
            span.set(this.handler.handleSend(this.injector, tracedHeaders, req));
            if (log.isDebugEnabled()) {
                log.debug("Handled send of " + span.get());
            }//w w  w  . j av  a 2  s . c om
            io.netty.handler.codec.http.HttpHeaders addedHeaders = tracedHeaders.copy();
            originalHeaders.forEach(header -> addedHeaders.remove(header.getKey()));
            try (Tracer.SpanInScope clientInScope = this.tracer.withSpanInScope(span.get())) {
                if (log.isDebugEnabled()) {
                    log.debug("Created a new client span for Netty client");
                }
                return handle(function, new TracedHttpClientRequest(req, addedHeaders), nettyOutbound);
            }
        }
    };
    // run
    Mono<HttpClientResponse> responseMono = (Mono<HttpClientResponse>) pjp
            .proceed(new Object[] { combinedFunction });
    // get response
    return responseMono.doOnSuccessOrError((httpClientResponse, throwable) -> {
        try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.get())) {
            // status codes and CR
            if (span.get() != null) {
                this.handler.handleReceive(httpClientResponse, throwable, span.get());
                if (log.isDebugEnabled()) {
                    log.debug("Setting client sent spans");
                }
            }
        }
    });
}

From source file:interactivespaces.util.web.HttpClientHttpContentCopierTest.java

/**
 * Test a file upload from a file./*  www  .ja  va  2s.  com*/
 */
@Test
public void testFileUploadFile() throws Exception {
    File source = getTempFile();
    final File destination = getTempFile();

    Files.writeFile(source, TEST_CONTENT);

    final AtomicReference<Map<String, String>> receivedParameters = new AtomicReference<Map<String, String>>();
    final CountDownLatch latch = new CountDownLatch(1);

    webServer.setHttpFileUploadListener(new HttpFileUploadListener() {
        @Override
        public void handleHttpFileUpload(HttpFileUpload fileUpload) {
            fileUpload.moveTo(destination);
            receivedParameters.set(fileUpload.getParameters());
            latch.countDown();
        }
    });

    String sourceParameterName = "myfile";
    Map<String, String> expectedParameters = Maps.newHashMap();
    expectedParameters.put("foo", "bar");
    expectedParameters.put("bletch", "spam");

    copier.copyTo(getUrlPrefix(), source, sourceParameterName, expectedParameters);

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

    Assert.assertEquals(TEST_CONTENT, Files.readFile(destination).trim());
    Assert.assertEquals(expectedParameters, receivedParameters.get());
}

From source file:org.zodiark.subscriber.SubscriberTest.java

@Test(enabled = false)
public void joinStreamingSession() throws IOException, InterruptedException {
    final ZodiarkClient wowzaClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch connected = new CountDownLatch(1);
    final AtomicReference<String> uuid = new AtomicReference<>();
    final AtomicReference<String> paths = new AtomicReference<>();

    // =============== Wowza

    paths.set("");
    wowzaClient.handler(new OnEnvelopHandler() {
        @Override/*from www .j av  a2  s . com*/
        public boolean onEnvelop(Envelope e) throws IOException {

            Message m = e.getMessage();
            switch (m.getPath()) {
            case Paths.WOWZA_CONNECT:
                // Connected. Listen
                uuid.set(e.getUuid());
                break;
            case Paths.SERVER_VALIDATE_OK:
                Envelope publisherOk = Envelope
                        .newClientToServerRequest(new Message(new Path(paths.get()), e.getMessage().getData()));
                wowzaClient.send(publisherOk);
                break;
            default:
                // ERROR
            }

            connected.countDown();
            return false;
        }
    }).open();

    Envelope wowzaConnect = Envelope.newClientToServerRequest(new Message(new Path(Paths.WOWZA_CONNECT),
            mapper.writeValueAsString(new UserPassword("wowza", "bar"))));
    wowzaClient.send(wowzaConnect);
    connected.await();

    // ================ Publisher

    final AtomicReference<PublisherResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> publisherUUID = new AtomicReference<>();
    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            publisherUUID.set(e.getUuid());
            latch.countDown();
            return true;
        }
    }).open();

    Envelope createSessionMessage = Envelope.newClientToServerRequest(
            new Message(new Path(""), mapper.writeValueAsString(new UserPassword("publisherex", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(createSessionMessage);
    latch.await();
    assertEquals("OK", answer.get().getResults());
    answer.set(null);

    final CountDownLatch tlatch = new CountDownLatch(1);
    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            tlatch.countDown();
            return true;
        }
    });

    Envelope startStreamingSession = Envelope
            .newClientToServerRequest(new Message(new Path(Paths.VALIDATE_PUBLISHER_STREAMING_SESSION),
                    mapper.writeValueAsString(new WowzaUUID(uuid.get()))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(startStreamingSession);

    tlatch.await();

    assertEquals("OK", answer.get().getResults());

    // ================ Subscriber

    paths.set(Paths.JOIN_SUBSCRIBER_STREAMING_SESSION);
    final AtomicReference<SubscriberResults> sanswer = new AtomicReference<>();
    final ZodiarkClient subscriberClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch platch = new CountDownLatch(1);
    final AtomicReference<String> subscriberUUID = new AtomicReference<>();

    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            sanswer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class));
            subscriberUUID.set(e.getUuid());
            platch.countDown();
            return true;
        }
    }).open();

    createSessionMessage = Envelope.newClientToServerRequest(subscriberUUID.get(),
            new Message(new Path(Paths.DB_POST_SUBSCRIBER_SESSION_CREATE),
                    mapper.writeValueAsString(new UserPassword("123456", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.SUBSCRIBER));
    subscriberClient.send(createSessionMessage);
    platch.await();
    assertEquals("OK", sanswer.get().getResults());
    sanswer.set(null);

    final CountDownLatch elatch = new CountDownLatch(1);
    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            sanswer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class));
            elatch.countDown();
            return true;
        }
    });

    StreamingRequest request = new StreamingRequestImpl(publisherUUID.get(), uuid.get());

    startStreamingSession = Envelope.newClientToServerRequest(subscriberUUID.get(), new Message(
            new Path(Paths.VALIDATE_SUBSCRIBER_STREAMING_SESSION), mapper.writeValueAsString(request)));
    createSessionMessage.setFrom(new From(ActorValue.SUBSCRIBER));
    subscriberClient.send(startStreamingSession);

    elatch.await();

    assertEquals("OK", sanswer.get().getResults());

}