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.opopov.cloud.image.DecodeImageTest.java

@Test
public void testLoadImage() throws Exception {
    ImageStitchingConfiguration config = new ImageStitchingConfiguration();
    config.setRowCount(3);//  w  ww  .  j a v  a2  s .  com
    config.setColumnCount(3);
    config.setSourceHeight(256);
    config.setSourceWidth(256);

    String[][] imageUrls = new String[][] {
            //rows left to right, top to bottom
            { "z15/9/x9650/5/y5596", "z15/9/x9650/5/y5597", "z15/9/x9650/5/y5598" },
            { "z15/9/x9651/5/y5596", "z15/9/x9651/5/y5597", "z15/9/x9651/5/y5598" },
            { "z15/9/x9652/5/y5596", "z15/9/x9652/5/y5597", "z15/9/x9652/5/y5598" } };

    String pattern = "http://www.opopov.com/osmtopo1/%s.png";
    for (String[] row : imageUrls) {
        for (String cell : row) {
            config.getUrlList().add(String.format(pattern, cell));
        }
    }

    final AtomicReference<byte[]> buffer = new AtomicReference<>();
    DeferredResult<ResponseEntity<?>> result = service.getStitchedImage(config);
    result.setResultHandler(new DeferredResult.DeferredResultHandler() {
        @Override
        public void handleResult(Object result) {
            ResponseEntity<byte[]> responseEntity = (ResponseEntity<byte[]>) result;
            buffer.set(responseEntity.getBody());

        }
    });

    Thread.sleep(TIMEOUT_MILLIS);

    InputStream is = getClass().getResourceAsStream("/horizontal-stitched-test-1-frame.png");
    byte[] expectedBytes = IOUtils.toByteArray(is);
    //        Uncomment the lines below to see the generated stitched image
    //        FileOutputStream fos = new FileOutputStream("/tmp/horizontal-stitched-test-1-frame.png");
    //        IOUtils.write(buffer.get(), fos);
    //        fos.close();

    Assert.assertTrue("Image data of stitched PNG image", Arrays.equals(expectedBytes, buffer.get()));

}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.mock.TestUtils.java

/**
 * Get the future build to start as reference.
 *
 * @param event the event to monitor./*from   www.  j  a v  a 2 s .co m*/
 * @return the reference of future build to start.
 */
public static AtomicReference<Run> getFutureBuildToStart(GerritEventLifecycle event) {
    final AtomicReference<Run> reference = new AtomicReference<Run>();
    event.addListener(new GerritEventLifeCycleAdaptor() {
        @Override
        public void buildStarted(GerritEvent event, Run build) {
            reference.getAndSet(build);
        }
    });
    return reference;
}

From source file:my.adam.smo.client.Client.java

public BlockingRpcChannel blockingConnect(final InetSocketAddress sa) {
    return new BlockingRpcChannel() {
        private int countDownCallTimesToRelease = 1;
        private RpcChannel rpc = connect(sa);

        @Override/*  www .j  a va  2  s  .c  o m*/
        public Message callBlockingMethod(Descriptors.MethodDescriptor method, RpcController controller,
                Message request, Message responsePrototype) throws ServiceException {
            StopWatch stopWatch = new StopWatch("callBlockingMethod");
            stopWatch.start();

            final CountDownLatch callbackLatch = new CountDownLatch(countDownCallTimesToRelease);

            final AtomicReference<Message> result = new AtomicReference<Message>();

            RpcCallback<Message> done = new RpcCallback<Message>() {
                @Override
                public void run(Message parameter) {
                    result.set(parameter);
                    callbackLatch.countDown();
                }
            };

            rpc.callMethod(method, controller, request, responsePrototype, done);
            try {
                boolean succeededBeforeTimeout = callbackLatch.await(blocking_method_call_timeout,
                        TimeUnit.SECONDS);
                if (!succeededBeforeTimeout) {
                    throw new ServiceException(
                            "blocking method timeout reached for method:" + method.getFullName());
                }
            } catch (InterruptedException e) {
                getLogger().error("call failed", e);
                stopWatch.stop();
            }

            stopWatch.stop();
            getLogger().trace(stopWatch.shortSummary());

            return result.get();
        }
    };
}

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

@Test(enabled = false)
public void createSessionTest() throws IOException, InterruptedException {
    final AtomicReference<SubscriberResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);

    publisherClient.handler(new OnEnvelopHandler() {
        @Override/*from w w w.  ja va  2s .c om*/
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class));
            latch.countDown();
            return true;
        }
    }).open();

    Envelope createSessionMessage = Envelope
            .newClientToServerRequest(new Message(new Path(Paths.DB_POST_SUBSCRIBER_SESSION_CREATE),
                    mapper.writeValueAsString(new UserPassword("foo", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.SUBSCRIBER));
    publisherClient.send(createSessionMessage);
    latch.await();
    assertEquals("OK", answer.get().getResults());
}

From source file:arlocros.ArMarkerPoseEstimator.java

private ArMarkerPoseEstimator(final ConnectedNode connectedNode, Parameter parameter,
        Publisher<PoseStamped> posePublisher) {
    mostRecentPose = new AtomicReference<>();
    this.parameter = parameter;
    this.posePublisher = posePublisher;
    Executors.newSingleThreadExecutor().submit(new Runnable() {
        @Override/*  ww w. j  a v a2 s  . c om*/
        public void run() {
            start(connectedNode);
        }
    });
}

From source file:com.github.horrorho.liquiddonkey.cloud.engine.Donkey.java

Donkey(HttpAgent agent, ChunksClient chunksClient, ChunkManager storeManager, SignatureManager signatureManager,
        int retryCount) {

    this(agent, chunksClient, storeManager, signatureManager, retryCount, new AtomicReference());
}

From source file:io.soabase.web.filters.LanguageFilter.java

@Override
public String getLanguageCode(String queryString, Optional<String> cookie) {
    String code = getFromQueryString(queryString, new AtomicReference<>());
    if (code != null) {
        return code;
    }/*  w  ww .j  av a  2s . c o  m*/

    if (cookie.isPresent()) {
        try {
            return validate(cookie.get());
        } catch (IllegalArgumentException e) {
            log.debug("Cookie set to invalid language", cookie.get());
        }
    }
    return defaultLanguageCode;
}

From source file:de.hybris.platform.jdbcwrapper.DataSourceFactoryTest.java

@Test
public void testPoolShutdownAfterError() {
    final Tenant t = Registry.getCurrentTenantNoFallback();
    final Map<String, String> params = new HashMap<String, String>(
            t.getMasterDataSource().getConnectionParameters());
    // make it fail on connect by messing up the user name
    params.put(SystemSpecificParams.DB_USERNAME, "FooDosntExist");

    final DataSourceFactory dataSourceFactory = t.getMasterDataSource().getDataSourceFactory();

    final AtomicReference<WeakReference<JDBCConnectionPool>> poolRef = new AtomicReference<WeakReference<JDBCConnectionPool>>();

    final DataSourceFactory f = new DataSourceFactory() {

        @Override//from  w  w  w.  jav a2  s  . com
        public HybrisDataSource createJNDIDataSource(final String id, final Tenant tenant,
                final String jndiName, final boolean readOnly) {
            throw new UnsupportedOperationException();
        }

        @Override
        public HybrisDataSource createDataSource(final String id, final Tenant tenant,
                final Map<String, String> connectionParams, final boolean readOnly) {
            throw new UnsupportedOperationException();
        }

        @Override
        public JDBCConnectionPool createConnectionPool(final HybrisDataSource dataSource,
                final Config poolConfig) {
            final JDBCConnectionPool ret = dataSourceFactory.createConnectionPool(dataSource, poolConfig);
            poolRef.set(new WeakReference<JDBCConnectionPool>(ret));
            return ret;
        }

        @Override
        public Connection wrapConnection(final HybrisDataSource wrappedDataSource,
                final Connection rawConnection) {
            return dataSourceFactory.wrapConnection(wrappedDataSource, rawConnection);
        }

        @Override
        public Statement wrapStatement(final Connection wrappedConnection, final Statement rawStatement) {
            return dataSourceFactory.wrapStatement(wrappedConnection, rawStatement);
        }

        @Override
        public PreparedStatement wrapPreparedStatement(final Connection wrappedConnection,
                final PreparedStatement rawStatement, final String query) {
            return dataSourceFactory.wrapPreparedStatement(wrappedConnection, rawStatement, query);
        }

        @Override
        public ResultSet wrapResultSet(final Statement wrappedStatement, final ResultSet rawResultSet) {
            return dataSourceFactory.wrapResultSet(wrappedStatement, rawResultSet);
        }
    };

    HybrisDataSource ds = null;
    try {
        TestUtils.disableFileAnalyzer("DataSource creation should throw exception");
        ds = new DataSourceImpl(t, "DummyDS", params, false, f);
    } catch (final Exception e) {
        // fine so far - now check how the pool behaves
        assertPoolIsShutDown(poolRef.get(), 30);
    } finally {
        TestUtils.enableFileAnalyzer();
    }
    if (ds != null) {
        // in case data source creation did not fail as expected we must clean up for sure 
        ds.destroy();
        fail("data source creation was supposed to fail but did not");
    }
}

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));
    }/*from  w  ww  . j  av a2s.  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;
}

From source file:io.pravega.segmentstore.server.host.stat.AutoScaleProcessor.java

AutoScaleProcessor(AutoScalerConfig configuration, Executor executor,
        ScheduledExecutorService maintenanceExecutor) {
    this.configuration = configuration;
    this.maintenanceExecutor = maintenanceExecutor;
    this.executor = executor;

    serializer = new JavaSerializer<>();
    writerConfig = EventWriterConfig.builder().build();
    writer = new AtomicReference<>();

    cache = CacheBuilder.newBuilder().initialCapacity(INITIAL_CAPACITY).maximumSize(MAX_CACHE_SIZE)
            .expireAfterAccess(configuration.getCacheExpiry().getSeconds(), TimeUnit.SECONDS).removalListener(
                    RemovalListeners.asynchronous((RemovalListener<String, Pair<Long, Long>>) notification -> {
                        if (notification.getCause().equals(RemovalCause.EXPIRED)) {
                            triggerScaleDown(notification.getKey(), true);
                        }/*from w  w  w.j a va 2 s  .c o  m*/
                    }, maintenanceExecutor))
            .build();

    CompletableFuture.runAsync(this::bootstrapRequestWriters, maintenanceExecutor);
}