List of usage examples for java.util.concurrent.atomic AtomicBoolean get
public final boolean get()
From source file:de.dal33t.powerfolder.test.transfer.BandwidthLimitText.java
public void testBandwidthStats() { BandwidthLimiter bl = BandwidthLimiter.LAN_INPUT_BANDWIDTH_LIMITER; bl.setAvailable(0);/*ww w . j ava2 s . c o m*/ provider.start(); provider.setLimitBPS(bl, 1000); final AtomicBoolean gotStat = new AtomicBoolean(); BandwidthStatsListener listener = new BandwidthStatsListener() { public void handleBandwidthStat(BandwidthStat stat) { System.out.println("Got a stat..."); gotStat.set(true); } public boolean fireInEventDispatchThread() { return false; } }; provider.addBandwidthStatListener(listener); try { Thread.sleep(2000); } catch (InterruptedException e) { fail(e.toString()); } provider.removeLimiter(bl); provider.shutdown(); assertTrue("Failed to get any stats?", gotStat.get()); }
From source file:de.taimos.pipeline.aws.cloudformation.EventPrinter.java
public void waitAndPrintStackEvents(String stack, Waiter<DescribeStacksRequest> waiter) { Date startDate = new Date(); final AtomicBoolean done = new AtomicBoolean(false); waiter.runAsync(new WaiterParameters<>(new DescribeStacksRequest().withStackName(stack)), new WaiterHandler() { @Override// w w w . ja va 2s . c o m public void onWaitSuccess(AmazonWebServiceRequest request) { done.set(true); } @Override public void onWaitFailure(Exception e) { done.set(true); } }); String lastEventId = null; this.printLine(); this.printStackName(stack); this.printLine(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); while (!done.get()) { try { DescribeStackEventsResult result = this.client .describeStackEvents(new DescribeStackEventsRequest().withStackName(stack)); List<StackEvent> stackEvents = new ArrayList<>(); for (StackEvent event : result.getStackEvents()) { if (event.getEventId().equals(lastEventId) || event.getTimestamp().before(startDate)) { break; } stackEvents.add(event); } if (!stackEvents.isEmpty()) { Collections.reverse(stackEvents); for (StackEvent event : stackEvents) { this.printEvent(sdf, event); this.printLine(); } lastEventId = stackEvents.get(stackEvents.size() - 1).getEventId(); } } catch (AmazonCloudFormationException e) { // suppress and continue } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
From source file:biz.ganttproject.impex.csv.CsvImportTest.java
public void testSkipUntilFirstHeader() throws IOException { String notHeader = "FOO, BAR, A"; String header = "A, B"; String data = "a1, b1"; final AtomicBoolean wasCalled = new AtomicBoolean(false); RecordGroup recordGroup = new RecordGroup("ABC", ImmutableSet.<String>of("A", "B")) { @Override//from w w w. j av a 2s. c o m protected boolean doProcess(CSVRecord record) { if (!super.doProcess(record)) { return false; } wasCalled.set(true); assertEquals("a1", record.get("A")); assertEquals("b1", record.get("B")); return true; } }; GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(notHeader, header, data)), recordGroup); importer.load(); assertTrue(wasCalled.get()); assertEquals(1, importer.getSkippedLineCount()); }
From source file:ch.cyberduck.core.cryptomator.impl.CryptoVaultTest.java
@Test public void testFind() throws Exception { final NullSession session = new NullSession(new Host(new TestProtocol())) { @Override//from w w w .j a v a 2 s. co m @SuppressWarnings("unchecked") public <T> T _getFeature(final Class<T> type) { if (type == Read.class) { return (T) new Read() { @Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final String masterKey = "{\n" + " \"scryptSalt\": \"NrC7QGG/ouc=\",\n" + " \"scryptCostParam\": 16384,\n" + " \"scryptBlockSize\": 8,\n" + " \"primaryMasterKey\": \"Q7pGo1l0jmZssoQh9rXFPKJE9NIXvPbL+HcnVSR9CHdkeR8AwgFtcw==\",\n" + " \"hmacMasterKey\": \"xzBqT4/7uEcQbhHFLC0YmMy4ykVKbuvJEA46p1Xm25mJNuTc20nCbw==\",\n" + " \"versionMac\": \"hlNr3dz/CmuVajhaiGyCem9lcVIUjDfSMLhjppcXOrM=\",\n" + " \"version\": 5\n" + "}"; return IOUtils.toInputStream(masterKey, Charset.defaultCharset()); } @Override public boolean offset(final Path file) throws BackgroundException { return false; } }; } return super._getFeature(type); } }; final Path home = new Path("/", EnumSet.of((Path.Type.directory))); final CryptoVault vault = new CryptoVault(home, new DisabledPasswordStore()); assertEquals(home, vault.load(session, new DisabledPasswordCallback() { @Override public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) throws LoginCanceledException { return new VaultCredentials("vault"); } }).getHome()); assertEquals(Vault.State.open, vault.getState()); final AtomicBoolean found = new AtomicBoolean(); assertEquals(vault, new DefaultVaultRegistry(new DisabledPasswordCallback()) { protected Vault find(final Session<?> session, final Path directory, final LoadingVaultLookupListener listener) throws VaultUnlockCancelException { found.set(true); return vault; } }.find(session, home)); assertTrue(found.get()); vault.close(); }
From source file:com.nokia.dempsy.container.TestMpContainer.java
@Test public void testEvictableWithBusyMp() throws Exception { // This forces the instantiation of an Mp inputQueue.add(serializer.serialize(new ContainerTestMessage("foo"))); // Once the poll finishes the Mp is instantiated and handling messages. assertNotNull(outputQueue.poll(baseTimeoutMillis, TimeUnit.MILLISECONDS)); assertEquals("did not create MP", 1, container.getProcessorCount()); TestProcessor mp = (TestProcessor) container.getMessageProcessor("foo"); assertNotNull("MP not associated with expected key", mp); assertEquals("activation count, 1st message", 1, mp.activationCount); assertEquals("invocation count, 1st message", 1, mp.invocationCount); // now we're going to cause the processing to be held up. mp.latch = new CountDownLatch(1); mp.evict.set(true); // allow eviction // sending it a message will now cause it to hang up while processing inputQueue.add(serializer.serialize(new ContainerTestMessage("foo"))); // keep track of the cloneCount for later checking int tmpCloneCount = TestProcessor.cloneCount.intValue(); // invocation count should go to 2 assertTrue(TestUtils.poll(baseTimeoutMillis, mp, new TestUtils.Condition<TestProcessor>() { @Override//from w w w .ja v a 2 s . c o m public boolean conditionMet(TestProcessor o) { return o.invocationCount == 2; } })); assertNull(outputQueue.peek()); // this is a double check that no message got all the way // now kick off the evict in a separate thread since we expect it to hang // until the mp becomes unstuck. final AtomicBoolean evictIsComplete = new AtomicBoolean(false); // this will allow us to see the evict pass complete Thread thread = new Thread(new Runnable() { @Override public void run() { container.evict(); evictIsComplete.set(true); } }); thread.start(); // now check to make sure eviction doesn't complete. Thread.sleep(50); // just a little to give any mistakes a change to work themselves through assertFalse(evictIsComplete.get()); // make sure eviction didn't finish mp.latch.countDown(); // this lets it go // wait until the eviction completes assertTrue(TestUtils.poll(baseTimeoutMillis, evictIsComplete, new TestUtils.Condition<AtomicBoolean>() { @Override public boolean conditionMet(AtomicBoolean o) { return o.get(); } })); // now it comes through. assertNotNull(outputQueue.poll(baseTimeoutMillis, TimeUnit.MILLISECONDS)); assertEquals("activation count, 2nd message", 1, mp.activationCount); assertEquals("invocation count, 2nd message", 2, mp.invocationCount); inputQueue.add(serializer.serialize(new ContainerTestMessage("foo"))); assertNotNull(outputQueue.poll(baseTimeoutMillis, TimeUnit.MILLISECONDS)); assertEquals("Clone count, 2nd message", tmpCloneCount + 1, TestProcessor.cloneCount.intValue()); }
From source file:org.lendingclub.mercator.docker.SwarmScanner.java
public void scanTasksForSwarm(String swarmClusterId) { logger.info("scanning tasks for swarm: {}", swarmClusterId); AtomicLong earlistUpdate = new AtomicLong(Long.MAX_VALUE); AtomicBoolean error = new AtomicBoolean(false); JsonNode response = getRestClient().getTasks(); response.forEach(it -> {/* ww w .j av a 2 s.c om*/ try { earlistUpdate.set(Math.min(earlistUpdate.get(), saveTask(it))); } catch (Exception e) { logger.warn("problem updating task", e); error.set(true); } }); if (error.get() == false) { if (earlistUpdate.get() < System.currentTimeMillis()) { dockerScanner.getNeoRxClient().execCypher( "match (x:DockerTask) where x.swarmClusterId={swarmClusterId} and x.updateTs<{cutoff} detach delete x", "cutoff", earlistUpdate.get(), "swarmClusterId", swarmClusterId); } } }
From source file:com.nesscomputing.jackson.datatype.TestCustomUuidModule.java
@Test public void testCustomUUIDSerialization() throws Exception { final AtomicBoolean called = new AtomicBoolean(false); ObjectMapper mapper = getObjectMapper(new AbstractModule() { @Override// w w w . j ava2s .c o m protected void configure() { bind(new TypeLiteral<JsonSerializer<UUID>>() { }).toInstance(new CustomUuidSerializer() { @Override public void serialize(UUID value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { called.set(true); super.serialize(value, jgen, provider); } }); } }); final UUID id = new UUID(9, 9); Assert.assertEquals('"' + id.toString() + '"', mapper.writeValueAsString(id)); Assert.assertTrue(called.get()); }
From source file:org.apache.hadoop.yarn.server.resourcemanager.TestApplicationMasterLauncher.java
@Test(timeout = 10000) public void testAMLaunchWithCryptoMaterial() throws Exception { conf.setBoolean(CommonConfigurationKeys.IPC_SERVER_SSL_ENABLED, true); conf.setBoolean(YarnConfiguration.RM_JWT_ENABLED, false); AtomicBoolean testPass = new AtomicBoolean(true); MockRM rm = new TestCryptoMockRM(conf, testPass); rm.start();//from w ww. ja v a2s . c o m MockNM nm = rm.registerNode("127.0.0.1:1337", 15 * 1024); RMApp app = rm.submitApp(1024); nm.nodeHeartbeat(true); RMAppAttempt appAttempt = app.getCurrentAppAttempt(); MockAM am = rm.sendAMLaunched(appAttempt.getAppAttemptId()); am.registerAppAttempt(true); nm.nodeHeartbeat(true); Assert.assertTrue(testPass.get()); rm.stop(); }
From source file:com.kixeye.chassis.support.test.hystrix.ChassisHystrixTest.java
@Test @SuppressWarnings("unused") public void testCommandTimeOut() throws InterruptedException { final AtomicBoolean done = new AtomicBoolean(false); // kick off async command Observable<String> observable = new TestTimeOutCommand().observe(); // Add handler observable.subscribe(new Observer<String>() { @Override// w w w .ja v a 2 s .com public void onCompleted() { Assert.assertNull("Should not complete"); done.set(true); } @Override public void onError(Throwable e) { done.set(true); } @Override public void onNext(String args) { Assert.assertNull("Should not get a result"); done.set(true); } }); // spin until done while (!done.get()) { Thread.sleep(100); } }
From source file:com.opinionlab.woa.WallOfAwesome.java
private static SockJSHandler makeEventStream(Vertx vertx) { final SockJSHandlerOptions options = new SockJSHandlerOptions().setHeartbeatInterval(2000); final SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options); sockJSHandler.socketHandler(socket -> { final AtomicInteger openCount = new AtomicInteger(); final AtomicBoolean running = new AtomicBoolean(true); LOGGER.info(format("[OPEN] Sockets: %d", openCount.incrementAndGet())); socket.endHandler(aVoid -> {// www. j av a 2 s . c o m running.set(false); LOGGER.info(format("[CLOSE] Sockets: %d", openCount.decrementAndGet())); }); socket.handler(buffer -> { String command = buffer.toString(); if ("purge".equals(command)) { EXECUTOR.execute(() -> { try { AwesomeImap.purge(s -> socket.write(buffer(objectToJson( HashTreePMap.empty().plus("deleted", true).plus("id", s.getId()), NO_TYPES)))); } catch (NoSuchProviderException e) { LOGGER.error("Could not purge messages", e); } }); } else { LOGGER.error(format("Unknown command: %s", command)); } }); try { final AtomicReference<Date> latestDate = new AtomicReference<>(new Date(0)); Consumer<Awesome> publishAwesome = awesome -> { socket.write(buffer(objectToJson(awesome, NO_TYPES))); final Date receivedDate = awesome.getReceivedDate(); if (latestDate.get().before(receivedDate)) { latestDate.set(receivedDate); } }; AwesomeImap.fetchAwesome().forEach(publishAwesome); EXECUTOR.execute(() -> { LOGGER.info("Polling started."); try { while (running.get()) { AwesomeImap.fetchAwesomeSince(latestDate.get()).forEach(publishAwesome); Thread.sleep(1000); } } catch (Throwable t) { running.set(false); socket.close(); LOGGER.error("Polling ended ABNORMALLY", t); } finally { LOGGER.info("Polling ended normally."); } }); } catch (MessagingException e) { LOGGER.error("Unable to fetch messages.", e); } }); return sockJSHandler; }