List of usage examples for java.util.concurrent.atomic AtomicReference get
public final V get()
From source file:org.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java
@Test public void concurrentLoginMultipleUsers() throws Throwable { log.info("*********************************************"); long start = System.currentTimeMillis(); AtomicReference<String> userSessionId = new AtomicReference<>(); LoginTask loginTask = null;//w ww .ja v a 2s. com 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"), createHttpClientContextForUser(httpClient, "john-doh@localhost", "password"), createHttpClientContextForUser(httpClient, "roleRichUser", "password"))); run(DEFAULT_THREADS, DEFAULT_CLIENTS_COUNT, loginTask); int clientSessionsCount = testingClient.testing().getClientSessionsCountInUserSession("test", userSessionId.get()); Assert.assertEquals(1 + DEFAULT_CLIENTS_COUNT / 3 + (DEFAULT_CLIENTS_COUNT % 3 <= 0 ? 0 : 1), clientSessionsCount); } finally { long end = System.currentTimeMillis() - start; log.infof("Statistics: %s", loginTask == null ? "??" : loginTask.getHistogram()); log.info("concurrentLoginMultipleUsers took " + (end / 1000) + "s"); log.info("*********************************************"); } }
From source file:fr.pilato.elasticsearch.crawler.fs.test.integration.ElasticsearchClientIT.java
@Test public void testBulkWithErrors() throws IOException, InterruptedException { // Create the index first elasticsearchClient.createIndex(getCrawlerName()); elasticsearchClient.waitForHealthyIndex(getCrawlerName()); AtomicReference<BulkResponse> bulkResponse = new AtomicReference<>(); BulkProcessor bulkProcessor = new BulkProcessor.Builder(elasticsearchClient, new BulkProcessor.Listener() { @Override// www.ja v a 2 s.co m public void beforeBulk(long executionId, BulkRequest request) { } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { bulkResponse.set(response); } @Override public void afterBulk(long executionId, BulkRequest request, Throwable failure) { } }).setBulkActions(100).setFlushInterval(TimeValue.timeValueMillis(200)).build(); bulkProcessor.add( new IndexRequest(getCrawlerName(), FsCrawlerUtil.INDEX_TYPE_DOC, "id").source("{\"foo\":\"bar\"")); bulkProcessor.close(); BulkResponse response = bulkResponse.get(); Throwable message = response.buildFailureMessage(); assertThat(message.getMessage(), containsString("1 failures")); // If we run the test with a TRACE level, we can check more things if (LogManager.getLogger(BulkResponse.class).isTraceEnabled()) { assertThat(message.getMessage(), containsString("failed to parse")); } }
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). *///from w w w . j av a2s . co m 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:com.netflix.iep.http.RxHttpTest.java
@Test public void redirectResponseMissingLocation() throws Exception { int code = 302; statusCode.set(code);/*from w w w.j av a2 s. c om*/ redirects.set(2); AtomicIntegerArray expected = copy(statusCounts); expected.addAndGet(code, 1); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> throwable = new AtomicReference<>(); rxHttp.get(uri("/redirectNoLocation")).subscribe(Actions.empty(), new Action1<Throwable>() { @Override public void call(Throwable t) { latch.countDown(); throwable.set(t); } }, new Action0() { @Override public void call() { latch.countDown(); } }); latch.await(); assertEquals(expected, statusCounts); Assert.assertNotNull(throwable.get()); }
From source file:org.zodiark.publisher.PublisherTest.java
@Test(enabled = false) public void createSessionTest() throws IOException, InterruptedException { final AtomicReference<PublisherResults> answer = new AtomicReference<>(); final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build(); final CountDownLatch latch = new CountDownLatch(1); publisherClient.handler(new OnEnvelopHandler() { @Override/*from w ww . jav a 2 s . c o m*/ public boolean onEnvelop(Envelope e) throws IOException { answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class)); latch.countDown(); return true; } }).open(); Envelope createSessionMessage = Envelope .newClientToServerRequest(new Message(new Path(DB_POST_PUBLISHER_SESSION_CREATE), mapper.writeValueAsString(new UserPassword("foo", "bar")))); createSessionMessage.setFrom(new From(ActorValue.PUBLISHER)); publisherClient.send(createSessionMessage); latch.await(); assertEquals("OK", answer.get().getResults()); }
From source file:interactivespaces.util.web.HttpClientHttpContentCopierTest.java
/** * Test a file upload from an input stream. *//*from ww w . j a va 2 s .co m*/ @Test public void testFileUploadInputStream() throws Exception { final File destination = getTempFile(); InputStream source = new ByteArrayInputStream(TEST_CONTENT.getBytes()); final AtomicReference<Map<String, String>> receivedParameters = new AtomicReference<Map<String, String>>(); final CountDownLatch latch = new CountDownLatch(1); webServer.setHttpFileUploadListener(new HttpFileUploadListener() { @Override public void handleHttpFileUpload(HttpFileUpload fileUpload) { fileUpload.moveTo(destination); receivedParameters.set(fileUpload.getParameters()); latch.countDown(); } }); String sourceParameterName = "myfile"; Map<String, String> expectedParameters = Maps.newHashMap(); expectedParameters.put("foo", "bar"); expectedParameters.put("bletch", "spam"); copier.copyTo(getUrlPrefix(), source, "foo.txt", sourceParameterName, expectedParameters); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertEquals(TEST_CONTENT, Files.readFile(destination).trim()); Assert.assertEquals(expectedParameters, receivedParameters.get()); }
From source file:my.adam.smo.client.Client.java
public BlockingRpcChannel blockingConnect(final InetSocketAddress sa) { return new BlockingRpcChannel() { private int countDownCallTimesToRelease = 1; private RpcChannel rpc = connect(sa); @Override/*from w w w .ja va 2 s. c om*/ public Message callBlockingMethod(Descriptors.MethodDescriptor method, RpcController controller, Message request, Message responsePrototype) throws ServiceException { StopWatch stopWatch = new StopWatch("callBlockingMethod"); stopWatch.start(); final CountDownLatch callbackLatch = new CountDownLatch(countDownCallTimesToRelease); final AtomicReference<Message> result = new AtomicReference<Message>(); RpcCallback<Message> done = new RpcCallback<Message>() { @Override public void run(Message parameter) { result.set(parameter); callbackLatch.countDown(); } }; rpc.callMethod(method, controller, request, responsePrototype, done); try { boolean succeededBeforeTimeout = callbackLatch.await(blocking_method_call_timeout, TimeUnit.SECONDS); if (!succeededBeforeTimeout) { throw new ServiceException( "blocking method timeout reached for method:" + method.getFullName()); } } catch (InterruptedException e) { getLogger().error("call failed", e); stopWatch.stop(); } stopWatch.stop(); getLogger().trace(stopWatch.shortSummary()); return result.get(); } }; }
From source file:com.dgtlrepublic.anitomyj.Tokenizer.java
/** Tokenize by bracket. */ private void tokenizeByBrackets() { /** a ref to the closing brace of a found opening brace. (e.g "}" if we found an "}") */ AtomicReference<String> matchingBracket = new AtomicReference<>(); /** function to find an opening brace */ BiFunction<Integer, Integer, Integer> findFirstBracket = (start, end) -> { for (int i = start; i < end; i++) { for (Pair<String, String> bracket : brackets) { if (String.valueOf(filename.charAt(i)).equals(bracket.getLeft())) { matchingBracket.set(bracket.getRight()); return i; }/* w w w . j av a 2s . co m*/ } } return -1; }; boolean isBracketOpen = false; for (int i = 0; i < filename.length();) { int foundIdx; if (!isBracketOpen) { /** look for opening brace */ foundIdx = findFirstBracket.apply(i, filename.length()); } else { /** look for closing brace */ foundIdx = filename.indexOf(matchingBracket.get(), i); } TokenRange range = new TokenRange(i, foundIdx == -1 ? filename.length() : foundIdx - i); if (range.getSize() > 0) { /** check if our range contains any known anime identifies */ tokenizeByPreidentified(isBracketOpen, range); } if (foundIdx != -1) { /** mark as bracket */ addToken(TokenCategory.kBracket, true, new TokenRange(range.getOffset() + range.getSize(), 1)); isBracketOpen = !isBracketOpen; i = foundIdx + 1; } else { break; } } }
From source file:de.sainth.recipe.backend.db.repositories.FoodRepository.java
public Food save(Food food) { AtomicReference<Food> bu = new AtomicReference<>(); create.transaction(configuration -> { Long id = using(configuration).select(FOODS.ID).from(FOODS).where(FOODS.NAME.eq(food.getName())) .forUpdate().fetchOneInto(Long.class); FoodsRecord record;/* ww w. j a v a 2 s. c om*/ if (id == null) { record = using(configuration) .insertInto(FOODS, FOODS.NAME, FOODS.POINTS, FOODS.POINTS_BASE_AMOUNT, FOODS.BASIC_UNIT) .values(food.getName(), food.getPoints(), food.getPointsBaseAmount(), food.getBasicUnit()) .returning().fetchOne(); } else { record = using(configuration).update(FOODS).set(FOODS.NAME, food.getName()) .set(FOODS.POINTS, food.getPoints()) .set(FOODS.POINTS_BASE_AMOUNT, food.getPointsBaseAmount()) .set(FOODS.BASIC_UNIT, food.getBasicUnit()).where(FOODS.ID.eq(id)).returning().fetchOne(); } bu.set(new Food(record.getId(), record.getName(), record.getPoints(), record.getPointsBaseAmount(), record.getBasicUnit())); }); return bu.get(); }
From source file:com.android.ide.common.process.MtlProcessExecutor.java
private static ListenableFuture<Integer> grabProcessOutput(@NonNull final Process process, @NonNull final ProcessOutput output) { final SettableFuture<Integer> result = SettableFuture.create(); final AtomicReference<Exception> exceptionHolder = new AtomicReference<Exception>(); /*/* w w w . j av a 2 s . c o m*/ * It looks like on windows process#waitFor() can return before the thread have filled the * arrays, so we wait for both threads and the process itself. * * To make sure everything is complete before setting the future, the thread handling * "out" will wait for all its input to be read, will wait for the "err" thread to finish * and will wait for the process to finish. Only after all three are done will it set * the future and terminate. * * This means that the future will be set while the "out" thread is still running, but * no output is pending and the process has already finished. */ final Thread threadErr = new Thread("stderr") { @Override public void run() { InputStream stderr = process.getErrorStream(); OutputStream stream = output.getErrorOutput(); try { ByteStreams.copy(stderr, stream); stream.flush(); } catch (IOException e) { exceptionHolder.compareAndSet(null, e); } } }; Thread threadOut = new Thread("stdout") { @Override public void run() { InputStream stdout = process.getInputStream(); OutputStream stream = output.getStandardOutput(); try { ByteStreams.copy(stdout, stream); stream.flush(); } catch (Exception e) { exceptionHolder.compareAndSet(null, e); } try { threadErr.join(); int processResult = process.waitFor(); if (exceptionHolder.get() != null) { result.setException(exceptionHolder.get()); } result.set(processResult); output.close(); } catch (Exception e) { result.setException(e); } } }; threadErr.start(); threadOut.start(); return result; }