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.netflix.suro.SuroServer.java

public static void main(String[] args) throws IOException {
    final AtomicReference<Injector> injector = new AtomicReference<Injector>();

    try {/*from w w  w  .  j av a2s  .c om*/
        // Parse the command line
        Options options = createOptions();
        final CommandLine line = new BasicParser().parse(options, args);

        // Load the properties file
        final Properties properties = new Properties();
        if (line.hasOption('p')) {
            properties.load(new FileInputStream(line.getOptionValue('p')));
        }

        // Bind all command line options to the properties with prefix "SuroServer."
        for (Option opt : line.getOptions()) {
            String name = opt.getOpt();
            String value = line.getOptionValue(name);
            String propName = PROP_PREFIX + opt.getArgName();
            if (propName.equals(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY)) {
                properties.setProperty(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertySinkConfigurator.SINK_PROPERTY)) {
                properties.setProperty(DynamicPropertySinkConfigurator.SINK_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY)) {
                properties.setProperty(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else {
                properties.setProperty(propName, value);
            }
        }

        create(injector, properties);
        injector.get().getInstance(LifecycleManager.class).start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
                } catch (IOException e) {
                    // do nothing because Closeables.close will swallow IOException
                }
            }
        });

        waitForShutdown(getControlPort(properties));
    } catch (Throwable e) {
        System.err.println("SuroServer startup failed: " + e.getMessage());
        System.exit(-1);
    } finally {
        Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
    }
}

From source file:org.tommy.stationery.moracle.core.client.load.StompWebSocketLoadTestClient.java

public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
        host = args[0];//from   ww  w .j a va 2 s.c  o m
    }

    int port = 59984;
    if (args.length > 1) {
        port = Integer.valueOf(args[1]);
    }

    String url = "http://" + host + ":" + port + "/home";
    logger.debug("Sending warm-up HTTP request to " + url);
    HttpStatus status = new RestTemplate().getForEntity(url, Void.class).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    Executor executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    org.eclipse.jetty.websocket.client.WebSocketClient jettyClient = new WebSocketClient(executor);
    JettyWebSocketClient webSocketClient = new JettyWebSocketClient(jettyClient);
    webSocketClient.start();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
        URI uri = new URI("ws://" + host + ":" + port + "/stomp");
        WebSocketStompClient stompClient = new WebSocketStompClient(uri, null, sockJsClient);
        stompClient.setMessageConverter(new StringMessageConverter());

        logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
        StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
        stopWatch.start();

        List<ConsumerStompMessageHandler> consumers = new ArrayList<>();
        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            consumers.add(new ConsumerStompMessageHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch,
                    messageLatch, disconnectLatch, failure));
            stompClient.connect(consumers.get(i));
        }

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users connected, remaining: " + connectLatch.getCount());
        }
        if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users subscribed, remaining: " + subscribeLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users ");
        stopWatch.start();

        ProducerStompMessageHandler producer = new ProducerStompMessageHandler(BROADCAST_MESSAGE_COUNT,
                failure);
        stompClient.connect(producer);

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            for (ConsumerStompMessageHandler consumer : consumers) {
                if (consumer.messageCount.get() < consumer.expectedMessageCount) {
                    logger.debug(consumer);
                }
            }
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all handlers received every message, remaining: " + messageLatch.getCount());
        }

        producer.session.disconnect();
        if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        System.out.println("\nPress any key to exit...");
        System.in.read();
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        webSocketClient.stop();
        jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
}

From source file:Main.java

public static void runInThread(final Runnable runnable) throws Throwable {
    final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
    Runnable exceptionGuard = new Runnable() {
        public void run() {
            try {
                runnable.run();//from  ww w .ja v  a 2 s  . co m
            } catch (Throwable throwable) {
                exception.set(throwable);
            }
        }
    };
    Thread thread = new Thread(exceptionGuard);
    thread.setDaemon(true);
    thread.start();
    thread.join();
    if (exception.get() != null) {
        throw exception.get();
    }
}

From source file:org.elasticsearch.xpack.test.rest.XPackRestTestHelper.java

/**
 * Waits for the Machine Learning templates to be created
 * and check the version is up to date//from   w  ww.j a  v  a 2  s.  com
 */
public static void waitForMlTemplates(RestClient client) throws InterruptedException {
    AtomicReference<Version> masterNodeVersion = new AtomicReference<>();
    ESTestCase.awaitBusy(() -> {
        String response;
        try {
            response = EntityUtils.toString(client
                    .performRequest("GET", "/_cat/nodes", singletonMap("h", "master,version")).getEntity());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        for (String line : response.split("\n")) {
            if (line.startsWith("*")) {
                masterNodeVersion.set(Version.fromString(line.substring(2).trim()));
                return true;
            }
        }
        return false;
    });

    final List<String> templateNames = Arrays.asList(AuditorField.NOTIFICATIONS_INDEX, MlMetaIndex.INDEX_NAME,
            AnomalyDetectorsIndex.jobStateIndexName(), AnomalyDetectorsIndex.jobResultsIndexPrefix());
    for (String template : templateNames) {
        ESTestCase.awaitBusy(() -> {
            Map<?, ?> response;
            try {
                String string = EntityUtils
                        .toString(client.performRequest("GET", "/_template/" + template).getEntity());
                response = XContentHelper.convertToMap(JsonXContent.jsonXContent, string, false);
            } catch (ResponseException e) {
                if (e.getResponse().getStatusLine().getStatusCode() == 404) {
                    return false;
                }
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Map<?, ?> templateDefinition = (Map<?, ?>) response.get(template);
            return Version.fromId((Integer) templateDefinition.get("version")).equals(masterNodeVersion.get());
        });
    }
}

From source file:kn.uni.gis.foxhunt.context.GameContext.java

/**
 * creates a new fox game//from  w w  w.j a v a 2s.  c o  m
 * 
 * @param id
 * @param playerName
 */
public static void newFoxGame(String playerName) throws GameException {

    final AtomicReference<String> ref = new AtomicReference<String>();
    final AtomicReference<Exception> exc = new AtomicReference<Exception>();
    HttpContext.getInstance().put(SettingsContext.getInstance().getServerUrl(), null,
            new EntityHandlerAdapter() {
                @Override
                public void handleEntity(HttpEntity entity, int statusCode) {
                    if (statusCode == HttpStatus.SC_OK) {
                        try {
                            ref.set(EntityUtils.toString(entity));

                        } catch (ParseException e) {
                            exc.set(e);
                        } catch (IOException e) {
                            exc.set(e);
                        }
                    } else {
                        exc.set(new GameException("bad status code: " + statusCode));
                    }
                }

                @Override
                public void handleException(Exception exception) {
                    exc.set(exception);
                }
            });

    if (ref.get() == null) {
        throw exc.get() != null ? new GameException(exc.get())
                : new GameException("unrecognized error code from server");
    }
    currentGame = new Game(ref.get(), playerName, Util.createFoxUrl(ref.get()), Util.createGameUrl(ref.get()));
}

From source file:com.google.code.jahath.common.io.SwappableInputStreamTest.java

@Test
public void test() throws Throwable {
    final SwappableInputStream swappableInputStream = new SwappableInputStream("test");
    final CRC actualCRC = new CRC();
    final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                actualCRC.update(swappableInputStream);
            } catch (Throwable ex) {
                thrown.set(ex);//w w  w  .j  a v  a 2  s . c  o m
            }
        }
    });
    thread.start();
    Random random = new Random();
    CRC expectedCRC = new CRC();
    for (int i = 0; i < 100; i++) {
        int len = 2048 + random.nextInt(4096);
        byte[] data = new byte[len];
        random.nextBytes(data);
        expectedCRC.update(data);
        CountingInputStream in = new CountingInputStream(new ByteArrayInputStream(data));
        swappableInputStream.swap(in);
        // Check that the stream has been consumed entirely
        Assert.assertEquals(len, in.getCount());
    }
    swappableInputStream.sendEndOfStream();
    thread.join();
    if (thrown.get() != null) {
        throw thrown.get();
    }
    Assert.assertEquals(expectedCRC.getValue(), actualCRC.getValue());
}

From source file:com.facebook.config.TestFileJSONProvider.java

@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
    readerReference = new AtomicReference<BufferedReader>();
    jsonProvider = new FileJSONProvider(null) {
        @Override//from  w ww.j av  a  2  s . c  o m
        protected BufferedReader getReader() throws FileNotFoundException {
            return readerReference.get();
        }
    };
    jsonWithComments = "{\n" + "\tkey : \"value\",\n" + "\t// comment 1\n" + "\tnested : { x : 1 }\n"
            + "\t//nested2 : { y : 2 }\n" + "// comment 2\n" + "\t// comment 3\n" + "}";
}

From source file:org.elasticsearch.test.rest.yaml.ClientYamlTestExecutionContextTests.java

public void testHeadersSupportStashedValueReplacement() throws IOException {
    final AtomicReference<Map<String, String>> headersRef = new AtomicReference<>();
    final ClientYamlTestExecutionContext context = new ClientYamlTestExecutionContext(null, randomBoolean()) {
        @Override/*from  w ww .  ja v a2  s. c  om*/
        ClientYamlTestResponse callApiInternal(String apiName, Map<String, String> params, HttpEntity entity,
                Map<String, String> headers) {
            headersRef.set(headers);
            return null;
        }
    };
    final Map<String, String> headers = new HashMap<>();
    headers.put("foo", "$bar");
    headers.put("foo1", "baz ${c}");

    context.stash().stashValue("bar", "foo2");
    context.stash().stashValue("c", "bar1");

    assertNull(headersRef.get());
    context.callApi("test", Collections.emptyMap(), Collections.emptyList(), headers);
    assertNotNull(headersRef.get());
    assertNotEquals(headers, headersRef.get());

    assertEquals("foo2", headersRef.get().get("foo"));
    assertEquals("baz bar1", headersRef.get().get("foo1"));
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.index.DefaultCompoundValueResolver.java

@Override
public String resolve(Object value, JsonObject root, String id, String fieldName, RedissonIndex index) {
    AtomicReference<String> s = new AtomicReference<>();
    if (StringUtils.isBlank(index.valueField())) {
        s.set(value instanceof String ? (String) value : Json.encode(value));
    } else {/* w ww. ja  v a 2  s. com*/
        s.set(root.getString(index.valueField()));
    }
    Arrays.stream(index.compoundIndexFields()).forEach(
            e -> s.set(s.get().concat(RedisRepository.DEFAULT_SEPERATOR).concat(root.getValue(e).toString())));
    return s.get().concat(RedisRepository.DEFAULT_SEPERATOR).concat(id);
}

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

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