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.distributedlog.config.TestConfigurationSubscription.java

@Test(timeout = 60000)
public void testReloadConfiguration() throws Exception {
    PropertiesWriter writer = new PropertiesWriter();
    FileConfigurationBuilder builder = new PropertiesConfigurationBuilder(writer.getFile().toURI().toURL());
    ConcurrentConstConfiguration conf = new ConcurrentConstConfiguration(new DistributedLogConfiguration());
    DeterministicScheduler executorService = new DeterministicScheduler();
    List<FileConfigurationBuilder> fileConfigBuilders = Lists.newArrayList(builder);
    ConfigurationSubscription confSub = new ConfigurationSubscription(conf, fileConfigBuilders, executorService,
            100, TimeUnit.MILLISECONDS);
    final AtomicReference<ConcurrentBaseConfiguration> confHolder = new AtomicReference<>();
    confSub.registerListener(new org.apache.distributedlog.config.ConfigurationListener() {
        @Override/*from www.  j  a  va2s .c o m*/
        public void onReload(ConcurrentBaseConfiguration conf) {
            confHolder.set(conf);
        }
    });
    assertEquals(null, conf.getProperty("prop1"));

    // add
    writer.setProperty("prop1", "1");
    writer.save();
    // ensure the file change reloading event can be triggered
    ensureConfigReloaded();
    // reload the config
    confSub.reload();
    assertNotNull(confHolder.get());
    assertTrue(conf == confHolder.get());
    assertEquals("1", conf.getProperty("prop1"));
}

From source file:com.twitter.distributedlog.config.TestConfigurationSubscription.java

@Test(timeout = 60000)
public void testReloadConfiguration() throws Exception {
    PropertiesWriter writer = new PropertiesWriter();
    FileConfigurationBuilder builder = new PropertiesConfigurationBuilder(writer.getFile().toURI().toURL());
    ConcurrentConstConfiguration conf = new ConcurrentConstConfiguration(new DistributedLogConfiguration());
    DeterministicScheduler executorService = new DeterministicScheduler();
    List<FileConfigurationBuilder> fileConfigBuilders = Lists.newArrayList(builder);
    ConfigurationSubscription confSub = new ConfigurationSubscription(conf, fileConfigBuilders, executorService,
            100, TimeUnit.MILLISECONDS);
    final AtomicReference<ConcurrentBaseConfiguration> confHolder = new AtomicReference<>();
    confSub.registerListener(new com.twitter.distributedlog.config.ConfigurationListener() {
        @Override/* w w  w  . ja  va 2s.  c o  m*/
        public void onReload(ConcurrentBaseConfiguration conf) {
            confHolder.set(conf);
        }
    });
    assertEquals(null, conf.getProperty("prop1"));

    // add
    writer.setProperty("prop1", "1");
    writer.save();
    // ensure the file change reloading event can be triggered
    ensureConfigReloaded();
    // reload the config
    confSub.reload();
    assertNotNull(confHolder.get());
    assertTrue(conf == confHolder.get());
    assertEquals("1", conf.getProperty("prop1"));
}

From source file:io.symcpe.hendrix.nifi.lmm.interceptor.LMMInterceptor.java

@Override
public void onTrigger(ProcessContext ctx, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();//w w  w.  j av a  2  s .c  o  m
    if (flowFile == null) {
        return;
    }

    try {
        AtomicReference<String> message = new AtomicReference<String>();
        session.read(flowFile, true, new InputStreamCallback() {

            @Override
            public void process(InputStream in) throws IOException {
                message.set(IOUtils.toString(in));
            }
        });
        flowFile = session.putAttribute(flowFile, "message", message.get());
        flowFile = session.putAttribute(flowFile, ATTR_TENANT_ID, ctx.getProperty(TENANT_ID).getValue());
        flowFile = session.putAttribute(flowFile, ATTR_API_KEY, ctx.getProperty(API_KEY).getValue());
        flowFile = session.putAttribute(flowFile, ATTR_VERSION, _1);
        String timestamp = ctx.getProperty(TIMESTAMP).evaluateAttributeExpressions(flowFile).getValue();
        DateTime ts = formatter.withZoneUTC().parseDateTime(timestamp);
        flowFile = session.putAttribute(flowFile, ATTR_TIMESTAMP,
                ts.toString(TARGET_TIMESTAMP_PATTERN, Locale.ENGLISH));
        session.transfer(flowFile, SUCCESS);
    } catch (Exception e) {
        flowFile = session.putAttribute(flowFile, "Exception", e.getMessage());
        session.transfer(flowFile, FAILURE);
    }
}

From source file:com.vmware.admiral.adapter.docker.service.SystemImageRetrievalManagerTest.java

@Test
public void testGetFromUserResources() throws Throwable {
    Path testXenonImagesPath = Files.createTempDirectory("test-xenon-images");

    HostInitCommonServiceConfig.startServices(host);
    waitForServiceAvailability(ConfigurationFactoryService.SELF_LINK);
    waitForServiceAvailability(UriUtils.buildUriPath(UriUtils
            .buildUriPath(ConfigurationFactoryService.SELF_LINK, FileUtil.USER_RESOURCES_PATH_VARIABLE)));

    // Set expected configuration
    ConfigurationState config = new ConfigurationState();
    config.documentSelfLink = UriUtils.buildUriPath(ConfigurationFactoryService.SELF_LINK,
            FileUtil.USER_RESOURCES_PATH_VARIABLE);
    config.key = FileUtil.USER_RESOURCES_PATH_VARIABLE;
    config.value = testXenonImagesPath.toAbsolutePath().toString();

    doPost(config, ConfigurationFactoryService.SELF_LINK);

    File imageDir = new File(UriUtils.buildUriPath(testXenonImagesPath.toString(),
            SystemImageRetrievalManager.SYSTEM_IMAGES_PATH));
    imageDir.mkdir();//from  w  w w  .  j  a v a  2 s .  c om

    byte[] content = IOUtils
            .toByteArray(Thread.currentThread().getContextClassLoader().getResourceAsStream(TEST_IMAGE));
    // Basically, rename it so it must be loaded from user resources for sure
    File tmpFile = new File(UriUtils.buildUriPath(imageDir.getAbsolutePath(), TEST_IMAGE_RES));
    tmpFile.createNewFile();
    try (OutputStream os = new FileOutputStream(tmpFile)) {
        os.write(content);
    }

    AdapterRequest req = new AdapterRequest();
    req.resourceReference = host.getUri();

    AtomicReference<byte[]> retrievedImageRef = new AtomicReference<>();

    TestContext ctx = testCreate(1);
    retrievalManager.retrieveAgentImage(TEST_IMAGE_RES, req, (image) -> {
        retrievedImageRef.set(image);
        ctx.completeIteration();
    });

    ctx.await();

    byte[] image = retrievedImageRef.get();
    Assert.assertEquals("Unexpected content", new String(content), new String(image));
}

From source file:org.apache.distributedlog.common.config.TestConfigurationSubscription.java

@Test(timeout = 60000)
public void testReloadConfiguration() throws Exception {
    PropertiesWriter writer = new PropertiesWriter();
    FileConfigurationBuilder builder = new PropertiesConfigurationBuilder(writer.getFile().toURI().toURL());
    ConcurrentConstConfiguration conf = new ConcurrentConstConfiguration(new CompositeConfiguration());
    DeterministicScheduler executorService = new DeterministicScheduler();
    List<FileConfigurationBuilder> fileConfigBuilders = Lists.newArrayList(builder);
    ConfigurationSubscription confSub = new ConfigurationSubscription(conf, fileConfigBuilders, executorService,
            100, TimeUnit.MILLISECONDS);
    final AtomicReference<ConcurrentBaseConfiguration> confHolder = new AtomicReference<>();
    confSub.registerListener(new org.apache.distributedlog.common.config.ConfigurationListener() {
        @Override/*from  w w  w  . jav  a  2  s .  c om*/
        public void onReload(ConcurrentBaseConfiguration conf) {
            confHolder.set(conf);
        }
    });
    assertEquals(null, conf.getProperty("prop1"));

    // add
    writer.setProperty("prop1", "1");
    writer.save();
    // ensure the file change reloading event can be triggered
    ensureConfigReloaded();
    // reload the config
    confSub.reload();
    assertNotNull(confHolder.get());
    assertTrue(conf == confHolder.get());
    assertEquals("1", conf.getProperty("prop1"));
}

From source file:hudson.plugins.jobConfigHistory.FileHistoryDao.java

/**
 * Creates the new history dir, loops until "enough" time has passed if two events are too near.
 *
 * @param itemHistoryDir the basedir for history items.
 * @param timestampHolder of the event.//  ww w.j  ava 2  s.com
 * @return new directory.
 */
@SuppressWarnings("SleepWhileInLoop")
static File createNewHistoryDir(final File itemHistoryDir, final AtomicReference<Calendar> timestampHolder) {
    Calendar timestamp;
    File f;
    while (true) {
        timestamp = new GregorianCalendar();
        f = new File(itemHistoryDir, getIdFormatter().format(timestamp.getTime()));
        if (f.isDirectory()) {
            LOG.log(Level.FINE, "clash on {0}, will wait a moment", f);
            try {
                Thread.sleep(CLASH_SLEEP_TIME);
            } catch (InterruptedException x) {
                throw new RuntimeException(x);
            }
        } else {
            timestampHolder.set(timestamp);
            break;
        }
    }
    // mkdirs sometimes fails although the directory exists afterwards,
    // so check for existence as well and just be happy if it does.
    if (!(f.mkdirs() || f.exists())) {
        throw new RuntimeException("Could not create rootDir " + f);
    }
    return f;
}

From source file:org.apache.hadoop.hive.schshim.FairSchedulerShim.java

@Override
public void refreshDefaultQueue(Configuration conf, String userName) throws IOException {
    String requestedQueue = YarnConfiguration.DEFAULT_QUEUE_NAME;
    final AtomicReference<AllocationConfiguration> allocConf = new AtomicReference<AllocationConfiguration>();

    AllocationFileLoaderService allocsLoader = new AllocationFileLoaderService();
    allocsLoader.init(conf);//  w w  w  .  j ava 2s.c  om
    allocsLoader.setReloadListener(new AllocationFileLoaderService.Listener() {
        @Override
        public void onReload(AllocationConfiguration allocs) {
            allocConf.set(allocs);
        }
    });
    try {
        allocsLoader.reloadAllocations();
    } catch (Exception ex) {
        throw new IOException("Failed to load queue allocations", ex);
    }
    if (allocConf.get() == null) {
        allocConf.set(new AllocationConfiguration(conf));
    }
    QueuePlacementPolicy queuePolicy = allocConf.get().getPlacementPolicy();
    if (queuePolicy != null) {
        requestedQueue = queuePolicy.assignAppToQueue(requestedQueue, userName);
        if (StringUtils.isNotBlank(requestedQueue)) {
            LOG.debug("Setting queue name to " + requestedQueue + " for user " + userName);
            conf.set(MR2_JOB_QUEUE_PROPERTY, requestedQueue);
        }
    }
}

From source file:org.apache.tomee.jul.handler.rotating.ArchivingTest.java

@Test
public void logAndRotate() throws IOException, NoSuchMethodException {
    clean("target/ArchivingTest-" + 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/ArchivingTest-" + format + "/logs/test.%s.%d.log");
    config.put("archiveDirectory", "target/ArchivingTest-" + format + "/logs/archives");
    config.put("archiveFormat", format);
    config.put("archiveOlderThan", "1 s");
    config.put("limit", "10 kilobytes");
    config.put("level", "INFO");
    config.put("dateCheckInterval", "1 second");

    final LocalFileHandler handler = new LocalFileHandler() {
        @Override//  w  w w  .  j a  v  a2  s  .co m
        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 { // ensure we test the date
        Thread.sleep(2000);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }
    handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the archiving
    handler.close();

    withRetry(10, 3, new Runnable() {
        @Override
        public void run() {
            final File logGzip = new File(
                    "target/ArchivingTest-" + format + "/logs/archives/test.2015-09-01.0.log." + format);
            assertTrue(logGzip.getAbsolutePath(), logGzip.isFile());
        }
    });
    // note: size depends on the date so just use a > min
    if ("gzip".equals(format)) {
        try (final GZIPInputStream gis = new GZIPInputStream(
                new FileInputStream("target/ArchivingTest-gzip/logs/archives/test.2015-09-01.0.log.gzip"))) {
            final String content = IOUtils.toString(gis);
            assertTrue(
                    content.contains(Level.INFO.getLocalizedName() + ": abcdefghij" + System.lineSeparator()));
            assertTrue(content.length() > 10000);
        }
    } else {
        try (final ZipInputStream zis = new ZipInputStream(
                new FileInputStream("target/ArchivingTest-zip/logs/archives/test.2015-09-01.0.log.zip"))) {
            assertEquals("test.2015-09-01.0.log", zis.getNextEntry().getName());
            final String content = IOUtils.toString(zis);
            assertTrue(content,
                    content.contains(Level.INFO.getLocalizedName() + ": abcdefghij" + System.lineSeparator())); // INFO or INFOS
            assertTrue(content, content.length() > 10000);
            assertNull(zis.getNextEntry());
        }
    }
}

From source file:com.netflix.curator.framework.recipes.cache.TestNodeCache.java

@Test
public void testDeleteThenCreate() throws Exception {
    NodeCache cache = null;//from  w w w.j  a v  a2 s .  c o  m
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try {
        client.create().creatingParentsIfNeeded().forPath("/test/foo", "one".getBytes());

        final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
        client.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() {
            @Override
            public void unhandledError(String message, Throwable e) {
                error.set(e);
            }
        });

        final Semaphore semaphore = new Semaphore(0);
        cache = new NodeCache(client, "/test/foo");
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                semaphore.release();
            }
        });
        cache.start(true);

        Assert.assertEquals(cache.getCurrentData().getData(), "one".getBytes());

        client.delete().forPath("/test/foo");
        Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS));
        client.create().forPath("/test/foo", "two".getBytes());
        Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS));

        Throwable t = error.get();
        if (t != null) {
            Assert.fail("Assert", t);
        }

        Assert.assertEquals(cache.getCurrentData().getData(), "two".getBytes());

        cache.close();
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
    }
}

From source file:io.spring.initializr.metadata.Link.java

/**
 * Expand the link using the specified parameters.
 * @param parameters the parameters value
 * @return an URI where all variables have been expanded
 *//*w  ww.  j av a  2  s .  co m*/
public URI expand(Map<String, String> parameters) {
    AtomicReference<String> result = new AtomicReference<>(href);
    templateVariables.forEach(var -> {
        Object value = parameters.get(var);
        if (value == null) {
            throw new IllegalArgumentException(
                    "Could not expand " + href + ", missing value for '" + var + "'");
        }
        result.set(result.get().replace("{" + var + "}", value.toString()));
    });
    try {
        return new URI(result.get());
    } catch (URISyntaxException e) {
        throw new IllegalStateException("Invalid URL", e);
    }
}