List of usage examples for java.util.concurrent Semaphore release
public void release()
From source file:com.kurento.kmf.media.HttpPostEndpointAsyncTest.java
@Before public void setup() throws InterruptedException { final Semaphore sem = new Semaphore(0); pipeline.newHttpPostEndpoint().buildAsync(new Continuation<HttpPostEndpoint>() { @Override/*from ww w . j a v a 2s. c o m*/ public void onSuccess(HttpPostEndpoint result) { httpEp = result; sem.release(); } @Override public void onError(Throwable cause) { throw new KurentoMediaFrameworkException(cause); } }); Assert.assertTrue(sem.tryAcquire(500, MILLISECONDS)); }
From source file:com.netflix.curator.framework.recipes.cache.TestNodeCache.java
@Test public void testBasics() throws Exception { NodeCache cache = null;/* www . j a v a 2s . c o m*/ Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/test"); cache = new NodeCache(client, "/test/node"); cache.start(true); final Semaphore semaphore = new Semaphore(0); cache.getListenable().addListener(new NodeCacheListener() { @Override public void nodeChanged() throws Exception { semaphore.release(); } }); Assert.assertNull(cache.getCurrentData()); client.create().forPath("/test/node", "a".getBytes()); Assert.assertTrue(timing.acquireSemaphore(semaphore)); Assert.assertEquals(cache.getCurrentData().getData(), "a".getBytes()); client.setData().forPath("/test/node", "b".getBytes()); Assert.assertTrue(timing.acquireSemaphore(semaphore)); Assert.assertEquals(cache.getCurrentData().getData(), "b".getBytes()); client.delete().forPath("/test/node"); Assert.assertTrue(timing.acquireSemaphore(semaphore)); Assert.assertNull(cache.getCurrentData()); } finally { IOUtils.closeQuietly(cache); IOUtils.closeQuietly(client); } }
From source file:org.openengsb.core.services.internal.deployer.connector.ConnectorDeployerService.java
@Override public void update(File artifact) throws Exception { LOGGER.debug("ConnectorDeployer.update(\"{}\")", artifact.getAbsolutePath()); Semaphore semaphore = updateSemaphores.get(artifact); semaphore.acquire();//from w w w . j a v a2 s . c o m try { doUpdate(artifact); } finally { semaphore.release(); } }
From source file:com.netflix.curator.x.discovery.TestServiceCache.java
@Test public void testCache() throws Exception { List<Closeable> closeables = Lists.newArrayList(); TestingServer server = new TestingServer(); closeables.add(server);// w w w . j a va 2 s. co m try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class) .basePath("/discovery").client(client).build(); closeables.add(discovery); discovery.start(); ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); cache.start(); final Semaphore semaphore = new Semaphore(0); ServiceCacheListener listener = new ServiceCacheListener() { @Override public void cacheChanged() { semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; cache.addListener(listener); ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("thing").name("test") .port(10064).build(); ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("thing").name("test") .port(10065).build(); discovery.registerService(instance1); Assert.assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS)); discovery.registerService(instance2); Assert.assertTrue(semaphore.tryAcquire(3, TimeUnit.SECONDS)); ServiceInstance<String> instance3 = ServiceInstance.<String>builder().payload("thing").name("another") .port(10064).build(); discovery.registerService(instance3); Assert.assertFalse(semaphore.tryAcquire(3, TimeUnit.SECONDS)); // should not get called for a different service } finally { Collections.reverse(closeables); for (Closeable c : closeables) { IOUtils.closeQuietly(c); } } }
From source file:com.netflix.curator.framework.recipes.cache.TestNodeCache.java
@Test public void testDeleteThenCreate() throws Exception { NodeCache cache = null;/*from ww w . j ava 2 s .c o m*/ CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().creatingParentsIfNeeded().forPath("/test/foo", "one".getBytes()); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); client.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() { @Override public void unhandledError(String message, Throwable e) { error.set(e); } }); final Semaphore semaphore = new Semaphore(0); cache = new NodeCache(client, "/test/foo"); cache.getListenable().addListener(new NodeCacheListener() { @Override public void nodeChanged() throws Exception { semaphore.release(); } }); cache.start(true); Assert.assertEquals(cache.getCurrentData().getData(), "one".getBytes()); client.delete().forPath("/test/foo"); Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); client.create().forPath("/test/foo", "two".getBytes()); Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); Throwable t = error.get(); if (t != null) { Assert.fail("Assert", t); } Assert.assertEquals(cache.getCurrentData().getData(), "two".getBytes()); cache.close(); } finally { IOUtils.closeQuietly(cache); IOUtils.closeQuietly(client); } }
From source file:org.commoncrawl.service.queryserver.master.S3Helper.java
public static ArcFileItem retrieveArcFileItem(ArchiveInfo archiveInfo, EventLoop eventLoop) throws IOException { // the default bucket id String bucketId = "commoncrawl-crawl-002"; //ok, see if we need to switch buckets if (archiveInfo.getCrawlNumber() == 1) { bucketId = "commoncrawl"; }/*from www.j a va 2s.co m*/ S3Downloader downloader = new S3Downloader(bucketId, "", "", false); // now activate the segment log ... final Semaphore downloadCompleteSemaphore = new Semaphore(0); final StreamingArcFileReader arcFileReader = new StreamingArcFileReader(false); //arcFileReader.setArcFileHasHeaderItemFlag(false); // create a buffer list we will append incoming content into ... final LinkedList<ByteBuffer> bufferList = new LinkedList<ByteBuffer>(); downloader.initialize(new S3Downloader.Callback() { @Override public boolean contentAvailable(int itemId, String itemKey, NIOBufferList contentBuffer) { LOG.info("ContentQuery contentAvailable called for Item:" + itemKey + " totalBytesAvailable:" + contentBuffer.available()); try { while (contentBuffer.available() != 0) { bufferList.add(contentBuffer.read()); } return true; } catch (IOException e) { LOG.error(CCStringUtils.stringifyException(e)); return false; } } @Override public void downloadComplete(int itemId, String itemKey) { LOG.info("S3 Download Complete for item:" + itemKey); downloadCompleteSemaphore.release(); } @Override public void downloadFailed(int itemId, String itemKey, String errorCode) { LOG.info("S3 Download Failed for item:" + itemKey); downloadCompleteSemaphore.release(); } @Override public boolean downloadStarting(int itemId, String itemKey, int contentLength) { LOG.info("ContentQuery DownloadStarting for Item:" + itemKey + " contentLength:" + contentLength); return true; } }, eventLoop); LOG.info("Starting request for Item:" + hdfsNameToS3ArcFileName(archiveInfo.getArcfileDate(), archiveInfo.getArcfileIndex()) + " Offset:" + archiveInfo.getArcfileOffset()); int sizeToRetrieve = (archiveInfo.getCompressedSize() != 0) ? archiveInfo.getCompressedSize() : 30000; sizeToRetrieve += 10; downloader.fetchPartialItem( hdfsNameToS3ArcFileName(archiveInfo.getArcfileDate(), archiveInfo.getArcfileIndex()), archiveInfo.getArcfileOffset() - 10, sizeToRetrieve); downloadCompleteSemaphore.acquireUninterruptibly(); if (bufferList.size() == 0) { return null; } ByteBuffer firstBuffer = bufferList.getFirst(); if (firstBuffer != null) { int offsetToGZIPHeader = scanForGZIPHeader(firstBuffer.duplicate()); if (offsetToGZIPHeader != -1) { firstBuffer.position(offsetToGZIPHeader); LOG.info("*** Offset to GZIP Header:" + offsetToGZIPHeader); } else { LOG.error("*** Failed to find GZIP Header offset"); } } // now try to decode content if possible for (ByteBuffer buffer : bufferList) { LOG.info("Adding Buffer of Size:" + buffer.remaining() + " Position:" + buffer.position() + " Limit:" + buffer.limit()); arcFileReader.available(buffer); } ArcFileItem item = arcFileReader.getNextItem(); if (item != null) { LOG.info("Request Returned item:" + item.getUri()); LOG.info("Uncompressed Size:" + item.getContent().getCount()); } return item; }
From source file:com.parse.ParseAnalyticsTest.java
@Test public void testTrackAppOpenedInBackgroundNormalCallback() throws Exception { Intent intent = makeIntentWithParseData("test"); final Semaphore done = new Semaphore(0); ParseAnalytics.trackAppOpenedInBackground(intent, new SaveCallback() { @Override/*from w ww. java 2s . c o m*/ public void done(ParseException e) { assertNull(e); done.release(); } }); // Make sure the callback is called assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS)); verify(controller, times(1)).trackAppOpenedInBackground(eq("test"), isNull(String.class)); }
From source file:org.apache.storm.daemon.DrpcServer.java
@Override public void failRequest(String id) throws AuthorizationException, TException { meterFailRequestCalls.mark();/*from w ww .jav a 2 s. co m*/ InternalRequest internalRequest = this.outstandingRequests.get(id); if (internalRequest != null) { Map<String, String> map = new HashMap<>(); map.put(DRPCAuthorizerBase.FUNCTION_NAME, internalRequest.function); checkAuthorization(authorizer, map, "failRequest"); Semaphore sem = internalRequest.sem; if (sem != null) { internalRequest.result = new DRPCExecutionException("Request failed"); sem.release(); } } }
From source file:com.netflix.curator.ensemble.exhibitor.TestExhibitorEnsembleProvider.java
@Test public void testExhibitorFailures() throws Exception { final AtomicReference<String> backupConnectionString = new AtomicReference<String>("backup1:1"); final AtomicReference<String> connectionString = new AtomicReference<String>( "count=1&port=2&server0=localhost"); Exhibitors exhibitors = new Exhibitors(Lists.newArrayList("foo", "bar"), 1000, new Exhibitors.BackupConnectionStringProvider() { @Override/*from w ww . j av a 2s .c om*/ public String getBackupConnectionString() { return backupConnectionString.get(); } }); ExhibitorRestClient mockRestClient = new ExhibitorRestClient() { @Override public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception { String localConnectionString = connectionString.get(); if (localConnectionString == null) { throw new IOException(); } return localConnectionString; } }; final Semaphore semaphore = new Semaphore(0); ExhibitorEnsembleProvider provider = new ExhibitorEnsembleProvider(exhibitors, mockRestClient, "/foo", 10, new RetryOneTime(1)) { @Override protected void poll() { super.poll(); semaphore.release(); } }; provider.pollForInitialEnsemble(); try { provider.start(); Assert.assertEquals(provider.getConnectionString(), "localhost:2"); connectionString.set(null); semaphore.drainPermits(); semaphore.acquire(); // wait for next poll Assert.assertEquals(provider.getConnectionString(), "backup1:1"); backupConnectionString.set("backup2:2"); semaphore.drainPermits(); semaphore.acquire(); // wait for next poll Assert.assertEquals(provider.getConnectionString(), "backup2:2"); connectionString.set("count=1&port=3&server0=localhost3"); semaphore.drainPermits(); semaphore.acquire(); // wait for next poll Assert.assertEquals(provider.getConnectionString(), "localhost3:3"); } finally { IOUtils.closeQuietly(provider); } }
From source file:com.qwazr.search.index.SchemaInstance.java
public <T extends ResultDocumentAbstract> ResultDefinition<T> search(QueryDefinition queryDef, ResultDocumentBuilder.BuilderFactory<T> documentBuilderFactory) throws ServerException, IOException, QueryNodeException, InterruptedException, ParseException, ReflectiveOperationException { final Semaphore sem = acquireReadSemaphore(); try {/*from w w w . ja v a2 s . c o m*/ return atomicSearch(searchContext, queryDef, documentBuilderFactory); } finally { if (sem != null) sem.release(); } }