Java Code Examples for java.util.Queue.peek()

The following are Jave code examples for showing how to use peek() of the java.util.Queue class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: polcla   File: ConstituencyTree.java   Source Code and License Vote up 6 votes
private boolean containsTerminal(Object phrase, List<Terminal> candidates) {
	// cannot contain any terminal node if it is not a nonterminal
	if (!(phrase instanceof Nonterminal))
		return false;

	// Gather all child nodes in 'todo' and check whether one of them is a
	// candidate terminal. If this is the case one of the terminals is
	// part of the phrase.
	Queue<Object> todo = new LinkedList<Object>();
	todo.offer(phrase);
	while (todo.peek() != null) {
		Object top = todo.poll();
		if (candidates.contains(top))
			return true;

		List<Object> children = this.transitions.get(top);
		if (children == null)
			continue;

		for (Object child : children)
			todo.offer(child);
	}

	// default case: no candidate terminal is part of the phrase
	return false;
}
 
Example 2
Project: incubator-netbeans   File: Registry.java   Source Code and License Vote up 6 votes
public List<RegistryNode> query(final RegistryFilter filter) {
    List<RegistryNode> matches = new LinkedList<RegistryNode>();
    Queue<RegistryNode> queue = new LinkedList<RegistryNode>();
    
    queue.offer(registryRoot);
    while (queue.peek() != null) {
        final RegistryNode node = queue.poll();
        
        if (filter.accept(node)) {
            matches.add(node);
        }
        
        for (RegistryNode child: node.getChildren()) {
            queue.offer(child);
        }
    }
    
    return matches;
}
 
Example 3
Project: NetCom2   File: PipelineReceiver.java   Source Code and License Vote up 6 votes
@APILevel
final boolean test(Connection connection, Session session, T t) {
	NetCom2Utils.parameterNotNull(connection, session, t);
	final Queue<TriPredicate<Connection, Session, T>> predicateTemp = new LinkedList<>(predicates);
	while (predicateTemp.peek() != null) {
		if (! predicateTemp.remove().test(connection, session, t)) {
			return false;
		}
	}
	return true;
}
 
Example 4
Project: stock-patterns-recognition   File: AverageDirector.java   Source Code and License Vote up 6 votes
public void add(final Stock stock){
    final Queue<OhlcContainer> sequence = this.sequences.get(stock.getCode());
    final OhlcContainer latest = sequence.peek();

    if ((latest == null) || (latest.getTime().isBefore(stock.getTime()) && latest.getClose() != stock.getClose())) {
        getLogger().debug("New {} stock {} passed for average processing", stock.getCode(), stock);
        if (sequence.size() == 10)
            sequence.remove();

        sequence.add(stock);

        this.values.replace(stock.getCode(), sequence.stream()
                .mapToDouble(OhlcContainer::getClose)
                .sum() / 10);
    }
}
 
Example 5
Project: APCSAB   File: ZhuZhiyu_Period1_BinaryTreeLab.java   Source Code and License Vote up 6 votes
public static int width(TreeNode t) {
    int maxWdith = 0, levelWidth = 0;
    Queue<TreeNode> q = new LinkedList<>();
    q.add(t);
    q.add(null);
    while (!q.isEmpty()) {
        if (null == (t = q.poll())) {
            if (levelWidth > maxWdith)
                maxWdith = levelWidth;
            levelWidth = 0;
            if (null != q.peek()) q.add(null);
        } else {
            levelWidth++;
            if (null != t.getLeft()) q.add(t.getLeft());
            if (null != t.getRight()) q.add(t.getRight());
        }
    }
    return maxWdith;
}
 
Example 6
Project: boohee_v5.6   File: RxRingBuffer.java   Source Code and License Vote up 6 votes
public Object poll() {
    Object obj = null;
    synchronized (this) {
        Queue<Object> q = this.queue;
        if (q == null) {
        } else {
            obj = q.poll();
            Object ts = this.terminalState;
            if (obj == null && ts != null && q.peek() == null) {
                obj = ts;
                this.terminalState = null;
            }
        }
    }
    return obj;
}
 
Example 7
Project: boohee_v5.6   File: RxRingBuffer.java   Source Code and License Vote up 6 votes
public Object peek() {
    Object obj;
    synchronized (this) {
        Queue<Object> q = this.queue;
        if (q == null) {
            obj = null;
        } else {
            obj = q.peek();
            Object ts = this.terminalState;
            if (obj == null && ts != null && q.peek() == null) {
                obj = ts;
            }
        }
    }
    return obj;
}
 
Example 8
Project: swblocks-decisiontree   File: DecisionTreeFactory.java   Source Code and License Vote up 6 votes
private static void constructTreeFromRule(final TreeNode currentNode,
                                          final int currentLevel,
                                          final Queue<InputDriver> inputs,
                                          final DecisionTreeRule rule,
                                          final DecisionTreeType type) {
    final InputDriver value = inputs.poll();

    if (value == null) {
        return;
    }

    TreeNode newNode;
    final int nextLevel = currentLevel + 1;

    if (inputs.peek() == null) {
        newNode = createNode(value, nextLevel, type, NodeSupplier.Type.RESULT, rule);
    } else {
        newNode = createNode(value, nextLevel, type, NodeSupplier.Type.NODE, rule);
    }

    if (currentNode != null) {
        newNode = currentNode.addNode(newNode);
    }

    constructTreeFromRule(newNode, nextLevel, inputs, rule, type);
}
 
Example 9
Project: hashsdn-controller   File: ShardDataTree.java   Source Code and License Vote up 6 votes
private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
        final Consumer<CommitEntry> processor) {
    while (!queue.isEmpty()) {
        final CommitEntry entry = queue.peek();
        final SimpleShardDataTreeCohort cohort = entry.cohort;

        if (cohort.isFailed()) {
            LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
            queue.remove();
            continue;
        }

        if (cohort.getState() == allowedState) {
            processor.accept(entry);
        }

        break;
    }

    maybeRunOperationOnPendingTransactionsComplete();
}
 
Example 10
Project: Java-9-Programming-Blueprints   File: DateCalculator.java   Source Code and License Vote up 6 votes
public DateCalculatorResult calculate(String text) {
    final DateCalcExpressionParser parser = new DateCalcExpressionParser();
    final Queue<Token> tokens = parser.parse(text);

    try {
        if (!tokens.isEmpty()) {
            if (tokens.peek() instanceof DateToken) {
                return handleDateExpression(tokens);
            } else if (tokens.peek() instanceof TimeToken) {
                return handleTimeExpression(tokens);
            }
        }
    } catch (UnsupportedTemporalTypeException utte) {
        throw new DateCalcException(utte.getLocalizedMessage());
    }
    throw new DateCalcException("An invalid expression was given: " + text);
}
 
Example 11
Project: alfresco-repository   File: StandardNodeCrawlerImpl.java   Source Code and License Vote up 5 votes
public synchronized Set<NodeRef> crawl(Set<NodeRef> startingNodes)
{
    init();
    Queue<NodeRef> nodesToProcess = new LinkedList<NodeRef>();
    nodesToProcess.addAll(startingNodes);
    Set<NodeRef> resultingNodeSet = new HashSet<NodeRef>(89);
    Set<NodeRef> processedNodes = new HashSet<NodeRef>(89);

    // Do we have any more nodes to process?
    while (nodesToProcess.peek() != null)
    {
        // Yes, we do. Read the next noderef from the queue.
        NodeRef thisNode = nodesToProcess.poll();
        // Check that we haven't already processed it. Skip it if we have, process it if we haven't
        if (!processedNodes.contains(thisNode))
        {
            // Record the fact that we're processing this node
            processedNodes.add(thisNode);
            // We check this node against any filters that are in place (the nodes
            // that we were given to start with are always processed)
            if (startingNodes.contains(thisNode) || includeNode(thisNode))
            {
                resultingNodeSet.add(thisNode);
                Set<NodeRef> subsequentNodes = findSubsequentNodes(thisNode);
                for (NodeRef node : subsequentNodes)
                {
                    nodesToProcess.add(node);
                }
            }
        }
    }
    return resultingNodeSet;
}
 
Example 12
Project: PlayGround   File: SerializeBinarySearchTree.java   Source Code and License Vote up 5 votes
private TreeNode getNode(Queue<Integer> nodes) {
    if (nodes.isEmpty()) return null;
    Integer val = nodes.poll();
    Queue<Integer> smaller = new LinkedList<>();
    while (!nodes.isEmpty() && nodes.peek() <= val) {
        smaller.offer(nodes.poll());
    }

    TreeNode root = new TreeNode(val);
    root.left = getNode(smaller);
    root.right = getNode(nodes);
    return root;
}
 
Example 13
Project: Elasticsearch   File: ZenDiscovery.java   Source Code and License Vote up 5 votes
/**
 * Picks the cluster state with highest version with the same master from the queue. All cluster states with
 * lower versions are ignored. If a cluster state with a different master is seen the processing logic stops and the
 * last processed state is returned.
 */
static ClusterState selectNextStateToProcess(Queue<ProcessClusterState> processNewClusterStates) {
    // try and get the state with the highest version out of all the ones with the same master node id
    ProcessClusterState stateToProcess = processNewClusterStates.poll();
    if (stateToProcess == null) {
        return null;
    }
    stateToProcess.processed = true;
    while (true) {
        ProcessClusterState potentialState = processNewClusterStates.peek();
        // nothing else in the queue, bail
        if (potentialState == null) {
            break;
        }
        // if its not from the same master, then bail
        if (!Objects.equals(stateToProcess.clusterState.nodes().masterNodeId(), potentialState.clusterState.nodes().masterNodeId())) {
            break;
        }
        // we are going to use it for sure, poll (remove) it
        potentialState = processNewClusterStates.poll();
        if (potentialState == null) {
            // might happen if the queue is drained
            break;
        }
        potentialState.processed = true;

        if (potentialState.clusterState.version() > stateToProcess.clusterState.version()) {
            // we found a new one
            stateToProcess = potentialState;
        }
    }
    return stateToProcess.clusterState;
}
 
Example 14
Project: Java-9-Programming-Blueprints   File: DateCalculator.java   Source Code and License Vote up 5 votes
private DateCalculatorResult handleDateExpression(final Queue<Token> tokens) {
    DateToken startDateToken = (DateToken) tokens.poll();
    validateToken(tokens.peek(), OperatorToken.class);
    OperatorToken operatorToken = (OperatorToken) tokens.poll();
    Token thirdToken = tokens.peek();

    if (thirdToken instanceof IntegerToken) {
        return performDateMath(startDateToken, operatorToken, tokens);
    } else if (thirdToken instanceof DateToken) {
        return getDateDiff(startDateToken, tokens.poll());
    } else {
        throw new DateCalcException("Invalid expression");
    }
}
 
Example 15
Project: Java-9-Programming-Blueprints   File: DateCalculator.java   Source Code and License Vote up 5 votes
private DateCalculatorResult handleTimeExpression(final Queue<Token> tokens) {
    TimeToken startTimeToken = (TimeToken) tokens.poll();
    validateToken(tokens.peek(), OperatorToken.class);
    OperatorToken operatorToken = (OperatorToken) tokens.poll();
    Token thirdToken = tokens.peek();

    if (thirdToken instanceof IntegerToken) {
        return doTimeMath(operatorToken, startTimeToken, tokens);
    } else if (thirdToken instanceof TimeToken) {
        return getTimeDiff(operatorToken, startTimeToken, tokens.poll());
    } else {
        throw new DateCalcException("Invalid expression");
    }
}
 
Example 16
Project: Pogamut3   File: Test01_AgentJMXProxy.java   Source Code and License Vote up 4 votes
/**
   * Test of getAgentState method from class AgentMBeanAdapter.
   */
  @Test
  public void testAgentNotifications() {

  	final Queue<Class> expectingStateChanges = new LinkedList<Class>();
  	expectingStateChanges.add(IAgentStateStarting.class);
  	expectingStateChanges.add(IAgentStateStarted.class);
  	expectingStateChanges.add(IAgentStatePausing.class);
  	expectingStateChanges.add(IAgentStatePaused.class);
  	expectingStateChanges.add(IAgentStateResuming.class);
  	expectingStateChanges.add(IAgentStateResumed.class);
  	expectingStateChanges.add(IAgentStatePausing.class);
  	expectingStateChanges.add(IAgentStatePaused.class);
  	expectingStateChanges.add(IAgentStateResuming.class);
  	expectingStateChanges.add(IAgentStateResumed.class);
  	expectingStateChanges.add(IAgentStateStopping.class);
  	expectingStateChanges.add(IAgentStateStopped.class);
  	
  	FlagListener<IAgentState> stateListener = new FlagListener<IAgentState>() {
	@Override
	public void flagChanged(IAgentState changedValue) {
		Class cls = expectingStateChanges.peek();
		if (cls.isAssignableFrom(changedValue.getClass())) {
			System.out.println("CONSUMING " + cls);
			expectingStateChanges.poll();
		}
	}
};
agentProxy.getState().addListener(stateListener);
  	
Assert.assertTrue("name should be Test01_AgentJMXProxy", agentProxy.getName().equals("Test01_AgentJMXProxy"));
Assert.assertTrue("token should be " + token.getToken(), token.getToken().equals(agentProxy.getComponentId().getToken()));

agent.start();
agent.pause();
agent.resume();
agent.pause();
agent.resume();
agent.stop();

new WaitForFlagChange<IAgentState>(agentProxy.getState(), new IAccept<IAgentState>() {

	@Override
	public boolean accept(IAgentState flagValue) {
		return flagValue instanceof IAgentStateStopped;
	}
	
}).await();

try {
	// should not be needed
	Thread.sleep(50);
} catch (InterruptedException e) {
}

Assert.assertTrue("agent should have gone through all expected states, remaining state changes " + expectingStateChanges.size(), expectingStateChanges.size() == 0);

System.out.println("---/// TEST OK ///---");
  }
 
Example 17
Project: laravel-insight   File: BladeFoldingBuilder.java   Source Code and License Vote up 4 votes
private static void processDirectives(
    @Nullable final BladePsiDirective baseDirective,
    @NotNull final Queue<BladePsiDirective> directives,
    @NotNull final Collection<FoldingDescriptor> foldingDescriptors,
    @NotNull final Document document
) {
    while (true) {
        final BladePsiDirective directive = directives.peek();

        if (directive == null) {
            break;
        }

        if (IGNORED_DIRECTIVES.contains(directive.getName())) {
            directives.poll();
            continue;
        }

        if (baseDirective == null) {
            if (!directive.isToBeClosed()) {
                directives.poll();
                continue;
            }

            processDirectives(directives.poll(), directives, foldingDescriptors, document);
            continue;
        }

        // Eg. @endif or @elseif closes @if.
        // Or that @elseif continues @if.
        if (directive.closes(baseDirective) ||
            directive.continues(baseDirective)) {
            // Eg. @endif closes definitively an @if, @else or @elseif.
            // But @elseif or @else don't have the same effect.
            final boolean isDefinitivelyClosing = directive.isClosing() &&
                                                  !directive.isContinued();

            final TextRange foldingRange = new TextRange(
                baseDirective.getTextRange().getEndOffset(),
                directive.getTextRange().getStartOffset() - calculateEndOffsetReductor(directive, isDefinitivelyClosing)
            );

            if ((foldingRange.getLength() > 0) &&
                !StringUtils.strip(document.getText(foldingRange), " ").isEmpty()) {
                foldingDescriptors.add(new FoldingDescriptor(baseDirective.getNode(), foldingRange, FoldingGroup.newGroup("Blade")));
            }

            if (isDefinitivelyClosing) {
                directives.poll();
                break;
            }

            processDirectives(directives.poll(), directives, foldingDescriptors, document);
            break;
        }

        // Eg. @if or @elseif (but it will be catched on previous condition).
        if (directive.isContinued()) {
            processDirectives(directives.poll(), directives, foldingDescriptors, document);
            continue;
        }

        directives.poll();
    }
}
 
Example 18
Project: AWGW   File: Unit.java   Source Code and License Vote up 4 votes
/**
 * Moves the {@link Unit} along a path of {@link Terrain}s.
 *
 * @param path A {@link Queue} of adjacent {@link Terrain}s
 * @return Whether or not {@link Unit} was successful in moving all the way along the path.
 * For now, it should always be successful because fog of war/land mines etc are not implemented yet
 */
public boolean move(Queue<Terrain> path, boolean... realMove) {
    if (0 == path.size()) {
        //already done
        return true;
    }
    Terrain t = path.poll();
    Grid<Actor> gr = this.getGrid();
    //reached end of path, success
    if (t == null) {
        return true;
    }
    //invalid Terrain, fail -- should never happen
    if (!(gr.isValid(t))) {
        System.err.println("invalid terrain, not sure what happened here");
        return false;
    }
    //not enough mobility -- should never happen
    if (t.getMoveCost((this.getMovementType())) > this.getCurrentMobility()) {
        System.err.println("not enough mobi -- check BFS algorithm???");
        return false;
    }
    //Terrain is occupied by something other than allied Unit, fail
    try {
        Unit u = (Unit) (gr.get(t));
        if (null != u && u.getOwner() != this.getOwner()) {
            System.err.println("Terrain is occupied by something other than allied Unit, fail");
            return false;
        }
    } catch (ClassCastException actorIsNotAUnit) {
        System.out.println(actorIsNotAUnit.getStackTrace());
        System.err.println("why do you have non-units in the grid");
        return false;
    }
    //move on
    traverse(getGrid(), t);
    if (path.peek() == null && realMove.length != 0) {
        teleport(t);
    }
    return realMove.length == 0 ? move(path) : move(path, true);
}
 
Example 19
Project: ditb   File: MultiThreadedWriterBase.java   Source Code and License Vote up 4 votes
@Override
public void run() {
  Thread.currentThread().setName(getClass().getSimpleName());
  try {
    long expectedKey = startKey;
    Queue<Long> sortedKeys = new PriorityQueue<Long>();
    while (expectedKey < endKey) {
      // Block until a new element is available.
      Long k;
      try {
        k = wroteKeys.poll(1, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
        LOG.info("Inserted key tracker thread interrupted", e);
        break;
      }
      if (k == null) {
        continue;
      }
      if (k == expectedKey) {
        // Skip the "sorted key" queue and consume this key.
        wroteUpToKey.set(k);
        ++expectedKey;
      } else {
        sortedKeys.add(k);
      }

      // See if we have a sequence of contiguous keys lined up.
      while (!sortedKeys.isEmpty()
          && ((k = sortedKeys.peek()) == expectedKey)) {
        sortedKeys.poll();
        wroteUpToKey.set(k);
        ++expectedKey;
      }

      wroteKeyQueueSize.set(wroteKeys.size() + sortedKeys.size());
    }
  } catch (Exception ex) {
    LOG.error("Error in inserted/updaed key tracker", ex);
  } finally {
    numThreadsWorking.decrementAndGet();
  }
}