Example usage for java.util ListIterator previous

List of usage examples for java.util ListIterator previous

Introduction

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

Prototype

E previous();

Source Link

Document

Returns the previous element in the list and moves the cursor position backwards.

Usage

From source file:hudson.model.AbstractItem.java

/**
 * Deletes this item./*from   w  ww. j a v  a2 s  .  co  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:org.codehaus.mojo.webminifier.WebMinifierMojo.java

/**
 * Main entry point for the MOJO.// w  w w.  j  av  a2 s.  c om
 * 
 * @throws MojoExecutionException if there's a problem in the normal course of execution.
 * @throws MojoFailureException if there's a problem with the MOJO itself.
 */
public void execute() throws MojoExecutionException, MojoFailureException {
    // Start off by copying all files over. We'll ultimately remove the js files that we don't need from there, and
    // create new ones in there (same goes for css files and anything else we minify).

    FileUtils.deleteQuietly(destinationFolder);
    try {
        FileUtils.copyDirectory(sourceFolder, destinationFolder);
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot copy file to target folder", e);
    }

    // Process each HTML source file and concatenate into unminified output scripts
    int minifiedCounter = 0;

    // If a split point already exists on disk then we've been through the minification process. As
    // minification can be expensive, we would like to avoid performing it multiple times. Thus storing
    // a set of what we've previously minified enables us.
    Set<File> existingConcatenatedJsResources = new HashSet<File>();
    Set<File> consumedJsResources = new HashSet<File>();

    for (String targetHTMLFile : getArrayOfTargetHTMLFiles()) {
        File targetHTML = new File(destinationFolder, targetHTMLFile);

        // Parse HTML file and locate SCRIPT elements
        DocumentResourceReplacer replacer;
        try {
            replacer = new DocumentResourceReplacer(targetHTML);
        } catch (SAXException e) {
            throw new MojoExecutionException("Problem reading html document", e);
        } catch (IOException e) {
            throw new MojoExecutionException("Problem opening html document", e);
        }

        List<File> jsResources = replacer.findJSResources();

        if (jsSplitPoints == null) {
            jsSplitPoints = new Properties();
        }

        File concatenatedJsResource = null;

        URI destinationFolderUri = destinationFolder.toURI();

        // Split the js resources into two lists: one containing all external dependencies, the other containing
        // project sources. We do this so that project sources can be minified without the dependencies (libraries
        // generally don't need to distribute the dependencies).
        int jsDependencyProjectResourcesIndex;

        if (splitDependencies) {
            List<File> jsDependencyResources = new ArrayList<File>(jsResources.size());
            List<File> jsProjectResources = new ArrayList<File>(jsResources.size());
            for (File jsResource : jsResources) {
                String jsResourceUri = destinationFolderUri.relativize(jsResource.toURI()).toString();
                File jsResourceFile = new File(projectSourceFolder, jsResourceUri);
                if (jsResourceFile.exists()) {
                    jsProjectResources.add(jsResource);
                } else {
                    jsDependencyResources.add(jsResource);
                }
            }

            // Re-constitute the js resource list from dependency resources + project resources and note the index
            // in the list that represents the start of project sources in the list. We need this information later.
            jsDependencyProjectResourcesIndex = jsDependencyResources.size();

            jsResources = jsDependencyResources;
            jsResources.addAll(jsProjectResources);
        } else {
            jsDependencyProjectResourcesIndex = 0;
        }

        // Walk backwards through the script declarations and note what files will map to what split point.
        Map<File, File> jsResourceTargetFiles = new LinkedHashMap<File, File>(jsResources.size());
        ListIterator<File> jsResourcesIter = jsResources.listIterator(jsResources.size());

        boolean splittingDependencies = false;

        while (jsResourcesIter.hasPrevious()) {
            int jsResourceIterIndex = jsResourcesIter.previousIndex();
            File jsResource = jsResourcesIter.previous();

            String candidateSplitPointNameUri = destinationFolderUri.relativize(jsResource.toURI()).toString();
            String splitPointName = (String) jsSplitPoints.get(candidateSplitPointNameUri);

            // If we do not have a split point name and the resource is a dependency of this project i.e. it is not
            // within our src/main folder then we give it a split name of "dependencies". Factoring out dependencies
            // into their own split point is a useful thing to do and will always be required when building
            // libraries.
            if (splitDependencies && splitPointName == null && !splittingDependencies) {
                if (jsResourceIterIndex < jsDependencyProjectResourcesIndex) {
                    splitPointName = Integer.valueOf(++minifiedCounter).toString();
                    splittingDependencies = true;
                }
            }

            // If we have no name and we've not been in here before, then assign an initial name based on a number.
            if (splitPointName == null && concatenatedJsResource == null) {
                splitPointName = Integer.valueOf(++minifiedCounter).toString();
            }

            // We have a new split name so use it for this file and upwards in the script statements until we
            // either hit another split point or there are no more script statements.
            if (splitPointName != null) {
                concatenatedJsResource = new File(destinationFolder, splitPointName + ".js");

                // Note that we've previously created this.
                if (concatenatedJsResource.exists()) {
                    existingConcatenatedJsResources.add(concatenatedJsResource);
                }
            }

            jsResourceTargetFiles.put(jsResource, concatenatedJsResource);
        }

        for (File jsResource : jsResources) {
            concatenatedJsResource = jsResourceTargetFiles.get(jsResource);
            if (!existingConcatenatedJsResources.contains(concatenatedJsResource)) {
                // Concatenate input file onto output resource file
                try {
                    concatenateFile(jsResource, concatenatedJsResource);
                } catch (IOException e) {
                    throw new MojoExecutionException("Problem concatenating JS files", e);
                }

                // Finally, remove the JS resource from the target folder as it is no longer required (we've
                // concatenated it).
                consumedJsResources.add(jsResource);
            }
        }

        // Reduce the list of js resource target files to a distinct set
        LinkedHashSet<File> concatenatedJsResourcesSet = new LinkedHashSet<File>(
                jsResourceTargetFiles.values());
        File[] concatenatedJsResourcesArray = new File[concatenatedJsResourcesSet.size()];
        concatenatedJsResourcesSet.toArray(concatenatedJsResourcesArray);
        List<File> concatenatedJsResources = Arrays.asList(concatenatedJsResourcesArray);

        // Minify the concatenated JS resource files

        if (jsCompressorType != JsCompressorType.NONE) {
            List<File> minifiedJSResources = new ArrayList<File>(concatenatedJsResources.size());

            ListIterator<File> concatenatedJsResourcesIter = concatenatedJsResources
                    .listIterator(concatenatedJsResources.size());
            while (concatenatedJsResourcesIter.hasPrevious()) {
                concatenatedJsResource = concatenatedJsResourcesIter.previous();

                File minifiedJSResource;
                try {
                    String uri = concatenatedJsResource.toURI().toString();
                    int i = uri.lastIndexOf(".js");
                    String minUri;
                    if (i > -1) {
                        minUri = uri.substring(0, i) + "-min.js";
                    } else {
                        minUri = uri;
                    }
                    minifiedJSResource = FileUtils.toFile(new URL(minUri));
                } catch (MalformedURLException e) {
                    throw new MojoExecutionException("Problem determining file URL", e);
                }

                minifiedJSResources.add(minifiedJSResource);

                // If we've not actually performed the minification before... then do so. This is the expensive bit
                // so we like to avoid it if we can.
                if (!existingConcatenatedJsResources.contains(concatenatedJsResource)) {
                    boolean warningsFound;
                    try {
                        warningsFound = minifyJSFile(concatenatedJsResource, minifiedJSResource);
                    } catch (IOException e) {
                        throw new MojoExecutionException("Problem reading/writing JS", e);
                    }

                    logCompressionRatio(minifiedJSResource.getName(), concatenatedJsResource.length(),
                            minifiedJSResource.length());

                    // If there were warnings then the user may want to manually invoke the compressor for further
                    // investigation.
                    if (warningsFound) {
                        getLog().warn("Warnings were found. " + concatenatedJsResource
                                + " is available for your further investigations.");
                    }
                }
            }

            // Update source references
            replacer.replaceJSResources(destinationFolder, targetHTML, minifiedJSResources);
        } else {
            List<File> unminifiedJSResources = new ArrayList<File>(concatenatedJsResources.size());

            ListIterator<File> concatenatedJsResourcesIter = concatenatedJsResources
                    .listIterator(concatenatedJsResources.size());
            while (concatenatedJsResourcesIter.hasPrevious()) {
                concatenatedJsResource = concatenatedJsResourcesIter.previous();
                unminifiedJSResources.add(concatenatedJsResource);
            }

            replacer.replaceJSResources(destinationFolder, targetHTML, unminifiedJSResources);
            getLog().info("Concatenated resources with no compression");
        }

        // Write HTML file to output dir
        try {
            replacer.writeHTML(targetHTML, encoding);
        } catch (TransformerException e) {
            throw new MojoExecutionException("Problem transforming html", e);
        } catch (IOException e) {
            throw new MojoExecutionException("Problem writing html", e);
        }

    }

    // Clean up including the destination folder recursively where directories have nothing left in them.
    for (File consumedJsResource : consumedJsResources) {
        consumedJsResource.delete();
    }
    removeEmptyFolders(destinationFolder);
}

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

@SuppressWarnings("unchecked")
@Override/*from   w  w w .j  a v a2 s  . c o  m*/
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. j ava 2 s.  c o  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.libreplan.business.resources.entities.Resource.java

private CriterionSatisfaction getNext(ListIterator<CriterionSatisfaction> listIterator) {
    if (listIterator.hasNext()) {
        CriterionSatisfaction result = listIterator.next();
        listIterator.previous();
        return result;
    }//  w  w w .j  a  v a  2s .c  o m
    return null;
}

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() + ")");
                        }//from w ww. j a v a  2 s .  c  om
                    }
                }
            } 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:name.livitski.tools.springlet.Launcher.java

/**
 * Configures the manager using command-line arguments.
 * The arguments are checked in their command line sequence.
 * If an argument begins with {@link Command#COMMAND_PREFIX},
 * its part that follows it is treated as a (long) command's name.
 * If an argument begins with {@link Command#SWITCH_PREFIX},
 * the following character(s) are treated as a switch.
 * The name or switch extracted this way, prepended with
 * a bean name prefix for a {@link #BEAN_NAME_PREFIX_COMMAND command}
 * or a {@link #BEAN_NAME_PREFIX_SWITCH switch}, becomes the name
 * of a bean to look up in the framework's
 * {@link #MAIN_BEAN_CONFIG_FILE configuration file(s)}.
 * The bean that handles a command must extend the
 * {@link Command} class. Once a suitable bean is found,
 * it is called to act upon the command or switch and process
 * any additional arguments associated with it. 
 * If no bean can be found or the argument is not prefixed
 * properly, it is considered unclaimed. You may configure a
 * special subclass of {@link Command} to process such arguments
 * by placing a bean named {@link #BEAN_NAME_DEFAULT_HANDLER} on
 * the configuration. If there is no such bean configured, or when
 * any {@link Command} bean throws an exception while processing
 * a command, a command line error is reported and the application
 * quits.//from   w  w  w . j  a v  a2  s. c o m
 * @param args the command line
 * @return this manager object
 */
public Launcher withArguments(String[] args) {
    configureDefaultLogging();
    final Log log = log();
    ListIterator<String> iargs = Arrays.asList(args).listIterator();
    while (iargs.hasNext()) {
        String arg = iargs.next();
        String prefix = null;
        String beanPrefix = null;
        Command cmd = null;
        if (arg.startsWith(Command.COMMAND_PREFIX))
            prefix = Command.COMMAND_PREFIX;
        else if (arg.startsWith(Command.SWITCH_PREFIX))
            prefix = Command.SWITCH_PREFIX;
        if (null != prefix) {
            arg = arg.substring(prefix.length());
            beanPrefix = Command.SWITCH_PREFIX == prefix ? BEAN_NAME_PREFIX_SWITCH : BEAN_NAME_PREFIX_COMMAND;
            try {
                cmd = getBeanFactory().getBean(beanPrefix + arg, Command.class);
            } catch (NoSuchBeanDefinitionException noBean) {
                log.debug("Could not find a handler for command-line argument " + prefix + arg, noBean);
            }
        }
        if (null == cmd) {
            iargs.previous();
            try {
                cmd = getBeanFactory().getBean(BEAN_NAME_DEFAULT_HANDLER, Command.class);
            } catch (RuntimeException ex) {
                log.error("Unknown command line argument: " + (null != prefix ? prefix : "") + arg, ex);
                status = STATUS_COMMAND_PARSING_FAILURE;
                break;
            }
        }
        try {
            cmd.process(iargs);
        } catch (SkipApplicationRunRequest skip) {
            if (log.isTraceEnabled())
                log.trace("Handler for argument " + (null != prefix ? prefix : "") + arg
                        + " requested to skip the application run", skip);
            status = STATUS_RUN_SKIPPED;
            break;
        } catch (RuntimeException err) {
            log.error("Invalid command line argument(s) near " + (null != prefix ? prefix : "") + arg + ": "
                    + err.getMessage(), err);
            status = STATUS_COMMAND_PARSING_FAILURE;
            break;
        } catch (ApplicationBeanException err) {
            log.error("Error processing command line argument " + (null != prefix ? prefix : "") + arg + ": "
                    + err.getMessage(), err);
            try {
                err.updateBeanStatus();
            } catch (RuntimeException noStatus) {
                final ApplicationBean appBean = err.getApplicationBean();
                log.warn("Could not obtain status code" + (null != appBean ? " from " + appBean : ""),
                        noStatus);
                status = STATUS_INTERNAL_ERROR;
            }
            break;
        }
    }
    return this;
}

From source file:playground.sergioo.ptsim2013.qnetsimengine.PTQLink.java

/**
 * This method/*from   w w w.  j  a va 2  s  .  com*/
 * moves transit vehicles from the stop queue directly to the front of the
 * "queue" of the QLink. An advantage is that this will observe flow
 * capacity restrictions. 
 */
private void moveTransitToQueue(final double now) {
    QVehicle veh;
    // handle transit traffic in stop queue
    List<QVehicle> departingTransitVehicles = null;
    while ((veh = transitVehicleStopQueue.peek()) != null) {
        // there is a transit vehicle.
        if (veh.getEarliestLinkExitTime() > now) {
            break;
        }
        if (departingTransitVehicles == null) {
            departingTransitVehicles = new LinkedList<QVehicle>();
        }
        departingTransitVehicles.add(transitVehicleStopQueue.poll());
    }
    if (departingTransitVehicles != null) {
        // add all departing transit vehicles at the front of the vehQueue
        ListIterator<QVehicle> iter = departingTransitVehicles.listIterator(departingTransitVehicles.size());
        while (iter.hasPrevious()) {
            this.vehQueue.addFirst(iter.previous());
        }
    }
}

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  a2s  . c  o m*/
            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;
}

From source file:net.sf.jabref.bst.VM.java

private void reverse(Tree child) {

    BstFunction f = functions.get(child.getChild(0).getText());

    ListIterator<BstEntry> i = entries.listIterator(entries.size());
    while (i.hasPrevious()) {
        f.execute(i.previous());
    }/*from   ww  w  .ja  va 2 s  .c o m*/
}