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:io.galeb.router.tests.handlers.PathGlobHandlerTest.java

@Test
public void checkMatch() {
    final AtomicReference<String> result = new AtomicReference<>("default");

    HttpHandler defaultHandler = mock(HttpHandler.class);
    PathGlobHandler pathGlobHandler = new PathGlobHandler();
    pathGlobHandler.setDefaultHandler(defaultHandler);

    pathGlobHandler.addPath("/x", 0, exchange -> result.set("x"));
    pathGlobHandler.addPath("/y", 0, exchange -> result.set("y"));
    pathGlobHandler.addPath("/z", 0, exchange -> result.set("z"));
    pathGlobHandler.addPath("/w", 0, exchange -> result.set("w"));
    pathGlobHandler.addPath("/1", 1, exchange -> result.set("1"));
    pathGlobHandler.addPath("/2", 2, exchange -> result.set("2"));
    pathGlobHandler.addPath("/3", 3, exchange -> result.set("3"));
    pathGlobHandler.addPath("/4", 4, exchange -> result.set("4"));
    pathGlobHandler.addPath("/5*", 4, exchange -> result.set("5"));
    pathGlobHandler.addPath("/6/*", Integer.MAX_VALUE - 1, exchange -> result.set("6"));
    pathGlobHandler.addPath("/7/*.json", Integer.MAX_VALUE - 1, exchange -> result.set("7"));
    pathGlobHandler.addPath("/", Integer.MAX_VALUE, exchange -> result.set("slash"));

    ServerConnection serverConnection = mock(ServerConnection.class);
    try {//from   w  w  w .j a v  a 2 s.c  o  m
        HttpServerExchange exchangeNotMatch = new HttpServerExchange(serverConnection);
        exchangeNotMatch.setRelativePath(UUID.randomUUID().toString());
        HttpServerExchange exchangeX = new HttpServerExchange(serverConnection);
        exchangeX.setRelativePath("/x");
        HttpServerExchange exchangeY = new HttpServerExchange(serverConnection);
        exchangeY.setRelativePath("/y");
        HttpServerExchange exchangeZ = new HttpServerExchange(serverConnection);
        exchangeZ.setRelativePath("/z");
        HttpServerExchange exchangeW = new HttpServerExchange(serverConnection);
        exchangeW.setRelativePath("/w");
        HttpServerExchange exchange1 = new HttpServerExchange(serverConnection);
        exchange1.setRelativePath("/1");
        HttpServerExchange exchange2 = new HttpServerExchange(serverConnection);
        exchange2.setRelativePath("/2");
        HttpServerExchange exchange3 = new HttpServerExchange(serverConnection);
        exchange3.setRelativePath("/3");
        HttpServerExchange exchange4 = new HttpServerExchange(serverConnection);
        exchange4.setRelativePath("/4");
        HttpServerExchange exchange5 = new HttpServerExchange(serverConnection);
        exchange5.setRelativePath("/555");
        HttpServerExchange exchange6 = new HttpServerExchange(serverConnection);
        exchange6.setRelativePath("/6/xpto");
        HttpServerExchange exchange7 = new HttpServerExchange(serverConnection);
        exchange7.setRelativePath("/7/xpto/test.json");
        HttpServerExchange exchangeSlash = new HttpServerExchange(serverConnection);
        exchangeSlash.setRelativePath("/");

        pathGlobHandler.handleRequest(exchangeNotMatch);
        assertThat(result.get(), equalTo("default"));

        pathGlobHandler.handleRequest(exchangeX);
        assertThat(result.get(), equalTo("x"));

        pathGlobHandler.handleRequest(exchangeY);
        assertThat(result.get(), equalTo("y"));

        pathGlobHandler.handleRequest(exchangeZ);
        assertThat(result.get(), equalTo("z"));

        pathGlobHandler.handleRequest(exchangeW);
        assertThat(result.get(), equalTo("w"));

        pathGlobHandler.handleRequest(exchange1);
        assertThat(result.get(), equalTo("1"));

        pathGlobHandler.handleRequest(exchange2);
        assertThat(result.get(), equalTo("2"));

        pathGlobHandler.handleRequest(exchange3);
        assertThat(result.get(), equalTo("3"));

        pathGlobHandler.handleRequest(exchange4);
        assertThat(result.get(), equalTo("4"));

        pathGlobHandler.handleRequest(exchange2);
        assertThat(result.get(), equalTo("2"));

        pathGlobHandler.handleRequest(exchange1);
        assertThat(result.get(), equalTo("1"));

        pathGlobHandler.handleRequest(exchange5);
        assertThat(result.get(), equalTo("5"));

        pathGlobHandler.handleRequest(exchange6);
        assertThat(result.get(), equalTo("6"));

        pathGlobHandler.handleRequest(exchange7);
        assertThat(result.get(), equalTo("7"));

        pathGlobHandler.handleRequest(exchangeSlash);
        assertThat(result.get(), equalTo("slash"));

    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
    } catch (AssertionError assertionError) {
        pathGlobHandler.getPaths().forEach((k, v) -> logger.error(k.getPath() + " -> " + k.getOrder()));
        throw assertionError;
    }
}

From source file:com.example.app.ui.DemoUserProfileEditor.java

@Override
public ModificationState getModificationState() {
    if (!isInited())
        return ModificationState.UNCHANGED;
    final AtomicReference<ModificationState> state = new AtomicReference<>(ModificationState.UNCHANGED);
    _forEach(value -> {//from  ww  w  .j a  v  a2  s . c  om
        if (!state.get().isModified() && value.getModificationState().isModified())
            state.set(ModificationState.CHANGED);
    });
    return state.get();
}

From source file:com.kixeye.janus.client.http.rest.DefaultRestHttpClientTest.java

@Test
public void getParamListTest() throws Exception {
    MetricRegistry metricRegistry = new MetricRegistry();
    Janus janus = new Janus(VIP_TEST, new ConstServerList(VIP_TEST, "http://localhost:" + server1Port),
            new ZoneAwareLoadBalancer(VIP_TEST, "default", metricRegistry),
            new ServerStatsFactory(ServerStats.class, metricRegistry));
    DefaultRestHttpClient client = new DefaultRestHttpClient(janus, 0, DefaultRestHttpClient.UTF8_STRING_SER_DE,
            "text/plain");

    final AtomicReference<String> requestMethod = new AtomicReference<>(null);
    final AtomicReference<String> requestPath = new AtomicReference<>(null);

    testContainer = new Container() {
        public void handle(Request req, Response resp) {
            requestMethod.set(req.getMethod());
            requestPath.set(req.getTarget());

            try {
                resp.getByteChannel().write(ByteBuffer.wrap("goofy".getBytes(StandardCharsets.UTF_8)));
            } catch (IOException e) {
                logger.error("Unable to write to channel.");
            }//from  w  w  w. ja va2 s .c  om
        }
    };

    String result = client.post("/test_params/{}", null, String.class, "goofy").getBody().deserialize();
    Assert.assertEquals("POST", requestMethod.get());
    Assert.assertEquals("/test_params/goofy", requestPath.get());
    Assert.assertEquals("goofy", result);
}

From source file:com.kixeye.janus.client.http.rest.DefaultRestHttpClientTest.java

@Test
public void postNoParamsTest() throws Exception {
    Janus janus = new Janus(VIP_TEST, new ConstServerList(VIP_TEST, "http://localhost:" + server1Port),
            new RandomLoadBalancer(), new ServerStatsFactory(ServerStats.class, new MetricRegistry()));

    DefaultRestHttpClient client = new DefaultRestHttpClient(janus, 0, DefaultRestHttpClient.UTF8_STRING_SER_DE,
            "text/plain");

    final AtomicReference<String> requestMethod = new AtomicReference<>(null);
    final AtomicReference<String> requestPath = new AtomicReference<>(null);

    testContainer = new Container() {
        public void handle(Request req, Response resp) {
            requestMethod.set(req.getMethod());
            requestPath.set(req.getTarget());

            try {
                resp.getByteChannel().write(ByteBuffer.wrap(IOUtils.toByteArray(req.getInputStream())));
            } catch (IOException e) {
                logger.error("Unable to write to channel.");
            }/*from w w  w . j ava2s  .co m*/
        }
    };

    String result = client.post("/test_no_params", "post body", String.class).getBody().deserialize();
    Assert.assertNotNull(result);

    Assert.assertEquals("POST", requestMethod.get());
    Assert.assertEquals("/test_no_params", requestPath.get());
}

From source file:com.kixeye.janus.client.http.rest.DefaultRestHttpClientTest.java

@Test
public void postParamListTest() throws Exception {
    Janus janus = new Janus(VIP_TEST, new ConstServerList(VIP_TEST, "http://localhost:" + server1Port),
            new RandomLoadBalancer(), new ServerStatsFactory(ServerStats.class, new MetricRegistry()));

    DefaultRestHttpClient client = new DefaultRestHttpClient(janus, 0, DefaultRestHttpClient.UTF8_STRING_SER_DE,
            "text/plain");

    final AtomicReference<String> requestMethod = new AtomicReference<>(null);
    final AtomicReference<String> requestPath = new AtomicReference<>(null);

    testContainer = new Container() {
        public void handle(Request req, Response resp) {
            requestMethod.set(req.getMethod());
            requestPath.set(req.getTarget());

            try {
                resp.getByteChannel().write(ByteBuffer.wrap(IOUtils.toByteArray(req.getInputStream())));
            } catch (IOException e) {
                logger.error("Unable to write to channel.");
            }/*from ww w.  j av a 2 s .  com*/
        }
    };

    String result = client.post("/test_params/{}", "body", String.class, "goofy").getBody().deserialize();
    Assert.assertEquals("body", result);

    Assert.assertEquals("POST", requestMethod.get());
    Assert.assertEquals("/test_params/goofy", requestPath.get());
}

From source file:com.dgtlrepublic.anitomyj.KeywordManager.java

/**
 * Finds a particular {@code keyword}. If found sets {@code category} and {@code options} to the found search
 * result.//from ww w  . ja v  a2 s . c o  m
 *
 * @param keyword  the keyword to search for
 * @param category an atomic reference that will be set/changed to the found keyword category
 * @param options  an atomic reference that will be set/changed to the found keyword options
 * @return true if the keyword was found; false otherwise
 */
public boolean findAndSet(String keyword, AtomicReference<ElementCategory> category,
        AtomicReference<KeywordOptions> options) {
    Map<String, Keyword> keys = getKeywordContainer(category.get());
    Keyword foundEntry = keys.get(keyword);
    if (foundEntry != null) {
        if (category.get() == kElementUnknown) {
            category.set(foundEntry.getCategory());
        } else if (foundEntry.getCategory() != category.get()) {
            return false;
        }

        options.set(foundEntry.getOptions());
        return true;
    }

    return false;
}

From source file:org.apache.accumulo.test.functional.ZooCacheIT.java

@Test
public void test() throws Exception {
    assertEquals(0, exec(CacheTestClean.class, pathName, testDir.getAbsolutePath()).waitFor());
    final AtomicReference<Exception> ref = new AtomicReference<Exception>();
    List<Thread> threads = new ArrayList<Thread>();
    for (int i = 0; i < 3; i++) {
        Thread reader = new Thread() {
            @Override/*w  ww  .  j av a2  s.c  o  m*/
            public void run() {
                try {
                    CacheTestReader.main(new String[] { pathName, testDir.getAbsolutePath(),
                            getConnector().getInstance().getZooKeepers() });
                } catch (Exception ex) {
                    ref.set(ex);
                }
            }
        };
        reader.start();
        threads.add(reader);
    }
    assertEquals(0, exec(CacheTestWriter.class, pathName, testDir.getAbsolutePath(), "3", "50").waitFor());
    for (Thread t : threads) {
        t.join();
        if (ref.get() != null)
            throw ref.get();
    }
}

From source file:io.restassured.module.mockmvc.ContentTypeTest.java

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

    RestAssuredMockMvc.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")));
                }//w  w  w . j  a v a2s.  c  om
            }).when().get("/greeting?name={name}", "Johan").then().statusCode(200);

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

From source file:com.jayway.restassured.itest.java.FilterITest.java

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

    given().filter(new Filter() {
        public Response filter(FilterableRequestSpecification requestSpec,
                FilterableResponseSpecification responseSpec, FilterContext ctx) {
            contentType.set(requestSpec.getRequestContentType());
            return ctx.next(requestSpec, responseSpec);
        }/*  ww  w  .  j a v  a2  s .c o  m*/
    }).formParam("firstName", "John").formParam("lastName", "Doe").when().post("/greet").then().statusCode(200);

    assertThat(contentType.get(), equalTo("application/x-www-form-urlencoded; charset=ISO-8859-1"));
}

From source file:org.apache.beam.runners.apex.ApexRunner.java

@Override
public ApexRunnerResult run(final Pipeline pipeline) {
    pipeline.replaceAll(getOverrides());

    final ApexPipelineTranslator translator = new ApexPipelineTranslator(options);
    final AtomicReference<DAG> apexDAG = new AtomicReference<>();
    final AtomicReference<File> tempDir = new AtomicReference<>();

    StreamingApplication apexApp = (dag, conf) -> {
        apexDAG.set(dag);
        dag.setAttribute(DAGContext.APPLICATION_NAME, options.getApplicationName());
        if (options.isEmbeddedExecution()) {
            // set unique path for application state to allow for parallel execution of unit tests
            // (the embedded cluster would set it to a fixed location under ./target)
            tempDir.set(Files.createTempDir());
            dag.setAttribute(DAGContext.APPLICATION_PATH, tempDir.get().toURI().toString());
        }/*from  w  w w .j  ava 2 s  .  co  m*/
        translator.translate(pipeline, dag);
    };

    Properties configProperties = new Properties();
    try {
        if (options.getConfigFile() != null) {
            URI configURL = new URI(options.getConfigFile());
            if (CLASSPATH_SCHEME.equals(configURL.getScheme())) {
                InputStream is = this.getClass().getResourceAsStream(configURL.getPath());
                if (is != null) {
                    configProperties.load(is);
                    is.close();
                }
            } else {
                if (!configURL.isAbsolute()) {
                    // resolve as local file name
                    File f = new File(options.getConfigFile());
                    configURL = f.toURI();
                }
                try (InputStream is = configURL.toURL().openStream()) {
                    configProperties.load(is);
                }
            }
        }
    } catch (IOException | URISyntaxException ex) {
        throw new RuntimeException("Error loading properties", ex);
    }

    if (options.isEmbeddedExecution()) {
        EmbeddedAppLauncher<?> launcher = Launcher.getLauncher(LaunchMode.EMBEDDED);
        Attribute.AttributeMap launchAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
        launchAttributes.put(EmbeddedAppLauncher.RUN_ASYNC, true);
        if (options.isEmbeddedExecutionDebugMode()) {
            // turns off timeout checking for operator progress
            launchAttributes.put(EmbeddedAppLauncher.HEARTBEAT_MONITORING, false);
        }
        Configuration conf = new Configuration(false);
        ApexYarnLauncher.addProperties(conf, configProperties);
        try {
            if (translateOnly) {
                launcher.prepareDAG(apexApp, conf);
                return new ApexRunnerResult(launcher.getDAG(), null);
            }
            ApexRunner.ASSERTION_ERROR.set(null);
            AppHandle apexAppResult = launcher.launchApp(apexApp, conf, launchAttributes);
            return new ApexRunnerResult(apexDAG.get(), apexAppResult) {
                @Override
                protected void cleanupOnCancelOrFinish() {
                    if (tempDir.get() != null) {
                        FileUtils.deleteQuietly(tempDir.get());
                    }
                }
            };
        } catch (Exception e) {
            Throwables.throwIfUnchecked(e);
            throw new RuntimeException(e);
        }
    } else {
        try {
            ApexYarnLauncher yarnLauncher = new ApexYarnLauncher();
            AppHandle apexAppResult = yarnLauncher.launchApp(apexApp, configProperties);
            return new ApexRunnerResult(apexDAG.get(), apexAppResult);
        } catch (IOException e) {
            throw new RuntimeException("Failed to launch the application on YARN.", e);
        }
    }
}