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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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;
}
 
Example 41
Project: Cubes_2   File: SocketMonitor.java   Source Code and License 5 votes vote down vote up
public SocketMonitor(Socket socket, Networking networking, Side side) {
  this.socket = socket;
  this.networking = networking;
  this.side = side;
  this.remoteAddress = socket.getRemoteAddress();
  running = new AtomicBoolean(true);
  socketInput = new SocketInput(this);
  socketOutput = new SocketOutput(this);
  socketInput.start("Socket Input: " + remoteAddress);
  socketOutput.start("Socket Output: " + remoteAddress);
  this.packetIDDatabase = new PacketIDDatabase();
}
 
Example 42
Project: cyberduck   File: SwiftDirectoryFeatureTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCreatePlaceholder() throws Exception {
    final Host host = new Host(new SwiftProtocol(), "identity.api.rackspacecloud.com", new Credentials(
        System.getProperties().getProperty("rackspace.key"), System.getProperties().getProperty("rackspace.secret")
    ));
    final SwiftSession session = new SwiftSession(host);
    final AtomicBoolean put = new AtomicBoolean();
    final String name = UUID.randomUUID().toString();
    session.withListener(new TranscriptListener() {
        @Override
        public void log(final Type request, final String message) {
            switch(request) {
                case request:
                    if(("PUT /v1/MossoCloudFS_59113590-c679-46c3-bf62-9d7c3d5176ee/test.cyberduck.ch/" + name + " HTTP/1.1").equals(message)) {
                        put.set(true);
                    }
            }
        }
    });
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path container = new Path("/test.cyberduck.ch", EnumSet.of(Path.Type.volume, Path.Type.directory));
    container.attributes().setRegion("ORD");
    final Path placeholder = new Path(container, name, EnumSet.of(Path.Type.directory));
    final SwiftDirectoryFeature feature = new SwiftDirectoryFeature(session, new SwiftRegionService(session), new SwiftWriteFeature(session, new SwiftRegionService(session)));
    feature.mkdir(placeholder, null, new TransferStatus());
    Thread.sleep(1000L);
    assertTrue(put.get());
    assertTrue(new SwiftFindFeature(session).find(placeholder));
    assertTrue(new DefaultFindFeature(session).find(placeholder));
    new SwiftDeleteFeature(session).delete(Collections.singletonList(placeholder), new DisabledLoginCallback(), new Delete.DisabledCallback());
    assertFalse(new SwiftFindFeature(session).find(placeholder));
    session.close();
}
 
Example 43
Project: RxJava3-preview   File: FlowableToSingleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testShouldUseUnsafeSubscribeInternallyNotSubscribe() {
    TestObserver<String> subscriber = TestObserver.create();
    final AtomicBoolean unsubscribed = new AtomicBoolean(false);
    Single<String> single = single(Flowable.just("Hello World!").doOnCancel(new Action() {

        @Override
        public void run() {
            unsubscribed.set(true);
        }}), "");
    single.subscribe(subscriber);
    subscriber.assertComplete();
    Assert.assertFalse(unsubscribed.get());
}
 
Example 44
Project: firebase-admin-java   File: QueryTestIT.java   Source Code and License 5 votes vote down vote up
@Test
public void testCacheInvalidation()
    throws InterruptedException, TestFailure, TimeoutException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference reader = refs.get(0);
  DatabaseReference writer = refs.get(1);

  final AtomicBoolean startChecking = new AtomicBoolean(false);
  final Semaphore ready = new Semaphore(0);
  final ReadFuture future = new ReadFuture(reader.limitToLast(2), 
      new ReadFuture.CompletionCondition() {
        @Override
        public boolean isComplete(List<EventRecord> events) {
          DataSnapshot snap = events.get(events.size() - 1).getSnapshot();
          Object result = snap.getValue();
          if (startChecking.compareAndSet(false, true) && result == null) {
            ready.release(1);
            return false;
          }
          // We already initialized the location, and now the remove has
          // happened
          // so that
          // we have no more data
          return startChecking.get() && result == null;
        }
      });

  TestHelpers.waitFor(ready);
  for (int i = 0; i < 4; ++i) {
    writer.child("k" + i).setValueAsync(i);
  }

  writer.removeValueAsync();
  future.timedGet();
}
 
Example 45
Project: FirefoxData-android   File: PoolingHttpClientConnectionManager.java   Source Code and License 5 votes vote down vote up
PoolingHttpClientConnectionManager(
        final CPool pool,
        final Lookup<ConnectionSocketFactory> socketFactoryRegistry,
        final SchemePortResolver schemePortResolver,
        final DnsResolver dnsResolver) {
    super();
    this.configData = new ConfigData();
    this.pool = pool;
    this.connectionOperator = new HttpClientConnectionOperator(
            socketFactoryRegistry, schemePortResolver, dnsResolver);
    this.isShutDown = new AtomicBoolean(false);
}
 
Example 46
Project: cyberduck   File: S3BucketCreateServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCreateBucket() throws Exception {
    final S3Session session = new S3Session(
        new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(),
            new Credentials(
                System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")
            )));
    final AtomicBoolean header = new AtomicBoolean();
    final AtomicBoolean signature = new AtomicBoolean();
    session.withListener(new TranscriptListener() {
        @Override
        public void log(final Type request, final String message) {
            if(StringUtils.contains(message, "Expect: 100-continue")) {
                header.set(true);
            }
            if(StringUtils.contains(message, "SignedHeaders=content-type;date;expect;host;x-amz-acl;x-amz-content-sha256;x-amz-date")) {
                signature.set(true);
            }
        }
    });
    assertNotNull(session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback()));
    final S3BucketCreateService create = new S3BucketCreateService(session);
    final Path bucket = new Path(new AsciiRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume));
    create.create(bucket, "eu-central-1");
    assertTrue(header.get());
    bucket.attributes().setRegion("eu-central-1");
    assertTrue(new S3FindFeature(session).find(bucket));
    new S3DefaultDeleteFeature(session).delete(Collections.<Path>singletonList(bucket), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 47
Project: pgcodekeeper   File: PgColumn.java   Source Code and License 5 votes vote down vote up
@Override
public String getCreationSQL() {
    StringBuilder sb = new StringBuilder();

    if (type != null) {
        sb.append(getAlterTable());
        sb.append("\n\tADD COLUMN ")
        .append(PgDiffUtils.getQuotedName(name))
        .append(' ')
        .append(type);
        if (collation != null) {
            sb.append(" COLLATE ").append(collation);
        }
        sb.append(';');
    }

    compareDefaults(null, defaultValue, new AtomicBoolean(), sb);
    compareNullValues(true, nullValue, sb);
    compareStorages(null, storage, sb);

    appendPrivileges(sb);

    compareForeignOptions(Collections.<String, String>emptyMap(), fOptions, sb);
    writeOptions(true, sb);
    compareStats(null, statistics, sb);
    compareIdentity(null, identityType, null, sequence, sb);

    if (comment != null && !comment.isEmpty()) {
        sb.append("\n\n");
        appendCommentSql(sb);
    }

    return sb.toString();
}
 
Example 48
Project: incubator-netbeans   File: ElementOpen.java   Source Code and License 5 votes vote down vote up
/**
 * Opens given {@link Element}.
 * 
 * @param toSearch fileobject whose {@link ClasspathInfo} will be used
 * @param toOpen   {@link ElementHandle} of the element which should be opened.
 * @return true if and only if the declaration was correctly opened,
 *                false otherwise
 */
public static boolean open(
        @NonNull final FileObject toSearch,
        @NonNull final ElementHandle<? extends Element> toOpen) {
    final AtomicBoolean cancel = new AtomicBoolean();
    if (SwingUtilities.isEventDispatchThread() && !JavaSourceAccessor.holdsParserLock()) {
        final Object[] openInfo = new Object[3];
        ProgressUtils.runOffEventDispatchThread(new Runnable() {
                public void run() {
                    Object[] info = !isClassFile(toSearch) ? getOpenInfo (toSearch, toOpen, cancel) : null;
                    if (info != null) {
                        openInfo[0] = info[0];
                        openInfo[1] = info[1];
                        openInfo[2] = info[2];
                    }
                }
            },
            NbBundle.getMessage(ElementOpen.class, "TXT_CalculatingDeclPos"),
            cancel,
            false);
        if (cancel.get()) {
            return false;
        }
        if (openInfo[0] instanceof FileObject) {
            return doOpen((FileObject)openInfo[0],(int)openInfo[1], (int)openInfo[2]);
        }
        return binaryOpen(toSearch, toOpen, cancel);
    } else {
        return open(toSearch, toOpen, cancel);
    }
}
 
Example 49
Project: grpc-java-contrib   File: MoreFuturesTest.java   Source Code and License 5 votes vote down vote up
@Test
public void addCallbackFailure() {
    AtomicBoolean called = new AtomicBoolean(false);
    final Exception ex = new Exception();

    SettableFuture<Object> future = SettableFuture.create();
    MoreFutures.onFailure(
            future,
            e -> { assertEquals(ex, e); called.set(true); },
            MoreExecutors.directExecutor());

    assertFalse(called.get());
    future.setException(ex);
    assertTrue(called.get());
}
 
Example 50
Project: rapidminer   File: JFreeChartPlotEngine.java   Source Code and License 5 votes vote down vote up
public JFreeChartPlotEngine(PlotInstance plotInstanceForEngine, boolean zoomInOnSelection, boolean useBuffer) {

		this.plotInstance = plotInstanceForEngine;
		updatingChart = new AtomicBoolean(false);

		chartPanel = new LinkAndBrushChartPanel(new JFreeChart(new CategoryPlot()), 50, 50, 50, 50, zoomInOnSelection,
				useBuffer);
		chartPanel.setMinimumDrawWidth(50);
		chartPanel.setMinimumDrawHeight(50);
		chartPanel.setMaximumDrawWidth(10000);
		chartPanel.setMaximumDrawHeight(10000);
		chartPanel.addMouseListener(popupMenuListener);

		subscribeAtPlotInstance(plotInstance);
	}
 
Example 51
Project: armadillo   File: SecureSharedPreferenceUnitTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testChangeListener() throws Exception {
    AtomicBoolean b = new AtomicBoolean(false);
    SharedPreferences.OnSharedPreferenceChangeListener listener = (sharedPreferences, s) -> b.set(true);
    preferences.registerOnSharedPreferenceChangeListener(listener);
    preferences.edit().putString("s", "test").commit();
    assertTrue(b.get());
    preferences.unregisterOnSharedPreferenceChangeListener(listener);
}
 
Example 52
Project: java-red   File: TestRedFuture.java   Source Code and License 5 votes vote down vote up
/**
 * Test the failing of {@link OpenRedFutureOf} through {@link OpenRedFutureOf#fail(Throwable)}
 */
@Test
public void testFutureOfFail() throws Throwable {
    AtomicBoolean failureBlockReached = new AtomicBoolean(false);
    AtomicBoolean correctThrowableReturned = new AtomicBoolean(false);
    AtomicBoolean successBlockReached = new AtomicBoolean(false);
    AtomicBoolean finallyBlockReached = new AtomicBoolean(false);
    AtomicBoolean valueSuccessBlockReached = new AtomicBoolean(false);
    OpenRedFutureOf<Object> future = RedFuture.futureOf();
    Throwable throwable = new TestException();
    future.addFailureCallback(aThrowable -> {
        if (throwable == aThrowable) {
            correctThrowableReturned.set(true);
        }
        failureBlockReached.set(true);
    });
    future.addSuccessCallback(() -> successBlockReached.set(true));
    future.addFinallyCallback(() -> finallyBlockReached.set(true));
    future.addSuccessCallback(o -> valueSuccessBlockReached.set(true));
    future.fail(throwable);
    Assert.assertEquals(failureBlockReached.get(), true);
    Assert.assertEquals(correctThrowableReturned.get(), true);
    Thread.sleep(VALIDATION_SLEEP_TIME);
    Assert.assertEquals(successBlockReached.get(), false);
    Assert.assertEquals(finallyBlockReached.get(), true);
    Assert.assertEquals(valueSuccessBlockReached.get(), false);
}
 
Example 53
Project: incubator-netbeans   File: WhiteListTaskProvider.java   Source Code and License 5 votes vote down vote up
private static void updateErrorsInRoot(
        @NonNull final Callback callback,
        @NonNull final FileObject root,
        @NonNull final AtomicBoolean canceled) {
    Set<FileObject> filesWithErrors = getFilesWithAttachedErrors(root);
    Set<FileObject> fixedFiles = new HashSet<FileObject>(filesWithErrors);
    filesWithErrors.clear();
    Set<FileObject> nueFilesWithErrors = new HashSet<FileObject>();
    final Map<FileObject,List<Task>> filesToTasks = new HashMap<FileObject,List<Task>>();
    for (WhiteListIndex.Problem problem : WhiteListIndex.getDefault().getWhiteListViolations(root, null)) {
        if (canceled.get()) {
            return;
        }
        final Map.Entry<FileObject,List<? extends Task>> task = createTask(problem);
        if (task != null) {
            List<Task> tasks = filesToTasks.get(task.getKey());
            if (tasks == null) {
                tasks = new ArrayList<Task>();
                filesToTasks.put(task.getKey(), tasks);
            }
            tasks.addAll(task.getValue());
        }
    }
    for (Map.Entry<FileObject,List<Task>> e : filesToTasks.entrySet()) {
        LOG.log(Level.FINE, "Setting {1} for {0}\n",
                new Object[] {e.getKey(), e.getValue()});
                callback.setTasks(e.getKey(), e.getValue());
        if (!fixedFiles.remove(e.getKey())) {
            nueFilesWithErrors.add(e.getKey());
        }
    }
    for (FileObject f : fixedFiles) {
        LOG.log(Level.FINE, "Clearing errors for {0}", f);
        callback.setTasks(f, Collections.<Task>emptyList());
    }
    filesWithErrors.addAll(nueFilesWithErrors);
}
 
Example 54
Project: jax-rs-moshi   File: MoshiMessageBodyWriterTest.java   Source Code and License 5 votes vote down vote up
@Test public void writeDoesNotClose() throws IOException {
  final AtomicBoolean closed = new AtomicBoolean();
  BufferedSink data = Okio.buffer(new ForwardingSink(new Buffer()) {
    @Override public void close() throws IOException {
      closed.set(true);
      super.close();
    }
  });
  writer.writeTo("hey", String.class, String.class, new Annotation[0], APPLICATION_JSON_TYPE,
      new MultivaluedHashMap<>(), data.outputStream());
  assertFalse(closed.get());
}
 
Example 55
Project: jdk8u-jdk   File: TestAlwaysOnTopBeforeShow.java   Source Code and License 5 votes vote down vote up
static void waitFocused(Window w, AtomicBoolean b) {
    try {
        synchronized(b) {
            if (w.isFocusOwner()) {
                return;
            }
            b.wait(3000);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (!w.isFocusOwner()) {
        throw new RuntimeException("Can't make " + w + " focus owner");
    }
}
 
Example 56
Project: incubator-netbeans   File: ChangeParametersPlugin.java   Source Code and License 5 votes vote down vote up
private List<ExecutableElement> findDuplicateSubMethods(TypeElement enclosingTypeElement, ExecutableElement method, ParameterInfo[] paramTable, AtomicBoolean cancel) {
    List<ExecutableElement> returnmethods = new LinkedList<ExecutableElement>();
    Set<ElementHandle<TypeElement>> subTypes = RefactoringUtils.getImplementorsAsHandles(javac.getClasspathInfo().getClassIndex(), javac.getClasspathInfo(), enclosingTypeElement, cancel);
    for (ElementHandle<TypeElement> elementHandle : subTypes) {
        TypeElement subtype = elementHandle.resolve(javac);
        if(subtype != null) {
            List<ExecutableElement> methods = ElementFilter.methodsIn(javac.getElements().getAllMembers(subtype));
            for (ExecutableElement exMethod : methods) {
                if (!exMethod.equals(method)) {
                    if (exMethod.getSimpleName().equals(method.getSimpleName())
                            && exMethod.getParameters().size() == paramTable.length) {
                        boolean sameParameters = true;
                        for (int j = 0; j < exMethod.getParameters().size(); j++) {
                            TypeMirror exType = ((VariableElement) exMethod.getParameters().get(j)).asType();
                            String type = paramTable[j].getType();
                            if (type == null || type.length() == 0) {
                                sameParameters = false;
                            } else {
                                TypeMirror paramType = javac.getTreeUtilities().parseType(type, enclosingTypeElement);
                                if (!javac.getTypes().isSameType(exType, paramType)) {
                                    sameParameters = false;
                                }
                            }
                        }
                        if (sameParameters) {
                            returnmethods.add(exMethod);
                        }
                    }
                }
            }
        }
    }
    return returnmethods;
}
 
Example 57
Project: JRediClients   File: RedissonTopicTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCommandsOrdering() throws InterruptedException {
    RedissonClient redisson1 = BaseTest.createInstance();
    RTopic<Long> topic1 = redisson1.getTopic("topic", LongCodec.INSTANCE);
    AtomicBoolean stringMessageReceived = new AtomicBoolean();
    topic1.addListener((channel, msg) -> {
        assertThat(msg).isEqualTo(123);
        stringMessageReceived.set(true);
    });
    topic1.publish(123L);

    Awaitility.await().atMost(Duration.ONE_SECOND).untilTrue(stringMessageReceived);

    redisson1.shutdown();
}
 
Example 58
Project: monarch   File: PersistentColocatedPartitionedRegionDUnitTest.java   Source Code and License 5 votes vote down vote up
public Object call() throws Exception {
  // Setup for capturing logger messages
  Appender mockAppender = mock(Appender.class);
  when(mockAppender.getName()).thenReturn("MockAppender");
  when(mockAppender.isStarted()).thenReturn(true);
  when(mockAppender.isStopped()).thenReturn(false);
  Logger logger = (Logger) LogManager.getLogger(ColocationLogger.class);
  logger.addAppender(mockAppender);
  logger.setLevel(Level.WARN);
  loggingEventCaptor = ArgumentCaptor.forClass(LogEvent.class);

  // Logger interval may have been hooked by the test, so adjust test delays here
  int logInterval = ColocationLogger.getLogInterval();
  List<LogEvent> logEvents = Collections.emptyList();

  AtomicBoolean isDone = new AtomicBoolean(false);
  try {
    createPR(PR_REGION_NAME, true);
    // Let this thread continue running long enough for the missing region to be logged a
    // couple times.
    // Child regions do not get created by this thread.
    await().atMost(MAX_WAIT, TimeUnit.MILLISECONDS).until(() -> {
      verify(mockAppender, times(numExpectedLogMessages))
          .append(loggingEventCaptor.capture());
    });
    // createPR("region2", PR_REGION_NAME, true); // This child region is never created
  } finally {
    logEvents = loggingEventCaptor.getAllValues();
    assertEquals(String.format("Expected %d messages to be logged, got %d.",
        numExpectedLogMessages, logEvents.size()), numExpectedLogMessages,
        logEvents.size());
    String logMsg = logEvents.get(0).getMessage().getFormattedMessage();
    logger.removeAppender(mockAppender);
    numExpectedLogMessages = 1;
    return logMsg;
  }
}
 
Example 59
Project: incubator-netbeans   File: OrganizeImports.java   Source Code and License 5 votes vote down vote up
@Override
public void actionPerformed(final ActionEvent evt, final JTextComponent component) {
    if (component == null || !component.isEditable() || !component.isEnabled()) {
        Toolkit.getDefaultToolkit().beep();
        return;
    }
    final BaseDocument doc = (BaseDocument) component.getDocument();
    final Source source = Source.create(doc);
    if (source != null) {
        final AtomicBoolean cancel = new AtomicBoolean();
        ProgressUtils.runOffEventDispatchThread(new Runnable() {
            @Override
            public void run() {
                try {
                    ModificationResult.runModificationTask(Collections.singleton(source), new UserTask() {
                        @Override
                        public void run(ResultIterator resultIterator) throws Exception {
                            WorkingCopy copy = WorkingCopy.get(resultIterator.getParserResult());
                            copy.toPhase(Phase.RESOLVED);
                            doOrganizeImports(copy, false);
                        }
                    }).commit();
                } catch (Exception ex) {
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        }, NbBundle.getMessage(OrganizeImports.class, "MSG_OragnizeImports"), cancel, false); //NOI18N
    }
}
 
Example 60
Project: jtier-ctx   File: RxJavaExample.java   Source Code and License 5 votes vote down vote up
@Test
public void testUnsubscribeOnCancel() throws Exception {
    final TestScheduler ticker = Schedulers.test();

    final Ctx ctx = Ctx.empty();

    final AtomicBoolean failed = new AtomicBoolean(false);
    final AtomicBoolean completed = new AtomicBoolean(false);
    final AtomicInteger counter = new AtomicInteger();

    final Observable os = Observable.interval(10, TimeUnit.MILLISECONDS, ticker);

    final Subscription s = os.subscribe((i) -> counter.getAndIncrement(),
                                        (e) -> failed.set(true),
                                        () -> completed.set(true));

    // unsubscribe when currentExchange is cancelled
    ctx.onCancel(s::unsubscribe);

    // receive first event
    ticker.advanceTimeBy(10, TimeUnit.MILLISECONDS);
    ticker.triggerActions();
    assertThat(counter.get()).isEqualTo(1);

    // receive second event
    ticker.advanceTimeBy(10, TimeUnit.MILLISECONDS);
    ticker.triggerActions();
    assertThat(counter.get()).isEqualTo(2);

    // should led to unsubscribe, not receive future elements
    ctx.cancel();

    // advance time enough to trigger third event, but we should not get it
    ticker.advanceTimeBy(10, TimeUnit.MILLISECONDS);
    ticker.triggerActions();
    assertThat(counter.get()).isEqualTo(2);

    // verify it was not completed or failed
    assertThat(completed.get()).isFalse();
    assertThat(failed.get()).isFalse();
}