Example usage for java.util Queue peek

List of usage examples for java.util Queue peek

Introduction

In this page you can find the example usage for java.util Queue peek.

Prototype

E peek();

Source Link

Document

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

Usage

From source file:au.org.ala.delta.intkey.directives.StandardIntkeyDirective.java

@Override
public IntkeyDirectiveInvocation doProcess(IntkeyContext context, String data) throws Exception {
    StringBuilder stringRepresentationBuilder = new StringBuilder();
    stringRepresentationBuilder.append(StringUtils.join(getControlWords(), " ").toUpperCase());

    List<String> tokens = ParsingUtils.tokenizeDirectiveCall(data);
    Queue<String> tokenQueue = new ArrayDeque<String>(tokens);

    IntkeyDirectiveInvocation invoc = buildCommandObject();

    if (_intkeyFlagsList != null && tokenQueue.size() > 0) {
        boolean matchingFlags = true;
        while (matchingFlags) {
            boolean tokenMatched = false;
            String token = tokenQueue.peek();

            if (token != null) {
                for (IntkeyDirectiveFlag flag : _intkeyFlagsList) {
                    if (flag.takesStringValue()) {
                        // Flag can have a string value supplied with it in
                        // format "/X=string", where X is the character
                        // symbol. Note that
                        // it is acceptable to supply such a flag without a
                        // following equals sign and string value.
                        if (token.matches("^/[" + Character.toLowerCase(flag.getSymbol())
                                + Character.toUpperCase(flag.getSymbol()) + "](=.+)?")) {

                            // If string value is not supplied, it defaults
                            // to empty string
                            String flagStringValue = "";

                            String[] tokenPieces = token.split("=");

                            // There should only be 0 or 1 equals sign. If
                            // more than none is supplied, no match.
                            if (tokenPieces.length < 3) {
                                if (tokenPieces.length == 2) {
                                    flagStringValue = tokenPieces[1];
                                }/*from   ww w  .  j a  v  a 2s.  com*/

                                BeanUtils.setProperty(invoc, flag.getName(), flagStringValue);
                                tokenQueue.remove();
                                tokenMatched = true;
                                stringRepresentationBuilder.append(" ");
                                stringRepresentationBuilder.append(token);
                                break;
                            }
                        }
                    } else {
                        if (token.equalsIgnoreCase("/" + flag.getSymbol())) {

                            BeanUtils.setProperty(invoc, flag.getName(), true);
                            tokenQueue.remove();
                            tokenMatched = true;
                            stringRepresentationBuilder.append(" ");
                            stringRepresentationBuilder.append(token);
                            break;
                        }
                    }
                }

                matchingFlags = tokenMatched;
            } else {
                matchingFlags = false;
            }
        }
    }

    // The arguments list needs to be generated each time a call to the
    // directive is processed. This is
    // because most arguments need to have provided with an initial value
    // which is used when prompting the user.
    // This initial value needs to be read out of the IntkeyContext at the
    // time of parsing.
    // E.g. the integer argument for the SET TOLERANCE directive will have
    // an initial value equal to the
    // the value of the tolerance setting before the call to the directive.
    List<IntkeyDirectiveArgument<?>> intkeyArgsList = generateArgumentsList(context);

    if (intkeyArgsList != null) {
        for (IntkeyDirectiveArgument<?> arg : intkeyArgsList) {
            Object parsedArgumentValue = arg.parseInput(tokenQueue, context,
                    StringUtils.join(_controlWords, " "), stringRepresentationBuilder);
            if (parsedArgumentValue != null) {
                BeanUtils.setProperty(invoc, arg.getName(), parsedArgumentValue);
            } else {
                // No argument value supplied, user cancelled out of the
                // prompt dialog.
                return null;
            }
        }
    }

    invoc.setStringRepresentation(stringRepresentationBuilder.toString());

    return invoc;
}

From source file:com.feilong.commons.core.util.CollectionsUtilTest.java

/**
 * TestCollectionsUtilTest.//from w  ww  . j  a va2 s. c  o m
 */
@Test
public void testCollectionsUtilTest33() {
    Queue<Object> queue = new PriorityQueue<Object>();

    queue.add(1);
    queue.add(2);
    queue.add(3);
    queue.add(4);
    queue.add(5);
    queue.add(6);

    if (log.isDebugEnabled()) {
        log.debug(JsonUtil.format(queue));
        log.debug("" + queue.peek());

    }

}

From source file:com.github.aptd.simulation.elements.train.CDoor.java

private void nextpassengerifpossible(final Queue<IPassenger<?>> p_queue) {
    if (p_queue != null) {
        switch (m_state) {
        case OPEN_CLOSEABLE:
        case OPEN_FREE:
            m_state = EDoorState.OPEN_BUSY;
            output(new CMessage(this, p_queue.peek().id(), EMessageType.DOOR_TO_PASSENGER_YOURTURN, m_stationid,
                    m_platformid));/*from   w ww  .  java 2  s  .c  o m*/
            break;
        case OPEN_FREE_SHALL_CLOSE:
            m_state = EDoorState.OPEN_BUSY_SHALL_CLOSE;
            output(new CMessage(this, p_queue.peek().id(), EMessageType.DOOR_TO_PASSENGER_YOURTURN, m_stationid,
                    m_platformid));
            break;
        case CLOSING:
        case CLOSED_RELEASED:
            m_state = EDoorState.OPENING;
            break;
        case CLOSING_LOCKED:
            m_state = EDoorState.OPENING_SHALL_CLOSE;
            break;
        default:
            // making checkstyle happy
        }
    }
}

From source file:candr.yoclip.Parser.java

/**
 * Creates a {@code ParsedOptionParameter} for the option property parameter at the head of the queue. The value of the parsed option will
 * contain option property key and value. As an example if the parameters queue head contains "<code>-Dkey=value</code>" the parsed option value
 * will be the string "<code>key=value</code>" (assuming the bean contains a field annotated with {@link candr.yoclip.annotation.OptionProperties
 * OptionProperties})./*from   www  .ja v  a 2  s.  c om*/
 *
 * @param parameters The current queue of command parameters.
 * @return a parsed option parameter or {@code null} in the following cases.
 * <ul>
 * <li>The parameters queue is empty.</li>
 * <li>The bean does not contain option property annotations.</li>
 * <li>The head of the parameters queue does not match an option property annotation on the bean.</li>
 * </ul>
 */
protected ParsedOption<T> getParsedOptionProperty(final Queue<String> parameters) {

    ParsedOption<T> parsedOption = null;

    String parameter = parameters.peek();
    if (!StringUtils.isEmpty(parameter)) {

        final String prefix = getParserOptions().getPrefix();
        if (parameter.startsWith(prefix)) {

            parameter = parameter.substring(prefix.length());
            for (final Pair<Matcher, String> propertyMatcher : getPropertyMatchers()) {

                final Matcher matcher = propertyMatcher.getLeft();
                if (matcher.reset(parameter).matches()) {

                    parameters.remove();

                    // this always succeeds because the parser has set up the property matcher
                    final String optionParametersKey = propertyMatcher.getRight();
                    final ParserOption<T> optionParameter = getParserOptions().get(optionParametersKey);
                    final String value = matcher.group(1);
                    parsedOption = new ParsedOption<T>(optionParameter, value);

                    break;
                }
            }
        }
    }

    return parsedOption;
}

From source file:com.github.fauu.natrank.service.RankingServiceImpl.java

@Override
public void createRankings() throws DataAccessException {
    List<Match> matches = (List<Match>) matchRepository.findAll();

    calculateTeamRatingsAndRankChanges(matches);
    calculateTeamExtremes();/*from w w w  .  j  a va2s .co  m*/

    List<Ranking> rankings = new LinkedList<>();
    Map<Integer, RankingEntry> entryMap = new HashMap<>();

    rankingRepository.deleteAll();

    Queue<LocalDate> rankingDateQueue = new LinkedList<>();
    rankingDateQueue.add(matches.get(matches.size() - 1).getDate());

    for (Match match : matches) {
        LocalDate nextRankingDate = rankingDateQueue.peek();
        if (nextRankingDate == null) {
            break;
        }

        if (match.getDate().isAfter(nextRankingDate)) {
            rankings.add(createRankingForDate(rankingDateQueue.poll(), entryMap));
        }

        List<Team> matchTeams = new ArrayList<>();
        matchTeams.add(match.getTeam1());
        matchTeams.add(match.getTeam2());

        for (Team team : matchTeams) {
            if (!entryMap.containsKey(team.getId())) {
                RankingEntry newEntry = new RankingEntry();
                newEntry.setTeam(team);

                entryMap.put(team.getId(), newEntry);
            }
        }

        List<RankingEntry> matchTeamEntries = new ArrayList<>();
        matchTeamEntries.add(entryMap.get(matchTeams.get(0).getId()));
        matchTeamEntries.add(entryMap.get(matchTeams.get(1).getId()));

        matchTeamEntries.get(0).incrementMatchesTotal();
        matchTeamEntries.get(1).incrementMatchesTotal();

        if (match.getHomeTeam() == null) {
            matchTeamEntries.get(0).incrementMatchesOnNeutralGround();
            matchTeamEntries.get(1).incrementMatchesOnNeutralGround();
        } else if (match.getHomeTeam() == matchTeams.get(0)) {
            matchTeamEntries.get(0).incrementMatchesHome();
            matchTeamEntries.get(1).incrementMatchesAway();
        } else if (match.getHomeTeam() == matchTeams.get(1)) {
            matchTeamEntries.get(0).incrementMatchesAway();
            matchTeamEntries.get(1).incrementMatchesHome();
        }

        if (match.getWinnerTeam() == null) {
            matchTeamEntries.get(0).incrementDraws();
            matchTeamEntries.get(1).incrementDraws();
        } else if (match.getWinnerTeam() == matchTeams.get(0)) {
            matchTeamEntries.get(0).incrementWins();
            matchTeamEntries.get(1).incrementLosses();
        } else if (match.getWinnerTeam() == matchTeams.get(1)) {
            matchTeamEntries.get(0).incrementLosses();
            matchTeamEntries.get(1).incrementWins();
        }

        matchTeamEntries.get(0).addGoalsFor(match.getTeam1Goals());
        matchTeamEntries.get(0).addGoalsAgainst(match.getTeam2Goals());
        matchTeamEntries.get(1).addGoalsFor(match.getTeam2Goals());
        matchTeamEntries.get(1).addGoalsAgainst(match.getTeam1Goals());
    }

    LocalDate nextRankingDate;
    while ((nextRankingDate = rankingDateQueue.poll()) != null) {
        rankings.add(createRankingForDate(nextRankingDate, entryMap));
    }

    rankingRepository.save(rankings);
}

From source file:com.github.rinde.rinsim.core.model.road.GraphRoadModel.java

@Override
protected MoveProgress doFollowPath(MovingRoadUser object, Queue<Point> path, TimeLapse time) {
    final Loc objLoc = verifyLocation(objLocs.get(object));
    Loc tempLoc = objLoc;//from   w ww. j av a2 s  .c o  m
    final MoveProgress.Builder mpBuilder = MoveProgress.builder(unitConversion, time);

    boolean cont = true;
    long timeLeft = time.getTimeLeft();
    while (timeLeft > 0 && !path.isEmpty() && cont) {
        checkMoveValidity(tempLoc, path.peek());
        // speed in internal speed unit
        final double speed = getMaxSpeed(object, tempLoc, path.peek());
        checkState(speed >= 0, "Found a bug in getMaxSpeed, return value must be >= 0, but is %s.", speed);
        // distance that can be traveled in current conn with timeleft
        final double travelableDistance = computeTravelableDistance(tempLoc, path.peek(), speed, timeLeft,
                time.getTimeUnit());
        checkState(travelableDistance >= 0d,
                "Found a bug in computeTravelableDistance, return value must be >= 0," + " but is %s.",
                travelableDistance);
        final double connLength = unitConversion.toInDist(computeDistanceOnConnection(tempLoc, path.peek()));
        checkState(connLength >= 0d,
                "Found a bug in computeDistanceOnConnection, return value must be " + ">= 0, but is %s.",
                connLength);

        double traveledDistance;
        if (travelableDistance >= connLength) {
            // jump to next node in path (this may be a node or a point on a
            // connection)
            tempLoc = verifyLocation(asLoc(path.remove()));
            traveledDistance = connLength;
            mpBuilder.addNode(tempLoc);
        } else {
            // travelableDistance < connLength
            cont = false;
            traveledDistance = travelableDistance;
            final Connection<?> conn = getConnection(tempLoc, path.peek());
            tempLoc = verifyLocation(
                    newLoc(conn, tempLoc.relativePos + unitConversion.toExDist(travelableDistance)));
        }
        mpBuilder.addDistance(traveledDistance);
        final long timeSpent = DoubleMath.roundToLong(
                unitConversion.toExTime(traveledDistance / speed, time.getTimeUnit()), RoundingMode.HALF_DOWN);
        timeLeft -= timeSpent;
    }
    time.consume(time.getTimeLeft() - timeLeft);
    // update location and construct a MoveProgress object
    objLocs.put(object, tempLoc);
    return mpBuilder.build();
}

From source file:candr.yoclip.Parser.java

/**
 * Creates a {@code ParsedOptionParameter} for the option parameter at the head of the queue. The parsed option will not contain an error if an
 * option value is missing. The parsed option will contain an error if the option appears to have an associated value and does not take a value.
 *
 * @param parameters The current queue of command parameters.
 * @return a parsed option parameter or {@code null} in the following cases.
 * <ul>//from   w  ww  .j av a2s .  c o  m
 * <li>The parameters queue is empty.</li>
 * <li>The head of the parameters queue is not an option.</li>
 * </ul>
 */
protected ParsedOption<T> getParsedOption(final Queue<String> parameters) {

    ParsedOption<T> parsedOptionParameter = null;

    final String parameter = parameters.peek();
    if (!StringUtils.isEmpty(parameter) && isOption(parameter)) {

        final String prefix = getParserOptions().getPrefix();
        final String separator = getParserOptions().getSeparator();
        final boolean isSeparatorWhitespace = StringUtils.isWhitespace(separator);

        final int separatorIndex = isSeparatorWhitespace ? -1 : parameter.indexOf(separator);
        final String optionParameterKey = parameter.substring(prefix.length(),
                separatorIndex < 0 ? parameter.length() : separatorIndex);
        final ParserOption<T> optionParameter = getParserOptions().get(optionParameterKey);
        if (null != optionParameter) {

            parameters.remove();

            // get the value if the option takes one
            if (optionParameter.hasValue()) {

                String value = null;
                if (isSeparatorWhitespace) {

                    if (parameters.size() > 0 && !isOption(parameters.peek())) {

                        // remove the value from the queue
                        value = parameters.remove();
                    }

                } else if (separatorIndex != -1) {

                    final int valueIndex = separatorIndex + 1;
                    if (valueIndex < parameter.length()) {
                        value = parameter.substring(valueIndex);
                    }
                }

                // The value can be null here, without it being an error condition, to facilitate actions later on
                // such as using a default.
                parsedOptionParameter = new ParsedOption<T>(optionParameter, value);

            } else if (separatorIndex > 1) {

                // if the separator is not white space and a value was present with the option parameter
                parsedOptionParameter = new ParsedOption<T>(optionParameter, null);
                parsedOptionParameter.setError("Does not take a value.");

            } else {

                // If the option does not take a value it must be a boolean so force it true
                parsedOptionParameter = new ParsedOption<T>(optionParameter, Boolean.TRUE.toString());
            }
        }
    }

    return parsedOptionParameter;
}

From source file:azkaban.jobtype.AzkabanPigListener.java

@Override
public void initialPlanNotification(String scriptId, MROperPlan plan) {
    logger.info("**********initialPlanNotification!**********");

    // First pass: generate dagNodeNameMap.
    Map<OperatorKey, MapReduceOper> planKeys = plan.getKeys();
    for (Map.Entry<OperatorKey, MapReduceOper> entry : planKeys.entrySet()) {
        String nodeName = entry.getKey().toString();
        String[] aliases = toArray(ScriptState.get().getAlias(entry.getValue()).trim());
        String[] features = toArray(ScriptState.get().getPigFeature(entry.getValue()).trim());

        PigJobDagNode node = new PigJobDagNode(nodeName, aliases, features);
        this.dagNodeNameMap.put(node.getName(), node);

        // This shows how we can get the basic info about all nameless jobs 
        // before any execute. We can traverse the plan to build a DAG of this 
        // info./* w ww .java 2 s.co  m*/
        logger.info("initialPlanNotification: aliases: " + StringUtils.join(aliases, ",") + ", name: "
                + node.getName() + ", features: " + StringUtils.join(features, ","));
    }

    // Second pass: connect the edges
    for (Map.Entry<OperatorKey, MapReduceOper> entry : planKeys.entrySet()) {
        PigJobDagNode node = this.dagNodeNameMap.get(entry.getKey().toString());
        List<String> successorNodeList = new ArrayList<String>();
        List<MapReduceOper> successors = plan.getSuccessors(entry.getValue());
        if (successors != null) {
            for (MapReduceOper successor : successors) {
                PigJobDagNode successorNode = this.dagNodeNameMap.get(successor.getOperatorKey().toString());
                successorNodeList.add(successorNode.getName());
                successorNode.addParent(node);
            }
        }
        node.setSuccessors(successorNodeList);
    }

    // Third pass: find roots.
    Queue<PigJobDagNode> parentQueue = new LinkedList<PigJobDagNode>();
    Queue<PigJobDagNode> childQueue = new LinkedList<PigJobDagNode>();
    for (Map.Entry<String, PigJobDagNode> entry : this.dagNodeNameMap.entrySet()) {
        PigJobDagNode node = entry.getValue();
        if (node.getParents().isEmpty()) {
            node.setLevel(0);
            parentQueue.add(node);
        }
    }

    // Final pass: BFS to set levels.
    int level = 0;
    Set<PigJobDagNode> visited = new HashSet<PigJobDagNode>();
    while (parentQueue.peek() != null) {
        PigJobDagNode node = null;
        while ((node = parentQueue.poll()) != null) {
            if (visited.contains(node)) {
                continue;
            }
            node.setLevel(level);
            for (String jobName : node.getSuccessors()) {
                PigJobDagNode successorNode = this.dagNodeNameMap.get(jobName);
                childQueue.add(successorNode);
            }
        }

        Queue<PigJobDagNode> tmp = childQueue;
        childQueue = parentQueue;
        parentQueue = tmp;
        ++level;
    }

    updateJsonFile();
}

From source file:candr.yoclip.Parser.java

/**
 * Creates a collection of parsed option parameters from the queue of parameters passed in. The parameters queue is modified as parameters are
 * parsed, removing option parameters from the queue as they are parsed.
 *
 * @param parameters The command parameters that will be parsed.
 * @return a collection of parsed option parameters or {@code null} if the parameters queue is empty.
 *//*from   w  w w .  j  a  v  a2 s.c o  m*/
protected List<ParsedOption<T>> getParsedParameters(final String[] parameters) {

    final LinkedList<ParsedOption<T>> parsedOptionParameters = new LinkedList<ParsedOption<T>>();

    final Queue<String> parametersQueue = new LinkedList<String>(Arrays.asList(parameters));
    while (!parametersQueue.isEmpty()) {

        ParsedOption<T> parsedOptionParameter;
        if (!isOption(parametersQueue.peek())) {

            parsedOptionParameter = getParsedArgument(parametersQueue);

        } else {

            // check for an option property match first
            parsedOptionParameter = getParsedOptionProperty(parametersQueue);

            // an option next
            if (null == parsedOptionParameter) {
                parsedOptionParameter = getParsedOption(parametersQueue);
            }
        }

        // not an option
        if (null == parsedOptionParameter) {
            final String parameter = parametersQueue.remove();
            parsedOptionParameter = new ParsedOption<T>("'" + parameter + "': Unsupported option.");
        }

        parsedOptionParameters.add(parsedOptionParameter);

    }

    return parsedOptionParameters;
}

From source file:com.github.rinde.rinsim.core.model.road.PlaneRoadModel.java

@Override
protected MoveProgress doFollowPath(MovingRoadUser object, Queue<Point> path, TimeLapse time) {
    final long startTimeConsumed = time.getTimeConsumed();
    Point loc = objLocs.get(object);

    double traveled = 0;
    final double speed = min(unitConversion.toInSpeed(object.getSpeed()), maxSpeed);
    if (speed == 0d) {
        // FIXME add test for this case, also check GraphRoadModel
        final Measure<Double, Length> dist = Measure.valueOf(0d, getDistanceUnit());
        final Measure<Long, Duration> dur = Measure.valueOf(0L, time.getTimeUnit());
        return MoveProgress.create(dist, dur, new ArrayList<Point>());
    }/*from   w  ww  . j  a va  2 s. com*/

    final List<Point> travelledNodes = new ArrayList<>();
    while (time.hasTimeLeft() && !path.isEmpty()) {
        checkArgument(isPointInBoundary(path.peek()),
                "points in the path must be within the predefined boundary of the " + "plane");

        // distance in internal time unit that can be traveled with timeleft
        final double travelDistance = speed * unitConversion.toInTime(time.getTimeLeft(), time.getTimeUnit());
        final double stepLength = unitConversion.toInDist(Point.distance(loc, path.peek()));

        if (travelDistance >= stepLength) {
            loc = path.remove();
            travelledNodes.add(loc);

            final long timeSpent = DoubleMath.roundToLong(
                    unitConversion.toExTime(stepLength / speed, time.getTimeUnit()), RoundingMode.HALF_DOWN);
            time.consume(timeSpent);
            traveled += stepLength;
        } else {
            final Point diff = Point.diff(path.peek(), loc);

            if (stepLength - travelDistance < DELTA) {
                loc = path.peek();
                traveled += stepLength;
            } else {
                final double perc = travelDistance / stepLength;
                loc = new Point(loc.x + perc * diff.x, loc.y + perc * diff.y);
                traveled += travelDistance;
            }
            time.consumeAll();

        }
    }
    objLocs.put(object, loc);

    // convert to external units
    final Measure<Double, Length> distTraveled = unitConversion.toExDistMeasure(traveled);
    final Measure<Long, Duration> timeConsumed = Measure.valueOf(time.getTimeConsumed() - startTimeConsumed,
            time.getTimeUnit());
    return MoveProgress.create(distTraveled, timeConsumed, travelledNodes);
}