List of usage examples for java.util.concurrent Semaphore Semaphore
public Semaphore(int permits)
From source file:org.artifactory.addon.CoreAddonsImpl.java
@Override public SemaphoreWrapper getSemaphore(String semaphoreName) { Semaphore semaphore = new Semaphore(HaCommonAddon.DEFAULT_SEMAPHORE_PERMITS); return new JVMSemaphoreWrapper(semaphore); }
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 w w w . ja v a 2 s . co m 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:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java
@Test public void testNetSingleUseWithInbound() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();/*from w w w.ja v a2s . co m*/ for (int i = 1; i < 3; i++) { Socket socket = server.accept(); semaphore.release(); byte[] b = new byte[6]; readFully(socket.getInputStream(), b); b = ("Reply" + i + "\r\n").getBytes(); socket.getOutputStream().write(b); socket.close(); } server.close(); } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(10000); ccf.start(); ccf.setSingleUse(true); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(ccf); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS)); Set<String> replies = new HashSet<String>(); for (int i = 0; i < 2; i++) { Message<?> mOut = channel.receive(10000); assertNotNull(mOut); replies.add(new String((byte[]) mOut.getPayload())); } assertTrue(replies.remove("Reply1")); assertTrue(replies.remove("Reply2")); done.set(true); ccf.stop(); }
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 a v a2 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:com.parse.ParsePushTest.java
@Test public void testSendDataInBackgroundWithCallback() throws Exception { // Mock controller ParsePushController controller = mock(ParsePushController.class); when(controller.sendInBackground(any(ParsePush.State.class), anyString())) .thenReturn(Task.<Void>forResult(null)); ParseCorePlugins.getInstance().registerPushController(controller); // Make sample ParsePush data and call method JSONObject data = new JSONObject(); data.put("key", "value"); data.put("keyAgain", "valueAgain"); ParseQuery<ParseInstallation> query = ParseInstallation.getQuery(); query.getBuilder().whereEqualTo("foo", "bar"); final Semaphore done = new Semaphore(0); final Capture<Exception> exceptionCapture = new Capture<>(); ParsePush.sendDataInBackground(data, query, new SendCallback() { @Override/*from ww w. j a va 2s. c om*/ public void done(ParseException e) { exceptionCapture.set(e); done.release(); } }); // Make sure controller is executed and state parameter is correct assertNull(exceptionCapture.get()); assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS)); ArgumentCaptor<ParsePush.State> stateCaptor = ArgumentCaptor.forClass(ParsePush.State.class); verify(controller, times(1)).sendInBackground(stateCaptor.capture(), anyString()); ParsePush.State state = stateCaptor.getValue(); // Verify query state ParseQuery.State<ParseInstallation> queryState = state.queryState(); JSONObject queryStateJson = queryState.toJSON(PointerEncoder.get()); assertEquals("bar", queryStateJson.getJSONObject("where").getString("foo")); // Verify data assertEquals(data, state.data(), JSONCompareMode.NON_EXTENSIBLE); }
From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java
@Test public void testNioSingleUseWithInbound() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();/*from w w w.j av a2s . c o m*/ for (int i = 1; i < 3; i++) { Socket socket = server.accept(); semaphore.release(); byte[] b = new byte[6]; readFully(socket.getInputStream(), b); b = ("Reply" + i + "\r\n").getBytes(); socket.getOutputStream().write(b); socket.close(); } server.close(); } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(10000); ccf.start(); ccf.setSingleUse(true); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(ccf); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS)); Set<String> replies = new HashSet<String>(); for (int i = 0; i < 2; i++) { Message<?> mOut = channel.receive(10000); assertNotNull(mOut); replies.add(new String((byte[]) mOut.getPayload())); } assertTrue(replies.remove("Reply1")); assertTrue(replies.remove("Reply2")); done.set(true); ccf.stop(); }
From source file:org.apache.solr.request.SimpleFacets.java
License:asdf
/** * Returns a list of value constraints and the associated facet counts * for each facet field specified in the params. * * @see FacetParams#FACET_FIELD//from w w w . ja v a 2s . c o m * @see #getFieldMissingCount * @see #getFacetTermEnumCounts */ @SuppressWarnings("unchecked") public NamedList<Object> getFacetFieldCounts() throws IOException, SyntaxError { NamedList<Object> res = new SimpleOrderedMap<>(); String[] facetFs = global.getParams(FacetParams.FACET_FIELD); if (null == facetFs) { return res; } // Passing a negative number for FACET_THREADS implies an unlimited number of threads is acceptable. // Also, a subtlety of directExecutor is that no matter how many times you "submit" a job, it's really // just a method call in that it's run by the calling thread. int maxThreads = req.getParams().getInt(FacetParams.FACET_THREADS, 0); Executor executor = maxThreads == 0 ? directExecutor : facetExecutor; final Semaphore semaphore = new Semaphore((maxThreads <= 0) ? Integer.MAX_VALUE : maxThreads); List<Future<NamedList>> futures = new ArrayList<>(facetFs.length); if (fdebugParent != null) { fdebugParent.putInfoItem("maxThreads", maxThreads); } try { //Loop over fields; submit to executor, keeping the future for (String f : facetFs) { if (fdebugParent != null) { fdebug = new FacetDebugInfo(); fdebugParent.addChild(fdebug); } final ParsedParams parsed = parseParams(FacetParams.FACET_FIELD, f); final SolrParams localParams = parsed.localParams; final String termList = localParams == null ? null : localParams.get(CommonParams.TERMS); final String key = parsed.key; final String facetValue = parsed.facetValue; Callable<NamedList> callable = () -> { try { NamedList<Object> result = new SimpleOrderedMap<>(); if (termList != null) { List<String> terms = StrUtils.splitSmart(termList, ",", true); result.add(key, getListedTermCounts(facetValue, parsed, terms)); } else { result.add(key, getTermCounts(facetValue, parsed)); } return result; } catch (SolrException se) { throw se; } catch (Exception e) { throw new SolrException(ErrorCode.SERVER_ERROR, "Exception during facet.field: " + facetValue, e); } finally { semaphore.release(); } }; RunnableFuture<NamedList> runnableFuture = new FutureTask<>(callable); semaphore.acquire();//may block and/or interrupt executor.execute(runnableFuture);//releases semaphore when done futures.add(runnableFuture); } //facetFs loop //Loop over futures to get the values. The order is the same as facetFs but shouldn't matter. for (Future<NamedList> future : futures) { res.addAll(future.get()); } assert semaphore.availablePermits() >= maxThreads; } catch (InterruptedException e) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error while processing facet fields: InterruptedException", e); } catch (ExecutionException ee) { Throwable e = ee.getCause();//unwrap if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error while processing facet fields: " + e.toString(), e); } return res; }
From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java
@Test public void testStop() throws InterruptedException { _wireMockRule// w ww . j a v a2 s. c om .stubFor(WireMock.post(WireMock.urlEqualTo(PATH)).willReturn(WireMock.aResponse().withStatus(200))); final Semaphore semaphore = new Semaphore(0); @SuppressWarnings("unchecked") final ApacheHttpSink sink = (ApacheHttpSink) new ApacheHttpSink.Builder() .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)) .setEventHandler(new CompletionHandler(semaphore)).build(); final Map<String, String> annotations = new LinkedHashMap<>(); annotations.put("foo", "bar"); annotations.put("_start", Instant.now().minusMillis(812).atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_INSTANT)); annotations.put("_end", Instant.now().atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_INSTANT)); annotations.put("_host", "some.host.com"); annotations.put("_service", "myservice"); annotations.put("_cluster", "mycluster"); annotations.put("_id", UUID.randomUUID().toString()); final TsdEvent event = new TsdEvent(annotations, createQuantityMap("timer", TsdQuantity.newInstance(123, Units.NANOSECOND)), createQuantityMap("counter", TsdQuantity.newInstance(8, null)), createQuantityMap("gauge", TsdQuantity.newInstance(10, Units.BYTE))); sink.stop(); Thread.sleep(1000); sink.record(event); Assert.assertFalse(semaphore.tryAcquire(1, TimeUnit.SECONDS)); // 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(0, requestPattern); Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty()); }
From source file:fur.shadowdrake.minecraft.InstallPanel.java
private List<String> fetchUpdateInstructions(Pack pack) throws NetworkException { final Semaphore semaphore = new Semaphore(0); final StringBuffer sb = new StringBuffer(); while (true) { result = ftpClient.openDataChannel((ActionEvent e) -> { if (e.getID() == FtpClient.FTP_OK) { try { InputStreamReader isr; int n; char[] buffer = new char[4096]; isr = new InputStreamReader(((Socket) e.getSource()).getInputStream()); while (true) { n = isr.read(buffer); if (n < 0) { break; }/*from ww w. j av a 2 s . co m*/ sb.append(buffer, 0, n); } } catch (IOException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, "Download", ex); log.println("Faild to save file."); ftpClient.closeDataChannel(); } } }); switch (result) { case FtpClient.FTP_OK: int status = ftpClient.uins(pack, (ActionEvent e) -> { ftpClient.closeDataChannel(); semaphore.release(); }); switch (status) { case FtpClient.FTP_OK: try { semaphore.acquire(); } catch (InterruptedException ex) { return null; } break; case FtpClient.FTP_NODATA: log.println("Oops! Server's complaining about missing data channel, although I've opened it."); ftpClient.abandonDataChannel(); return null; default: ftpClient.abandonDataChannel(); return null; } break; case FtpClient.FTP_TIMEOUT: if (reconnect()) { continue; } else { return null; } default: return null; } break; } return Arrays.asList(sb.toString().split("\n")); }
From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java
@Test public void testNioSingleUseWithInboundMany() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); final List<Socket> serverSockets = new ArrayList<Socket>(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port, 100); latch.countDown();// www.j ava 2s . c om for (int i = 0; i < 100; i++) { Socket socket = server.accept(); serverSockets.add(socket); semaphore.release(); byte[] b = new byte[9]; readFully(socket.getInputStream(), b); b = ("Reply" + i + "\r\n").getBytes(); socket.getOutputStream().write(b); socket.close(); } server.close(); } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(10000); ccf.setSingleUse(true); ccf.setTaskExecutor(Executors.newFixedThreadPool(100)); ccf.start(); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(ccf); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); assertTrue(latch.await(10, TimeUnit.SECONDS)); int i = 0; try { for (i = 100; i < 200; i++) { handler.handleMessage(MessageBuilder.withPayload("Test" + i).build()); } } catch (Exception e) { e.printStackTrace(); fail("Exception at " + i); } assertTrue(semaphore.tryAcquire(100, 20000, TimeUnit.MILLISECONDS)); Set<String> replies = new HashSet<String>(); for (i = 100; i < 200; i++) { Message<?> mOut = channel.receive(20000); assertNotNull(mOut); replies.add(new String((byte[]) mOut.getPayload())); } for (i = 0; i < 100; i++) { assertTrue("Reply" + i + " missing", replies.remove("Reply" + i)); } done.set(true); ccf.stop(); }