List of usage examples for java.util.concurrent Semaphore release
public void release()
From source file:com.parse.ParsePushTest.java
@Test public void testSendInBackgroundWithCallbackFail() throws Exception { // Mock controller ParsePushController controller = mock(ParsePushController.class); final ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error"); when(controller.sendInBackground(any(ParsePush.State.class), anyString())) .thenReturn(Task.<Void>forError(exception)); ParseCorePlugins.getInstance().registerPushController(controller); // Make sample ParsePush data and call method ParsePush push = new ParsePush(); JSONObject data = new JSONObject(); data.put("key", "value"); List<String> channels = new ArrayList<>(); channels.add("test"); channels.add("testAgain"); push.builder.expirationTime((long) 1000).data(data).pushToIOS(true).channelSet(channels); final Semaphore done = new Semaphore(0); final Capture<Exception> exceptionCapture = new Capture<>(); push.sendInBackground(new SendCallback() { @Override//from w w w .j a v a 2s.com public void done(ParseException e) { exceptionCapture.set(e); done.release(); } }); // Make sure controller is executed and state parameter is correct assertSame(exception, 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(); assertTrue(state.pushToIOS()); assertEquals(data, state.data(), JSONCompareMode.NON_EXTENSIBLE); assertEquals(2, state.channelSet().size()); assertTrue(state.channelSet().contains("test")); assertTrue(state.channelSet().contains("testAgain")); }
From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java
@Test public void shouldReturnBackupStartedBy() throws InterruptedException { assertThat(backupService.backupStartedBy(), is(Optional.empty())); final Semaphore waitForBackupToStart = new Semaphore(1); final Semaphore waitForAssertionToCompleteWhileBackupIsOn = new Semaphore(1); final BackupUpdateListener backupUpdateListener = new BackupUpdateListener() { private boolean backupStarted = false; @Override//from w w w .j av a 2 s . com public void updateStep(BackupProgressStatus step) { if (!backupStarted) { backupStarted = true; waitForBackupToStart.release(); try { waitForAssertionToCompleteWhileBackupIsOn.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } @Override public void error(String message) { } @Override public void completed() { } }; waitForAssertionToCompleteWhileBackupIsOn.acquire(); waitForBackupToStart.acquire(); Thread backupThd = new Thread(() -> backupService.startBackup(admin, backupUpdateListener)); backupThd.start(); waitForBackupToStart.acquire(); String backupStartedBy = backupService.backupStartedBy().get(); ServerBackup runningBackup = (ServerBackup) ReflectionUtil.getField(backupService, "runningBackup"); assertThat(runningBackup.getUsername(), is(backupStartedBy)); waitForAssertionToCompleteWhileBackupIsOn.release(); backupThd.join(); }
From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java
@Test public void shouldReturnBackupRunningSinceValue_inISO8601_format() throws InterruptedException { assertThat(backupService.backupRunningSinceISO8601(), is(Optional.empty())); final Semaphore waitForBackupToStart = new Semaphore(1); final Semaphore waitForAssertionToCompleteWhileBackupIsOn = new Semaphore(1); final BackupUpdateListener backupUpdateListener = new BackupUpdateListener() { private boolean backupStarted = false; @Override/*from ww w . j a v a 2 s .c o m*/ public void updateStep(BackupProgressStatus step) { if (!backupStarted) { backupStarted = true; waitForBackupToStart.release(); try { waitForAssertionToCompleteWhileBackupIsOn.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } @Override public void error(String message) { } @Override public void completed() { } }; waitForAssertionToCompleteWhileBackupIsOn.acquire(); waitForBackupToStart.acquire(); Thread backupThd = new Thread(() -> backupService.startBackup(admin, backupUpdateListener)); backupThd.start(); waitForBackupToStart.acquire(); String backupStartedTimeString = backupService.backupRunningSinceISO8601().get(); DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime(); DateTime backupTime = dateTimeFormatter.parseDateTime(backupStartedTimeString); ServerBackup runningBackup = (ServerBackup) ReflectionUtil.getField(backupService, "runningBackup"); assertThat(new DateTime(runningBackup.getTime()), is(backupTime)); waitForAssertionToCompleteWhileBackupIsOn.release(); backupThd.join(); }
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//w w w . j a v a 2 s . co m 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:com.parse.ParsePushTest.java
@Test public void testSendMessageInBackgroundWithCallback() 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 ParseQuery<ParseInstallation> query = ParseInstallation.getQuery(); query.getBuilder().whereEqualTo("foo", "bar"); final Semaphore done = new Semaphore(0); final Capture<Exception> exceptionCapture = new Capture<>(); ParsePush.sendMessageInBackground("test", query, new SendCallback() { @Override/*from w ww . j av a2 s . co m*/ 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 message assertEquals("test", state.data().getString(ParsePush.KEY_DATA_MESSAGE)); }
From source file:de.codecentric.batch.jsr352.CustomJsrJobOperator.java
@Override public long start(String jobName, Properties params) throws JobStartException, JobSecurityException { final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(params); batchContext.setValidating(false);/*from w ww .j ava 2 s.c o m*/ Resource batchXml = new ClassPathResource("/META-INF/batch.xml"); String jobConfigurationLocation = "/META-INF/batch-jobs/" + jobName + ".xml"; Resource jobXml = new ClassPathResource(jobConfigurationLocation); if (batchXml.exists()) { batchContext.load(batchXml); } if (jobXml.exists()) { batchContext.load(jobXml); } AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder .genericBeanDefinition("org.springframework.batch.core.jsr.JsrJobContextFactoryBean") .getBeanDefinition(); beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON); batchContext.registerBeanDefinition(JSR_JOB_CONTEXT_BEAN_NAME, beanDefinition); batchContext.setParent(parentContext); try { batchContext.refresh(); } catch (BeanCreationException e) { throw new JobStartException(e); } Assert.notNull(jobName, "The job name must not be null."); final org.springframework.batch.core.JobExecution jobExecution; try { JobParameters jobParameters = jobParametersConverter.getJobParameters(params); String[] jobNames = batchContext.getBeanNamesForType(Job.class); if (jobNames == null || jobNames.length <= 0) { throw new BatchRuntimeException("No Job defined in current context"); } org.springframework.batch.core.JobInstance jobInstance = jobRepository.createJobInstance(jobNames[0], jobParameters); jobExecution = jobRepository.createJobExecution(jobInstance, jobParameters, jobConfigurationLocation); } catch (Exception e) { throw new JobStartException(e); } try { final Semaphore semaphore = new Semaphore(1); final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>()); semaphore.acquire(); taskExecutor.execute(new Runnable() { @Override public void run() { JsrJobContextFactoryBean factoryBean = null; try { factoryBean = (JsrJobContextFactoryBean) batchContext .getBean("&" + JSR_JOB_CONTEXT_BEAN_NAME); factoryBean.setJobExecution(jobExecution); final AbstractJob job = batchContext.getBean(AbstractJob.class); addListenerToJobService.addListenerToJob(job); semaphore.release(); // Initialization of the JobExecution for job level dependencies jobRegistry.register(job, jobExecution); job.execute(jobExecution); jobRegistry.remove(jobExecution); } catch (Exception e) { exceptionHolder.add(e); } finally { if (factoryBean != null) { factoryBean.close(); } batchContext.close(); if (semaphore.availablePermits() == 0) { semaphore.release(); } } } }); semaphore.acquire(); if (exceptionHolder.size() > 0) { semaphore.release(); throw new JobStartException(exceptionHolder.get(0)); } } catch (Exception e) { if (jobRegistry.exists(jobExecution.getId())) { jobRegistry.remove(jobExecution); } jobExecution.upgradeStatus(BatchStatus.FAILED); if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) { jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e)); } jobRepository.update(jobExecution); if (batchContext.isActive()) { batchContext.close(); } throw new JobStartException(e); } return jobExecution.getId(); }
From source file:org.apache.solr.cloud.TestTlogReplica.java
@SuppressWarnings("unchecked") @BadApple(bugUrl = "https://issues.apache.org/jira/browse/SOLR-12028") public void testRecovery() throws Exception { boolean useKill = random().nextBoolean(); createAndWaitForCollection(1, 0, 2, 0); CloudSolrClient cloudClient = cluster.getSolrClient(); new UpdateRequest().add(sdoc("id", "3")).add(sdoc("id", "4")).commit(cloudClient, collectionName); new UpdateRequest().add(sdoc("id", "5")).process(cloudClient, collectionName); JettySolrRunner solrRunner = getSolrRunner(false).get(0); if (useKill) { ChaosMonkey.kill(solrRunner);//from ww w .j a va2s . c o m } else { ChaosMonkey.stop(solrRunner); } waitForState("Replica still up", collectionName, activeReplicaCount(0, 1, 0)); new UpdateRequest().add(sdoc("id", "6")).process(cloudClient, collectionName); ChaosMonkey.start(solrRunner); waitForState("Replica didn't recover", collectionName, activeReplicaCount(0, 2, 0)); // We skip peerSync, so replica will always trigger commit on leader // We query only the non-leader replicas, since we haven't opened a new searcher on the leader yet waitForNumDocsInAllReplicas(4, getNonLeaderReplias(collectionName), 10); //timeout for stale collection state // If I add the doc immediately, the leader fails to communicate with the follower with broken pipe. // Options are, wait or retry... for (int i = 0; i < 3; i++) { UpdateRequest ureq = new UpdateRequest().add(sdoc("id", "7")); ureq.setParam("collection", collectionName); ureq.setParam(UpdateRequest.MIN_REPFACT, "2"); NamedList<Object> response = cloudClient.request(ureq); if ((Integer) ((NamedList<Object>) response.get("responseHeader")).get(UpdateRequest.REPFACT) >= 2) { break; } LOG.info("Min RF not achieved yet. retrying"); } checkRTG(3, 7, cluster.getJettySolrRunners()); DirectUpdateHandler2.commitOnClose = false; ChaosMonkey.stop(solrRunner); waitForState("Replica still up", collectionName, activeReplicaCount(0, 1, 0)); DirectUpdateHandler2.commitOnClose = true; ChaosMonkey.start(solrRunner); waitForState("Replica didn't recover", collectionName, activeReplicaCount(0, 2, 0)); waitForNumDocsInAllReplicas(5, getNonLeaderReplias(collectionName), 10); //timeout for stale collection state checkRTG(3, 7, cluster.getJettySolrRunners()); cluster.getSolrClient().commit(collectionName); // Test replica recovery apply buffer updates Semaphore waitingForBufferUpdates = new Semaphore(0); Semaphore waitingForReplay = new Semaphore(0); RecoveryStrategy.testing_beforeReplayBufferingUpdates = () -> { try { waitingForReplay.release(); waitingForBufferUpdates.acquire(); } catch (InterruptedException e) { e.printStackTrace(); fail("Test interrupted: " + e.getMessage()); } }; if (useKill) { ChaosMonkey.kill(solrRunner); } else { ChaosMonkey.stop(solrRunner); } ChaosMonkey.start(solrRunner); waitingForReplay.acquire(); new UpdateRequest().add(sdoc("id", "8")).add(sdoc("id", "9")).process(cloudClient, collectionName); waitingForBufferUpdates.release(); RecoveryStrategy.testing_beforeReplayBufferingUpdates = null; waitForState("Replica didn't recover", collectionName, activeReplicaCount(0, 2, 0)); checkRTG(3, 9, cluster.getJettySolrRunners()); for (SolrCore solrCore : getSolrCore(false)) { RefCounted<IndexWriter> iwRef = solrCore.getUpdateHandler().getSolrCoreState().getIndexWriter(null); assertFalse("IndexWriter at replicas must not see updates ", iwRef.get().hasUncommittedChanges()); iwRef.decref(); } }
From source file:com.qwazr.search.index.IndexInstance.java
final ResultDefinition.WithMap deleteByQuery(final QueryDefinition queryDefinition) throws IOException, InterruptedException, QueryNodeException, ParseException, ServerException, ReflectiveOperationException { final Semaphore sem = schema.acquireWriteSemaphore(); try {/* w w w . j av a2 s. com*/ final QueryContext queryContext = new QueryContext(null, queryAnalyzer, null, queryDefinition); final Query query = QueryUtils.getLuceneQuery(queryContext); int docs = indexWriter.numDocs(); indexWriter.deleteDocuments(query); nrtCommit(); docs -= indexWriter.numDocs(); return new ResultDefinition.WithMap(docs); } finally { if (sem != null) sem.release(); } }
From source file:org.ut.biolab.medsavant.client.plugin.AppController.java
/** * Try to load all JAR files in the given directory. */// w ww . ja v a 2 s . c om 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.bt.sdk.callcontrol.sip.util.EhCacheCollectionImpl.java
public void remove(String infoId) { if (!semaphoreCache.getKeys().contains(infoId)) return;//from w w w . j a v a 2 s. co m Semaphore semaphore = (Semaphore) semaphoreCache.get(infoId).getObjectValue(); if (semaphore == null) return; try { semaphore.acquire(); } catch (InterruptedException e) { log.error(String.format(FAILED_TO_REMOVE_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(), e.getMessage())); throw new CollectionAccessInterruptedException(String.format(FAILED_TO_REMOVE_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(), e.getMessage()), e); } try { boolean b = cache.remove(infoId); System.out.println(b + ":" + infoId); if (b) { semaphoreCache.remove(infoId); log.info(String.format("Removed info %s", infoId)); } else log.warn(String.format("Failed to find info %s", infoId)); } finally { semaphore.release(); } }