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.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:kn.uni.gis.foxhunt.context.GameContext.java

/**
 * creates a new fox game/*from   w w  w  . j a v  a  2  s.c  o  m*/
 * 
 * @param id
 * @param playerName
 */
public static void newFoxGame(String playerName) throws GameException {

    final AtomicReference<String> ref = new AtomicReference<String>();
    final AtomicReference<Exception> exc = new AtomicReference<Exception>();
    HttpContext.getInstance().put(SettingsContext.getInstance().getServerUrl(), null,
            new EntityHandlerAdapter() {
                @Override
                public void handleEntity(HttpEntity entity, int statusCode) {
                    if (statusCode == HttpStatus.SC_OK) {
                        try {
                            ref.set(EntityUtils.toString(entity));

                        } catch (ParseException e) {
                            exc.set(e);
                        } catch (IOException e) {
                            exc.set(e);
                        }
                    } else {
                        exc.set(new GameException("bad status code: " + statusCode));
                    }
                }

                @Override
                public void handleException(Exception exception) {
                    exc.set(exception);
                }
            });

    if (ref.get() == null) {
        throw exc.get() != null ? new GameException(exc.get())
                : new GameException("unrecognized error code from server");
    }
    currentGame = new Game(ref.get(), playerName, Util.createFoxUrl(ref.get()), Util.createGameUrl(ref.get()));
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.IssueScanner.java

/**
 * Call this when you're done creating all the Issues.  This creates an output stream and writes out the beans one
 * by one calling each bean's toString() which returns a comma delimited string of the values contained in that
 * bean. This method also prints out the header of the file before looping over the beans.
 *
 * @throws java.io.IOException if we're not able to write the file out.
 *//*from   www  . j a  v  a 2  s  .c o m*/
private void writeCommaDelimitedFile() throws IOException {

    AtomicReference<BufferedWriter> out = null;
    FileWriter fileWriter = null;
    BufferedWriter bufferedWriter = null;
    try {
        // Create file
        //noinspection IOResourceOpenedButNotSafelyClosed
        fileWriter = new FileWriter(FILE_SYSTEM_LOCATION + "gforge-issues" + new Date().toString() + ".txt");
        final AtomicReference<FileWriter> fstream = new AtomicReference<FileWriter>(fileWriter);
        //noinspection IOResourceOpenedButNotSafelyClosed
        bufferedWriter = new BufferedWriter(fstream.get());
        out = new AtomicReference<BufferedWriter>(bufferedWriter);
        out.get().write(getHeader());
        for (final Issue anIssue : issueList) {
            out.get().write(anIssue.toString());
        }
    } finally {
        out.get().close();
        IOUtils.closeQuietly(fileWriter);
        IOUtils.closeQuietly(bufferedWriter);
    }
}

From source file:com.brienwheeler.svc.monitor.telemetry.impl.GraphiteTelemetryInfoProcessorTest.java

@Test
@SuppressWarnings("unchecked")
public void testProcess() throws IOException, InterruptedException {
    TestListener testListener = new TestListener();

    GraphiteTelemetryInfoProcessor processor = new GraphiteTelemetryInfoProcessor();
    processor.setHostname("localhost");
    processor.setPort(testListener.getListenPort());

    processor.start();//  w  w  w.  j  a v  a  2  s. co m
    testListener.accept(); // wait for connect

    AtomicReference<ReconnectingSocket> socket = (AtomicReference<ReconnectingSocket>) ReflectionTestUtils
            .getField(processor, "reconnectingSocket");
    while (!socket.get().isConnected())
        Thread.sleep(5L);

    try {
        TelemetryInfo info = new TelemetryInfo(INFO_NAME);

        info.set(ATTR_DOUBLE, 1.0d);
        info.set(ATTR_FLOAT, 1.0f);
        info.set(ATTR_INTEGER, 1);
        info.set(ATTR_LONG, 1L);
        info.set(ATTR_STRING, "1");

        info.publish();
        processor.process(info);

        log.info(testListener.readLine());
        log.info(testListener.readLine());
        log.info(testListener.readLine());
        log.info(testListener.readLine());
    } finally {
        processor.stop(1000L);
        testListener.close();
    }
}

From source file:com.gaodashang.demo.SampleWebSocketsApplicationTests.java

@Test
public void reverseEndpoint() throws Exception {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class,
            PropertyPlaceholderAutoConfiguration.class)
                    .properties("websocket.uri:ws://localhost:" + this.port + "/reverse")
                    .run("--spring.main.web_environment=false");
    long count = context.getBean(ClientConfiguration.class).latch.getCount();
    AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload;
    context.close();//from w  w  w . j  a  v  a 2  s  .  c om
    assertEquals(0, count);
    assertEquals("Reversed: !dlrow olleH", messagePayloadReference.get());
}

From source file:com.gaodashang.demo.SampleWebSocketsApplicationTests.java

@Test
public void echoEndpoint() throws Exception {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class,
            PropertyPlaceholderAutoConfiguration.class)
                    .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket")
                    .run("--spring.main.web_environment=false");
    long count = context.getBean(ClientConfiguration.class).latch.getCount();
    AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload;
    context.close();/*from ww  w  .  j  a va2  s  .  c o m*/
    assertEquals(0, count);
    assertEquals("Did you say \"Hello world!\"?", messagePayloadReference.get());
}

From source file:com.brienwheeler.lib.concurrent.NamedThreadFactoryTest.java

@SuppressWarnings("unchecked")
@Test//from   w w  w . j ava 2s  .  c om
public void testSetUncaughtExceptionHandler() {
    NamedThreadFactory factory = new NamedThreadFactory();
    UncaughtExceptionHandler handler = new UncaughtExceptionHandler();
    factory.setUncaughtExceptionHandler(handler);
    AtomicReference<Thread.UncaughtExceptionHandler> ref = (AtomicReference<Thread.UncaughtExceptionHandler>) ReflectionTestUtils
            .getField(factory, "uncaughtExceptionHandler");
    Assert.assertSame(handler, ref.get());
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.BaselineFolderCollection.java

/**
 * Creates and opens a file with the specified path. If the parent folder
 * does not exist, we create it and mark it and its parent as hidden -- we
 * assume that file reside in $tf\10\ and we need to mark both $tf and 10 as
 * hidden. If filePath was not specified or its creation failed, and
 * createTempOnFailure=true we will create a new temporary file, using
 * tempUniqueString./* w  w w  . ja v a 2 s . c o m*/
 *
 *
 * @param filePath
 *        in: the path to create the file at, out: the path actually created
 *        (possibly a temporary file in another directory) (must not be
 *        <code>null</code>)
 * @param createTempOnFailure
 * @param tempUniqueString
 * @param tempCreated
 * @return
 * @throws IOException
 */
public static FileOutputStream createFile(final AtomicReference<String> filePath,
        final boolean createTempOnFailure, final String tempUniqueString, final AtomicBoolean tempCreated)
        throws IOException {
    Check.notNull(filePath, "filePath"); //$NON-NLS-1$

    FileOutputStream localStream = null;
    tempCreated.set(false);

    Exception createException = null;
    if (filePath.get() != null && filePath.get().length() > 0) {
        try {
            localStream = new FileOutputStream(filePath.get());
        } catch (final Exception ex) {
            createException = ex;
            if (!createTempOnFailure) {
                throw new VersionControlException(ex);
            }
        }
    }
    if (localStream == null && createTempOnFailure) {
        tempCreated.set(true);

        final File tempFile = TempStorageService.getInstance().createTempFile();
        localStream = new FileOutputStream(tempFile);

        log.info(MessageFormat.format(
                "Could not create baseline folder collection file {0}, using temporary file {1}", //$NON-NLS-1$
                filePath.get(), tempFile), createException);

        filePath.set(tempFile.getAbsolutePath());
    } else {
        Check.notNullOrEmpty(filePath.get(), "filePath.get()"); //$NON-NLS-1$
    }

    return localStream;
}

From source file:com.gaodashang.demo.echo.CustomContainerWebSocketsApplicationTests.java

@Test
public void reverseEndpoint() throws Exception {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class,
            PropertyPlaceholderAutoConfiguration.class)
                    .properties("websocket.uri:ws://localhost:" + PORT + "/ws/reverse")
                    .run("--spring.main.web_environment=false");
    long count = context.getBean(ClientConfiguration.class).latch.getCount();
    AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload;
    context.close();//from ww w.  j  a  v  a  2 s .c  o  m
    assertEquals(0, count);
    assertEquals("Reversed: !dlrow olleH", messagePayloadReference.get());
}

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

@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
    JavaType javaType = getJavaType(clazz, null);
    if (!jackson23Available) {
        return (this.objectMapper.canDeserialize(javaType) && canRead(mediaType));
    }//www .  jav  a2 s .  c  om
    AtomicReference<Throwable> causeRef = new AtomicReference<>();
    if (this.objectMapper.canDeserialize(javaType, causeRef) && canRead(mediaType)) {
        return true;
    }
    Throwable cause = causeRef.get();
    if (cause != null) {
        log.warn("Failed to evaluate deserialization for type {}", javaType, cause);
    }
    return false;
}