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 testHttpClientResponseException() throws InterruptedException, IOException { final CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class); final CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class); Mockito.doReturn(httpResponse).when(httpClient).execute(Mockito.any(HttpPost.class)); Mockito.doThrow(new NullPointerException("Throw by default")).when(httpResponse).getStatusLine(); final org.slf4j.Logger logger = Mockito.mock(org.slf4j.Logger.class); final Semaphore semaphore = new Semaphore(0); final Sink sink = new ApacheHttpSink( new ApacheHttpSink.Builder().setUri(URI.create("http://nohost.example.com" + PATH)) .setEventHandler(new CompletionHandler(semaphore)), () -> httpClient, logger); final TsdEvent event = new TsdEvent(ANNOTATIONS, TEST_EMPTY_SERIALIZATION_TIMERS, TEST_EMPTY_SERIALIZATION_COUNTERS, TEST_EMPTY_SERIALIZATION_GAUGES); sink.record(event);/*from w w w . ja v a2 s .c om*/ semaphore.acquire(); // Verify mocks Mockito.verify(httpClient).execute(Mockito.any(HttpPost.class)); Mockito.verifyNoMoreInteractions(httpClient); Mockito.verify(httpResponse).getStatusLine(); Mockito.verify(httpResponse).close(); Mockito.verifyNoMoreInteractions(httpResponse); // 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()); // Assert that the runtime exception was captured Mockito.verify(logger).error( Mockito.startsWith("Encountered failure when sending metrics to HTTP endpoint; uri="), Mockito.any(NullPointerException.class)); }
From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java
@Test public void testHttpClientResponseCloseException() throws InterruptedException, IOException { final CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class); final CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class); Mockito.doReturn(httpResponse).when(httpClient).execute(Mockito.any(HttpPost.class)); Mockito.doThrow(new NullPointerException("Throw by default")).when(httpResponse).getStatusLine(); Mockito.doThrow(new IllegalStateException("Throw by default")).when(httpResponse).close(); final org.slf4j.Logger logger = Mockito.mock(org.slf4j.Logger.class); final Semaphore semaphore = new Semaphore(0); final Sink sink = new ApacheHttpSink( new ApacheHttpSink.Builder().setUri(URI.create("http://nohost.example.com" + PATH)) .setEventHandler(new CompletionHandler(semaphore)), () -> httpClient, logger); final TsdEvent event = new TsdEvent(ANNOTATIONS, TEST_EMPTY_SERIALIZATION_TIMERS, TEST_EMPTY_SERIALIZATION_COUNTERS, TEST_EMPTY_SERIALIZATION_GAUGES); sink.record(event);/*from ww w. j ava 2 s . c om*/ semaphore.acquire(); // Verify mocks Mockito.verify(httpClient).execute(Mockito.any(HttpPost.class)); Mockito.verifyNoMoreInteractions(httpClient); Mockito.verify(httpResponse).getStatusLine(); Mockito.verify(httpResponse).close(); Mockito.verifyNoMoreInteractions(httpResponse); // 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()); // Assert that the runtime exception was captured Mockito.verify(logger).error( Mockito.startsWith("Encountered failure when sending metrics to HTTP endpoint; uri="), Mockito.any(NullPointerException.class)); Mockito.verifyNoMoreInteractions(logger); }
From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java
@Test public void testCustomUnit() 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", 8d); Assert.assertEquals(0, r.getCountersCount()); Assert.assertEquals(0, r.getGaugesCount()); })).willReturn(WireMock.aResponse().withStatus(200))); final Semaphore semaphore = new Semaphore(0); final Sink sink = new ApacheHttpSink.Builder() .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)) .setEventHandler(new CompletionHandler(semaphore)).build(); final TsdEvent event = new TsdEvent(Collections.emptyMap(), createQuantityMap("timer", TsdQuantity.newInstance(8d, () -> "Foo")), TEST_EMPTY_SERIALIZATION_COUNTERS, TEST_EMPTY_SERIALIZATION_GAUGES); sink.record(event);//w w w .jav a 2s . co 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(1, requestPattern); Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty()); }
From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java
@Test public void testNoUnits() 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(0); final Sink sink = new ApacheHttpSink.Builder() .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)) .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))); sink.record(event);/*from ww w. j av 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(1, requestPattern); Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty()); }
From source file:com.impetus.ankush2.cassandra.deployer.CassandraDeployer.java
/** * method to deploy Cassandra packages on all nodes * /* w w w .j av a 2 s . c o m*/ * @param conf * {@link ClusterConfig} * @param nodeMap * {@link Map} * * @return <code>true</code>, if successful * */ private boolean deployNodes(final ClusterConfig conf, Set<String> nodeMap) throws AnkushException { try { // Node Deployment process ... final Semaphore semaphore = new Semaphore(nodeMap.size()); for (final String host : nodeMap) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { conf.getNodes().get(host).setStatus(createNode(host)); if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodeMap.size()); } catch (Exception e) { throw new AnkushException("Could not deploy " + getComponentName(), e); } return AnkushUtils.getStatus(conf.getNodes()); }
From source file:com.impetus.ankush2.cassandra.deployer.CassandraDeployer.java
@Override public boolean register(final ClusterConfig conf) { try {// ww w . j a v a2 s. co m ComponentConfig compConfig = clusterConfig.getComponents().get(this.componentName); if (!AnkushUtils.isMonitoredByAnkush(compConfig)) { logger.info("Skipping " + getComponentName() + " registration for Level1", this.componentName); return true; } final String infoMsg = "Registering Cassandra"; logger.info(infoMsg); // Getting node map for cluster deployment Map<String, Map<String, Object>> nodeMap = new HashMap<String, Map<String, Object>>( componentConfig.getNodes()); // Node Registration process ... final Semaphore semaphore = new Semaphore(nodeMap.size()); for (final String host : nodeMap.keySet()) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { conf.getNodes().get(host).setStatus(registerNode(host)); if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodeMap.size()); // Return false if any of the node is not deployed. return AnkushUtils.getStatus(conf.getNodes()); } catch (Exception e) { return addClusterError("Could not register " + getComponentName(), e); } }
From source file:com.impetus.ankush2.cassandra.deployer.CassandraDeployer.java
@Override public boolean unregister(final ClusterConfig conf) { try {//from w w w .j av a2 s. com ComponentConfig compConfig = clusterConfig.getComponents().get(this.componentName); if (!AnkushUtils.isMonitoredByAnkush(compConfig)) { logger.info("Skipping " + getComponentName() + " unregistration for Level1", this.componentName); return true; } if (!setClassVariables(conf)) { return false; } final String infoMsg = "Unregistering Cassandra"; logger.info(infoMsg, getComponentName()); // Getting node map for cluster deployment Map<String, Map<String, Object>> nodeMap = new HashMap<String, Map<String, Object>>( componentConfig.getNodes()); // Node Registration process ... final Semaphore semaphore = new Semaphore(nodeMap.size()); for (final String host : nodeMap.keySet()) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { conf.getNodes().get(host).setStatus(unregisterNode(host)); if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodeMap.size()); // Return false if any of the node is not deployed. return AnkushUtils.getStatus(conf.getNodes()); } catch (AnkushException e) { return addClusterError(e.getMessage(), e); } catch (Exception e) { return addClusterError("Could not unregister " + getComponentName(), e); } }
From source file:com.impetus.ankush2.cassandra.deployer.CassandraDeployer.java
/** * Function to update topology information on all nodes in cluster after add * or remove nodes/*w ww. j a v a 2s . c o m*/ */ private void updateTopologyFile() { Map<String, Map<String, Object>> nodes = new HashMap<String, Map<String, Object>>( componentConfig.getNodes()); if (clusterConfig.getState().equals(Constant.Cluster.State.REMOVE_NODE)) { nodes = new HashMap<String, Map<String, Object>>(returnNodes()); } final Semaphore semaphore = new Semaphore(nodes.size()); try { for (final String host : nodes.keySet()) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { try { SSHExec connection = getConnection(host); if (connection != null) { editTopologyFile(connection, host); } } catch (AnkushException e) { addClusterError(e.getMessage(), host, e); } catch (Exception e) { addClusterError("Could not update topology details.", host, e); } if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodes.size()); } catch (Exception e) { logger.error("Error in updating topology file.", e); } }
From source file:com.impetus.ankush2.cassandra.deployer.CassandraDeployer.java
/** * Function to update seed node information after add or remove nodes on all * nodes in a cluster// ww w .j ava 2 s . c o m */ private void updateSeedNodeValue() { // Seeds update command String cassandraYaml = advanceConf.get(CassandraConstants.ClusterProperties.CONF_DIR) + CassandraConstants.Cassandra_Configuration_Files.CASSANDRA_YAML; final String command = "sed -i -e 's/- seeds: \".*$/- seeds: \"" + getSeedNodeString() + "\"/' " + cassandraYaml; Map<String, Map<String, Object>> nodes = new HashMap<String, Map<String, Object>>( componentConfig.getNodes()); if (clusterConfig.getState().equals(Constant.Cluster.State.REMOVE_NODE)) { nodes = new HashMap<String, Map<String, Object>>(returnNodes()); } final Semaphore semaphore = new Semaphore(nodes.size()); try { for (final String host : nodes.keySet()) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { try { SSHExec connection = getConnection(host); if (connection != null) { execCustomtask(command, connection, host, "Could not update seeds value"); } } catch (AnkushException e) { addClusterError(e.getMessage(), host, e); } catch (Exception e) { addClusterError("Could not update seed node value in cassandra.yaml file.", host, e); } if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodes.size()); } catch (Exception e) { logger.error("Error in editing seeds values.", e); } }
From source file:com.impetus.ankush2.cassandra.deployer.CassandraDeployer.java
@Override public boolean removeNode(final ClusterConfig conf, Collection<String> nodes) { logger.info("Deleting Cassandra packages...", getComponentName()); try {//from w ww . jav a 2 s . c om if (newClusterConf == null) { // setting clusterconf, componentconf and logger if (!setClassVariables(conf)) { return false; } } final Semaphore semaphore = new Semaphore(nodes.size()); // undeploying package from each node for (final String host : nodes) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { // setting nodestatus default value to false boolean nodestatus = false; // if service stopped successfully, then removing // component from node if (stopNode(host)) { nodestatus = removeNode(host); } conf.getNodes().get(host).setStatus(nodestatus); if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodes.size()); return AnkushUtils.getStatus(conf.getNodes()); } catch (Exception e) { return addClusterError("Could not remove " + getComponentName(), e); } }