List of usage examples for java.util.concurrent.atomic AtomicBoolean get
public final boolean get()
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
@Test @Ignore/*www . j a v a 2 s . c o m*/ public void testReplicationQuorumLoss() throws Throwable { System.out.println("======================================"); System.out.println(" Start 2 ActiveMQ nodes."); System.out.println("======================================"); startBrokerAsync(createBrokerNode("node-1", port)); startBrokerAsync(createBrokerNode("node-2", port)); BrokerService master = waitForNextMaster(); System.out.println("======================================"); System.out.println(" Start the producer and consumer"); System.out.println("======================================"); final AtomicBoolean stopClients = new AtomicBoolean(false); final ArrayBlockingQueue<String> errors = new ArrayBlockingQueue<String>(100); final AtomicLong receivedCounter = new AtomicLong(); final AtomicLong sentCounter = new AtomicLong(); Thread producer = startFailoverClient("producer", new Client() { @Override public void execute(Connection connection) throws Exception { Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue("test")); long actual = 0; while (!stopClients.get()) { TextMessage msg = session.createTextMessage("Hello World"); msg.setLongProperty("id", actual++); producer.send(msg); sentCounter.incrementAndGet(); } } }); Thread consumer = startFailoverClient("consumer", new Client() { @Override public void execute(Connection connection) throws Exception { connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(session.createQueue("test")); long expected = 0; while (!stopClients.get()) { Message msg = consumer.receive(200); if (msg != null) { long actual = msg.getLongProperty("id"); if (actual != expected) { errors.offer("Received got unexpected msg id: " + actual + ", expected: " + expected); } msg.acknowledge(); expected = actual + 1; receivedCounter.incrementAndGet(); } } } }); try { assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS); assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS); assertNull(errors.poll()); System.out.println("======================================"); System.out.println(" Master should stop once the quorum is lost."); System.out.println("======================================"); ArrayList<BrokerService> stopped = stopSlaves();// stopping the slaves should kill the quorum. assertStopsWithin(master, 10, TimeUnit.SECONDS); assertNull(errors.poll()); // clients should not see an error since they are failover clients. stopped.add(master); System.out.println("======================================"); System.out.println(" Restart the slave. Clients should make progress again.."); System.out.println("======================================"); startBrokersAsync(createBrokerNodes(stopped)); assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS); assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS); assertNull(errors.poll()); } catch (Throwable e) { e.printStackTrace(); throw e; } finally { // Wait for the clients to stop.. stopClients.set(true); producer.join(); consumer.join(); } }
From source file:io.druid.segment.realtime.plumber.RealtimePlumberSchoolTest.java
@Test(timeout = 60000) public void testPersistFails() throws Exception { final AtomicBoolean committed = new AtomicBoolean(false); plumber.getSinks().put(0L, new Sink(new Interval(0, TimeUnit.HOURS.toMillis(1)), schema, tuningConfig, new DateTime("2014-12-01T12:34:56.789").toString())); plumber.startJob();/* ww w . j av a 2 s . c om*/ final InputRow row = EasyMock.createNiceMock(InputRow.class); EasyMock.expect(row.getTimestampFromEpoch()).andReturn(0L); EasyMock.expect(row.getDimensions()).andReturn(new ArrayList<String>()); EasyMock.replay(row); plumber.add(row, Committers.supplierOf(Committers.nil())); plumber.persist(Committers.supplierFromRunnable(new Runnable() { @Override public void run() { committed.set(true); throw new RuntimeException(); } }).get()); while (!committed.get()) { Thread.sleep(100); } // Exception may need time to propagate while (metrics.failedPersists() < 1) { Thread.sleep(100); } Assert.assertEquals(1, metrics.failedPersists()); }
From source file:com.jayway.restassured.path.xml.XmlPathObjectDeserializationTest.java
@Test public void xml_path_supports_custom_deserializer_using_static_configuration() { // Given// w w w .j a v a 2 s . c o m final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false); XmlPath.config = xmlPathConfig().defaultObjectDeserializer(new XmlPathObjectDeserializer() { public <T> T deserialize(ObjectDeserializationContext ctx) { customDeserializerUsed.set(true); final String xml = ctx.getDataToDeserialize().asString(); final Greeting greeting = new Greeting(); greeting.setFirstName(StringUtils.substringBetween(xml, "<firstName>", "</firstName>")); greeting.setLastName(StringUtils.substringBetween(xml, "<lastName>", "</lastName>")); return (T) greeting; } }); // When try { final XmlPath xmlPath = new XmlPath(COOL_GREETING); final Greeting greeting = xmlPath.getObject("", Greeting.class); // Then assertThat(greeting.getFirstName(), equalTo("John")); assertThat(greeting.getLastName(), equalTo("Doe")); assertThat(customDeserializerUsed.get(), is(true)); } finally { XmlPath.reset(); } }
From source file:brooklyn.networking.cloudstack.legacy.LegacyJcloudsCloudstackSubnetLocation.java
@Override protected JcloudsSshMachineLocation createJcloudsSshMachineLocation(ComputeService computeService, NodeMetadata node, Optional<Template> template, LoginCredentials userCredentials, HostAndPort managementHostAndPort, ConfigBag setup) throws IOException { String subnetSpecificHostname = null; String vmHostname = managementHostAndPort.getHostText(); String sshHost = vmHostname;/*from ww w . jav a2 s.c o m*/ Integer sshPort = null; PortForwardManager pfw = null; String publicIpId = null; final String serviceNetworkId = getConfig(CLOUDSTACK_SERVICE_NETWORK_ID); boolean portForwardingMode = Strings.isBlank(serviceNetworkId); LOG.debug("creating subnet JcloudsSshMachineLocation -- port forwarding={}, node={}", new Object[] { node, portForwardingMode }); if (!portForwardingMode) { LOG.debug( "Using service network for Brooklyn access - service network ID is {} - searching for NIC connected to this network", serviceNetworkId); CloudStackApi cloudStackApi = getComputeService().getContext().unwrapApi(CloudStackApi.class); VirtualMachineApi vmClient = cloudStackApi.getVirtualMachineApi(); VirtualMachine vm = vmClient.getVirtualMachine(node.getProviderId()); Iterable<NIC> allNics = vm.getNICs(); Predicate<NIC> isServiceNetwork = new Predicate<NIC>() { @Override public boolean apply(@Nullable NIC input) { return input != null && serviceNetworkId.equals(input.getNetworkId()); } }; Optional<NIC> serviceNic = Iterables.tryFind(allNics, isServiceNetwork); Iterable<NIC> otherNics = Iterables.filter(allNics, Predicates.not(isServiceNetwork)); checkState(serviceNic.isPresent(), "unable to identify NIC connected to service network " + serviceNetworkId); String ipAddress = serviceNic.get().getIPAddress(); checkState(Strings.isNonBlank(ipAddress), "no IP address on the NIC connected to service network " + serviceNetworkId); checkState(!Iterables.isEmpty(otherNics), "VM needs another NIC, in addition to the service network"); // NIC anotherNic = Iterables.get(otherNics, 0); sshHost = ipAddress; sshPort = 22; } else { pfw = getRequiredConfig(PORT_FORWARDING_MANAGER); publicIpId = getRequiredConfig(CLOUDSTACK_TIER_PUBLIC_IP_ID); Cidr cidr = getConfig(MANAGEMENT_ACCESS_CIDR); // others, besides 22! int privatePort = 22; int publicPort = pfw.acquirePublicPort(publicIpId); systemCreatePortForwarding(cidr, publicPort, node, privatePort); sshPort = publicPort; sshHost = checkNotNull(pfw.getPublicIpHostname(publicIpId), "No ip recorded for id %s", publicIpId); } LOG.info("Created VM in " + this + " in subnet at " + node + ", ssh accessible via " + sshHost + ":" + sshPort); // and wait for it to be reachable LOG.debug(" waiting for new VM " + node + " in " + this + " to be port reachable on " + sshHost + ":" + sshPort); boolean isReachable = NetworkMultiAddressUtils2.isAccessible(sshHost, sshPort, TimeUnit.MINUTES.toMillis(15)); if (!isReachable) { throw new IllegalStateException("Unable to contact forwarded SSH port for new VM " + node + " in " + this + " on " + sshHost + ":" + sshPort); } if (!NetworkMultiAddressUtils2.isResolveable(vmHostname)) { String oldHostname = vmHostname; vmHostname = Iterables.getFirst(Iterables.concat(node.getPublicAddresses(), node.getPrivateAddresses()), null); LOG.info("Renaming unresolvable hostname " + oldHostname + " to " + vmHostname); } // "public hostname" might be different // - sometimes it is not pingable from brooklyn (making sensors hard) // - sometimes furthest is the public one, we might want it // (eg if we are in different 10.x subnet - closest not always accessible) // or we might want nearest (if public is not accessible); // and also consider we are on /16 subnet with host, host has another 10.x/8 address, but no public address; // ie furthest might be inaccessible for other reasons // TODO i think the "right" way to do this is to have a pluggable "address chooser" ? LOG.debug(" vmHostname: " + vmHostname); // supply forwarded host and port Map<String, Object> sshConfig = extractSshConfig(setup, node); sshConfig.put(SshMachineLocation.SSH_HOST.getName(), sshHost); if (sshPort != null) sshConfig.put(SshMachineLocation.SSH_PORT.getName(), sshPort); if (LOG.isDebugEnabled()) { LOG.debug( "creating JcloudsSshMachineLocation in subnet {}, service network {}, for {}@{} for {} with {}", new Object[] { getRequiredConfig(CLOUDSTACK_SUBNET_NETWORK_ID), getConfig(CLOUDSTACK_SERVICE_NETWORK_ID), userCredentials.getUser(), vmHostname, setup.getDescription(), Sanitizer.sanitize(sshConfig) }); } final JcloudsSshMachineLocation l = new AbstractJcloudsSubnetSshMachineLocation( MutableMap.builder().put("address", Networking.getInetAddressWithFixedName(vmHostname)) .put("displayName", vmHostname).put("user", userCredentials.getUser()) // don't think "config" does anything .putAll(sshConfig).put("config", sshConfig).put("jcloudsParent", this) .put(SshMachineLocation.PASSWORD, userCredentials.getOptionalPassword().orNull()) .put(SshMachineLocation.PRIVATE_KEY_DATA, userCredentials.getOptionalPrivateKey().orNull()) .put("node", node).put("template", template.orNull()).put("port", sshPort) .put(CALLER_CONTEXT, setup.get(CALLER_CONTEXT)).build(), this, node) { @Override public HostAndPort getSocketEndpointFor(Cidr accessor, int privatePort) { return getPortForwardingTo(accessor, this, privatePort); } }; l.init(); getManagementContext().getLocationManager().manage(l); l.config().set(SUBNET_HOSTNAME_CONFIG, subnetSpecificHostname); l.config().set(VM_IDENTIFIER, node.getId()); if (portForwardingMode) { // record port 22 forwarding pfw.associate(publicIpId, sshPort, l, 22); } LOG.debug(" waiting for new VM {} in {} to be SSH reachable on {}:{}", new Object[] { node, this, sshHost, sshPort }); final AtomicBoolean isActive = new AtomicBoolean(false); Repeater.create().repeat(new Runnable() { @Override public void run() { try { int rc = l.execCommands("test accessibility", ImmutableList.of("hostname")); isActive.set(rc == 0); } catch (Throwable t) { isActive.set(false); } } }).every(Duration.FIVE_SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return isActive.get(); } }).limitTimeTo(Duration.FIVE_MINUTES).run(); LOG.debug(" waited for new VM {} in {} to be SSH reachable on {}:{}, result={}", new Object[] { node, this, sshHost, sshPort, isActive.get() }); OperatingSystem operatingSystem = l.getNode().getOperatingSystem(); if (operatingSystem != null) { OsFamily family = operatingSystem.getFamily(); LOG.info("VM {}: OS family is {}", new Object[] { node, family }); if (family != OsFamily.WINDOWS && family != OsFamily.UNRECOGNIZED) { LOG.warn("VM {}: disabling iptables", new Object[] { node }); l.execScript(MutableMap.of(SshTool.PROP_ALLOCATE_PTY.getName(), true), "disabling requiretty", Arrays.asList(BashCommands.dontRequireTtyForSudo())); l.execScript("disabling iptables", Arrays.asList("sudo /etc/init.d/iptables stop", "sudo chkconfig iptables off")); } else { LOG.warn("VM {}: NOT disabling iptables because OS family is {}", new Object[] { node, family }); } } else { LOG.warn("VM {}: NOT disabling iptables because OS is not detected", new Object[] { node }); } String setupScript = setup.get(JcloudsLocationConfig.CUSTOM_MACHINE_SETUP_SCRIPT_URL); if (Strings.isNonBlank(setupScript)) { String setupVarsString = setup.get(JcloudsLocationConfig.CUSTOM_MACHINE_SETUP_SCRIPT_VARS); Map<String, String> substitutions = (setupVarsString != null) ? Splitter.on(",").withKeyValueSeparator(":").split(setupVarsString) : ImmutableMap.<String, String>of(); String scriptContent = ResourceUtils.create(this).getResourceAsString(setupScript); String script = TemplateProcessor.processTemplateContents(scriptContent, substitutions); l.execScript(MutableMap.of(SshTool.PROP_ALLOCATE_PTY.getName(), true), "disabling requiretty", Arrays.asList(BashCommands.dontRequireTtyForSudo())); l.execCommands("Customizing node " + this, ImmutableList.of(script)); } return l; }
From source file:org.piraso.server.service.ResponseLoggerServiceImplTest.java
@Test public void testWaitAndStop() throws Exception { final AtomicBoolean fail = new AtomicBoolean(false); ExecutorService executor = Executors.newFixedThreadPool(2); Runnable startServiceRunnable = new Runnable() { public void run() { try { service.start();/* w ww.j a v a2 s. c o m*/ } catch (Exception e) { fail.set(true); e.printStackTrace(); } } }; Runnable logMessagesRunnable = new Runnable() { public void run() { try { service.stopAndWait(3000l); } catch (Exception e) { fail.set(true); e.printStackTrace(); } } }; Future future = executor.submit(startServiceRunnable); executor.submit(logMessagesRunnable); future.get(); executor.shutdown(); if (fail.get()) { fail("failure see exception trace."); } // no harm invoking it again service.stopAndWait(1000l); assertFalse(service.isAlive()); }
From source file:io.restassured.path.xml.XmlPathObjectDeserializationTest.java
@Test public void xml_path_supports_custom_deserializer_using_static_configuration() { // Given/*from w ww . j a v a 2 s.c o m*/ final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false); XmlPath.config = XmlPathConfig.xmlPathConfig().defaultObjectDeserializer(new XmlPathObjectDeserializer() { public <T> T deserialize(ObjectDeserializationContext ctx) { customDeserializerUsed.set(true); final String xml = ctx.getDataToDeserialize().asString(); final Greeting greeting = new Greeting(); greeting.setFirstName(StringUtils.substringBetween(xml, "<firstName>", "</firstName>")); greeting.setLastName(StringUtils.substringBetween(xml, "<lastName>", "</lastName>")); return (T) greeting; } }); // When try { final XmlPath xmlPath = new XmlPath(COOL_GREETING); final Greeting greeting = xmlPath.getObject("", Greeting.class); // Then assertThat(greeting.getFirstName(), equalTo("John")); assertThat(greeting.getLastName(), equalTo("Doe")); assertThat(customDeserializerUsed.get(), is(true)); } finally { XmlPath.reset(); } }
From source file:com.jayway.restassured.path.xml.XmlPathObjectDeserializationTest.java
@Test public void xml_path_supports_custom_deserializer() { // Given/*from w w w . jav a2 s . c om*/ final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false); final XmlPath xmlPath = new XmlPath(COOL_GREETING) .using(xmlPathConfig().defaultObjectDeserializer(new XmlPathObjectDeserializer() { public <T> T deserialize(ObjectDeserializationContext ctx) { customDeserializerUsed.set(true); final String xml = ctx.getDataToDeserialize().asString(); final Greeting greeting = new Greeting(); greeting.setFirstName(StringUtils.substringBetween(xml, "<firstName>", "</firstName>")); greeting.setLastName(StringUtils.substringBetween(xml, "<lastName>", "</lastName>")); return (T) greeting; } })); // When final Greeting greeting = xmlPath.getObject("", Greeting.class); // Then assertThat(greeting.getFirstName(), equalTo("John")); assertThat(greeting.getLastName(), equalTo("Doe")); assertThat(customDeserializerUsed.get(), is(true)); }
From source file:org.apache.hadoop.hbase.master.procedure.TestMasterProcedureScheduler.java
@Test public void testConcurrentCreateDelete() throws Exception { final MasterProcedureScheduler procQueue = queue; final TableName table = TableName.valueOf("testtb"); final AtomicBoolean running = new AtomicBoolean(true); final AtomicBoolean failure = new AtomicBoolean(false); Thread createThread = new Thread() { @Override/*from ww w . j a va2 s . co m*/ public void run() { try { TestTableProcedure proc = new TestTableProcedure(1, table, TableProcedureInterface.TableOperationType.CREATE); while (running.get() && !failure.get()) { if (procQueue.tryAcquireTableExclusiveLock(proc, table)) { procQueue.releaseTableExclusiveLock(proc, table); } } } catch (Throwable e) { LOG.error("create failed", e); failure.set(true); } } }; Thread deleteThread = new Thread() { @Override public void run() { try { TestTableProcedure proc = new TestTableProcedure(2, table, TableProcedureInterface.TableOperationType.DELETE); while (running.get() && !failure.get()) { if (procQueue.tryAcquireTableExclusiveLock(proc, table)) { procQueue.releaseTableExclusiveLock(proc, table); } procQueue.markTableAsDeleted(table); } } catch (Throwable e) { LOG.error("delete failed", e); failure.set(true); } } }; createThread.start(); deleteThread.start(); for (int i = 0; i < 100 && running.get() && !failure.get(); ++i) { Thread.sleep(100); } running.set(false); createThread.join(); deleteThread.join(); assertEquals(false, failure.get()); }
From source file:net.dempsy.container.TestContainer.java
@Test public void testEvictableWithBusyMp() throws Throwable { final TestProcessor mp = createAndGet("foo"); // 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 final TestAdaptor adaptor = context.getBean(TestAdaptor.class); adaptor.dispatcher.dispatchAnnotated(new ContainerTestMessage("foo")); final TestProcessor prototype = context.getBean(TestProcessor.class); // keep track of the cloneCount for later checking final int tmpCloneCount = prototype.cloneCount.intValue(); // invocation count should go to 2 assertTrue(poll(mp, o -> o.invocationCount == 2)); // 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 final Thread thread = new Thread(new Runnable() { @Override/*from ww w . ja v a 2s.c o m*/ public void run() { container.evict(); evictIsComplete.set(true); } }); thread.start(); // now check to make sure eviction doesn't complete. Thread.sleep(100); // 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(poll(evictIsComplete, o -> o.get())); Thread.sleep(100); assertEquals("activation count, 2nd message", 1, mp.activationCount); assertEquals("invocation count, 2nd message", 2, mp.invocationCount); adaptor.dispatcher.dispatchAnnotated(new ContainerTestMessage("foo")); assertTrue(poll(o -> prototype.cloneCount.intValue() > tmpCloneCount)); Thread.sleep(1000); assertEquals("Clone count, 2nd message", tmpCloneCount + 1, prototype.cloneCount.intValue()); }
From source file:io.restassured.path.xml.XmlPathObjectDeserializationTest.java
@Test public void xml_path_supports_custom_deserializer() { // Given/*from w ww .jav a 2s. co m*/ final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false); final XmlPath xmlPath = new XmlPath(COOL_GREETING) .using(XmlPathConfig.xmlPathConfig().defaultObjectDeserializer(new XmlPathObjectDeserializer() { public <T> T deserialize(ObjectDeserializationContext ctx) { customDeserializerUsed.set(true); final String xml = ctx.getDataToDeserialize().asString(); final Greeting greeting = new Greeting(); greeting.setFirstName(StringUtils.substringBetween(xml, "<firstName>", "</firstName>")); greeting.setLastName(StringUtils.substringBetween(xml, "<lastName>", "</lastName>")); return (T) greeting; } })); // When final Greeting greeting = xmlPath.getObject("", Greeting.class); // Then assertThat(greeting.getFirstName(), equalTo("John")); assertThat(greeting.getLastName(), equalTo("Doe")); assertThat(customDeserializerUsed.get(), is(true)); }