Example usage for java.util.concurrent.atomic AtomicReference set

List of usage examples for java.util.concurrent.atomic AtomicReference set

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference set.

Prototype

public final void set(V newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:org.apache.edgent.samples.apps.sensorAnalytics.Sensor1.java

/**
 * Add the sensor's analytics to the topology.
 *//*  w w w.  j a v a 2  s. c  o m*/
public void addAnalytics() {

    // Need synchronization for set/get of dynamically changeable values.
    AtomicReference<Range<Integer>> range = new AtomicReference<>();
    AtomicReference<Boolean> isPublish1hzOutsideRange = new AtomicReference<>();

    // Initialize the controls
    range.set(app.utils().getRangeInteger(sensorId, "outside1hzMeanRange"));
    isPublish1hzOutsideRange.set(false);

    // Handle the sensor's device commands
    app.mqttDevice().commands(commandId("set1hzMeanRangeThreshold"))
            .tag(commandId("set1hzMeanRangeThresholdCmd")).sink(jo -> {
                Range<Integer> newRange = Ranges.valueOfInteger(getCommandValue(jo));
                System.out.println("===== Changing range to " + newRange + " ======");
                range.set(newRange);
            });
    app.mqttDevice().commands(commandId("setPublish1hzOutsideRange"))
            .tag(commandId("setPublish1hzOutsideRangeCmd")).sink(jo -> {
                Boolean b = new Boolean(getCommandValue(jo));
                System.out.println("===== Changing isPublish1hzOutsideRange to " + b + " ======");
                isPublish1hzOutsideRange.set(b);
            });

    // Create a raw simulated sensor stream of 1000 tuples/sec.
    // Each tuple is Pair<Long timestampMsec, sensor-reading (0..255)>.
    PeriodicRandomSensor simulatedSensorFactory = new PeriodicRandomSensor();
    TStream<Pair<Long, Integer>> raw1khz = simulatedSensorFactory.newInteger(t, 1/*periodMsec*/, 255)
            .tag("raw1khz");
    traceStream(raw1khz, "raw1khz");

    // Wrap the raw sensor reading in a JsonObject for convenience.
    TStream<JsonObject> j1khz = JsonTuples.wrap(raw1khz, sensorId).tag("j1khz");
    traceStream(j1khz, "j1khz");

    // Data-reduction: reduce 1khz samples down to
    // 1hz aggregate statistics samples.
    TStream<JsonObject> j1hzStats = j1khz.last(1000, JsonTuples.keyFn())
            .batch(JsonTuples.statistics(MIN, MAX, MEAN, STDDEV)).tag("1hzStats");

    // Create a 30 second sliding window of average trailing Mean values
    // and enrich samples with that information.
    j1hzStats = j1hzStats.last(30, JsonTuples.keyFn()).aggregate((samples, key) -> {
        // enrich and return the most recently added tuple
        JsonObject jo = samples.get(samples.size() - 1);
        double meanSum = 0;
        for (JsonObject js : samples) {
            meanSum += JsonTuples.getStatistic(js, MEAN).getAsDouble();
        }
        jo.addProperty("AvgTrailingMean", Math.round(meanSum / samples.size()));
        jo.addProperty("AvgTrailingMeanCnt", samples.size());
        return jo;
    }).tag("1hzStats.enriched");
    traceStream(j1hzStats, "j1hzStats");

    // Detect 1hz samples whose MEAN value are
    // outside the configuration specified range.
    TStream<JsonObject> outside1hzMeanRange = j1hzStats.filter(sample -> {
        int value = JsonTuples.getStatistic(sample, MEAN).getAsInt();
        return !range.get().contains(value);
    }).tag("outside1hzMeanRange");
    traceStream(outside1hzMeanRange, () -> "outside1hzMeanRange" + range.get());

    // Log every outside1hzMeanRange event
    app.utils().logStream(outside1hzMeanRange, "ALERT", "outside1hzMeanRange");

    // Conditionally publish every outside1hzMeanRange event.
    // Use a pressureReliever to prevent backpressure if the broker
    // can't be contacted.
    // TODO enhance MqttDevice with configurable reliever. 
    app.mqttDevice().events(
            PlumbingStreams
                    .pressureReliever(outside1hzMeanRange.filter(tuple -> isPublish1hzOutsideRange.get())
                            .tag("outside1hzMeanRangeEvent.conditional"), tuple -> 0, 30)
                    .tag("outside1hzMeanRangeEvent.pressureRelieved"),
            app.sensorEventId(sensorId, "outside1hzMeanRangeEvent"), QoS.FIRE_AND_FORGET);

    // Demonstrate periodic publishing of a sliding window if
    // something changed since it was last published.
    periodicallyPublishLastNInfo(outside1hzMeanRange, 10, 30, "periodicLastOutsideRangeEvent");

    // TODO histogram: #alerts over the last 8hr

}

From source file:com.opopov.cloud.image.DecodeImageTest.java

@Test
public void testLoadImage() throws Exception {
    ImageStitchingConfiguration config = new ImageStitchingConfiguration();
    config.setRowCount(3);//from   w  ww  .  j a va  2  s . c o m
    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:org.apache.tomee.jul.handler.rotating.ArchivingTest.java

@SuppressWarnings("unchecked")
@Test/*from   w w w  .  j  av  a2 s  .c  o m*/
public void logAndRotateAndPurge() throws Exception {
    clean("target/ArchivingTestPurge-" + format + "/logs");

    final AtomicReference<String> today = new AtomicReference<>();
    final Map<String, String> config = new HashMap<>();

    // initial config
    today.set("2015-09-01");
    config.put("filenamePattern", "target/ArchivingTestPurge-" + format + "/logs/test.%s.%d.log");
    config.put("archiveDirectory", "target/ArchivingTestPurge-" + format + "/logs/archives");
    config.put("archiveFormat", format);
    config.put("archiveOlderThan", "1 s");
    config.put("purgeOlderThan", "2 s");
    config.put("limit", "10 kilobytes");
    config.put("level", "INFO");
    config.put("dateCheckInterval", "1 second");

    final LocalFileHandler handler = new LocalFileHandler() {
        @Override
        protected String currentDate() {
            return today.get();
        }

        @Override
        protected String getProperty(final String name, final String defaultValue) {
            final String s = config.get(name.substring(name.lastIndexOf('.') + 1));
            return s != null ? s : defaultValue;
        }
    };

    final String string10chars = "abcdefghij";
    final int iterations = 950;
    for (int i = 0; i < iterations; i++) {
        handler.publish(new LogRecord(Level.INFO, string10chars));
    }

    today.set("2015-09-02");
    try {
        Thread.sleep(2000);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }

    final File logArchive = new File(
            "target/ArchivingTestPurge-" + format + "/logs/archives/test.2015-09-01.0.log." + format);
    final File parentFile = logArchive.getParentFile();
    if (!parentFile.exists() && !parentFile.mkdirs()) {
        Assert.fail("Unable to create: " + parentFile);
    }
    final Path dir = parentFile.toPath();
    final WatchService watcher = FileSystems.getDefault().newWatchService();
    final WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);

    latch.set(new CountDownLatch(1));
    watch(key);

    handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the archiving

    assertTrue("Failed to get archived log", latch.get().await(20, TimeUnit.SECONDS));
    final WatchEvent<?> watchEvent = lastEvent.get();

    assertTrue(StandardWatchEventKinds.ENTRY_CREATE.equals(watchEvent.kind())
            || StandardWatchEventKinds.ENTRY_MODIFY.equals(watchEvent.kind()));

    final WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;

    final String io = ev.context().toString();
    assertTrue(io.startsWith("test.2015-09-01.") && io.endsWith(format));

    today.set("2015-09-03");
    try {
        Thread.sleep(2500);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }

    handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the purging
    handler.close();
    withRetry(10, 2, new Runnable() {
        @Override
        public void run() {
            assertFalse(logArchive.getAbsolutePath() + " was purged", logArchive.exists());
        }
    });
}

From source file:com.netflix.config.ConcurrentMapConfigurationTest.java

@Test
public void testListeners() {
    ConcurrentMapConfiguration conf = new ConcurrentMapConfiguration();
    final AtomicReference<ConfigurationEvent> eventRef = new AtomicReference<ConfigurationEvent>();
    conf.addConfigurationListener(new ConfigurationListener() {
        @Override/*  w  w  w  .  j  a  v a  2 s .  c  o  m*/
        public void configurationChanged(ConfigurationEvent arg0) {
            eventRef.set(arg0);
        }

    });
    conf.addProperty("key", "1");
    assertEquals(1, conf.getInt("key"));
    ConfigurationEvent event = eventRef.get();
    assertEquals("key", event.getPropertyName());
    assertEquals("1", event.getPropertyValue());
    assertTrue(conf == event.getSource());
    assertEquals(AbstractConfiguration.EVENT_ADD_PROPERTY, event.getType());
    conf.setProperty("key", "2");
    event = eventRef.get();
    assertEquals("key", event.getPropertyName());
    assertEquals("2", event.getPropertyValue());
    assertTrue(conf == event.getSource());
    assertEquals(AbstractConfiguration.EVENT_SET_PROPERTY, event.getType());
    conf.clearProperty("key");
    event = eventRef.get();
    assertEquals("key", event.getPropertyName());
    assertNull(event.getPropertyValue());
    assertTrue(conf == event.getSource());
    assertEquals(AbstractConfiguration.EVENT_CLEAR_PROPERTY, event.getType());
    conf.clear();
    assertFalse(conf.getKeys().hasNext());
    event = eventRef.get();
    assertTrue(conf == event.getSource());
    assertEquals(AbstractConfiguration.EVENT_CLEAR, event.getType());
}

From source file:org.apache.brooklyn.util.http.HttpTool.java

/**
 * Connects to the given url and returns the connection.
 * Caller should {@code connection.getInputStream().close()} the result of this
 * (especially if they are making heavy use of this method).
 *//* ww  w  . ja  v a2s.  c om*/
public static URLConnection connectToUrl(String u) throws Exception {
    final URL url = new URL(u);
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();

    // sometimes openConnection hangs, so run in background
    Future<URLConnection> f = executor.submit(new Callable<URLConnection>() {
        public URLConnection call() {
            try {
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });
                URLConnection connection = url.openConnection();
                TrustingSslSocketFactory.configure(connection);
                connection.connect();

                connection.getContentLength(); // Make sure the connection is made.
                return connection;
            } catch (Exception e) {
                exception.set(e);
                LOG.debug("Error connecting to url " + url + " (propagating): " + e, e);
            }
            return null;
        }
    });
    try {
        URLConnection result = null;
        try {
            result = f.get(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("Error connecting to url " + url + ", probably timed out (rethrowing): " + e);
            throw new IllegalStateException(
                    "Connect to URL not complete within 60 seconds, for url " + url + ": " + e);
        }
        if (exception.get() != null) {
            LOG.debug("Error connecting to url " + url + ", thread caller of " + exception,
                    new Throwable("source of rethrown error " + exception));
            throw exception.get();
        } else {
            return result;
        }
    } finally {
        f.cancel(true);
    }
}

From source file:org.apache.geode.internal.process.FileProcessController.java

private String status(final File workingDir, final String statusRequestFileName, final String statusFileName)
        throws IOException, InterruptedException, TimeoutException {
    // monitor for statusFile
    File statusFile = new File(workingDir, statusFileName);
    AtomicReference<String> statusRef = new AtomicReference<>();

    ControlRequestHandler statusHandler = () -> {
        // read the statusFile
        StringBuilder lines = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(statusFile))) {
            reader.lines().forEach(lines::append);
        } finally {
            statusRef.set(lines.toString());
        }/*ww w.jav  a 2s .  com*/
    };

    ControlFileWatchdog statusFileWatchdog = new ControlFileWatchdog(workingDir, statusFileName, statusHandler,
            true);
    statusFileWatchdog.start();

    File statusRequestFile = new File(workingDir, statusRequestFileName);
    if (!statusRequestFile.exists()) {
        statusRequestFile.createNewFile();
    }

    // if timeout invoke stop and then throw TimeoutException
    long start = System.currentTimeMillis();
    while (statusFileWatchdog.isAlive()) {
        Thread.sleep(10);
        if (System.currentTimeMillis() >= start + statusTimeoutMillis) {
            statusFileWatchdog.stop();
            throw new TimeoutException("Timed out waiting for process to create " + statusFile);
        }
    }

    String lines = statusRef.get();
    if (isBlank(lines)) {
        throw new IllegalStateException("Status file '" + statusFile + "' is blank");
    }
    return lines;
}

From source file:eu.eubrazilcc.lvl.storage.oauth2.dao.TokenDAO.java

/**
 * Checks whether or not the specified secret (token) was previously stored and is currently valid (not expired).
 * @param token - the secret associated to the token
 * @param ownerIdRef - if set and the resource owner is valid, then the Id of the resource owner is returned 
 *        to the caller/*from w  w w .j a  v  a  2s  .  c om*/
 * @return {@code true} only if the provided secret (token) is found in the storage and is currently valid (not expired). 
 *         Otherwise, returns {@code false}.
 */
public boolean isValid(final String token, final @Nullable AtomicReference<String> ownerIdRef) {
    checkArgument(isNotBlank(token), "Uninitialized or invalid token");
    final AccessToken accessToken = find(token);
    final boolean isValid = isValid(token);
    if (isValid(token) && ownerIdRef != null) {
        ownerIdRef.set(accessToken.getOwnerId());
    }
    return isValid;
}

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/*from ww  w .  j  av  a  2 s  .com*/
        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:com.jayway.restassured.module.mockmvc.ContentTypeTest.java

@Test
public void adds_default_charset_to_content_type_by_default() {
    final AtomicReference<String> contentType = new AtomicReference<String>();

    given().standaloneSetup(new GreetingController()).contentType(ContentType.JSON)
            .interceptor(new MockHttpServletRequestBuilderInterceptor() {
                public void intercept(MockHttpServletRequestBuilder requestBuilder) {
                    MultiValueMap<String, Object> headers = Whitebox.getInternalState(requestBuilder,
                            "headers");
                    contentType.set(String.valueOf(headers.getFirst("Content-Type")));
                }//ww w  . ja v  a  2s.c  o  m
            }).when().get("/greeting?name={name}", "Johan").then().statusCode(200);

    assertThat(contentType.get()).isEqualTo("application/json;charset="
            + RestAssuredMockMvcConfig.config().getEncoderConfig().defaultContentCharset());
}

From source file:it.anyplace.sync.bep.IndexFinder.java

public SearchCompletedEvent doSearch(final String term) throws InterruptedException {
    final Object lock = new Object();
    final AtomicReference<SearchCompletedEvent> reference = new AtomicReference<>();
    final Object eventListener = new Object() {
        @Subscribe/*  www  .  j a  va  2s.c  o  m*/
        public void handleSearchCompletedEvent(SearchCompletedEvent event) {
            if (equal(event.getQuery(), term)) {
                synchronized (lock) {
                    reference.set(event);
                    lock.notify();
                }
            }
        }
    };
    synchronized (lock) {
        eventBus.register(eventListener);
        submitSearch(term);
        try {
            while (!Thread.currentThread().isInterrupted() && reference.get() == null) {
                lock.wait();
            }
            checkNotNull(reference.get());
            return reference.get();
        } finally {
            eventBus.unregister(eventListener);
        }
    }
}