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:io.restassured.module.mockmvc.ContentTypeTest.java

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

    RestAssuredMockMvc.given()//from  w  w w.  j  a v a 2  s  .c o  m
            .config(RestAssuredMockMvc.config().encoderConfig(
                    EncoderConfig.encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false)))
            .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")));
                }
            }).when().get("/greeting?name={name}", "Johan").then().statusCode(200);

    assertThat(contentType.get()).isEqualTo("application/json");
}

From source file:com.jeremydyer.iot.GPIORESTProcessor.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {

    final ProcessorLog log = this.getLogger();
    final AtomicReference<Integer> value = new AtomicReference<>();

    final FlowFile flowfile = session.get();
    final Integer delayThreshold = context.getProperty(PROP_SWITCH_DELAY_THRESHOLD).asInteger();

    session.read(flowfile, new InputStreamCallback() {
        @Override/*from  w  w  w  .j a v  a 2s.c  o m*/
        public void process(InputStream in) throws IOException {
            try {
                String json = IOUtils.toString(in);
                int numFaces = JsonPath.read(json, "$.faces");
                value.set(numFaces);
            } catch (Exception ex) {
                getLogger().error("Failed to process face detection context", ex);
                session.transfer(flowfile, REL_FAILURE);
            }
        }
    });

    // Write the results to an attribute
    int numFaces = value.get();

    if (CURRENTLY_ON.get()) {
        //Outlet is on. If no faces detected turn off. Else do nothing
        if (numFaces == 0 && (((System.currentTimeMillis() - LAST_SWITCH_TS.get()) / 1000) > delayThreshold)) {
            CURRENTLY_ON.set(false);
            LAST_SWITCH_TS.set(System.currentTimeMillis());
            session.transfer(flowfile, REL_TURN_OFF);
        } else {
            session.transfer(flowfile, REL_NO_CHANGE);
        }
    } else {
        //Outlet is currently turned off
        if (numFaces > 0 && (((System.currentTimeMillis() - LAST_SWITCH_TS.get()) / 1000) > delayThreshold)) {
            CURRENTLY_ON.set(true);
            LAST_SWITCH_TS.set(System.currentTimeMillis());
            session.transfer(flowfile, REL_TURN_ON);
        } else {
            session.transfer(flowfile, REL_NO_CHANGE);
        }
    }

}

From source file:com.networknt.basic.BasicAuthHandlerTest.java

@Test
public void testEncryptedPassword() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*w  ww  . j  av  a2  s  .com*/
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "BASIC " + encodeCredentials("user2", "password"));
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
    }
}

From source file:com.networknt.basic.BasicAuthHandlerTest.java

@Test
public void testWithRightCredentials() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from www  .j a  v  a2  s  .c  om
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "BASIC " + encodeCredentials("user1", "user1pass"));
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
    }
}

From source file:com.networknt.basic.BasicAuthHandlerTest.java

@Test
public void testInvalidUsername() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from   w w  w.j  a  va2s  .c om*/
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "BASIC " + encodeCredentials("user3", "user1pass"));
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(401, statusCode);
    if (statusCode == 401) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10047", status.getCode());
    }
}

From source file:com.networknt.basic.BasicAuthHandlerTest.java

@Test
public void testInvalidBasicHeader() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from w w  w.ja v a  2s.  c om
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "Bearer " + encodeCredentials("user1", "user1pass"));
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(401, statusCode);
    if (statusCode == 401) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10046", status.getCode());
    }
}

From source file:org.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java

@Test
public void concurrentLoginSingleUserSingleClient() throws Throwable {
    log.info("*********************************************");
    long start = System.currentTimeMillis();

    AtomicReference<String> userSessionId = new AtomicReference<>();
    LoginTask loginTask = null;//from w ww.j a  va  2  s . co  m

    try (CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setRedirectStrategy(new LaxRedirectStrategy()).build()) {
        loginTask = new LoginTask(httpClient, userSessionId, 100, 1, true,
                Arrays.asList(createHttpClientContextForUser(httpClient, "test-user@localhost", "password")));
        run(DEFAULT_THREADS, DEFAULT_CLIENTS_COUNT, loginTask);
        int clientSessionsCount = testingClient.testing().getClientSessionsCountInUserSession("test",
                userSessionId.get());
        Assert.assertEquals(2, clientSessionsCount);
    } finally {
        long end = System.currentTimeMillis() - start;
        log.infof("Statistics: %s", loginTask == null ? "??" : loginTask.getHistogram());
        log.info("concurrentLoginSingleUserSingleClient took " + (end / 1000) + "s");
        log.info("*********************************************");
    }
}

From source file:org.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java

@Test
public void concurrentLoginSingleUser() throws Throwable {
    log.info("*********************************************");
    long start = System.currentTimeMillis();

    AtomicReference<String> userSessionId = new AtomicReference<>();
    LoginTask loginTask = null;//ww w  .  j a  v  a  2 s  .  co  m

    try (CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setRedirectStrategy(new LaxRedirectStrategy()).build()) {
        loginTask = new LoginTask(httpClient, userSessionId, 100, 1, false,
                Arrays.asList(createHttpClientContextForUser(httpClient, "test-user@localhost", "password")));
        run(DEFAULT_THREADS, DEFAULT_CLIENTS_COUNT, loginTask);
        int clientSessionsCount = testingClient.testing().getClientSessionsCountInUserSession("test",
                userSessionId.get());
        Assert.assertEquals(1 + DEFAULT_CLIENTS_COUNT, clientSessionsCount);
    } finally {
        long end = System.currentTimeMillis() - start;
        log.infof("Statistics: %s", loginTask == null ? "??" : loginTask.getHistogram());
        log.info("concurrentLoginSingleUser took " + (end / 1000) + "s");
        log.info("*********************************************");
    }
}

From source file:com.globocom.grou.report.ReportService.java

public void send(Test test) throws Exception {
    final AtomicReference<List<Throwable>> exceptions = new AtomicReference<>(new ArrayList<>());
    final Map<String, Double> report = getReport(test);
    final HashMap<String, Double> reportSanitized = sanitizeKeyName(report);
    test.setResult(reportSanitized);/* w  w  w. j  av a2 s  .com*/
    testRepository.save(test);
    test.getNotify().forEach(notify -> {
        try {
            if (VALID_EMAIL_ADDRESS_REGEX.matcher(notify).matches()) {
                notifyByMail(test, notify.replaceAll("^mailto:[/]{0,2}", ""), report);
            } else if (VALID_HTTP_ADDRESS_REGEX.matcher(notify).matches()) {
                notifyByHttp(test, notify);
            } else {
                throw new UnsupportedOperationException("notify destination unsupported: " + notify);
            }
        } catch (Exception e) {
            exceptions.get().add(e);
        }
    });
    String exceptionsStr = exceptions.get().stream().map(Throwable::getMessage)
            .collect(Collectors.joining(" "));
    if (!exceptionsStr.isEmpty()) {
        throw new IllegalStateException(exceptionsStr);
    }
}

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

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

    RestAssuredMockMvc.given().standaloneSetup(new GreetingController())
            .config(RestAssuredMockMvc.config()
                    .encoderConfig(EncoderConfig.encoderConfig().defaultCharsetForContentType(
                            StandardCharsets.UTF_16.toString(), ContentType.JSON)))
            .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")));
                }/*from  w w w .ja va2s . c o  m*/
            }).when().get("/greeting?name={name}", "Johan").then().statusCode(200);

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