List of usage examples for java.util.concurrent.atomic AtomicBoolean get
public final boolean get()
From source file:com.atlassian.jira.bc.group.TestDefaultGroupService.java
/** Tests we pass through to the bulk method. */ @Test//w ww . j a v a 2s . co m public void testValidateAddUsertoGroup() { final AtomicBoolean bulkWasCalled = new AtomicBoolean(false); final DefaultGroupService defaultGroupService = new DefaultGroupService(null, null, null, null, null, null, null, null, null, null, null, null, null, null) { @Override public BulkEditGroupValidationResult validateAddUsersToGroup( final JiraServiceContext jiraServiceContext, final Collection groupsToJoin, final Collection userNames) { bulkWasCalled.set(true); return new BulkEditGroupValidationResult(true); } }; assertTrue(defaultGroupService.validateAddUserToGroup(null, null, null)); assertTrue(bulkWasCalled.get()); }
From source file:org.elasticsearch.client.sniff.SnifferTests.java
/** * Test behaviour when a bunch of onFailure sniffing rounds are triggered in parallel. Each run will always * schedule a subsequent afterFailure round. Also, for each onFailure round that starts, the net scheduled round * (either afterFailure or ordinary) gets cancelled. *///from w w w. ja v a2 s .c o m public void testSniffOnFailure() throws Exception { RestClient restClient = mock(RestClient.class); CountingHostsSniffer hostsSniffer = new CountingHostsSniffer(); final AtomicBoolean initializing = new AtomicBoolean(true); final long sniffInterval = randomLongBetween(1, Long.MAX_VALUE); final long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE); int minNumOnFailureRounds = randomIntBetween(5, 10); final CountDownLatch initializingLatch = new CountDownLatch(1); final Set<Sniffer.ScheduledTask> ordinaryRoundsTasks = new CopyOnWriteArraySet<>(); final AtomicReference<Future<?>> initializingFuture = new AtomicReference<>(); final Set<Sniffer.ScheduledTask> onFailureTasks = new CopyOnWriteArraySet<>(); final Set<Sniffer.ScheduledTask> afterFailureTasks = new CopyOnWriteArraySet<>(); final AtomicBoolean onFailureCompleted = new AtomicBoolean(false); final CountDownLatch completionLatch = new CountDownLatch(1); final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); try { Scheduler scheduler = new Scheduler() { @Override public Future<?> schedule(final Sniffer.Task task, long delayMillis) { if (initializing.compareAndSet(true, false)) { assertEquals(0L, delayMillis); Future<?> future = executor.submit(new Runnable() { @Override public void run() { try { task.run(); } finally { //we need to make sure that the sniffer is initialized, so the sniffOnFailure //call does what it needs to do. Otherwise nothing happens until initialized. initializingLatch.countDown(); } } }); assertTrue(initializingFuture.compareAndSet(null, future)); return future; } if (delayMillis == 0L) { Future<?> future = executor.submit(task); onFailureTasks.add(new Sniffer.ScheduledTask(task, future)); return future; } if (delayMillis == sniffAfterFailureDelay) { Future<?> future = scheduleOrSubmit(task); afterFailureTasks.add(new Sniffer.ScheduledTask(task, future)); return future; } assertEquals(sniffInterval, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); if (onFailureCompleted.get() && onFailureTasks.size() == afterFailureTasks.size()) { completionLatch.countDown(); return mock(Future.class); } Future<?> future = scheduleOrSubmit(task); ordinaryRoundsTasks.add(new Sniffer.ScheduledTask(task, future)); return future; } private Future<?> scheduleOrSubmit(Sniffer.Task task) { if (randomBoolean()) { return executor.schedule(task, randomLongBetween(0L, 200L), TimeUnit.MILLISECONDS); } else { return executor.submit(task); } } @Override public void shutdown() { } }; final Sniffer sniffer = new Sniffer(restClient, hostsSniffer, scheduler, sniffInterval, sniffAfterFailureDelay); assertTrue("timeout waiting for sniffer to get initialized", initializingLatch.await(1000, TimeUnit.MILLISECONDS)); ExecutorService onFailureExecutor = Executors.newFixedThreadPool(randomIntBetween(5, 20)); Set<Future<?>> onFailureFutures = new CopyOnWriteArraySet<>(); try { //with tasks executing quickly one after each other, it is very likely that the onFailure round gets skipped //as another round is already running. We retry till enough runs get through as that's what we want to test. while (onFailureTasks.size() < minNumOnFailureRounds) { onFailureFutures.add(onFailureExecutor.submit(new Runnable() { @Override public void run() { sniffer.sniffOnFailure(); } })); } assertThat(onFailureFutures.size(), greaterThanOrEqualTo(minNumOnFailureRounds)); for (Future<?> onFailureFuture : onFailureFutures) { assertNull(onFailureFuture.get()); } onFailureCompleted.set(true); } finally { onFailureExecutor.shutdown(); onFailureExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS); } assertFalse(initializingFuture.get().isCancelled()); assertTrue(initializingFuture.get().isDone()); assertNull(initializingFuture.get().get()); assertTrue("timeout waiting for sniffing rounds to be completed", completionLatch.await(1000, TimeUnit.MILLISECONDS)); assertThat(onFailureTasks.size(), greaterThanOrEqualTo(minNumOnFailureRounds)); assertEquals(onFailureTasks.size(), afterFailureTasks.size()); for (Sniffer.ScheduledTask onFailureTask : onFailureTasks) { assertFalse(onFailureTask.future.isCancelled()); assertTrue(onFailureTask.future.isDone()); assertNull(onFailureTask.future.get()); assertTrue(onFailureTask.task.hasStarted()); assertFalse(onFailureTask.task.isSkipped()); } int cancelledTasks = 0; int completedTasks = onFailureTasks.size() + 1; for (Sniffer.ScheduledTask afterFailureTask : afterFailureTasks) { if (assertTaskCancelledOrCompleted(afterFailureTask)) { completedTasks++; } else { cancelledTasks++; } } assertThat(ordinaryRoundsTasks.size(), greaterThan(0)); for (Sniffer.ScheduledTask task : ordinaryRoundsTasks) { if (assertTaskCancelledOrCompleted(task)) { completedTasks++; } else { cancelledTasks++; } } assertEquals(onFailureTasks.size(), cancelledTasks); assertEquals(completedTasks, hostsSniffer.runs.get()); int setHostsRuns = hostsSniffer.runs.get() - hostsSniffer.failures.get() - hostsSniffer.emptyList.get(); verify(restClient, times(setHostsRuns)).setHosts(Matchers.<HttpHost>anyVararg()); verifyNoMoreInteractions(restClient); } finally { executor.shutdown(); executor.awaitTermination(1000L, TimeUnit.MILLISECONDS); } }
From source file:org.dataconservancy.packaging.tool.integration.PackageGenerationTest.java
@Test public void verifyRemediationTest() throws Exception { PackageState state = initializer.initialize(DCS_PROFILE); Set<URI> originalFileLocations = new HashSet<>(); ipm2rdf.transformToNode(state.getPackageTree()) .walk(node -> originalFileLocations.add(node.getFileInfo().getLocation())); // The package should contain two files: // - READMX//from www. j a v a 2s . c o m // - READM // // The file with the acute E will be remediated to a resource named 'READMX', which will collide with // an existing resource of the same name. // assert that our sample problem files are in the content to be packaged assertTrue(originalFileLocations.stream().anyMatch(uri -> uri.getPath().endsWith("READMX"))); // 0x0301 is the UTF-16 encoding of the 'COMBINING ACUTE ACCENT' combining diacritic // 0x00c9 is the UTF-16 encoding of 'LATIN CAPITAL LETTER E WITH ACUTE' assertTrue(originalFileLocations.stream().anyMatch(uri -> (uri.getPath().endsWith("README" + '\u0301')) || (uri.getPath().endsWith("READM" + '\u00c9')))); OpenedPackage opened = packager.createPackage(state, folder.getRoot()); AtomicBoolean foundIllegal = new AtomicBoolean(Boolean.FALSE); AtomicBoolean foundRemediated = new AtomicBoolean(Boolean.FALSE); AtomicReference<String> remediatedFilename = new AtomicReference<>(); AtomicBoolean foundCollision = new AtomicBoolean(Boolean.FALSE); AtomicReference<String> collidingFilename = new AtomicReference<>(); // Walk the generated package, and make sure that // 1. That a resource with illegal characters does not exist // 2. That a resource named 'READMX' does exist // 3. That a resource named after the SHA-1 hex of its identifier exists // 4. That those two resources originate from two different files in the original package content opened.getPackageTree().walk(node -> { if (node.getFileInfo() == null || !node.getFileInfo().isFile()) { return; } System.err.println(node.getFileInfo().getName()); System.err.println(" " + node.getFileInfo().getLocation().toString()); // this should not happen, because a file name with invalid characters should have // been remediated prior to being inserted into the package if (node.getFileInfo().getLocation().getPath().endsWith("README" + '\u0301') || node.getFileInfo().getLocation().getPath().endsWith("READM" + '\u00c9')) { foundIllegal.set(Boolean.TRUE); } if (node.getFileInfo().getLocation().getPath().endsWith(shaHex(node.getIdentifier().toString()))) { foundRemediated.set(Boolean.TRUE); remediatedFilename.set(node.getFileInfo().getName()); // short circuit return; } if (node.getFileInfo().getName().equals("READMX") || node.getFileInfo().getName().equals("READM")) { foundCollision.set(Boolean.TRUE); collidingFilename.set(node.getFileInfo().getName()); } }); assertFalse(foundIllegal.get()); assertTrue(foundCollision.get()); assertTrue(foundRemediated.get()); assertNotNull(remediatedFilename.get()); assertNotNull(collidingFilename.get()); assertNotEquals(remediatedFilename.get(), collidingFilename.get()); }
From source file:com.streamsets.pipeline.stage.destination.hdfs.HdfsTargetConfigBean.java
private boolean validateHadoopDir(final Stage.Context context, final String configName, final String configGroup, String dirPathTemplate, final List<Stage.ConfigIssue> issues) { final AtomicBoolean ok = new AtomicBoolean(true); if (!dirPathTemplate.startsWith("/")) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_40)); ok.set(false);//from www .j a v a 2 s . c o m } else { dirPathTemplate = (dirPathTemplate.isEmpty()) ? "/" : dirPathTemplate; try { final Path dir = new Path(dirPathTemplate); final FileSystem fs = getFileSystemForInitDestroy(); getUGI().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { if (!fs.exists(dir)) { try { if (fs.mkdirs(dir)) { ok.set(true); } else { issues.add( context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_41)); ok.set(false); } } catch (IOException ex) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_42, ex.toString())); ok.set(false); } } else { try { Path dummy = new Path(dir, "_sdc-dummy-" + UUID.randomUUID().toString()); fs.create(dummy).close(); fs.delete(dummy, false); ok.set(true); } catch (IOException ex) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_43, ex.toString())); ok.set(false); } } return null; } }); } catch (Exception ex) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_44, ex.toString())); ok.set(false); } } return ok.get(); }
From source file:org.apache.hadoop.hdfs.qjournal.client.TestQJMWriteRead.java
@Test public void testTailing() throws Exception { // Unlike the other unit test, numEdits here is constant as this is // a longer running test final int numEdits = 1000; final AtomicBoolean finishedProducing = new AtomicBoolean(false); final EditLogOutputStream out = qjm.startLogSegment(0); Callable<Void> producerThread = new Callable<Void>() { @Override/* www. jav a 2 s. com*/ public Void call() throws Exception { try { for (int i = 0; i < numEdits; i++) { FSEditLogOp op = FSEditLogTestUtil.getNoOpInstance(); // Set an increasing transaction id to verify correctness op.setTransactionId(i); if (LOG.isDebugEnabled()) { LOG.debug("Writing " + op); } FSEditLogTestUtil.writeToStreams(op, out); if (i % 50 == 0) { Thread.sleep(100); FSEditLogTestUtil.flushStreams(out); } } FSEditLogTestUtil.flushStreams(out); FSEditLogTestUtil.closeStreams(out); } finally { // Let the producer know that we've reached the end. finishedProducing.set(true); } return null; } }; Callable<Void> consumerThread = new Callable<Void>() { @Override public Void call() throws Exception { List<EditLogInputStream> streams = Lists.newArrayList(); qjm.selectInputStreams(streams, 0, true, false); EditLogInputStream in = streams.get(0); long numOps = 0; long maxTxId = -1; FSEditLogOp op; long lastPos = in.getPosition(); do { op = in.readOp(); if (op == null) { // If we've reached the end prematurely... Thread.sleep(200); LOG.info("Refreshing to " + lastPos); in.refresh(lastPos, maxTxId); // Then refresh to last known good position } else { long txId = op.getTransactionId(); if (txId > maxTxId) { // Standby ingest contains similar logic: transactions // with ids lower than what is already read are ignored. numOps++; maxTxId = txId; } // Remember the last known safe position that we can refresh to lastPos = in.getPosition(); } } while (op != null || !finishedProducing.get()); Thread.sleep(1000); // finalize the segment, so we can read to the end qjm.finalizeLogSegment(0, numEdits - 1); // Once producer is shutdown, scan again from last known good position // until the end of the ledger. This mirrors the Ingest logic (last // read when being quiesced). in.refresh(lastPos, maxTxId); do { op = in.readOp(); if (op != null) { long txId = op.getTransactionId(); if (txId > maxTxId) { numOps++; maxTxId = txId; } } } while (op != null); assertEquals("Must have read " + numEdits + " edits", numEdits, numOps); assertEquals("Must end at txid = " + (numEdits - 1), numEdits - 1, maxTxId); return null; } }; // Allow producer and consumer to run concurrently ExecutorService executor = Executors.newFixedThreadPool(2); Future<Void> producerFuture = executor.submit(producerThread); Future<Void> consumerFuture = executor.submit(consumerThread); // Calling a .get() on the future will rethrow any exceptions thrown in // the future. producerFuture.get(); consumerFuture.get(); }
From source file:de.dal33t.powerfolder.Controller.java
/** * Waits for the repo to finish syncing. Then request system shutdown and * exit PF./*from w w w.ja v a 2s .c o m*/ * * @param secWait * number of seconds to wait. */ public void exitAfterSync(int secWait) { logInfo("Sync and exit initiated. Begin check in " + secWait + 's'); final AtomicBoolean oneShot = new AtomicBoolean(true); scheduleAndRepeat(new Runnable() { @Override public void run() { // ALPS Problem: Change to check for all in sync. if (oneShot.get() && folderRepository.isInSync()) { // Make sure we only try to shutdown once, // in case the user aborts the shutdown. oneShot.set(false); log.info("I'm in sync - exit now. Sync and exit was triggered."); exit(0); } } }, 1000L * secWait, 10000); }
From source file:de.dal33t.powerfolder.Controller.java
/** * Wait for the repo to finish syncing. Then request system shutdown and * exit PF./*from www . ja v a 2 s . c o m*/ * * @param password * required only for Linux shutdowns. */ public void shutdownAfterSync(final String password) { final AtomicBoolean oneShot = new AtomicBoolean(true); scheduleAndRepeat(new Runnable() { @Override public void run() { // ALPS Problem: Change to check for all in sync. if (oneShot.get() && folderRepository.isInSync()) { // Make sure we only try to shutdown once, // in case the user aborts the shutdown. oneShot.set(false); log.info("Sync and shutdown in sync."); if (SystemUtil.shutdown(password)) { log.info("Shutdown command issued."); exit(0); } else { log.warning("Shutdown command failed."); } } } }, 10000, 10000); }
From source file:android.webkit.cts.WebViewTest.java
public void testAddJavascriptInterfaceExceptions() throws Exception { WebSettings settings = mOnUiThread.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); final AtomicBoolean mJsInterfaceWasCalled = new AtomicBoolean(false) { @JavascriptInterface/* w w w . j a v a2 s . c o m*/ public synchronized void call() { set(true); // The main purpose of this test is to ensure an exception here does not // crash the implementation. throw new RuntimeException("Javascript Interface exception"); } }; mOnUiThread.addJavascriptInterface(mJsInterfaceWasCalled, "dummy"); mOnUiThread.loadUrlAndWaitForCompletion("about:blank"); assertFalse(mJsInterfaceWasCalled.get()); final CountDownLatch resultLatch = new CountDownLatch(1); mOnUiThread.evaluateJavascript("try {dummy.call(); 'fail'; } catch (exception) { 'pass'; } ", new ValueCallback<String>() { @Override public void onReceiveValue(String result) { assertEquals("\"pass\"", result); resultLatch.countDown(); } }); assertTrue(resultLatch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(mJsInterfaceWasCalled.get()); }
From source file:de.hybris.platform.test.TransactionTest.java
@Test public void testItemUpdateDuringCommit_PLA10839() throws Exception { final Title title1 = UserManager.getInstance().createTitle("t1"); final Title title2 = UserManager.getInstance().createTitle("t2"); final Title title3 = UserManager.getInstance().createTitle("t3"); final Title title4 = UserManager.getInstance().createTitle("t4"); final AtomicBoolean listenerHasBeenCalled = new AtomicBoolean(false); final InvalidationListener listener = new InvalidationListener() { @Override//from ww w . j a v a2s .c o m public void keyInvalidated(final Object[] key, final int invalidationType, final InvalidationTarget target, final RemoteInvalidationSource remoteSrc) { listenerHasBeenCalled.set(true); // change t1 here title1.setName("newOne"); } }; final InvalidationTopic topic = InvalidationManager.getInstance() .getInvalidationTopic(new Object[] { Cache.CACHEKEY_HJMP, Cache.CACHEKEY_ENTITY }); try { topic.addInvalidationListener(listener); final Transaction tx = Transaction.current(); tx.execute(new TransactionBody() { @Override public Object execute() throws Exception { title2.setName("foo"); title3.setName("foo"); title4.setName("foo"); return null; } }); assertEquals("foo", title2.getName()); assertEquals("foo", title3.getName()); assertEquals("foo", title4.getName()); assertEquals("newOne", title1.getName()); assertTrue(listenerHasBeenCalled.get()); } finally { topic.removeInvalidationListener(listener); } }
From source file:com.alibaba.wasp.master.FMaster.java
private boolean isAvailable(final byte[] rootTableName) throws IOException { final AtomicBoolean available = new AtomicBoolean(true); final AtomicInteger entityGroupCount = new AtomicInteger(0); MetaScannerVisitorBase visitor = new MetaScannerVisitorBase() { @Override//from www . j a v a 2 s.c o m public boolean processRow(Result rowResult) throws IOException { byte[] value = rowResult.getValue(FConstants.CATALOG_FAMILY, FConstants.EGINFO); EntityGroupInfo eginfo = EntityGroupInfo.parseFromOrNull(value); if (eginfo != null) { if (Bytes.equals(eginfo.getTableName(), rootTableName)) { value = rowResult.getValue(FConstants.CATALOG_FAMILY, FConstants.EGLOCATION); if (value == null) { available.set(false); return false; } entityGroupCount.incrementAndGet(); } } // Returning true means "keep scanning" return true; } }; FMetaScanner.metaScan(conf, visitor, rootTableName); return available.get() && (entityGroupCount.get() > 0); }