List of usage examples for java.util.concurrent.atomic AtomicBoolean get
public final boolean get()
From source file:com.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java
/** * Test method for executing Hadoop job w/ properties. *//*from w w w .ja v a 2 s. c o m*/ @Test public void executeJob_w_properties() { prepareJobflow(); AtomicBoolean call = new AtomicBoolean(); MockHadoopJob.callback((args, conf) -> { call.set(true); assertThat(conf.get("com.example.testing"), is("true")); return 0; }); TestExecutionPlan.Job job = job(MockHadoopJob.class.getName(), "com.example.testing", "true"); JobExecutor executor = new InProcessJobExecutor(context); try { executor.execute(job, Collections.emptyMap()); } catch (IOException e) { throw new AssertionError(e); } assertThat(call.get(), is(true)); }
From source file:com.nridge.connector.common.con_com.crawl.CrawlQueue.java
/** * Evaluates if the phase has completed its processing cycle. A phase * is considered complete if the application is no longer alive or the * queue item represents a crawl finish or abort marker. * * @param aPhase Name of the phase being evaluated (used for logging). * @param aQueueItem Queue item./*from w w w. ja v a 2 s . c o m*/ * * @return <i>true</i> or <i>false</i> */ public boolean isPhaseComplete(String aPhase, String aQueueItem) { boolean isPhaseAlreadyComplete; Logger appLogger = mAppMgr.getLogger(this, "isPhaseComplete"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); AtomicBoolean atomicBoolean = mPhaseComplete.get(aPhase); if (atomicBoolean == null) { isPhaseAlreadyComplete = true; appLogger.error(String.format("Phase name '%s' atomic boolean is null.", aPhase)); } else isPhaseAlreadyComplete = atomicBoolean.get(); boolean appMgrIsAlive = mAppMgr.isAlive(); boolean queueItemIsValid = isQueueItemValid(aQueueItem); boolean queueIsAborted = StringUtils.equals(aQueueItem, Connector.QUEUE_ITEM_CRAWL_ABORT); boolean queueIsFinished = StringUtils.equals(aQueueItem, Connector.QUEUE_ITEM_CRAWL_FINISH); boolean isComplete = ((!appMgrIsAlive) || (isPhaseAlreadyComplete) || (queueIsAborted) || (queueIsFinished)); if (isComplete) { if ((atomicBoolean != null) && (!atomicBoolean.get())) atomicBoolean.set(true); appLogger.debug(String.format( "Phase Complete %s: queueItemIsValid = %s, isPhaseAlreadyComplete = %s, appMgrIsAlive = %s, queueIsAborted = %s, queueIsFinished = %s", aPhase, queueItemIsValid, isPhaseAlreadyComplete, appMgrIsAlive, queueIsAborted, queueIsFinished)); } else appLogger.debug(String.format( "Phase Continue %s: queueItemIsValid = %s, isPhaseAlreadyComplete = %s, appMgrIsAlive = %s, queueIsAborted = %s, queueIsFinished = %s", aPhase, queueItemIsValid, isPhaseAlreadyComplete, appMgrIsAlive, queueIsAborted, queueIsFinished)); appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return isComplete; }
From source file:io.restassured.examples.springmvc.controller.AutoSpringSecurityConfigurerITest.java
@Test public void doesnt_add_spring_security_configurer_automatically_when_a_spring_security_configurer_has_been_manually_applied() { final AtomicBoolean filterUsed = new AtomicBoolean(false); RestAssuredMockMvc.given().webAppContextSetup(context, springSecurity(), springSecurity(new Filter() { public void init(FilterConfig filterConfig) throws ServletException { }/*from w w w .j ava 2 s .c o m*/ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { filterUsed.set(true); chain.doFilter(request, response); } public void destroy() { } })).postProcessors(httpBasic("username", "password")).param("name", "Johan").when().get("/secured/greeting") .then().statusCode(200).body("content", equalTo("Hello, Johan!")) .expect(authenticated().withUsername("username")); assertThat(filterUsed.get(), is(true)); }
From source file:ch.cyberduck.core.cryptomator.impl.CryptoVaultTest.java
@Test public void testLoadInvalidPassphrase() throws Exception { final NullSession session = new NullSession(new Host(new TestProtocol())) { @Override//from w w w . j ava 2 s .c o m @SuppressWarnings("unchecked") public <T> T _getFeature(final Class<T> type) { if (type == Read.class) { return (T) new Read() { @Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final String masterKey = "{\n" + " \"scryptSalt\": \"NrC7QGG/ouc=\",\n" + " \"scryptCostParam\": 16384,\n" + " \"scryptBlockSize\": 8,\n" + " \"primaryMasterKey\": \"Q7pGo1l0jmZssoQh9rXFPKJE9NIXvPbL+HcnVSR9CHdkeR8AwgFtcw==\",\n" + " \"hmacMasterKey\": \"xzBqT4/7uEcQbhHFLC0YmMy4ykVKbuvJEA46p1Xm25mJNuTc20nCbw==\",\n" + " \"versionMac\": \"hlNr3dz/CmuVajhaiGyCem9lcVIUjDfSMLhjppcXOrM=\",\n" + " \"version\": 5\n" + "}"; return IOUtils.toInputStream(masterKey, Charset.defaultCharset()); } @Override public boolean offset(final Path file) throws BackgroundException { return false; } }; } return super._getFeature(type); } }; final AtomicBoolean prompt = new AtomicBoolean(); final CryptoVault vault = new CryptoVault(new Path("/", EnumSet.of(Path.Type.directory)), new DisabledPasswordStore()); try { vault.load(session, new DisabledPasswordCallback() { @Override public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) throws LoginCanceledException { if (!prompt.get()) { assertEquals("Provide your passphrase to unlock the Cryptomator Vault /", reason); prompt.set(true); return new VaultCredentials("null"); } else { assertEquals( "Failure to decrypt master key file. Provide your passphrase to unlock the Cryptomator Vault /.", reason); throw new LoginCanceledException(); } } }); fail(); } catch (LoginCanceledException e) { // } assertTrue(prompt.get()); }
From source file:com.inqool.dcap.office.indexer.indexer.SolrBulkIndexer.java
protected SolrInputDocument modelToSolrInputDoc(ZdoModel model) { logger.debug("Constructing new SolrInputDocument..."); final Map<String, SolrInputField> fields = new HashMap<>(); //Add all Dublin Core terms for (String property : DCTools.getDcTermList()) { SolrInputField field = new SolrInputField(property); List<String> values = model.getAll(new PropertyImpl("http://purl.org/dc/terms/" + property)); if (values.isEmpty()) continue; //Skip fields that were not ticked to be published String visible = model.get(new PropertyImpl("http://purl.org/dc/terms/" + property + "_visibility")); if ("false".equals(visible) || "0".equals(visible)) { //0 should not occur any more continue; }/*w ww . j a v a 2 s .com*/ if ("isPartOf".equals(property)) { //remove ip address from isPartOf values.set(0, store.getOnlyIdFromUrl(values.get(0))); } if ("".equals(values.get(0))) { values.set(0, "unknown"); } field.addValue(values, INDEX_TIME_BOOST); fields.put(property, field); //Suggester data if ("title".equals(property) || "creator".equals(property)) { SolrInputDocument suggesterDoc = new SolrInputDocument(); String suggestVal = values.get(0).trim(); if (!suggestVal.isEmpty() && !suggestVal.equals("unknown")) { suggesterDoc.addField("suggesterData", values.get(0).trim()); dataForSuggester.add(suggesterDoc); } } } //Add system fields SolrInputField field = new SolrInputField("id"); field.addValue(store.getOnlyIdFromUrl(model.getUrl()), INDEX_TIME_BOOST); fields.put("id", field); addSolrFieldFromFedoraProperty("inventoryId", ZdoTerms.inventoryId, model, fields); addSolrFieldFromFedoraProperty("zdoType", ZdoTerms.zdoType, model, fields); addSolrFieldFromFedoraProperty("zdoGroup", ZdoTerms.group, model, fields); addSolrFieldFromFedoraProperty("orgIdmId", ZdoTerms.organization, model, fields); addSolrFieldFromFedoraProperty("allowContentPublicly", ZdoTerms.allowContentPublicly, model, fields); addSolrFieldFromFedoraProperty("allowPdfExport", ZdoTerms.allowPdfExport, model, fields); addSolrFieldFromFedoraProperty("allowEpubExport", ZdoTerms.allowEpubExport, model, fields); addSolrFieldFromFedoraProperty("watermark", ZdoTerms.watermark, model, fields); addSolrFieldFromFedoraProperty("watermarkPosition", ZdoTerms.watermarkPosition, model, fields); addSolrFieldFromFedoraProperty("imgThumb", ZdoTerms.imgThumb, model, fields); addSolrFieldFromFedoraProperty("imgNormal", ZdoTerms.imgNormal, model, fields); String publishFromStr = model.get(ZdoTerms.publishFrom); if (publishFromStr != null) { String publishFromUtc = ZonedDateTime .ofInstant(Instant.ofEpochSecond(Long.valueOf(publishFromStr)), ZoneId.systemDefault()) .withZoneSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); addSolrField("publishFrom", publishFromUtc, fields); } String publishToStr = model.get(ZdoTerms.publishTo); if (publishToStr != null) { String publishToUtc = ZonedDateTime .ofInstant(Instant.ofEpochSecond(Long.valueOf(publishToStr)), ZoneId.systemDefault()) .withZoneSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); addSolrField("publishTo", publishToUtc, fields); } String created = model.get(DCTerms.created); if (created != null) { AtomicInteger yearStart = new AtomicInteger(); AtomicInteger yearEnd = new AtomicInteger(); AtomicBoolean startValid = new AtomicBoolean(); AtomicBoolean endValid = new AtomicBoolean(); YearNormalizer.normalizeCreatedYear(created, yearStart, startValid, yearEnd, endValid); if (startValid.get()) { addSolrField("yearStart", yearStart.get(), fields); } else { logger.warn("Year could not be normalized for input string " + created); } if (endValid.get()) { addSolrField("yearEnd", yearEnd.get(), fields); } } String orgName = orgNameMapping.get(model.get(ZdoTerms.organization)); if (orgName == null) { orgName = "Neznm"; } addSolrField("organization", orgName, fields); String documentTypeId = model.get(ZdoTerms.documentType); //type and subtype names must be found for id String documentSubTypeId = model.get(ZdoTerms.documentSubType); if (documentTypeId != null) { addSolrField("documentType", documentTypeAccess.getTypeNameForId(Integer.valueOf(documentTypeId)), fields); } if (documentSubTypeId != null) { addSolrField("documentSubType", documentTypeAccess.getSubTypeNameForId(Integer.valueOf(documentSubTypeId)), fields); } //Add customFields int fieldIndex = 0; //we actually start from 1 do { fieldIndex++; String fieldName = model .get(new PropertyImpl("http://inqool.cz/zdo/1.0/customField_" + fieldIndex + "_name")); if (fieldName == null) break; fieldName = "customField_" + fieldName; String visible = model .get(new PropertyImpl("http://inqool.cz/zdo/1.0/customField_" + fieldIndex + "_visibility")); if ("false".equals(visible) || "0".equals(visible)) continue; List<String> fieldValues = model .getAll(new PropertyImpl("http://inqool.cz/zdo/1.0/customField_" + fieldIndex)); if ("".equals(fieldValues.get(0))) { fieldValues.set(0, "unknown"); } SolrInputField customField = new SolrInputField(fieldName); customField.addValue(fieldValues, INDEX_TIME_BOOST); fields.put(fieldName, customField); } while (true); SolrInputDocument solrInputDocument = new SolrInputDocument(fields); return solrInputDocument; }
From source file:io.pravega.controller.eventProcessor.impl.SerializedRequestHandlerTest.java
@Test(timeout = 10000) public void testPostponeEvent() throws InterruptedException, ExecutionException { AtomicInteger postponeS1e1Count = new AtomicInteger(); AtomicInteger postponeS1e2Count = new AtomicInteger(); AtomicBoolean allowCompletion = new AtomicBoolean(false); SerializedRequestHandler<TestEvent> requestHandler = new SerializedRequestHandler<TestEvent>( executorService()) {//from ww w .j a v a 2 s. c o m @Override public CompletableFuture<Void> processEvent(TestEvent event) { if (!event.future.isDone()) { return Futures.failedFuture(new TestPostponeException()); } return event.getFuture(); } @Override public boolean toPostpone(TestEvent event, long pickupTime, Throwable exception) { boolean retval = true; if (allowCompletion.get()) { if (event.number == 1) { postponeS1e1Count.incrementAndGet(); retval = exception instanceof TestPostponeException && postponeS1e1Count.get() < 2; } if (event.number == 2) { postponeS1e2Count.incrementAndGet(); retval = exception instanceof TestPostponeException && (System.currentTimeMillis() - pickupTime < Duration.ofMillis(100).toMillis()); } } return retval; } }; List<Pair<TestEvent, CompletableFuture<Void>>> stream1Queue = requestHandler .getEventQueueForKey(getKeyForStream("scope", "stream1")); assertNull(stream1Queue); // post 3 work for stream1 TestEvent s1e1 = new TestEvent("scope", "stream1", 1); CompletableFuture<Void> s1p1 = requestHandler.process(s1e1); TestEvent s1e2 = new TestEvent("scope", "stream1", 2); CompletableFuture<Void> s1p2 = requestHandler.process(s1e2); TestEvent s1e3 = new TestEvent("scope", "stream1", 3); CompletableFuture<Void> s1p3 = requestHandler.process(s1e3); // post events for some more arbitrary streams in background AtomicBoolean stop = new AtomicBoolean(false); runBackgroundStreamProcessing("stream2", requestHandler, stop); runBackgroundStreamProcessing("stream3", requestHandler, stop); runBackgroundStreamProcessing("stream4", requestHandler, stop); s1e3.complete(); // verify that s1p3 completes. assertTrue(Futures.await(s1p3)); // verify that s1e1 and s1e2 are still not complete. assertTrue(!s1e1.getFuture().isDone()); assertTrue(!s1p1.isDone()); assertTrue(!s1e2.getFuture().isDone()); assertTrue(!s1p2.isDone()); // Allow completion allowCompletion.set(true); assertFalse(Futures.await(s1p1)); assertFalse(Futures.await(s1p2)); AssertExtensions.assertThrows("", s1p1::join, e -> Exceptions.unwrap(e) instanceof TestPostponeException); AssertExtensions.assertThrows("", s1p2::join, e -> Exceptions.unwrap(e) instanceof TestPostponeException); assertTrue(postponeS1e1Count.get() == 2); assertTrue(postponeS1e2Count.get() > 0); stop.set(true); }
From source file:com.dragoniade.deviantart.favorites.FavoritesDownloader.java
public void execute(int offset) { int skipped = 0; requestCount = 0;// w ww . ja va 2 s .com searcher.setFrame(owner); searcher.setUser(userId); searcher.startAt(offset); progress.setTotalMax(Integer.MAX_VALUE); progress.setTotalValue(offset); int total = -1; YesNoAllDialog matureMoveDialog = new YesNoAllDialog(); YesNoAllDialog overwriteDialog = new YesNoAllDialog(); YesNoAllDialog overwriteNewerDialog = new YesNoAllDialog(); YesNoAllDialog deleteEmptyDialog = new YesNoAllDialog(); List<Collection> collections; if (skipCollection) { collections = new ArrayList<Collection>(); collections.add(null); } else { collections = searcher.getCollections(); } for (Collection collection : collections) { searcher.startAt(offset); progress.setTotalValue(offset); while (!progress.isCancelled()) { progress.setText("Fetching results " + (collection != null ? collection.getName() : "...")); List<Deviation> results = searcher.search(progress, collection); requestCount++; if (results == null) { return; } total = searcher.getTotal(); progress.setTotalMax(total); if (results.size() > 0) { for (Deviation da : results) { if (progress.isCancelled()) { return; } boolean downloaded = false; progress.setUnitMax(1); if (da.getDocumentDownloadUrl() != null) { String url = da.getDocumentDownloadUrl(); String filename = da.getDocumentFilename(); if (filename == null) { AtomicBoolean download = new AtomicBoolean(true); url = getDocumentUrl(da, download); if (url == null) { return; } if (!download.get()) { skipped++; if (!nextDeviation(skipped)) { return; } continue; } } filename = Deviation.extractFilename(url); STATUS status = downloadFile(da, url, filename, false, matureMoveDialog, overwriteDialog, overwriteNewerDialog, deleteEmptyDialog); if (status == null) { return; } switch (status) { case CANCEL: return; case SKIP: skipped++; if (!nextDeviation(skipped)) { return; } continue; case DOWNLOADED: downloaded = true; break; case NOTFOUND: if (da.getImageDownloadUrl() == null) { String text = "<br/><a style=\"color:red;\" href=\"" + da.getUrl() + "\">" + url + " was not found" + "</a>"; setPaneText(text); progress.incremTotal(); } } } if (da.getImageDownloadUrl() != null && !downloaded) { String url = da.getImageDownloadUrl(); String filename = da.getImageFilename(); STATUS status = downloadFile(da, url, filename, false, matureMoveDialog, overwriteDialog, overwriteNewerDialog, deleteEmptyDialog); if (status == null) { return; } switch (status) { case CANCEL: return; case SKIP: skipped++; if (!nextDeviation(skipped)) { return; } continue; case DOWNLOADED: downloaded = true; break; case NOTFOUND: String text = "<br/><a style=\"color:red;\" href=\"" + da.getUrl() + "\">" + url + " was not found" + "</a>"; setPaneText(text); progress.incremTotal(); } } if (!nextDeviation(skipped)) { return; } } } else { break; } } } }
From source file:com.ebay.cloud.cms.entmgr.entity.impl.EntityFieldTargetMerger.java
/** * Update the field operation entity based on the found entity. This step is * to make sure//w w w.j ava2s . co m * <ul> * <li>1. the array length would be updated correctly</li> * <li>2. support reference update based on reference ID matching</li> * </ul> */ public boolean mergeEntityOnField(IEntity givenEntity, String fieldName, IEntity foundEntity) { MetaClass metaClass = givenEntity.getMetaClass(); MetaField field = metaClass.getFieldByName(fieldName); boolean isRelation = DataTypeEnum.RELATIONSHIP.equals(field.getDataType()); boolean array = CardinalityEnum.Many.equals(field.getCardinality()); boolean hasFoundField = foundEntity.hasField(fieldName); List<?> givenValues = givenEntity.getFieldValues(fieldName); List<?> foundValues = foundEntity.getFieldValues(fieldName); AtomicBoolean hasChange = new AtomicBoolean(false); if (array) { boolean hasGivenField = givenEntity.hasField(fieldName); if (!hasGivenField || givenValues.isEmpty()) { return false; } // do merge only when we found both for array if (hasFoundField) { List<?> mergeValues = null; if (isRelation) { // relation will merge based on OID mergeValues = mergeTargetReference(givenValues, foundValues, hasChange); } else { // normal entity will merge by content mergeValues = mergeTargetContent(givenValues, foundValues, hasChange); } if (!hasChange.get()) { return false; } givenEntity.setFieldValues(fieldName, mergeValues); } return true; } else { // cardinality=ONE return mergeTargetSingle(givenEntity, fieldName, isRelation, hasFoundField, givenValues, foundValues); } }
From source file:com.liveramp.hank.test.ZkTestCase.java
@Before public final void setUpZk() throws Exception { setupZkServer();//from w w w. j a va2 s .c o m final Object lock = new Object(); final AtomicBoolean connected = new AtomicBoolean(false); zk = new ZooKeeperPlus("127.0.0.1:" + zkClientPort, 1000000, new Watcher() { @Override public void process(WatchedEvent event) { switch (event.getType()) { case None: if (event.getState() == KeeperState.SyncConnected) { connected.set(true); synchronized (lock) { lock.notifyAll(); } } } LOG.debug(event.toString()); } }); synchronized (lock) { lock.wait(2000); } if (!connected.get()) { fail("timed out waiting for the zk client connection to come online!"); } LOG.debug("session timeout: " + zk.getSessionTimeout()); zk.deleteNodeRecursively(zkRoot); WaitUntil.orDie(() -> { try { return zk.exists(zkRoot, false) == null; } catch (KeeperException | InterruptedException e) { throw new RuntimeException(e); } }); createNodeRecursively(zkRoot); }
From source file:com.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java
/** * Test method for executing Hadoop job w/ {@code asakusa-resources.xml}. *//*w w w . j ava2s. c o m*/ @Test public void executeJob_w_resources() { prepareJobflow(); AtomicBoolean call = new AtomicBoolean(); MockHadoopJob.callback((args, conf) -> { call.set(true); assertThat(conf.get("com.example.testing"), is("true")); return 0; }); JobExecutor executor = new InProcessJobExecutor(context); deploy("dummy.xml", new File(framework.getHome(), InProcessJobExecutor.PATH_ASAKUSA_RESOURCES)); try { executor.execute(job(MockHadoopJob.class.getName()), Collections.emptyMap()); } catch (IOException e) { throw new AssertionError(e); } assertThat(call.get(), is(true)); }