List of usage examples for java.util.concurrent Semaphore acquire
public void acquire() throws InterruptedException
From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java
@Test public void testHttpClientSupplierException() throws InterruptedException, IOException { final org.slf4j.Logger logger = Mockito.mock(org.slf4j.Logger.class); final Semaphore semaphore = new Semaphore(0); final ApacheHttpSinkEventHandler handler = Mockito.mock(ApacheHttpSinkEventHandler.class); final Sink sink = new ApacheHttpSink(new ApacheHttpSink.Builder() .setUri(URI.create("http://nohost.example.com" + PATH)).setEventHandler(handler), () -> { semaphore.release();// w w w . j av a 2 s . co m throw new IllegalStateException("Test Exception"); }, logger); final TsdEvent event = new TsdEvent(ANNOTATIONS, TEST_EMPTY_SERIALIZATION_TIMERS, TEST_EMPTY_SERIALIZATION_COUNTERS, TEST_EMPTY_SERIALIZATION_GAUGES); sink.record(event); semaphore.acquire(); // Assert that the runtime exception was captured Mockito.verify(logger, Mockito.timeout(1000)).error( Mockito.startsWith("MetricsSinkApacheHttpWorker failure"), Mockito.any(IllegalStateException.class)); // Request matcher final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH)) .withHeader("Content-Type", WireMock.equalTo("application/octet-stream")); // Assert that no data was sent _wireMockRule.verify(0, requestPattern); Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty()); // Verify no handler was invoked Mockito.verify(handler, Mockito.never()).attemptComplete(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyBoolean(), Mockito.any(Quantity.class)); }
From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java
/** * Called when the activity is first created. *///from www.j a va2 s . com @Override protected void onCreate(Bundle load) { try { super.onCreate(load); } catch (NullPointerException exceptions) { // Unrecoverable Google Maps V1 crash Toast.makeText(this, R.string.error_map_nullpointer, Toast.LENGTH_LONG); } setContentView(R.layout.map); Toolbar toolbar = (Toolbar) findViewById(R.id.support_actionbar); setSupportActionBar(toolbar); findViewById(R.id.mapScreen).setDrawingCacheEnabled(true); mUnits = new UnitsI18n(this); mLoggerServiceManager = new GPSLoggerServiceManager(); final Semaphore calulatorSemaphore = new Semaphore(0); Thread calulator = new Thread("OverlayCalculator") { @Override public void run() { Looper.prepare(); mHandler = new Handler(); calulatorSemaphore.release(); Looper.loop(); } }; calulator.start(); try { calulatorSemaphore.acquire(); } catch (InterruptedException e) { Log.e(this, "Failed waiting for a semaphore", e); } mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mMapView = (MapView) findViewById(R.id.myMapView); setupHardwareAcceleration(); mMylocation = new FixedMyLocationOverlay(this, mMapView); mMapView.setBuiltInZoomControls(true); mMapView.setClickable(true); TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04), (TextView) findViewById(R.id.speedview03), (TextView) findViewById(R.id.speedview02), (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) }; mSpeedtexts = speeds; mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed); mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude); mDistanceView = (TextView) findViewById(R.id.currentDistance); mFab = (FloatingActionButton) findViewById(R.id.tracking_control); createListeners(); if (load != null) { onRestoreInstanceState(load); } if (getIntent() != null) { handleIntentData(getIntent()); } }
From source file:com.impetus.ankush2.cassandra.deployer.CassandraDeployer.java
/** * Perform asynchronous operations nodes. * /*from w ww . j ava 2 s . c o m*/ * @param nodeList * {@link Collection} * @return <code>true</code>, if successful */ private boolean validate(Collection<String> nodeList) throws AnkushException { try { // Create semaphore to join threads final Semaphore semaphore = new Semaphore(nodeList.size()); for (final String host : nodeList) { final NodeConfig nodeConfig = clusterConfig.getNodes().get(host); semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { nodeConfig.setStatus(new CassandraValidator(clusterConfig, nodeConfig).validate()); if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodeList.size()); } catch (Exception e) { throw new AnkushException(getComponentName() + " validation failed."); } return AnkushUtils.getStatus(clusterConfig, nodeList); }
From source file:com.impetus.ankush2.cassandra.deployer.CassandraDeployer.java
@Override public boolean start(final ClusterConfig conf, Collection<String> nodes) { try {//from www.j a va 2 s . co m // Causing the thread to sleep for two minutes during add nodes case // to // update ring topology details if (this.clusterConfig.getState().equals(Constant.Cluster.State.ADD_NODE)) { // starting service on all newly added nodes for (final String host : nodes) { // setting cluster conf nodes status conf.getNodes().get(host).setStatus(startNode(host)); // Wait for two minutes try { logger.info("Waiting for two minutes...", getComponentName(), host); logger.debug("Wait for two minutes.", host); Thread.sleep(120000); } catch (InterruptedException e) { logger.debug(e.getMessage()); } } } else { final Semaphore semaphore = new Semaphore(nodes.size()); // starting service on each node in cluster for (final String host : nodes) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { // setting cluster conf nodes status conf.getNodes().get(host).setStatus(startNode(host)); if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodes.size()); } // Return false if any of the node is not deployed. return AnkushUtils.getStatus(conf.getNodes()); } catch (Exception e) { return addClusterError("Could not start " + getComponentName() + " services.", e); } }
From source file:com.impetus.ankush2.cassandra.deployer.CassandraDeployer.java
@Override public boolean stop(final ClusterConfig conf, Collection<String> nodes) { // Stop services only if cluster is not in REMOVING_NODES if (!conf.getState().equals(Constant.Cluster.State.REMOVE_NODE)) { final Semaphore semaphore = new Semaphore(nodes.size()); try {/* ww w. j a v a 2 s .c om*/ // stopping service on each of the cluster nodes for (final String host : nodes) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { conf.getNodes().get(host).setStatus(stopNode(host)); if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodes.size()); } catch (Exception e) { logger.error(e.getMessage()); } } return true; }
From source file:com.impetus.ankush2.ganglia.GangliaDeployer.java
@Override public boolean start(final ClusterConfig conf, Collection<String> nodes) { final Semaphore semaphore = new Semaphore(nodes.size()); String gangliaMaster = (String) advanceConf.get(GangliaConstants.ClusterProperties.GMETAD_HOST); try {/*from ww w. j av a 2 s . co m*/ // starting Ganglia master during deployment case if (newClusterConf == null) { // starting ganglia master first and then applying a 1 minute // sleep // before starting gmond if (!startGangliaMaster(gangliaMaster)) { return false; } } // starting service in each cluster node for (final String host : nodes) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { conf.getNodes().get(host).setStatus(startGmond(host)); if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodes.size()); } catch (Exception e) { logger.warn("There is some exception while stating " + getComponentName() + " services.", getComponentName(), e); } // Return false if any of the node service is not started. // return AnkushUtils.getStatus(conf.getNodes()); return true; }
From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java
@Test public void testPostFailure() throws InterruptedException { _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> { // Annotations Assert.assertEquals(0, r.getAnnotationsCount()); // Dimensions Assert.assertEquals(0, r.getDimensionsCount()); // Samples Assert.assertEquals(0, r.getTimersCount()); Assert.assertEquals(0, r.getCountersCount()); Assert.assertEquals(0, r.getGaugesCount()); })).willReturn(WireMock.aResponse().withStatus(400))); final AtomicBoolean assertionResult = new AtomicBoolean(false); final Semaphore semaphore = new Semaphore(0); final org.slf4j.Logger logger = Mockito.mock(org.slf4j.Logger.class); final Sink sink = new ApacheHttpSink( new ApacheHttpSink.Builder().setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)) .setEventHandler(new AttemptCompletedAssertionHandler(assertionResult, 1, 2, false, new CompletionHandler(semaphore))), logger);/*from w w w . java 2s. com*/ final TsdEvent event = new TsdEvent(ANNOTATIONS, TEST_EMPTY_SERIALIZATION_TIMERS, TEST_EMPTY_SERIALIZATION_COUNTERS, TEST_EMPTY_SERIALIZATION_GAUGES); sink.record(event); semaphore.acquire(); // Ensure expected handler was invoked Assert.assertTrue(assertionResult.get()); // Request matcher final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH)) .withHeader("Content-Type", WireMock.equalTo("application/octet-stream")); // Assert that data was sent _wireMockRule.verify(1, requestPattern); Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty()); // Assert that an IOException was captured Mockito.verify(logger) .error(Mockito.startsWith("Received failure response when sending metrics to HTTP endpoint; uri=")); }
From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java
@Test public void testEndpointNotAvailable() throws InterruptedException { _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> { // Annotations Assert.assertEquals(0, r.getAnnotationsCount()); // Dimensions Assert.assertEquals(0, r.getDimensionsCount()); // Samples Assert.assertEquals(0, r.getTimersCount()); Assert.assertEquals(0, r.getCountersCount()); Assert.assertEquals(0, r.getGaugesCount()); })).willReturn(WireMock.aResponse().withStatus(404))); final AtomicBoolean assertionResult = new AtomicBoolean(false); final Semaphore semaphore = new Semaphore(0); final org.slf4j.Logger logger = Mockito.mock(org.slf4j.Logger.class); final Sink sink = new ApacheHttpSink( new ApacheHttpSink.Builder().setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)) .setEventHandler(new AttemptCompletedAssertionHandler(assertionResult, 1, 2, false, new CompletionHandler(semaphore))), logger);// w w w.ja v a2 s . co m final TsdEvent event = new TsdEvent(ANNOTATIONS, TEST_EMPTY_SERIALIZATION_TIMERS, TEST_EMPTY_SERIALIZATION_COUNTERS, TEST_EMPTY_SERIALIZATION_GAUGES); sink.record(event); semaphore.acquire(); // Ensure expected handler was invoked Assert.assertTrue(assertionResult.get()); // Request matcher final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH)) .withHeader("Content-Type", WireMock.equalTo("application/octet-stream")); // Assert that data was sent _wireMockRule.verify(1, requestPattern); Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty()); // Assert that an IOException was captured Mockito.verify(logger).error( Mockito.startsWith("Encountered failure when sending metrics to HTTP endpoint; uri="), Mockito.any(RuntimeException.class)); }
From source file:org.ut.biolab.medsavant.client.plugin.AppController.java
/** * Try to load all JAR files in the given directory. *//*from w ww.j a v a2s. c o m*/ public void loadPlugins(File pluginsDir) { LOG.info("Loading plugins in " + pluginsDir.getAbsolutePath()); File[] files = pluginsDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".jar"); } }); for (File f : files) { try { addPlugin(f); } catch (PluginVersionException x) { LOG.warn(String.format("No compatible plugins found in %s.", f)); } } // Check to see if we have any outdated plugins. if (pluginErrors.size() > 0) { List<String> updated = new ArrayList<String>(); for (String s : pluginErrors.keySet()) { // Plugin is invalid, and we don't have a newer version. if (checkForPluginUpdate(s)) { updated.add(s); } } if (updated.size() > 0) { DialogUtils.displayMessage("Plugins Updated", String.format( "<html>The following plugins were updated to be compatible with MedSavant %s:<br><br><i>%s</i></html>", VersionSettings.getVersionString(), ClientMiscUtils.join(updated, ", "))); for (String s : updated) { pluginErrors.remove(s); } } if (pluginErrors.size() > 0) { StringBuilder errorStr = null; for (String s : pluginErrors.keySet()) { if (errorStr == null) { errorStr = new StringBuilder(); } else { errorStr.append("<br>"); } errorStr.append(s); errorStr.append(" "); errorStr.append(pluginErrors.get(s)); } if (errorStr != null) { // The following dialog will only report plugins which we can tell are faulty before calling loadPlugin(), typically // by checking the version in plugin.xml. // System.out.println("Showing dialog"); // JOptionPane.showMessageDialog(null, String.format("<html>The following plugins could not be loaded:<br><br><i>%s</i><br><br>They will not be available to MedSavant.</html>", errorStr),"Plugins Not Loaded", JOptionPane.ERROR_MESSAGE); DialogUtils.displayMessage("Apps Not Loaded", String.format( "<html>The following Apps could not be loaded:<br><br><i>%s</i><br><br>They will not be available to MedSavant.</html>", errorStr)); } } } Set<URL> jarURLs = new HashSet<URL>(); for (AppDescriptor desc : knownPlugins.values()) { try { if (!pluginErrors.containsKey(desc.getID())) { jarURLs.add(desc.getFile().toURI().toURL()); } } catch (MalformedURLException ignored) { } } if (jarURLs.size() > 0) { pluginLoader = new PluginLoader(jarURLs.toArray(new URL[0]), getClass().getClassLoader()); final Semaphore waitSem = new Semaphore(-knownPlugins.size() + 1); for (final AppDescriptor desc : knownPlugins.values()) { if (!pluginErrors.containsKey(desc.getID())) { new Thread("PluginLoader-" + desc) { @Override public void run() { try { loadPlugin(desc); waitSem.release(); } catch (Throwable x) { LOG.error(String.format("Unable to load %s.", desc.getName()), x); pluginErrors.put(desc.getID(), x.getClass().getName()); fireEvent(new PluginEvent(PluginEvent.Type.ERROR, desc.getID())); } } }.start(); } else { waitSem.release(); } } LOG.info("Waiting for Apps to load..."); try { waitSem.acquire(); } catch (InterruptedException ie) { LOG.error("Interrupted while waiting for apps to load"); } LOG.info("All Apps loaded."); waitSem.release(); } }
From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java
@Test public void testBatchesRequestsRespectsMax() throws InterruptedException { _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> { // Annotations Assert.assertEquals(0, r.getAnnotationsCount()); // Dimensions Assert.assertEquals(0, r.getDimensionsCount()); // Samples assertSample(r.getTimersList(), "timer", 7d); assertSample(r.getCountersList(), "counter", 8d); assertSample(r.getGaugesList(), "gauge", 9d); })).willReturn(WireMock.aResponse().withStatus(200))); final Semaphore semaphore = new Semaphore(-2); final Sink sink = new ApacheHttpSink.Builder() .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)).setMaxBatchSize(2) .setParallelism(1).setEmptyQueueInterval(Duration.ofMillis(1000)) .setEventHandler(new CompletionHandler(semaphore)).build(); final TsdEvent event = new TsdEvent(Collections.emptyMap(), createQuantityMap("timer", TsdQuantity.newInstance(7d, null)), createQuantityMap("counter", TsdQuantity.newInstance(8d, null)), createQuantityMap("gauge", TsdQuantity.newInstance(9d, null))); for (int x = 0; x < 5; x++) { sink.record(event);/*from w ww . ja v a 2 s . c o m*/ } semaphore.acquire(); // Request matcher final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH)) .withHeader("Content-Type", WireMock.equalTo("application/octet-stream")); // Assert that data was sent _wireMockRule.verify(3, requestPattern); Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty()); }