Example usage for java.util ListIterator hasPrevious

List of usage examples for java.util ListIterator hasPrevious

Introduction

In this page you can find the example usage for java.util ListIterator hasPrevious.

Prototype

boolean hasPrevious();

Source Link

Document

Returns true if this list iterator has more elements when traversing the list in the reverse direction.

Usage

From source file:org.apache.poi.ss.format.CellNumberFormatter.java

private Special previousNumber() {
    ListIterator<Special> it = specials.listIterator(specials.size());
    while (it.hasPrevious()) {
        Special s = it.previous();/*from  w w  w.  j a  va2 s  .  c  o m*/
        if (isDigitFmt(s)) {
            Special numStart = s;
            Special last = s;
            while (it.hasPrevious()) {
                s = it.previous();
                if (last.pos - s.pos > 1) // it has to be continuous digits
                    break;
                if (isDigitFmt(s))
                    numStart = s;
                else
                    break;
                last = s;
            }
            return numStart;
        }
    }
    return null;
}

From source file:org.apache.openjpa.jdbc.kernel.exps.PCPath.java

/**
 * Return the last action that gets a field.
 *///from  w w w.  j a va  2  s  . c om
private Action lastFieldAction() {
    if (_actions == null)
        return null;

    if (isXPath())
        return (Action) _actions.getLast();

    ListIterator itr = _actions.listIterator(_actions.size());
    Action prev;
    while (itr.hasPrevious()) {
        prev = (Action) itr.previous();
        if (prev.op == Action.GET || prev.op == Action.GET_OUTER || prev.op == Action.GET_KEY)
            return prev;
    }
    return null;
}

From source file:hudson.model.AbstractItem.java

/**
 * Deletes this item.//www. j  av a  2s .  c o  m
 * Note on the funny name: for reasons of historical compatibility, this URL is {@code /doDelete}
 * since it predates {@code <l:confirmationLink>}. {@code /delete} goes to a Jelly page
 * which should now be unused by core but is left in case plugins are still using it.
 */
@RequirePOST
public void doDoDelete(StaplerRequest req, StaplerResponse rsp)
        throws IOException, ServletException, InterruptedException {
    delete();
    if (req == null || rsp == null) { // CLI
        return;
    }
    List<Ancestor> ancestors = req.getAncestors();
    ListIterator<Ancestor> it = ancestors.listIterator(ancestors.size());
    String url = getParent().getUrl(); // fallback but we ought to get to Jenkins.instance at the root
    while (it.hasPrevious()) {
        Object a = it.previous().getObject();
        if (a instanceof View) {
            url = ((View) a).getUrl();
            break;
        } else if (a instanceof ViewGroup && a != this) {
            url = ((ViewGroup) a).getUrl();
            break;
        }
    }
    rsp.sendRedirect2(req.getContextPath() + '/' + url);
}

From source file:nl.armatiek.xslweb.web.servlet.XSLWebServlet.java

@SuppressWarnings("unchecked")
@Override//from  w  w  w. j a  va 2 s.com
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStream respOs = resp.getOutputStream();
    WebApp webApp = null;
    try {
        webApp = (WebApp) req.getAttribute(Definitions.ATTRNAME_WEBAPP);
        if (webApp.isClosed()) {
            resp.resetBuffer();
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            resp.setContentType("text/html; charset=UTF-8");
            Writer w = new OutputStreamWriter(respOs, "UTF-8");
            w.write("<html><body><h1>Service temporarily unavailable</h1></body></html>");
            return;
        }
        executeRequest(webApp, req, resp, respOs);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (webApp != null && webApp.getDevelopmentMode()) {
            resp.setContentType("text/plain; charset=UTF-8");
            e.printStackTrace(new PrintStream(respOs));
        } else if (!resp.isCommitted()) {
            resp.resetBuffer();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.setContentType("text/html; charset=UTF-8");
            Writer w = new OutputStreamWriter(respOs, "UTF-8");
            w.write("<html><body><h1>Internal Server Error</h1></body></html>");
        }
    } finally {
        // Delete any registered temporary files:
        try {
            List<File> tempFiles = (List<File>) req.getAttribute(Definitions.ATTRNAME_TEMPFILES);
            if (tempFiles != null) {
                ListIterator<File> li = tempFiles.listIterator();
                while (li.hasNext()) {
                    File file;
                    if ((file = li.next()) != null) {
                        FileUtils.deleteQuietly(file);
                    }
                }
            }
        } catch (Exception se) {
            logger.error("Error deleting registered temporary files", se);
        }

        // Close any closeables:
        try {
            List<Closeable> closeables = (List<Closeable>) req.getAttribute("xslweb-closeables");
            if (closeables != null) {
                ListIterator<Closeable> li = closeables.listIterator(closeables.size());
                while (li.hasPrevious()) {
                    li.previous().close();
                }
            }
        } catch (Exception se) {
            logger.error("Could not close Closeable", se);
        }
    }
}

From source file:org.apache.poi.ss.format.CellNumberFormatter.java

private void interpretCommas(StringBuffer sb) {
    // In the integer part, commas at the end are scaling commas; other commas mean to show thousand-grouping commas
    ListIterator<Special> it = specials.listIterator(integerEnd());

    boolean stillScaling = true;
    integerCommas = false;//from   w ww  . java 2 s. co  m
    while (it.hasPrevious()) {
        Special s = it.previous();
        if (s.ch != ',') {
            stillScaling = false;
        } else {
            if (stillScaling) {
                scale /= 1000;
            } else {
                integerCommas = true;
            }
        }
    }

    if (decimalPoint != null) {
        it = specials.listIterator(fractionalEnd());
        while (it.hasPrevious()) {
            Special s = it.previous();
            if (s.ch != ',') {
                break;
            } else {
                scale /= 1000;
            }
        }
    }

    // Now strip them out -- we only need their interpretation, not their presence
    it = specials.listIterator();
    int removed = 0;
    while (it.hasNext()) {
        Special s = it.next();
        s.pos -= removed;
        if (s.ch == ',') {
            removed++;
            it.remove();
            sb.deleteCharAt(s.pos);
        }
    }
}

From source file:org.pentaho.pms.mql.graph.MqlGraph.java

/**
 * Attempts to find next valid solution to the graph depending on what type of <code>PathType</code> is desired.
 *
 * @param searchTechnique Indicates type of search that should be performed
 * @param prevSolution    Previous solution to allow this search to continue from that point
 * @return The resulting solution/*from   ww w.  j  ava2  s.com*/
 * @throws ConsistencyException When determine that graph is impossible to satisfy
 */
private Solution searchForNextSolution(PathType searchTechnique, Solution prevSolution)
        throws ConsistencyException {
    // A left move equates to setting a requirement to false and a right move is equivalent to true.
    // Try setting to "false" first to reduce the number of tables for most searches.
    // For the "any relevant" search use "true" first which is quicker
    SearchDirection firstDirection;
    SearchDirection secondDirection;
    if (searchTechnique == PathType.ANY_RELEVANT) {
        firstDirection = SearchDirection.RIGHT;
        secondDirection = SearchDirection.LEFT;
    } else {
        firstDirection = SearchDirection.LEFT;
        secondDirection = SearchDirection.RIGHT;
    }

    // if this is a subsequent search after a solution was already found, we need
    // to return to the location where the last move in the first direction was made
    List<SearchDirection> searchPath = new LinkedList<SearchDirection>();
    List<Arc> searchArcs = new LinkedList<Arc>();
    if (prevSolution != null) {
        // check for situation where we have already traversed all possible paths
        boolean prevContainsFirstDirection = false;
        for (SearchDirection direction : prevSolution.searchPath) {
            if (direction == firstDirection) {
                prevContainsFirstDirection = true;
                break;
            }
        }
        if (!prevContainsFirstDirection) {
            return null;
        }

        ListIterator<SearchDirection> pathIter = prevSolution.searchPath
                .listIterator(prevSolution.searchPath.size());

        // continue to move back in search path until we find an arc that can
        // be assigned the second direction
        boolean foundSecondDir = false;
        while (pathIter.hasPrevious() && !foundSecondDir) {

            // reset the search function for next search operation
            reset(requiredTables);
            propagate();
            searchPath.clear();
            searchArcs.clear();

            // locate the last move that has an alternative
            while (pathIter.hasPrevious()) {
                SearchDirection direction = pathIter.previous();

                if (direction == firstDirection) {
                    break;
                }
            }

            // recreate path up to point where we can try a different direction
            Iterator<Arc> arcIter = prevSolution.getSearchArcs().iterator();
            if (pathIter.hasPrevious()) {
                Iterator<SearchDirection> redoIter = prevSolution.getSearchPath().iterator();
                int lastIdx = pathIter.previousIndex();
                for (int idx = 0; idx <= lastIdx; idx++) {

                    // all of these operations should work without issue
                    SearchDirection direction = redoIter.next();
                    Arc arc = arcIter.next();
                    if (!attemptArcAssignment(arc, direction)) {
                        throw new ConsistencyException(arc);
                    }

                    // add movement to newly constructed search path
                    searchPath.add(direction);
                    searchArcs.add(arc);
                }
            }

            // before any searching will begin, make sure the path we are going down shouldn't
            // just be skipped
            int rating = getRatingForCurrentState(searchTechnique);

            // current state isn't any better, return it as next solution
            if (rating >= prevSolution.getRating()) {
                return new Solution(arcs, rating, searchPath, searchArcs, true);
            }

            // retrieve arc which we are going to move second direction
            Arc arc = arcIter.next();

            // if we can't move the second direction here, continue
            // to move back in search path until we find an arc that can
            // be assigned the second direction
            if (attemptArcAssignment(arc, secondDirection)) {
                // update new search path
                searchPath.add(secondDirection);
                searchArcs.add(arc);

                // before any searching will begin, make sure the path we are going down shouldn't
                // just be skipped
                rating = getRatingForCurrentState(searchTechnique);

                // current state isn't any better, return it as next solution
                if (rating >= prevSolution.getRating()) {
                    return new Solution(arcs, rating, searchPath, searchArcs, true);
                }

                // set second direction flag so search will continue
                foundSecondDir = true;
            }
        }

        // if we weren't able to make another movement, there are not more solutions
        if (searchPath.size() == 0) {
            return null;
        }
    }

    // dump current state of graph
    if (logger.isDebugEnabled()) {
        logger.debug("-- Graph State Before Search --");
        dumpStateToLog();
    }

    // look for arcs that are not bound
    int rating = -1;
    for (Arc a : arcs) {
        if (!a.isRequirementKnown()) {
            // try the first direction
            if (attemptArcAssignment(a, firstDirection)) {
                searchPath.add(firstDirection);
            } else if (attemptArcAssignment(a, secondDirection)) { // if first direction fails, try the second
                searchPath.add(secondDirection);
            } else { // If arc cannot be assigned a requirement value, throw an exception
                throw new ConsistencyException(a);
            }

            // record arc that was altered in search path
            searchArcs.add(a);

            // make sure solution is getting better
            if (prevSolution != null) {
                rating = getRatingForCurrentState(searchTechnique);

                // current state isn't any better, return it as next solution
                if (rating >= prevSolution.getRating()) {
                    return new Solution(arcs, rating, searchPath, searchArcs, true);
                }
            }
        }
    }

    // compute rating if never computed
    if (rating < 0) {
        rating = getRatingForCurrentState(searchTechnique);
    }

    // return solution to graph problem
    return new Solution(arcs, rating, searchPath, searchArcs, false);
}

From source file:org.beepcore.beep.core.ChannelImpl.java

private void validateFrame(Frame frame) throws BEEPException {
    synchronized (this) {

        if (previousFrame == null) {
            // is the message number correct?
            if (frame.getMessageType() == Message.MESSAGE_TYPE_MSG) {
                synchronized (recvMSGQueue) {
                    ListIterator i = recvMSGQueue.listIterator(recvMSGQueue.size());
                    while (i.hasPrevious()) {
                        if (((Message) i.previous()).getMsgno() == frame.getMsgno()) {
                            throw new BEEPException("Received a frame " + "with a duplicate " + "msgno ("
                                    + frame.getMsgno() + ")");
                        }/*www . j av a 2s.  c  o  m*/
                    }
                }
            } else {
                MessageStatus mstatus;

                synchronized (sentMSGQueue) {
                    if (sentMSGQueue.size() == 0) {
                        throw new BEEPException("Received unsolicited reply");
                    }

                    mstatus = (MessageStatus) sentMSGQueue.get(0);
                }

                if (frame.getMsgno() != mstatus.getMsgno()) {
                    throw new BEEPException("Incorrect message number: was " + frame.getMsgno() + "; expecting "
                            + mstatus.getMsgno());
                }
            }
        } else {
            // is the message type the same as the previous frames?
            if (previousFrame.getMessageType() != frame.getMessageType()) {
                throw new BEEPException("Incorrect message type: was " + frame.getMessageTypeString()
                        + "; expecting " + previousFrame.getMessageTypeString());
            }

            // is the message number correct?
            if (frame.getMessageType() == Message.MESSAGE_TYPE_MSG
                    && frame.getMsgno() != previousFrame.getMsgno()) {
                throw new BEEPException("Incorrect message number: was " + frame.getMsgno() + "; expecting "
                        + previousFrame.getMsgno());
            }
        }

        // is the sequence number correct?
        if (frame.getSeqno() != recvSequence) {
            throw new BEEPException(
                    "Incorrect sequence number: was " + frame.getSeqno() + "; expecting " + recvSequence);
        }

    }

    if (frame.getMessageType() != Message.MESSAGE_TYPE_MSG) {
        MessageStatus mstatus;

        synchronized (sentMSGQueue) {
            if (sentMSGQueue.size() == 0) {
                throw new BEEPException("Received unsolicited reply");
            }

            mstatus = (MessageStatus) sentMSGQueue.get(0);

            if (mstatus.getMsgno() != frame.getMsgno()) {
                throw new BEEPException("Received reply out of order");
            }
        }
    }

    // save the previous frame to compare message types
    if (frame.isLast()) {
        previousFrame = null;
    } else {
        previousFrame = frame;
    }

}

From source file:org.pentaho.metadata.query.impl.sql.graph.MqlGraph.java

/**
 * Attempts to find next valid solution to the graph depending on what type of <code>PathType</code> is desired.
 * //w w  w.  j  a v  a 2 s.c om
 * @param searchTechnique
 *          Indicates type of search that should be performed
 * @param prevSolution
 *          Previous solution to allow this search to continue from that point
 * @return The resulting solution
 * @throws ConsistencyException
 *           When determine that graph is impossible to satisfy
 */
private Solution searchForNextSolution(PathType searchTechnique, Solution prevSolution)
        throws ConsistencyException {
    // A left move equates to setting a requirement to false and a right move is equivalent to true.
    // Try setting to "false" first to reduce the number of tables for most searches.
    // For the "any relevant" search use "true" first which is quicker
    SearchDirection firstDirection;
    SearchDirection secondDirection;
    if (searchTechnique == PathType.ANY_RELEVANT) {
        firstDirection = SearchDirection.RIGHT;
        secondDirection = SearchDirection.LEFT;
    } else {
        firstDirection = SearchDirection.LEFT;
        secondDirection = SearchDirection.RIGHT;
    }

    // if this is a subsequent search after a solution was already found, we need
    // to return to the location where the last move in the first direction was made
    List<SearchDirection> searchPath = new LinkedList<SearchDirection>();
    List<Arc> searchArcs = new LinkedList<Arc>();
    if (prevSolution != null) {
        // check for situation where we have already traversed all possible paths
        boolean prevContainsFirstDirection = false;
        for (SearchDirection direction : prevSolution.searchPath) {
            if (direction == firstDirection) {
                prevContainsFirstDirection = true;
                break;
            }
        }
        if (!prevContainsFirstDirection) {
            return null;
        }

        ListIterator<SearchDirection> pathIter = prevSolution.searchPath
                .listIterator(prevSolution.searchPath.size());

        // continue to move back in search path until we find an arc that can
        // be assigned the second direction
        boolean foundSecondDir = false;
        while (pathIter.hasPrevious() && !foundSecondDir) {

            // reset the search function for next search operation
            reset(requiredTables);
            propagate();
            searchPath.clear();
            searchArcs.clear();

            // locate the last move that has an alternative
            while (pathIter.hasPrevious()) {
                SearchDirection direction = pathIter.previous();

                if (direction == firstDirection) {
                    break;
                }
            }

            // recreate path up to point where we can try a different direction
            Iterator<Arc> arcIter = prevSolution.getSearchArcs().iterator();
            if (pathIter.hasPrevious()) {
                Iterator<SearchDirection> redoIter = prevSolution.getSearchPath().iterator();
                int lastIdx = pathIter.previousIndex();
                for (int idx = 0; idx <= lastIdx; idx++) {

                    // all of these operations should work without issue
                    SearchDirection direction = redoIter.next();
                    Arc arc = arcIter.next();
                    if (!attemptArcAssignment(arc, direction)) {
                        throw new ConsistencyException(arc);
                    }

                    // add movement to newly constructed search path
                    searchPath.add(direction);
                    searchArcs.add(arc);
                }
            }

            // before any searching will begin, make sure the path we are going down shouldn't
            // just be skipped
            int rating = getRatingForCurrentState(searchTechnique);

            // current state isn't any better, return it as next solution
            if (rating >= prevSolution.getRating()) {
                return new Solution(arcs, rating, searchPath, searchArcs, true);
            }

            // retrieve arc which we are going to move second direction
            Arc arc = arcIter.next();

            // if we can't move the second direction here, continue
            // to move back in search path until we find an arc that can
            // be assigned the second direction
            if (attemptArcAssignment(arc, secondDirection)) {
                // update new search path
                searchPath.add(secondDirection);
                searchArcs.add(arc);

                // before any searching will begin, make sure the path we are going down shouldn't
                // just be skipped
                rating = getRatingForCurrentState(searchTechnique);

                // current state isn't any better, return it as next solution
                if (rating >= prevSolution.getRating()) {
                    return new Solution(arcs, rating, searchPath, searchArcs, true);
                }

                // set second direction flag so search will continue
                foundSecondDir = true;
            }
        }

        // if we weren't able to make another movement, there are not more solutions
        if (searchPath.size() == 0) {
            return null;
        }
    }

    // dump current state of graph
    if (logger.isDebugEnabled()) {
        logger.debug("-- Graph State Before Search --");
        dumpStateToLog();
    }

    // look for arcs that are not bound
    int rating = -1;
    for (Arc a : arcs) {
        if (!a.isRequirementKnown()) {
            // try the first direction
            if (attemptArcAssignment(a, firstDirection)) {
                searchPath.add(firstDirection);
            } else if (attemptArcAssignment(a, secondDirection)) { // if first direction fails, try the second
                searchPath.add(secondDirection);
            } else { // If arc cannot be assigned a requirement value, throw an exception
                throw new ConsistencyException(a);
            }

            // record arc that was altered in search path
            searchArcs.add(a);

            // make sure solution is getting better
            if (prevSolution != null) {
                rating = getRatingForCurrentState(searchTechnique);

                // current state isn't any better, return it as next solution
                if (rating >= prevSolution.getRating()) {
                    return new Solution(arcs, rating, searchPath, searchArcs, true);
                }
            }
        }
    }

    // compute rating if never computed
    if (rating < 0) {
        rating = getRatingForCurrentState(searchTechnique);
    }
    // return solution to graph problem
    return new Solution(arcs, rating, searchPath, searchArcs, false);
}

From source file:org.libreplan.business.resources.entities.Resource.java

private CriterionSatisfaction getPrevious(ListIterator<CriterionSatisfaction> listIterator) {
    listIterator.previous();/* w ww.j  a v  a  2 s  . c om*/
    try {
        if (listIterator.hasPrevious()) {
            CriterionSatisfaction result = listIterator.previous();
            listIterator.next();
            return result;
        }
        return null;
    } finally {
        listIterator.next();
    }
}

From source file:de.uni_potsdam.hpi.asg.logictool.mapping.SequenceBasedAndGateDecomposer.java

private List<Boolean> evaluateBDD(BDD bddParam, State startState, List<Transition> sequence) {
    List<Boolean> retVal = new ArrayList<>();
    for (int i = sequence.size() - 1; i >= 0; i--) {
        BDD bdd = bddParam.or(factory.zero());
        ListIterator<Transition> it = sequence.listIterator(sequence.size() - i);
        List<Signal> alreadyset = new ArrayList<>();
        while (it.hasPrevious()) {
            BDD sigbdd = null;/* w  w w.  j a v a  2  s  .com*/
            Transition t = it.previous();
            if (!alreadyset.contains(t.getSignal())) {
                switch (t.getEdge()) {
                case falling:
                    sigbdd = getNegBDD(t.getSignal());
                    break;
                case rising:
                    sigbdd = getPosBDD(t.getSignal());
                    break;
                }
                bdd = bdd.restrictWith(sigbdd);
                alreadyset.add(t.getSignal());
            }
        }

        for (Entry<Signal, Value> entry : startState.getStateValues().entrySet()) {
            if (!alreadyset.contains(entry.getKey())) {
                BDD sigbdd = null;
                switch (entry.getValue()) {
                case falling:
                case high:
                    sigbdd = getPosBDD(entry.getKey());
                    break;
                case low:
                case rising:
                    sigbdd = getNegBDD(entry.getKey());
                    break;
                }
                bdd = bdd.restrictWith(sigbdd);
            }
        }
        for (Entry<NetlistVariable, Boolean> entry : netlist.getQuasiSignals().entrySet()) {
            BDD sigbdd = null;
            if (entry.getValue()) {
                //true => Normally 1
                sigbdd = getPosBDD(quasimap.get(entry.getKey()));
            } else {
                sigbdd = getNegBDD(quasimap.get(entry.getKey()));
            }
            bdd = bdd.restrictWith(sigbdd);
        }

        if (bdd.isOne()) {
            retVal.add(true);
        } else if (bdd.isZero()) {
            retVal.add(false);
        } else {
            logger.error("BDD not restricted enough?!");
            return null;
        }
    }

    return retVal;
}