Java Code Examples for java.util.concurrent.atomic.AtomicBoolean

The following are top voted examples for showing how to use java.util.concurrent.atomic.AtomicBoolean. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: LockSupportTest.java   View source code 6 votes vote down vote up
public void testParkAfterUnpark(final ParkMethod parkMethod) {
    final CountDownLatch pleaseUnpark = new CountDownLatch(1);
    final AtomicBoolean pleasePark = new AtomicBoolean(false);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() {
            pleaseUnpark.countDown();
            while (!pleasePark.get())
                Thread.yield();
            parkMethod.park();
        }});

    await(pleaseUnpark);
    LockSupport.unpark(t);
    pleasePark.set(true);
    awaitTermination(t);
}
 
Example 2
Project: jdk8u-jdk   File: BadHandshakeTest.java   View source code 6 votes vote down vote up
private static Process launch(String address, String class_name) throws Exception {
    String[] args = VMConnection.insertDebuggeeVMOptions(new String[] {
        "-agentlib:jdwp=transport=dt_socket" +
        ",server=y" + ",suspend=y" + ",address=" + address,
        class_name
    });

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args);

    final AtomicBoolean success = new AtomicBoolean();
    Process p = ProcessTools.startProcess(
        class_name,
        pb,
        (line) -> {
            // The first thing that will get read is
            //    Listening for transport dt_socket at address: xxxxx
            // which shows the debuggee is ready to accept connections.
            success.set(line.contains("Listening for transport dt_socket at address:"));
            return true;
        },
        Integer.MAX_VALUE,
        TimeUnit.MILLISECONDS
    );

    return success.get() ? p : null;
}
 
Example 3
Project: openjdk-jdk10   File: FileHandlerPath.java   View source code 6 votes vote down vote up
public SimplePolicy(TestCase test, AtomicBoolean allowAll) {
    this.allowAll = allowAll;
    permissions = new Permissions();
    permissions.add(new LoggingPermission("control", null)); // needed by new FileHandler()
    permissions.add(new FilePermission("<<ALL FILES>>", "read")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile, "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile+".lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(logFile+".1", "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile+".1.lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(tmpLogFile, "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpLogFile+".lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(tmpLogFile+".1", "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpLogFile+".1.lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(userDir, "write")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpDir, "write")); // needed by new FileHandler()
    permissions.add(new PropertyPermission("user.dir", "read"));
    permissions.add(new PropertyPermission("java.io.tmpdir", "read"));
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());
}
 
Example 4
Project: textmd   File: EditorExitItem.java   View source code 6 votes vote down vote up
@Override
public void getClickAction(final Stage stage, final TabFactory tabFactory) {
    List<Tab> tabs = FXCollections.observableArrayList(tabFactory.getTabPane().getTabs());
    Collections.reverse(tabs);
    AtomicBoolean close = new AtomicBoolean(true);
    tabs.forEach(t -> {
        if(close.get()){
            EditorTab eTab = ((EditorTab) t);
            if(!eTab.getEditorPane().exit()){
                close.set(false);
                return;
            }else{
                logger.debug("Closing tab {}", eTab.getEditorPane().getFile().getPath());
                tabFactory.getTabPane().getTabs().remove(eTab);
            }
        }
    });
    if(close.get())
        stage.close();
}
 
Example 5
Project: monarch   File: PartitionedRegionRebalanceOp.java   View source code 6 votes vote down vote up
/**
 * Create a rebalance operation for a single region.
 * 
 * @param region the region to rebalance
 * @param simulate true to only simulate rebalancing, without actually doing anything
 * @param replaceOfflineData true to replace offline copies of buckets with new live copies of
 *        buckets
 * @param isRebalance true if this op is a full rebalance instead of a more limited redundancy
 *        recovery
 * @param cancelled the AtomicBoolean reference used for cancellation; if any code sets the AB
 *        value to true then the rebalance will be cancelled
 * @param stats the ResourceManagerStats to use for rebalancing stats
 */
public PartitionedRegionRebalanceOp(PartitionedRegion region, boolean simulate,
    RebalanceDirector director, boolean replaceOfflineData, boolean isRebalance,
    AtomicBoolean cancelled, ResourceManagerStats stats) {

  PartitionedRegion leader = ColocationHelper.getLeaderRegion(region);
  Assert.assertTrue(leader != null);

  // set the region we are rebalancing to be leader of the colocation group.
  this.leaderRegion = leader;
  this.targetRegion = region;
  this.simulate = simulate;
  this.director = director;
  this.cancelled = cancelled;
  this.replaceOfflineData = replaceOfflineData;
  this.isRebalance = isRebalance;
  this.stats = simulate ? null : stats;
}
 
Example 6
Project: GitHub   File: OsSharedRealmTests.java   View source code 6 votes vote down vote up
@Test
public void registerSchemaChangedCallback_beginTransaction() {
    final AtomicBoolean listenerCalled = new AtomicBoolean(false);

    assertFalse(sharedRealm.hasTable("NewTable"));

    sharedRealm.registerSchemaChangedCallback(new OsSharedRealm.SchemaChangedCallback() {
        @Override
        public void onSchemaChanged() {
            assertTrue(sharedRealm.hasTable("NewTable"));
            listenerCalled.set(true);
        }
    });
    changeSchemaByAnotherRealm();
    sharedRealm.beginTransaction();
    assertTrue(listenerCalled.get());
}
 
Example 7
Project: incubator-netbeans   File: GoToSuperTypeAction.java   View source code 6 votes vote down vote up
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    final JavaSource js = JavaSource.forDocument(target.getDocument());
    
    if (js == null) {
        StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(GoToSupport.class, "WARN_CannotGoToGeneric",1));
        return;
    }
    
    final int caretPos = target.getCaretPosition();
    final AtomicBoolean cancel = new AtomicBoolean();
    
    ProgressUtils.runOffEventDispatchThread(new Runnable() {
        @Override
        public void run() {
            goToImpl(target, js, caretPos, cancel);
        }
    }, NbBundle.getMessage(JavaKit.class, "goto-super-implementation"), cancel, false);
}
 
Example 8
Project: kafka-0.11.0.0-src-with-comment   File: KafkaConsumerTest.java   View source code 6 votes vote down vote up
private AtomicBoolean prepareOffsetCommitResponse(MockClient client, Node coordinator, final Map<TopicPartition, Long> partitionOffsets) {
    final AtomicBoolean commitReceived = new AtomicBoolean(true);
    Map<TopicPartition, Errors> response = new HashMap<>();
    for (TopicPartition partition : partitionOffsets.keySet())
        response.put(partition, Errors.NONE);

    client.prepareResponseFrom(new MockClient.RequestMatcher() {
        @Override
        public boolean matches(AbstractRequest body) {
            OffsetCommitRequest commitRequest = (OffsetCommitRequest) body;
            for (Map.Entry<TopicPartition, Long> partitionOffset : partitionOffsets.entrySet()) {
                OffsetCommitRequest.PartitionData partitionData = commitRequest.offsetData().get(partitionOffset.getKey());
                // verify that the expected offset has been committed
                if (partitionData.offset != partitionOffset.getValue()) {
                    commitReceived.set(false);
                    return false;
                }
            }
            return true;
        }
    }, offsetCommitResponse(response), coordinator);
    return commitReceived;
}
 
Example 9
Project: incubator-netbeans   File: BasicCustomizer.java   View source code 6 votes vote down vote up
@Messages({
    "PROGRESS_loading_data=Loading project information",
    "# {0} - project display name", "LBL_CustomizerTitle=Project Properties - {0}"
})
public void showCustomizer(String preselectedCategory, final String preselectedSubCategory) {
    if (dialog != null) {
        dialog.setVisible(true);
    } else {
        final String category = (preselectedCategory != null) ? preselectedCategory : lastSelectedCategory;
        final AtomicReference<Lookup> context = new AtomicReference<Lookup>();
        ProgressUtils.runOffEventDispatchThread(new Runnable() {
            @Override public void run() {
                context.set(new ProxyLookup(prepareData(), Lookups.fixed(new SubCategoryProvider(category, preselectedSubCategory))));
            }
        }, PROGRESS_loading_data(), /* currently unused */new AtomicBoolean(), false);
        if (context.get() == null) { // canceled
            return;
        }
        OptionListener listener = new OptionListener();
        dialog = ProjectCustomizer.createCustomizerDialog(layerPath, context.get(), category, listener, null);
        dialog.addWindowListener(listener);
        dialog.setTitle(LBL_CustomizerTitle(ProjectUtils.getInformation(getProject()).getDisplayName()));
        dialog.setVisible(true);
    }
}
 
Example 10
Project: fdt   File: SelectionManager.java   View source code 6 votes vote down vote up
SelectionTask(Selector selector) {

            renewQueue = new ArrayDeque<FDTSelectionKey>();
            newQueue = new ArrayDeque<FDTSelectionKey>();

            hasToRun = new AtomicBoolean(false);

            if (selector == null) {
                throw new NullPointerException("Selector cannot be null in SelectionTask constructor");
            }

            if (!selector.isOpen()) {
                throw new IllegalArgumentException("Selector is not open in SelectionTask constructor");
            }

            this.selector = selector;
            hasToRun.set(true);
        }
 
Example 11
Project: cyberduck   File: ComparisonServiceFilterTest.java   View source code 6 votes vote down vote up
@Test
public void testCompareLocalOnlyDirectory() throws Exception {
    final AtomicBoolean found = new AtomicBoolean();
    final Find find = new Find() {
        @Override
        public boolean find(final Path file) throws BackgroundException {
            found.set(true);
            return false;
        }

        @Override
        public Find withCache(Cache<Path> cache) {
            return this;
        }
    };
    ComparisonServiceFilter s = new ComparisonServiceFilter(new NullSession(new Host(new TestProtocol())) {
    }, TimeZone.getDefault(), new DisabledProgressListener()).withFinder(find);
    assertEquals(Comparison.local, s.compare(new Path("t", EnumSet.of(Path.Type.directory)), new NullLocal("t") {
        @Override
        public boolean exists() {
            return true;
        }
    }));
    assertTrue(found.get());
}
 
Example 12
Project: letv   File: LoadAndDisplayImageTask.java   View source code 6 votes vote down vote up
private boolean waitIfPaused() {
    AtomicBoolean pause = this.engine.getPause();
    if (pause.get()) {
        synchronized (this.engine.getPauseLock()) {
            if (pause.get()) {
                L.d(LOG_WAITING_FOR_RESUME, this.memoryCacheKey);
                try {
                    this.engine.getPauseLock().wait();
                    L.d(LOG_RESUME_AFTER_PAUSE, this.memoryCacheKey);
                } catch (InterruptedException e) {
                    L.e(LOG_TASK_INTERRUPTED, this.memoryCacheKey);
                    return true;
                }
            }
        }
    }
    return isTaskNotActual();
}
 
Example 13
Project: WeatherWeight   File: ForecastPresenterTest.java   View source code 6 votes vote down vote up
@Test
public void searchOnSuccess() {
    String location = "San Francisco, CA";
    Channel channel = WeatherResponseFactory.createChannel();
    when(weatherRepository.getForecast(location)).thenReturn(Single.just(channel));

    final AtomicBoolean completableSubscribed = new AtomicBoolean(false);
    Completable saveCompletable = Completable.complete().doOnSubscribe(new Consumer<Disposable>() {
        @Override
        public void accept(Disposable disposable) throws Exception {
            completableSubscribed.set(true);
        }
    });
    when(lastForecastStore.save(channel)).thenReturn(saveCompletable);

    presenter.search(location);

    verify(view).showLoading(false);
    checkChannelSet(channel);
    assertThat(completableSubscribed.get(), is(true));
    assertThat(presenter.getAttributionUrl(), is(channel.getLink()));
}
 
Example 14
Project: java-red   File: TestRedFuture.java   View source code 6 votes vote down vote up
/**
 * Test the completion and callback invocation of {@link RedFutureHub}
 * pessimistic union of provided futures that later were successfully resolved
 */
@Test
public void testPessimisticProvidePostResolveSuccess() throws Throwable {
    AtomicBoolean reachedSuccessBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFailureBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFinallyBlock = new AtomicBoolean(false);
    RedFutureHub hub = RedFuture.hub();
    OpenRedFuture future1 = hub.provideFuture();
    OpenRedFuture future2 = hub.provideFuture();
    OpenRedFutureOf<Object> futureOf = hub.provideFutureOf();
    RedFuture union = hub.unitePessimistically();
    union.addSuccessCallback(() -> reachedSuccessBlock.set(true));
    union.addFailureCallback(throwable -> reachedFailureBlock.set(true));
    union.addFinallyCallback(() -> reachedFinallyBlock.set(true));
    Assert.assertFalse(reachedFinallyBlock.get());
    Assert.assertFalse(reachedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
    future1.resolve();
    future2.resolve();
    futureOf.resolve(new Object());
    Assert.assertTrue(reachedFinallyBlock.get());
    Assert.assertTrue(reachedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
}
 
Example 15
Project: googles-monorepo-demo   File: AtomicLongMap.java   View source code 6 votes vote down vote up
/**
 * If {@code key} is not already associated with a value or if {@code key} is associated with
 * zero, associate it with {@code newValue}. Returns the previous value associated with
 * {@code key}, or zero if there was no mapping for {@code key}.
 */
long putIfAbsent(K key, long newValue) {
  AtomicBoolean noValue = new AtomicBoolean(false);
  Long result =
      map.compute(
          key,
          (k, oldValue) -> {
            if (oldValue == null || oldValue == 0) {
              noValue.set(true);
              return newValue;
            } else {
              return oldValue;
            }
          });
  return noValue.get() ? 0L : result.longValue();
}
 
Example 16
Project: GitHub   File: RxJavaTests.java   View source code 6 votes vote down vote up
@Test
@UiThreadTest
public void realmObject_emittedOnSubscribe() {
    realm.beginTransaction();
    final AllTypes obj = realm.createObject(AllTypes.class);
    realm.commitTransaction();

    final AtomicBoolean subscribedNotified = new AtomicBoolean(false);
    subscription = obj.<AllTypes>asFlowable().subscribe(new Consumer <AllTypes>() {
        @Override
        public void accept(AllTypes rxObject) throws Exception {
            assertTrue(rxObject == obj);
            subscribedNotified.set(true);
        }
    });
    assertTrue(subscribedNotified.get());
    subscription.dispose();
}
 
Example 17
Project: cordova-plugin-smartconfig   File: __EsptouchTask.java   View source code 6 votes vote down vote up
public __EsptouchTask(String apSsid, String apBssid, String apPassword,
		Context context, IEsptouchTaskParameter parameter,
		boolean isSsidHidden) {
	Log.i(TAG, "Welcome Esptouch " + ESPTOUCH_VERSION);
	if (TextUtils.isEmpty(apSsid)) {
		throw new IllegalArgumentException(
				"the apSsid should be null or empty");
	}
	if (apPassword == null) {
		apPassword = "";
	}
	mContext = context;
	mApSsid = apSsid;
	mApBssid = apBssid;
	mApPassword = apPassword;
	mIsCancelled = new AtomicBoolean(false);
	mSocketClient = new UDPSocketClient();
	mParameter = parameter;
	mSocketServer = new UDPSocketServer(mParameter.getPortListening(),
			mParameter.getWaitUdpTotalMillisecond(), context);
	mIsSsidHidden = isSsidHidden;
	mEsptouchResultList = new ArrayList<IEsptouchResult>();
	mBssidTaskSucCountMap = new HashMap<String, Integer>();
}
 
Example 18
Project: incubator-netbeans   File: LinuxNotifier235632Test.java   View source code 6 votes vote down vote up
/**
 * Create a logging handler that sets value in an AtomicBoolean to true if
 * folder2 or text2.txt is refreshed.
 *
 * @param refreshedFlag The AtomicBoolean to be set to true if incorrect
 * refreshing was triggered.
 * @return The new logging handler.
 */
private Handler createHandler(final AtomicBoolean refreshedFlag) {
    Handler h = new Handler() {

        @Override
        public void publish(LogRecord record) {
            if (record.getMessage() != null
                    && record.getMessage().startsWith("refreshImpl for ")
                    && record.getParameters() != null
                    && record.getParameters().length > 0
                    && (record.getParameters()[0] == folder2FO
                    || record.getParameters()[0] == folder2text2TxtFO)) {
                refreshedFlag.set(true);
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };
    return h;
}
 
Example 19
Project: booter-injector   File: Suppliers.java   View source code 6 votes vote down vote up
/**
 * This method transforms input supplier which creates instances of other suppliers into lazily instantiating
 * supplier. In other words, input factory which creates instances of suppliers will be invoked only once and only
 * when first call to created supplier will be made. Note that after creation of supplier, resulting supplier
 * becomes very thin wrapper around created supplier and is subject of HotSpot optimizations during
 * further calls.
 *
 * @param factory
 *          Factory supplier which provides instances of supplier of specified type. Invoked only once.
 * @return Lazily instantiating supplier.
 */
public static <T> Supplier<T> factoryLazy(final Supplier<Supplier<T>> factory) {
    Utils.validateNotNull(factory);

    return new Supplier<T>() {
        private final Supplier<T> defaultDelegate = this::init;
        private final AtomicBoolean initialized = new AtomicBoolean();
        private Supplier<T> delegate = defaultDelegate;

        private T init() {
            if (initialized.compareAndSet(false, true)) {
                delegate = factory.get();
            } else {
                while (delegate == defaultDelegate) {
                    //Intentionally left empty
                }
            }
            return delegate.get();
        }

        public T get() {
            return delegate.get();
        }
    };
}
 
Example 20
Project: jdk8u-jdk   File: FileHandlerPath.java   View source code 6 votes vote down vote up
public SimplePolicy(TestCase test, AtomicBoolean allowAll) {
    this.allowAll = allowAll;
    permissions = new Permissions();
    permissions.add(new LoggingPermission("control", null)); // needed by new FileHandler()
    permissions.add(new FilePermission("<<ALL FILES>>", "read")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile, "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile+".lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(logFile+".1", "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile+".1.lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(tmpLogFile, "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpLogFile+".lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(tmpLogFile+".1", "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpLogFile+".1.lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(userDir, "write")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpDir, "write")); // needed by new FileHandler()
    permissions.add(new PropertyPermission("user.dir", "read"));
    permissions.add(new PropertyPermission("java.io.tmpdir", "read"));
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());
}
 
Example 21
Project: RxJava3-preview   File: FlowableCollectTest.java   View source code 6 votes vote down vote up
@Test
public void testCollectorFailureDoesNotResultInErrorAndOnNextEmissions() {
    final RuntimeException e = new RuntimeException();
    final AtomicBoolean added = new AtomicBoolean();
    BiConsumer<Object, Integer> throwOnFirstOnly = new BiConsumer<Object, Integer>() {

        boolean once = true;

        @Override
        public void accept(Object o, Integer t) {
            if (once) {
                once = false;
                throw e;
            } else {
                added.set(true);
            }
        }
    };
    Burst.items(1, 2).create() //
            .collect(callableListCreator(), throwOnFirstOnly)//
            .test() //
            .assertError(e) //
            .assertNoValues() //
            .assertNotComplete();
    assertFalse(added.get());
}
 
Example 22
Project: incubator-netbeans   File: RunOffEDTTest.java   View source code 6 votes vote down vote up
public void testDlgIsShown() throws Exception {
    final R r = new R();
    r.l = new CountDownLatch(1);
    final boolean[] shown = new boolean[] { false };
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
            if (w != null) {
                r.l.countDown();
                shown[0] = true;
            }
        }
    });
    SwingUtilities.invokeAndWait(new Runnable() {

        public void run() {
            ProgressUtils.runOffEventDispatchThread(r, "Test", new AtomicBoolean(false), true, 10, 100);
        }
    });
    if (!shown[0]) {
        fail("Dialog was not shown");
    }
}
 
Example 23
Project: flume-release-1.7.0   File: SinkRunner.java   View source code 6 votes vote down vote up
@Override
public void start() {
  SinkProcessor policy = getPolicy();

  policy.start();

  runner = new PollingRunner();

  runner.policy = policy;
  runner.counterGroup = counterGroup;
  runner.shouldStop = new AtomicBoolean();

  runnerThread = new Thread(runner);
  runnerThread.setName("SinkRunner-PollingRunner-" +
      policy.getClass().getSimpleName());
  runnerThread.start();

  lifecycleState = LifecycleState.START;
}
 
Example 24
Project: cyberduck   File: SFTPSessionTest.java   View source code 6 votes vote down vote up
@Test(expected = LoginCanceledException.class)
public void testValidateNoValidCredentials() throws Exception {
    final Host host = new Host(new SFTPProtocol(), "test.cyberduck.ch");
    final Session session = new SFTPSession(host);
    final AtomicBoolean change = new AtomicBoolean();
    final LoginConnectionService login = new LoginConnectionService(new DisabledLoginCallback() {
        @Override
        public Credentials prompt(final Host bookmark, String username,
                                  String title, String reason, LoginOptions options)
            throws LoginCanceledException {
            assertEquals("Login test.cyberduck.ch", title);
            assertEquals("Login test.cyberduck.ch – SFTP with username and password. No login credentials could be found in the Keychain.", reason);
            change.set(true);
            throw new LoginCanceledException();
        }
    }, new DisabledHostKeyCallback(), new DisabledPasswordStore(),
        new DisabledProgressListener());
    try {
        login.check(session, PathCache.empty(), new DisabledCancelCallback());
    }
    catch(LoginCanceledException e) {
        assertTrue(change.get());
        throw e;
    }
}
 
Example 25
Project: GitHub   File: MediaVariationsFallbackProducerTest.java   View source code 6 votes vote down vote up
@Test
public void testLooksForAllVariantsFromIndexIfNotFound() {
  when(mImageRequest.getMediaVariations()).thenReturn(mEmptyMediaVariations);
  whenIndexDbContainsAllVariants();

  mMediaVariationsFallbackProducer.produceResults(mConsumer, mProducerContext);

  // Check they're requested in the correct order
  InOrder inOrder = inOrder(mDefaultBufferedDiskCache);
  inOrder.verify(mDefaultBufferedDiskCache).get(eq(CACHE_KEY_M), any(AtomicBoolean.class));
  inOrder.verify(mDefaultBufferedDiskCache).get(eq(CACHE_KEY_L), any(AtomicBoolean.class));
  inOrder.verify(mDefaultBufferedDiskCache).get(eq(CACHE_KEY_S), any(AtomicBoolean.class));

  verifyInputProducerProduceResultsWithNewConsumer(true);
  verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
  verifySuccessSentToListener(
      NOT_FOUND,
      USED_AS_LAST_FLAG_NOT_EXPECTED,
      MediaVariations.SOURCE_INDEX_DB,
      VARIANTS_COUNT);
  verifyZeroInteractions(mConsumer, mSmallImageBufferedDiskCache);
}
 
Example 26
Project: pooled-jms   File: JmsPoolJMSProducerTest.java   View source code 5 votes vote down vote up
private void doTestSendAppliesPriorityWithMessageBody(Class<?> bodyType) throws JMSException {
    JMSProducer producer = context.createProducer();

    final AtomicBoolean lowPriority = new AtomicBoolean();
    final AtomicBoolean highPriority = new AtomicBoolean();

    MockJMSConnection connection = (MockJMSConnection) context.getConnection();
    connection.addConnectionListener(new MockJMSDefaultConnectionListener() {

        @Override
        public void onMessageSend(MockJMSSession session, Message message) throws JMSException {
            if (!lowPriority.get()) {
                assertEquals(0, message.getJMSPriority());
                lowPriority.set(true);
            } else {
                assertEquals(7, message.getJMSPriority());
                highPriority.set(true);
            }
        }
    });

    producer.setPriority(0);
    producer.send(JMS_DESTINATION, "text");

    producer.setPriority(7);
    producer.send(JMS_DESTINATION, "text");

    assertTrue(lowPriority.get());
    assertTrue(highPriority.get());
}
 
Example 27
Project: incubator-netbeans   File: CopyFinderBasedBulkSearch.java   View source code 5 votes vote down vote up
@Override
public BulkPattern create(Collection<? extends String> code, Collection<? extends Tree> patterns, Collection<? extends AdditionalQueryConstraints> additionalConstraints, AtomicBoolean cancel) {
    Map<Tree, String> pattern2Code = new HashMap<Tree, String>();

    Iterator<? extends String> itCode = code.iterator();
    Iterator<? extends Tree>   itPatt = patterns.iterator();

    while (itCode.hasNext() && itPatt.hasNext()) {
        pattern2Code.put(itPatt.next(), itCode.next());
    }

    return new BulkPatternImpl(additionalConstraints, pattern2Code);
}
 
Example 28
Project: incubator-servicecomb-java-chassis   File: TestEventBus.java   View source code 5 votes vote down vote up
@Test
public void test() throws InterruptedException {
  AtomicBoolean eventReceived = new AtomicBoolean(false);

  EventListener listener = new EventListener() {
    @Override
    public Class<? extends Event> getConcernedEvent() {
      return TestEvent.class;
    }

    @Override
    public void process(Event data) {
      eventReceived.set(true);
    }
  };

  EventUtils.registerEventListener(listener);
  EventUtils.triggerEvent(new TestEvent());
  await().atMost(1, TimeUnit.SECONDS)
      .until(eventReceived::get);
  Assert.assertTrue(eventReceived.get());

  eventReceived.set(false);

  EventUtils.unregisterEventListener(listener);
  EventUtils.triggerEvent(new TestEvent());
  Thread.sleep(1000);
  Assert.assertFalse(eventReceived.get());
}
 
Example 29
Project: incubator-netbeans   File: HtmlPaletteCompletionProvider.java   View source code 5 votes vote down vote up
@Override
protected boolean canFilter(final JTextComponent component) {
    final Collection<PaletteCompletionItem> currentItems = items;
    if(currentItems == null) {
        return false;
    }
    final Document doc = component.getDocument();
    final AtomicBoolean retval = new AtomicBoolean();
    doc.render(new Runnable() {

        @Override
        public void run() {
            try {
                int offset = component.getCaretPosition();
                if (completionExpressionStartOffset < 0  || offset < completionExpressionStartOffset) {
                    retval.set(false);
                    return;
                }
                String prefix = doc.getText(completionExpressionStartOffset, offset - completionExpressionStartOffset);
                //check the items
                for (PaletteCompletionItem item : currentItems) {
                    if (startsWithIgnoreCase(item.getItemName(), prefix)) {
                        retval.set(true); //at least one item will remain
                        return;
                    }
                }
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });


    return retval.get();

}
 
Example 30
Project: incubator-netbeans   File: Analyzer.java   View source code 5 votes vote down vote up
public static void process(Lookup context, HintsSettings hintsSettings) {
    final AtomicBoolean abCancel = new AtomicBoolean();
    class Cancel implements Cancellable {
        public boolean cancel() {
            abCancel.set(true);
            return true;
        }
    }
    
    ProgressHandle h = ProgressHandleFactory.createHandle(NbBundle.getMessage(Analyzer.class, "LBL_AnalyzingJavadoc"), new Cancel()); // NOI18N

    RP.post(new Analyzer(context, abCancel, h, hintsSettings));
}
 
Example 31
Project: FJ-VDMJ   File: TCForIndexStatement.java   View source code 5 votes vote down vote up
@Override
public TCNameSet getFreeVariables(Environment globals, Environment env, AtomicBoolean returns)
{
	TCNameSet names = from.getFreeVariables(globals, env);
	names.addAll(to.getFreeVariables(globals, env));
	
	if (by != null)
	{
		names.addAll(by.getFreeVariables(globals, env));
	}
	
	return names;
}
 
Example 32
Project: Matcher   File: FileMenu.java   View source code 5 votes vote down vote up
private static boolean clearDir(Path path, Predicate<Path> disallowed) throws IOException {
	try (Stream<Path> stream = Files.walk(path, FileVisitOption.FOLLOW_LINKS)) {
		if (stream.anyMatch(disallowed)) return false;
	}

	AtomicBoolean ret = new AtomicBoolean(true);

	Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
		@Override
		public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
			if (disallowed.test(file)) {
				ret.set(false);

				return FileVisitResult.TERMINATE;
			} else {
				Files.delete(file);

				return FileVisitResult.CONTINUE;
			}
		}

		@Override
		public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
			if (exc != null) throw exc;
			if (!dir.equals(path)) Files.delete(dir);

			return FileVisitResult.CONTINUE;
		}
	});

	return ret.get();
}
 
Example 33
Project: nativescript-simple-networking   File: TcpServer.java   View source code 5 votes vote down vote up
public TcpServer(int maxClients, TcpServerListener listener) {
    mMaxClients = maxClients;
    mListener = listener;
    mExecutor = Executors.newFixedThreadPool(maxClients + 2);
    mClients = new ConcurrentHashMap<>();
    mIsAccepting = new AtomicBoolean(false);
    mId = new AtomicInteger();
}
 
Example 34
Project: openjdk-jdk10   File: HandlersOnComplexUpdate.java   View source code 5 votes vote down vote up
public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
    this.allowAll = allowAll;
    permissions = new Permissions();
    permissions.add(new LoggingPermission("control", null));
    permissions.add(new FilePermission(PREFIX+".lck", "read,write,delete"));
    permissions.add(new FilePermission(PREFIX, "read,write"));

    // these are used for configuring the test itself...
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());

}
 
Example 35
Project: grooves   File: QueryExecutor.java   View source code 5 votes vote down vote up
/**
 * Decides how to proceed after inspecting the response of a method that returns an
 * {@link EventApplyOutcome}.
 *
 * @param stopApplyingEvents Whether a previous decision has been made to stop applying new
 *                           events
 * @param snapshot           The snapshot on which events are being added
 * @param methodName         The name of the method that was called
 * @param retval             The outcome of calling the method
 *
 * @return The snapshot after deciding what to do with the {@link EventApplyOutcome}
 */
private Flowable<? extends SnapshotT> handleMethodResponse(
        AtomicBoolean stopApplyingEvents, SnapshotT snapshot, String methodName,
        EventApplyOutcome retval) {
    switch (retval) {
        case RETURN:
            stopApplyingEvents.set(true);
            return just(snapshot);
        case CONTINUE:
            return just(snapshot);
        default:
            throw new GroovesException(
                    String.format("Unexpected value from calling '%s'", methodName));
    }
}
 
Example 36
Project: incubator-netbeans   File: LuceneIndex.java   View source code 5 votes vote down vote up
@Override
public <T> void queryTermFrequencies(
        final @NonNull Collection<? super T> result,
        final @NullAllowed Term seekTo,
        final @NonNull StoppableConvertor<Index.WithTermFrequencies.TermFreq,T> filter,
        final @NullAllowed AtomicBoolean cancel) throws IOException, InterruptedException {
    queryTermsImpl(result, seekTo, Convertors.newTermEnumToFreqConvertor(filter), cancel);
}
 
Example 37
Project: incubator-netbeans   File: UnitTestLibrariesNode.java   View source code 5 votes vote down vote up
private void refreshKeys() {
    ImportantFilesNodeFactory.getNodesSyncRP().post(new Runnable() {

        @Override
        public void run() {
            try {
                ProjectManager.mutex().readAccess(new Mutex.ExceptionAction<Object>() {
                    public @Override Object run() throws Exception {
                        final Collection<TestModuleDependency> deps = new TreeSet<TestModuleDependency>(TestModuleDependency.CNB_COMPARATOR);
                        final AtomicBoolean missingJUnit4 = new AtomicBoolean(true);
                        Set<TestModuleDependency> tmds = new ProjectXMLManager(project).getTestDependencies(project.getModuleList()).get(testType);
                        if (tmds != null) { // will be null if have no <test-dependencies> of this type
                            for (TestModuleDependency tmd : tmds) {
                                deps.add(tmd);
                                if (tmd.getModule().getCodeNameBase().equals("org.netbeans.libs.junit4")) { // NOI18N
                                    missingJUnit4.set(false);
                                }
                            }
                        }
                        ImportantFilesNodeFactory.getNodesSyncRP().post(new Runnable() {
                            public @Override void run() {
                                ((UnitTestLibrariesNode) getNode()).setMissingJUnit4(missingJUnit4.get());
                                setKeys(deps);
                            }
                        });
                        return null;
                    }
                });
            } catch (MutexException e) {
                LOG.log(Level.INFO, null, e);
            }
        }
    });
}
 
Example 38
Project: uavstack   File: BooleanCodec.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
    final JSONLexer lexer = parser.getLexer();

    Boolean boolObj;
    if (lexer.token() == JSONToken.TRUE) {
        lexer.nextToken(JSONToken.COMMA);
        boolObj = Boolean.TRUE;
    } else if (lexer.token() == JSONToken.FALSE) {
        lexer.nextToken(JSONToken.COMMA);
        boolObj = Boolean.FALSE;
    } else if (lexer.token() == JSONToken.LITERAL_INT) {
        int intValue = lexer.intValue();
        lexer.nextToken(JSONToken.COMMA);

        if (intValue == 1) {
            boolObj = Boolean.TRUE;
        } else {
            boolObj = Boolean.FALSE;
        }
    } else {
        Object value = parser.parse();

        if (value == null) {
            return null;
        }

        boolObj = TypeUtils.castToBoolean(value);
    }

    if (clazz == AtomicBoolean.class) {
        return (T) new AtomicBoolean(boolObj.booleanValue());
    }

    return (T) boolObj;
}
 
Example 39
Project: incubator-netbeans   File: ComputeOffAWT.java   View source code 5 votes vote down vote up
public static <T> T computeOffAWT(Worker<T> w, String featureName, final JavaSource source, Phase phase) {
    AtomicBoolean cancel = new AtomicBoolean();
    Compute<T> c = new Compute(cancel, source, phase, w);

    ProgressUtils.runOffEventDispatchThread(c, featureName, cancel, false);

    return c.result;
}
 
Example 40
Project: htsjdk-s3-plugin   File: PartReader.java   View source code 5 votes vote down vote up
PartReader(AmazonS3URI uri, long from, long to, AtomicBoolean canceledFlag,
        S3InputStreamFactory factory) {
    this.canceledFlag = canceledFlag;
    this.uri = uri;
    this.from = from;
    this.to = to;

    this.threadName = "[" + from + " : " + to + "](" + uri.toString() + ")";

    this.factory = factory;
}