Java 类org.apache.commons.lang3.mutable.MutableBoolean 实例源码

项目:tipi-engine    文件:MaxTopConcurrentTest.java   
@Override
protected ActivityResultContext execute() throws Exception {

    // on attend sur un lock, si nécessaire
    final String lockKey = getStringVariable(WAIT_LOCK_KEY);
    if (lockKey != null) {
        final MutableBoolean lock = (MutableBoolean) datastore.get(lockKey);
        if (lock != null) {
            //noinspection SynchronizationOnLocalVariableOrMethodParameter
            synchronized (lock) {
                while (lock.booleanValue()) {
                    lock.wait();
                }
            }
        }
    }

    // on stocke un pseudo-résultat dans le datastore global (pour simuler la database dans le cas ordinaire)
    final String key = getStringVariable(RESULTS_KEY);
    datastore.put(key, true);

    return new FinishedActivityResultContext();
}
项目:sling-org-apache-sling-testing-clients    文件:PollingTest.java   
@Test
public void testCallTwice() throws Exception {
    final MutableInt callCount = new MutableInt(0);
    final MutableBoolean called = new MutableBoolean(false);
    Polling p = new Polling() {
        @Override
        public Boolean call() throws Exception {
            callCount.increment();
            boolean b = called.booleanValue();
            called.setTrue();
            return b;
        }
    };
    p.poll(500, 10);

    assertEquals(2, callCount.intValue());
}
项目:sling-org-apache-sling-testing-clients    文件:PollingTest.java   
@Test
public void testCallableTwice() throws Exception {
    final MutableInt callCount = new MutableInt(0);
    final MutableBoolean called = new MutableBoolean(false);
    Polling p = new Polling(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            callCount.increment();
            boolean b = called.booleanValue();
            called.setTrue();
            return b;
        }
    });
    p.poll(500, 10);

    assertEquals(2, callCount.intValue());
}
项目:async-jackson    文件:AsyncJsonParserTest.java   
@Test
public void test() throws IOException {
    MutableBoolean parsed = new MutableBoolean(false);
    AsyncJsonParser parser = new AsyncJsonParser(root -> {
        parsed.setValue(true);
        try {
            Assert.assertEquals(mapper.treeToValue(root, Model.class), model);
        } catch (JsonProcessingException e) {
            Assert.fail(e.getMessage());
        }
    });

    for (byte b : new ObjectMapper().writeValueAsBytes(model)) {
        parser.consume(new byte[] { b }, 1);
    }

    Assert.assertTrue(parsed.booleanValue());
}
项目:async-jackson    文件:AsyncJsonParserTest.java   
@Test
public void test_chunks() throws IOException {
    MutableBoolean parsed = new MutableBoolean(false);
    AsyncJsonParser parser = new AsyncJsonParser(root -> {
        parsed.setValue(true);
        try {
            Assert.assertEquals(mapper.treeToValue(root, Model.class), model);
        } catch (JsonProcessingException e) {
            Assert.fail(e.getMessage());
        }
    });

    final int CHUNK_SIZE = 20;
    byte[] bytes = new ObjectMapper().writeValueAsBytes(model);
    for (int i = 0; i < bytes.length; i += CHUNK_SIZE) {
        byte[] chunk = new byte[20];
        int start = Math.min(bytes.length, i);
        int len = Math.min(CHUNK_SIZE, bytes.length - i);
        System.arraycopy(bytes, start, chunk, 0, len);
        parser.consume(chunk, len);
    }

    Assert.assertTrue(parsed.booleanValue());
}
项目:invesdwin-context-persistence    文件:ACustomIdDao.java   
private boolean determineDeleteInBatchSupported(final Class<?> genericType) {
    final MutableBoolean deleteInBatchSupported = new MutableBoolean(true);
    Reflections.doWithFields(genericType, new FieldCallback() {
        @Override
        public void doWith(final Field field) {
            if (!deleteInBatchSupported.getValue()) {
                return;
            } else if (Reflections.getAnnotation(field, ElementCollection.class) != null) {
                //element collections are mapped as separate tables, thus the values would cause a foreign key constraint violation
                deleteInBatchSupported.setValue(false);
            } else if (Reflections.getAnnotation(field, Embedded.class) != null) {
                //check embedded types for the same constraints
                if (!determineDeleteInBatchSupported(field.getType())) {
                    deleteInBatchSupported.setValue(false);
                }
            }
        }
    });
    return deleteInBatchSupported.getValue();
}
项目:apex-malhar    文件:SimpleDoneQueryQueueManagerTest.java   
@Test
public void firstDoneTest()
{
  SimpleDoneQueueManager<Query, Void> sdqqm = new SimpleDoneQueueManager<Query, Void>();

  sdqqm.setup(null);
  sdqqm.beginWindow(0);

  Query query = new MockQuery("1");
  sdqqm.enqueue(query, null, new MutableBoolean(true));

  QueryBundle<Query, Void, MutableBoolean> qb = sdqqm.dequeue();
  Assert.assertEquals("Should return back null.", null, qb);

  sdqqm.endWindow();
  sdqqm.beginWindow(1);

  qb = sdqqm.dequeue();

  Assert.assertEquals("Should return back null.", null, qb);
  qb = sdqqm.dequeue();
  Assert.assertEquals("Should return back null.", null, qb);

  sdqqm.endWindow();
  sdqqm.teardown();
}
项目:apex-malhar    文件:SimpleDoneQueryQueueManagerTest.java   
@Test
public void simpleEnqueueDequeueBlock()
{
  SimpleDoneQueueManager<Query, Void> sdqqm = new SimpleDoneQueueManager<Query, Void>();

  sdqqm.setup(null);
  sdqqm.beginWindow(0);

  Query query = new MockQuery("1");
  sdqqm.enqueue(query, null, new MutableBoolean(false));

  Assert.assertEquals(1, sdqqm.getNumLeft());
  Assert.assertEquals(sdqqm.getNumPermits(), sdqqm.getNumLeft());

  QueryBundle<Query, Void, MutableBoolean> qb = sdqqm.dequeueBlock();

  Assert.assertEquals(0, sdqqm.getNumLeft());
  Assert.assertEquals(sdqqm.getNumPermits(), sdqqm.getNumLeft());

  Assert.assertEquals("Should return same query.", query, qb.getQuery());

  sdqqm.endWindow();
  sdqqm.teardown();
}
项目:apex-malhar    文件:SimpleDoneQueryQueueManagerTest.java   
@Test
public void simpleEnqueueDequeueThenBlock() throws Exception
{
  SimpleDoneQueueManager<Query, Void> sdqqm = new SimpleDoneQueueManager<Query, Void>();

  sdqqm.setup(null);
  sdqqm.beginWindow(0);

  Query query = new MockQuery("1");
  sdqqm.enqueue(query, null, new MutableBoolean(false));

  Assert.assertEquals(1, sdqqm.getNumLeft());
  Assert.assertEquals(sdqqm.getNumPermits(), sdqqm.getNumLeft());

  QueryBundle<Query, Void, MutableBoolean> qb = sdqqm.dequeueBlock();

  Assert.assertEquals(0, sdqqm.getNumLeft());
  Assert.assertEquals(sdqqm.getNumPermits(), sdqqm.getNumLeft());

  testBlocking(sdqqm);

  sdqqm.endWindow();
  sdqqm.teardown();
}
项目:smoothcsv    文件:RangeImpl.java   
@Override
public boolean isBlank() {
  CsvGridSheetPane gridSheet = getGridSheet();
  MutableBoolean result = new MutableBoolean(true);
  forEachCell(new ICellConsumer() {
    @Override
    public boolean accept(int r, int c) {
      Object val = gridSheet.getValueAt(r, c);
      if (val != null && !val.toString().isEmpty()) {
        result.setFalse();
        return false;
      }
      return true;
    }
  });
  return result.booleanValue();
}
项目:nedis    文件:RedisResponseDecoder.java   
private String decodeString(ByteBuf in) throws ProtocolException {
    final StringBuilder buffer = new StringBuilder();
    final MutableBoolean reachCRLF = new MutableBoolean(false);
    setReaderIndex(in, in.forEachByte(new ByteBufProcessor() {

        @Override
        public boolean process(byte value) throws Exception {
            if (value == '\n') {
                if ((byte) buffer.charAt(buffer.length() - 1) != '\r') {
                    throw new ProtocolException("Response is not ended by CRLF");
                } else {
                    buffer.setLength(buffer.length() - 1);
                    reachCRLF.setTrue();
                    return false;
                }
            } else {
                buffer.append((char) value);
                return true;
            }
        }
    }));
    return reachCRLF.booleanValue() ? buffer.toString() : null;
}
项目:sqlg    文件:SchemaTableTree.java   
private String toRangeClause(SqlgGraph sqlgGraph, MutableBoolean mutableOrderBy) {
    if (this.sqlgRangeHolder != null && this.sqlgRangeHolder.isApplyOnDb()) {
        if (this.sqlgRangeHolder.hasRange()) {
            //This is MssqlServer, ugly but what to do???
            String sql = "";
            if (mutableOrderBy.isFalse() && sqlgGraph.getSqlDialect().isMssqlServer() && this.getDbComparators().isEmpty()) {
                sql = "\n\tORDER BY 1\n\t";
            }
            return sql + "\n" + sqlgGraph.getSqlDialect().getRangeClause(this.sqlgRangeHolder.getRange());
        } else {
            Preconditions.checkState(this.sqlgRangeHolder.hasSkip(), "If not a range query then it must be a skip.");
            return sqlgGraph.getSqlDialect().getSkipClause(this.sqlgRangeHolder.getSkip());
        }
    }
    return "";
}
项目:KicksEmu    文件:ChatCommands.java   
private static void onPunish(Session session, String ... args) {
    if (args.length < 2) return;

    if (PlayerInfo.isModerator(session.getPlayerId())) {
        int targetId = CharacterUtils.getCharacterIdByName(args[1]);

        MutableBoolean targetFound = new MutableBoolean(false);

        ServerManager.getSession(targetId).ifPresent(target -> {
            ChatUtils.sendServerMessage(target, "You have been punished by a moderator.");
            target.close();

            ChatUtils.sendServerMessage(session, "Player punished: " + args[1]);

            targetFound.setTrue();
        });

        if (targetFound.isFalse()) {
            ChatUtils.sendServerMessage(session, "Player not found.");
        }
    }
}
项目:viritin    文件:FilterableListContainerTest.java   
@Test
public void clearFilters() {
    final List<Person> listOfPersons = getListOfPersons(100);
    FilterableListContainer<Person> container = new FilterableListContainer<>(
            listOfPersons);
    container.addContainerFilter(new SimpleStringFilter("firstName",
            "First1", true, true));
    Assert.assertNotSame(listOfPersons.size(), container.size());
    container.removeAllContainerFilters();
    Assert.assertEquals(listOfPersons.size(), container.size());
    container.addContainerFilter(new SimpleStringFilter("firstName",
            "foobar", true, true));
    Assert.assertEquals(0, container.size());

    final MutableBoolean fired = new MutableBoolean(false);
    container.addListener(new Container.ItemSetChangeListener() {
        @Override
        public void containerItemSetChange(
                Container.ItemSetChangeEvent event) {
            fired.setTrue();
        }
    });
    container.removeAllContainerFilters();
    Assert.assertTrue(fired.booleanValue());
    Assert.assertEquals(listOfPersons.size(), container.size());
}
项目:bandwidth-on-demand    文件:VlanAllocation.java   
private static <T> VlanAllocation of(Collection<T> ports, Function<T, Optional<Integer>> sVlanId, Function<T, Optional<Vlan>> vlan) {
  MutableBoolean overlappingVlan = new MutableBoolean(false);
  Map<Optional<Integer>, Vlan> allocationsPerSVlan = ports.stream().collect(Collectors.toMap(
      sVlanId,
      port -> vlan.apply(port).orElse(Vlan.none()),
      (a, b) -> {
        if (a.overlaps(b)) {
          overlappingVlan.setTrue();
        }
        return a.union(b);
      }));
  Vlan allocatedSVlans = ports.stream()
      .map(port -> sVlanId.apply(port).map(Vlan::singleton).orElse(Vlan.none()))
      .reduce(Vlan.none(), Vlan::union);
  if (!overlappingVlan.booleanValue() && allocatedSVlans.overlaps(allocationsPerSVlan.getOrDefault(Optional.empty(), Vlan.none()))) {
    overlappingVlan.setTrue();
  };
  return new VlanAllocation(overlappingVlan.booleanValue(), allocationsPerSVlan, allocatedSVlans);
}
项目:codeforces-commons    文件:ZipUtil.java   
private static boolean writeBytesForView(
        CountingOutputStream countingOutputStream, byte[] bytes, int maxLength, MutableBoolean truncated) {
    if (truncated.booleanValue()) {
        return false;
    }

    if (countingOutputStream.getTotalWrittenByteCount() + bytes.length > maxLength) {
        truncated.setTrue();
        return false;
    } else {
        try {
            countingOutputStream.write(bytes);
            return true;
        } catch (IOException ignored) {
            truncated.setTrue();
            return false;
        }
    }
}
项目:sling-org-apache-sling-testing-clients    文件:PollingTest.java   
@Test
public void testCallableOnce() throws Exception {
    final MutableInt callCount = new MutableInt(0);
    final MutableBoolean called = new MutableBoolean(false);
    Polling p = new Polling(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            callCount.increment();
            return true;
        }
    });
    p.poll(500, 10);

    assertEquals(1, callCount.intValue());
}
项目:asglogic    文件:SequenceBasedAndGateDecomposer.java   
private boolean categoriseSequences(BDD bdd, SortedSet<IOBehaviour> sequences, List<IOBehaviour> falling, List<IOBehaviour> rising, List<IOBehaviour> constant) {
    for(IOBehaviour beh : sequences) {
        BDD startBDD = bdd;
        MutableBoolean resultStart = new MutableBoolean();
        if(!evaluateBDD(resultStart, startBDD, beh.getStart())) {
            logger.error("Something went wrong");
            return false;
        }
        BDD endBDD = bdd;
        MutableBoolean resultEnd = new MutableBoolean();
        if(!evaluateBDD(resultEnd, endBDD, beh.getEnd())) {
            logger.error("Something went wrong");
            return false;
        }

        if(resultStart.isTrue() && resultEnd.isFalse()) {
            falling.add(beh);
            //System.out.println("uups? falling?");
        } else if(resultStart.isFalse() && resultEnd.isTrue()) {
            rising.add(beh);
        } else if(resultStart.isFalse() && resultEnd.isFalse()) {
            constant.add(beh);
        } else {
            logger.error("Const 1 should not happen");
            return false;
        }
        //System.out.println(resultStart.booleanValue() + "=>" + resultEnd.booleanValue() + " : " + beh);
    }
    return true;
}
项目:jira-dvcs-connector    文件:ChangesetDaoImpl.java   
public boolean createOrAssociate(final Changeset changeset, final Set<String> extractedIssues)
{
    final MutableBoolean wasCreated = new MutableBoolean(false);
    ChangesetMapping changesetMapping = activeObjects.executeInTransaction(new TransactionCallback<ChangesetMapping>()
    {
        @Override
        public ChangesetMapping doInTransaction()
        {
            ChangesetMapping chm = getChangesetMapping(changeset);
            if (chm == null)
            {
                chm = activeObjects.create(ChangesetMapping.class);
                fillProperties(changeset, chm);
                chm.save();
                wasCreated.setValue(true);
            }

            associateRepositoryToChangeset(chm, changeset.getRepositoryId());
            if (extractedIssues != null)
            {
                associateIssuesToChangeset(chm, extractedIssues);
            }

            return chm;
        }
    });

    changeset.setId(changesetMapping.getID());
    return wasCreated.booleanValue();
}
项目:apex-malhar    文件:SimpleDoneQueryQueueManagerTest.java   
@Test
public void simpleEnqueueDequeue()
{
  SimpleDoneQueueManager<Query, Void> sdqqm = new SimpleDoneQueueManager<Query, Void>();

  sdqqm.setup(null);
  sdqqm.beginWindow(0);

  Query query = new MockQuery("1");
  sdqqm.enqueue(query, null, new MutableBoolean(false));

  QueryBundle<Query, Void, MutableBoolean> qb = sdqqm.dequeue();

  Assert.assertEquals("Should return same query.", query, qb.getQuery());
  qb = sdqqm.dequeue();
  Assert.assertEquals("Should return back null.", null, qb);

  sdqqm.endWindow();
  sdqqm.beginWindow(1);

  qb = sdqqm.dequeue();
  Assert.assertEquals("Should return same query.", query, qb.getQuery());
  qb = sdqqm.dequeue();
  Assert.assertEquals("Should return back null.", null, qb);

  sdqqm.endWindow();
  sdqqm.teardown();
}
项目:apex-malhar    文件:SimpleDoneQueryQueueManagerTest.java   
@Test
public void simpleExpire1()
{
  SimpleDoneQueueManager<Query, Void> sdqqm = new SimpleDoneQueueManager<Query, Void>();

  sdqqm.setup(null);
  sdqqm.beginWindow(0);

  Query query = new MockQuery("1");
  sdqqm.enqueue(query, null, new MutableBoolean(false));

  QueryBundle<Query, Void, MutableBoolean> qb = sdqqm.dequeue();

  Assert.assertEquals("Should return same query.", query, qb.getQuery());
  qb.getQueueContext().setValue(true);

  qb = sdqqm.dequeue();
  Assert.assertEquals("Should return back null.", null, qb);

  sdqqm.endWindow();
  sdqqm.beginWindow(1);

  qb = sdqqm.dequeue();
  Assert.assertEquals("Should return back null.", null, qb);

  sdqqm.endWindow();
  sdqqm.teardown();
}
项目:apex-malhar    文件:SimpleDoneQueryQueueManagerTest.java   
@Test
public void expiredTestBlocking() throws Exception
{
  SimpleDoneQueueManager<Query, Void> sdqqm = new SimpleDoneQueueManager<Query, Void>();

  sdqqm.setup(null);
  sdqqm.beginWindow(0);

  Query query = new MockQuery("1");
  MutableBoolean queueContext = new MutableBoolean(false);
  sdqqm.enqueue(query, null, queueContext);

  Assert.assertEquals(1, sdqqm.getNumLeft());
  Assert.assertEquals(sdqqm.getNumPermits(), sdqqm.getNumLeft());
  QueryBundle<Query, Void, MutableBoolean> qb = sdqqm.dequeueBlock();
  Assert.assertEquals(0, sdqqm.getNumLeft());
  Assert.assertEquals(sdqqm.getNumPermits(), sdqqm.getNumLeft());

  sdqqm.endWindow();

  sdqqm.beginWindow(1);

  Assert.assertEquals(1, sdqqm.getNumLeft());
  Assert.assertEquals(sdqqm.getNumPermits(), sdqqm.getNumLeft());

  queueContext.setValue(true);
  testBlocking(sdqqm);

  Assert.assertEquals(0, sdqqm.getNumLeft());
  Assert.assertEquals(sdqqm.getNumPermits(), sdqqm.getNumLeft());

  sdqqm.endWindow();
  sdqqm.teardown();
}
项目:apex-malhar    文件:SimpleDoneQueryQueueManagerTest.java   
@Test
public void simpleExpire1ThenBlock()
{
  SimpleDoneQueueManager<Query, Void> sdqqm = new SimpleDoneQueueManager<Query, Void>();

  sdqqm.setup(null);
  sdqqm.beginWindow(0);

  Query query = new MockQuery("1");
  sdqqm.enqueue(query, null, new MutableBoolean(false));

  QueryBundle<Query, Void, MutableBoolean> qb = sdqqm.dequeue();

  Assert.assertEquals("Should return same query.", query, qb.getQuery());
  qb.getQueueContext().setValue(true);

  qb = sdqqm.dequeue();
  Assert.assertEquals("Should return back null.", null, qb);

  sdqqm.endWindow();
  sdqqm.beginWindow(1);

  qb = sdqqm.dequeue();
  Assert.assertEquals("Should return back null.", null, qb);

  sdqqm.endWindow();
  sdqqm.teardown();
}
项目:apex-malhar    文件:SimpleDoneQueryQueueManagerTest.java   
@Test
public void simpleExpireBlockThenUnblock() throws Exception
{
  SimpleDoneQueueManager<Query, Void> sdqqm = new SimpleDoneQueueManager<Query, Void>();

  sdqqm.setup(null);
  sdqqm.beginWindow(0);

  Query query = new MockQuery("1");
  MutableBoolean expire = new MutableBoolean(false);
  sdqqm.enqueue(query, null, expire);

  sdqqm.endWindow();
  sdqqm.beginWindow(1);

  //Expire
  expire.setValue(true);

  ExceptionSaverExceptionHandler eseh = new ExceptionSaverExceptionHandler();
  testBlockingNoStop(sdqqm, eseh);

  query = new MockQuery("2");
  sdqqm.enqueue(query, null, new MutableBoolean(false));

  Thread.sleep(1000);

  Assert.assertNull(eseh.getCaughtThrowable());

  sdqqm.endWindow();
  sdqqm.teardown();
}
项目:apex-malhar    文件:SimpleDoneQueryQueueManagerTest.java   
@SuppressWarnings({"deprecation", "CallToThreadStopSuspendOrResumeManager"})
private void testBlocking(SimpleDoneQueueManager<Query, Void> sdqqm) throws InterruptedException
{
  Thread thread = new Thread(new BlockedThread<Query, Void, MutableBoolean>(sdqqm));
  //thread.setUncaughtExceptionHandler(new RethrowExceptionHandler(Thread.currentThread()));
  thread.start();
  Thread.sleep(100);

  Assert.assertEquals(Thread.State.WAITING, thread.getState());

  thread.stop();
}
项目:ravikumaran201504    文件:EventuallyConsistentMapImpl.java   
private boolean putInternal(K key, V value, Timestamp timestamp) {
    counter.incrementCount();
    Timestamp removed = removedItems.get(key);
    if (removed != null && removed.isNewerThan(timestamp)) {
        log.debug("ecmap - removed was newer {}", value);
        return false;
    }

    final MutableBoolean updated = new MutableBoolean(false);

    items.compute(key, (k, existing) -> {
        if (existing != null && existing.isNewerThan(timestamp)) {
            updated.setFalse();
            return existing;
        } else {
            updated.setTrue();
            return new Timestamped<>(value, timestamp);
        }
        });

    boolean success = updated.booleanValue();
    if (!success) {
        log.debug("ecmap - existing was newer {}", value);
    }

    if (success && removed != null) {
        removedItems.remove(key, removed);
    }

    if (success && persistent) {
        persistentStore.put(key, value, timestamp);
    }

    return success;
}
项目:ravikumaran201504    文件:MapDbPersistentStore.java   
private void putInternal(K key, V value, Timestamp timestamp) {
    byte[] keyBytes = serializer.encode(key);
    byte[] removedBytes = tombstones.get(keyBytes);

    Timestamp removed = removedBytes == null ? null :
                        serializer.decode(removedBytes);
    if (removed != null && removed.isNewerThan(timestamp)) {
        return;
    }

    final MutableBoolean updated = new MutableBoolean(false);

    items.compute(keyBytes, (k, existingBytes) -> {
        Timestamped<V> existing = existingBytes == null ? null :
                                  serializer.decode(existingBytes);
        if (existing != null && existing.isNewerThan(timestamp)) {
            updated.setFalse();
            return existingBytes;
        } else {
            updated.setTrue();
            return serializer.encode(new Timestamped<>(value, timestamp));
        }
    });

    boolean success = updated.booleanValue();

    if (success && removed != null) {
        tombstones.remove(keyBytes, removedBytes);
    }

    database.commit();
}
项目:ravikumaran201504    文件:MapDbPersistentStore.java   
private void removeInternal(K key, Timestamp timestamp) {
    byte[] keyBytes = serializer.encode(key);

    final MutableBoolean updated = new MutableBoolean(false);

    items.compute(keyBytes, (k, existingBytes) -> {
        Timestamp existing = existingBytes == null ? null :
                             serializer.decode(existingBytes);
        if (existing != null && existing.isNewerThan(timestamp)) {
            updated.setFalse();
            return existingBytes;
        } else {
            updated.setTrue();
            // remove from items map
            return null;
        }
    });

    if (!updated.booleanValue()) {
        return;
    }

    byte[] timestampBytes = serializer.encode(timestamp);
    byte[] removedBytes = tombstones.get(keyBytes);

    Timestamp removedTimestamp = removedBytes == null ? null :
                                 serializer.decode(removedBytes);
    if (removedTimestamp == null) {
        tombstones.putIfAbsent(keyBytes, timestampBytes);
    } else if (timestamp.isNewerThan(removedTimestamp)) {
        tombstones.replace(keyBytes, removedBytes, timestampBytes);
    }

    database.commit();
}
项目:cqrs    文件:InMemoryEventBusTest.java   
@Test
public void testHandlerShouldBeCalledIfUnspecificEvent() {
  final MutableBoolean handled = new MutableBoolean(false);
  Consumer<IAmAnEvent> handler = new Consumer<IAmAnEvent>() {
    @Override
    public void accept(IAmAnEvent event) {
      handled.setTrue();
    }
  };
  cut.registerHandler(handler);
  cut.send(new MockEvent());
  assertThat(handled.getValue(), is(true));
}
项目:hbase    文件:PreemptiveFastFailInterceptor.java   
public void handleThrowable(Throwable t1, ServerName serverName,
    MutableBoolean couldNotCommunicateWithServer,
    MutableBoolean guaranteedClientSideOnly) throws IOException {
  Throwable t2 = ClientExceptionsUtil.translatePFFE(t1);
  boolean isLocalException = !(t2 instanceof RemoteException);

  if ((isLocalException && ClientExceptionsUtil.isConnectionException(t2))) {
    couldNotCommunicateWithServer.setValue(true);
    guaranteedClientSideOnly.setValue(!(t2 instanceof CallTimeoutException));
    handleFailureToServer(serverName, t2);
  }
}
项目:KicksEmu    文件:MatchResultHandler.java   
private void doAfterResultUpdates() {
    getResult().getPlayers().forEach(playerResult -> {
        int playerId = playerResult.getPlayerId();
        Session session = room.getPlayer(playerId);

        // If match was not in training mode
        if (getRoom().trainingFactorAllowsRewards()) {
            updatePlayerHistory(playerResult);

            if (playerResult.hasReward()) {
                MutableBoolean mustNotifyExpiration = new MutableBoolean(false);

                // Decrease by 1 the remain usages of usage based items
                session.getCache().getItems(connection).values().stream()
                        .filter(Item::isSelectedUsageItem)
                        .forEach(item -> {
                            item.sumUsages((short) -1);

                            // Update the item in the database
                            PlayerInfo.setInventoryItem(item, playerId, getConnection());

                            // If the item expired
                            if (item.getUsages() <= 0) {
                                mustNotifyExpiration.setTrue();
                            }
                        });

                if (mustNotifyExpiration.isTrue()) {
                    CharacterManager.sendItemList(getRoom().getPlayer(playerId));
                }
            }
        }
    });
}
项目:KicksEmu    文件:RoomMessages.java   
public static void playerReady(Session session, ClientMessage msg) {
    int roomId = msg.readShort();
    int playerId = session.getPlayerId();

    if (session.getRoomId() == roomId) {
        MutableBoolean roomLoading = new MutableBoolean(false);

        RoomManager.getRoomById(roomId)
                .filter(Room::isLoading)
                .ifPresent(room -> {
                    if (!room.getConfirmedPlayers().contains(playerId)) {
                        room.getConfirmedPlayers().add(playerId);

                        // Instead of waiting 5 seconds (or not), we send an udp ping immediately to
                        // the client so we can update his udp port (if changed) before match starts
                        UdpPing.sendUdpPing(session);
                    }

                    if (room.getConfirmedPlayers().size() >= room.getCurrentSize()) {
                        room.setState(RoomState.PLAYING);
                        room.setTimeStart(DateUtils.currentTimeMillis());
                        room.broadcast(MessageBuilder.playerReady((short) 0));

                        if (room.getLoadingTimeoutFuture().isCancellable()) {
                            room.getLoadingTimeoutFuture().cancel(true);
                        }
                    }

                    roomLoading.setTrue();
                });

        if (roomLoading.isFalse()) {
            session.send(MessageBuilder.playerReady((short) 0));
        }
    }
}
项目:KicksEmu    文件:ChallengeRoomMessages.java   
public static void playerReady(Session session, ClientMessage msg) {
    int roomId = msg.readShort();
    int playerId = session.getPlayerId();

    MutableBoolean roomFound = new MutableBoolean(false);

    getRoomById(roomId).filter(room -> room.isLoading() && room.isPlayerIn(playerId))
            .ifPresent(room -> {
                if (!room.getConfirmedPlayers().contains(playerId)) {
                    room.getConfirmedPlayers().add(playerId);

                    // Instead of waiting 5 seconds (or not), we send an udp ping immediately to
                    // the client so we can update his udp port (if changed) before match starts
                    UdpPing.sendUdpPing(session);
                }

                if (room.getConfirmedPlayers().size() >= room.getCurrentSize()) {
                    room.setState(RoomState.PLAYING);
                    room.setTimeStart(DateUtils.currentTimeMillis());
                    room.broadcast(MessageBuilder.playerReady((short) 0));

                    if (room.getLoadingTimeoutFuture().isCancellable()) {
                        room.getLoadingTimeoutFuture().cancel(true);
                    }
                }

                roomFound.setTrue();
            });

    if (roomFound.isFalse()) {
        session.send(MessageBuilder.playerReady((short) 0));
    }
}
项目:pacaya    文件:ScheduleUtils.java   
public static <T> Iterable<T> iterable(Iterator<T> seq) {
    final MutableBoolean used = new MutableBoolean(false);
    return new Iterable<T>() {

        @Override
        public Iterator<T> iterator() {
            if (!used.booleanValue()) {
                used.setValue(true);
                return seq;
            } else {
                throw new IllegalStateException("only allowed to iterate this iterable once");
            }
        }
    };
}
项目:codeforces-commons    文件:StringUtil.java   
@Nullable
private static String fieldToString(@Nonnull Object value, @Nonnull String fieldName, ToStringOptions options) {
    if (value.getClass() == Boolean.class || value.getClass() == boolean.class) {
        return (boolean) value ? fieldName : '!' + fieldName;
    }

    MutableBoolean quoted = new MutableBoolean();
    String stringValue = valueToString(value, quoted);

    if (shouldSkipField(stringValue, options, quoted)) {
        return null;
    }

    return fieldName + '=' + stringValue;
}
项目:codeforces-commons    文件:StringUtil.java   
@SuppressWarnings({"AccessingNonPublicFieldOfAnotherObject", "OverlyComplexMethod"})
private static boolean shouldSkipField(
        @Nullable String stringValue, ToStringOptions options, MutableBoolean quoted) {
    if (options.skipNulls && stringValue == null) {
        return true;
    }

    if (options.skipEmptyStrings) {
        if (quoted != null && quoted.booleanValue()) {
            if ("''".equals(stringValue) || "\"\"".equals(stringValue)) {
                return true;
            }
        } else {
            if (isEmpty(stringValue)) {
                return true;
            }
        }
    }

    if (options.skipBlankStrings) {
        if (quoted != null && quoted.booleanValue()) {
            return isBlank(stringValue) || isBlank(stringValue.substring(1, stringValue.length() - 1));
        } else {
            return isBlank(stringValue);
        }
    }

    return false;
}
项目:sejda    文件:CommandLineTestBuilder.java   
public void assertTaskCompletes(String commandLine) {
    final MutableBoolean taskCompleted = new MutableBoolean(false);
    GlobalNotificationContext.getContext().addListener(new EventListener<TaskExecutionCompletedEvent>() {

        @Override
        public void onEvent(TaskExecutionCompletedEvent event) {
            taskCompleted.setValue(true);
        }

    });

    String consoleOutput = invokeConsoleAndReturnSystemOut(commandLine);
    assertThat("Task did not complete. Console output was:\n" + consoleOutput, taskCompleted.toBoolean(), is(true));
}
项目:tipi-engine    文件:MaxTopConcurrentTest.java   
/**
 * Ce test vérifie qu'il n'est pas possible de démarrer deux top-process avec maxTopConcurrent=1 de manière concurrente (= tipi va sérializer leurs exécutions)
 */
@Test
public void testLaunchTwoTopProcessesConcurrently() throws Exception {

    final MutableBoolean process1Lock = new MutableBoolean(true);
    datastore.put("process1Lock", process1Lock);

    // on démarre le premier process
    final long id1 = tipiFacade.launch(MaxTopOneJob.class, new VariableMap(
            RESULTS_KEY, "testLaunchTwoTopProcessesSequentially1",
            WAIT_LOCK_KEY, "process1Lock"));

    // on démarre le second process
    final long id2 = tipiFacade.launch(MaxTopOneJob.class, new VariableMap(
            RESULTS_KEY, "testLaunchTwoTopProcessesSequentially2"));

    // on laisse un peu de temps à Tipi pour tenter de démarrer le second process
    Thread.sleep(2000);
    Assert.assertTrue(tipiFacade.isRunning(id1)); // le premier process doit être démarré
    Assert.assertTrue(tipiFacade.isRunning(id2)); // le second process doit aussi être démarré (dans le sens : une demande de démarrage a été faite)
    Assert.assertTrue(tipiFacade.isProcessScheduled(id1)); // le premier process doit être en cours d'exécution
    Assert.assertFalse(tipiFacade.isProcessScheduled(id2)); // le second process ne doit pas être en cours d'exécution

    // on libère le lock du premier process
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (process1Lock) {
        process1Lock.setValue(false);
        process1Lock.notifyAll();
    }

    // on attend le fin d'exécution du premier process
    waitWhileRunning(id1, 5000);

    // on attend le fin d'exécution du second process
    waitWhileRunning(id2, 5000);

    // on vérifie que tout s'est bien passé pour le premier process
    final Boolean runned1 = (Boolean) datastore.get("testLaunchTwoTopProcessesSequentially1");
    Assert.assertTrue(runned1);

    // on vérifie que tout s'est bien passé pour le second process
    final Boolean runned2 = (Boolean) datastore.get("testLaunchTwoTopProcessesSequentially2");
    Assert.assertTrue(runned2);
}
项目:apex-malhar    文件:SimpleDoneQueueManager.java   
@Override
public boolean removeBundle(QueryBundle<QUERY_TYPE, META_QUERY, MutableBoolean> queryQueueable)
{
  return queryQueueable.getQueueContext().booleanValue();
}
项目:apex-malhar    文件:SimpleDoneQueueManager.java   
@Override
public void addedNode(QueueListNode<QueryBundle<QUERY_TYPE, META_QUERY, MutableBoolean>> queryQueueable)
{
  semaphore.release();
}