Example usage for java.util LinkedList pop

List of usage examples for java.util LinkedList pop

Introduction

In this page you can find the example usage for java.util LinkedList pop.

Prototype

public E pop() 

Source Link

Document

Pops an element from the stack represented by this list.

Usage

From source file:org.alfresco.bm.event.AbstractResultService.java

/**
 * Reports the oldest stats for the events and pops it off the list
 * /*from   ww  w . j  a  va  2s  .  c om*/
 * @param windowMultiple        the number of reporting entries to hold per event
 * @return                      <tt>true</tt> to stop processing
 */
private boolean reportAndCycleStats(Map<String, LinkedList<DescriptiveStatistics>> statsByEventName,
        Map<String, LinkedList<AtomicInteger>> failuresByEventName, long currentWindowStartTime,
        long currentWindowEndTime, int windowMultiple, ResultHandler handler) {
    // Handle stats
    Map<String, DescriptiveStatistics> stats = new HashMap<String, DescriptiveStatistics>(
            statsByEventName.size() + 7);
    for (Map.Entry<String, LinkedList<DescriptiveStatistics>> entry : statsByEventName.entrySet()) {
        // Grab the OLDEST stats from the beginning of the list
        String eventName = entry.getKey();
        LinkedList<DescriptiveStatistics> ll = entry.getValue();
        try {
            DescriptiveStatistics eventStats = ll.getFirst();
            stats.put(eventName, eventStats);
            if (ll.size() == windowMultiple) {
                // We have enough reporting points for the window, so pop the first and add a new to the end
                ll.pop();
            }
            ll.add(new DescriptiveStatistics());
        } catch (NoSuchElementException e) {
            throw new RuntimeException(
                    "An event name did not have a result for the reporting period: " + statsByEventName);
        }
    }

    // Handle failures
    Map<String, Integer> failures = new HashMap<String, Integer>(statsByEventName.size() + 7);
    for (Map.Entry<String, LinkedList<AtomicInteger>> entry : failuresByEventName.entrySet()) {
        // Grab the OLDEST stats from the beginning of the list
        String eventName = entry.getKey();
        LinkedList<AtomicInteger> ll = entry.getValue();
        try {
            AtomicInteger eventFailures = ll.getFirst();
            failures.put(eventName, Integer.valueOf(eventFailures.get()));
            if (ll.size() == windowMultiple) {
                // We have enough reporting points for the window, so pop the first and add a new to the end
                ll.pop();
            }
            ll.add(new AtomicInteger());
        } catch (NoSuchElementException e) {
            throw new RuntimeException("An event name did not have a failure count for the reporting period: "
                    + failuresByEventName);
        }
    }

    boolean stop = false;
    try {
        boolean go = handler.processResult(currentWindowStartTime, currentWindowEndTime, stats, failures);
        stop = !go;
    } catch (Throwable e) {
        logger.error("Exception while making callback.", e);
    }
    return stop;
}

From source file:org.nuxeo.ecm.platform.routing.core.impl.GraphRunner.java

protected void recursiveCancelInput(GraphRoute graph, GraphNode originalNode,
        LinkedList<GraphNode> pendingNodes) {
    LinkedList<GraphNode> todo = new LinkedList<GraphNode>();
    todo.add(originalNode);//from  www . j  av  a 2  s.  com
    Set<String> done = new HashSet<String>();
    while (!todo.isEmpty()) {
        GraphNode node = todo.pop();
        done.add(node.getId());
        for (Transition t : node.getInputTransitions()) {
            if (t.loop) {
                // don't recurse through loop transitions
                continue;
            }
            GraphNode source = t.source;
            if (done.contains(source.getId())) {
                // looping somewhere TODO check it's not happening
                continue;
            }
            source.setCanceled();
            State state = source.getState();
            source.setState(State.READY);
            pendingNodes.remove(node);
            if (state == State.SUSPENDED) {
                // we're suspended on a task, cancel it and stop recursion
                source.cancelTasks();
            } else {
                // else recurse
                todo.add(source);
            }
        }
    }
}

From source file:org.squashtest.tm.domain.library.structures.LibraryTree.java

/**
 * removes a node and its subtree//  w w w .j a  va  2s.  c  o  m
 *
 * @param key
 */
public void cut(IDENT key) {
    T node = getNode(key);

    T parent = node.getParent();
    if (parent != null) {
        parent.getChildren().remove(node);
    }

    LinkedList<T> processing = new LinkedList<>();
    processing.add(node);

    while (!processing.isEmpty()) {
        T current = processing.pop();
        List<T> layer = layers.get(current.getDepth());
        layer.remove(current);
        processing.addAll(current.getChildren());
    }

}

From source file:com.tulskiy.musique.library.Library.java

public void rescan(Map<String, Object> progress) {
    List<String> folders = LibraryConfiguration.getFolders();
    if (CollectionUtils.isEmpty(folders)) {
        return;/*from w  ww. j  a v a2  s.  co m*/
    }
    progress.put("processing.file", "");

    data.removeDeadItems();

    HashMap<TrackData, Track> trackDatas = new HashMap<TrackData, Track>();
    for (Track track : data) {
        trackDatas.put(track.getTrackData(), track);
    }

    LinkedList<File> queue = new LinkedList<File>();
    for (String path : folders) {
        File f = new File(path);
        if (f.exists())
            queue.add(f);
    }

    HashSet<Track> processed = new HashSet<Track>();
    final Set<String> formats = Codecs.getFormats();
    ArrayList<Track> temp = new ArrayList<Track>();
    while (!queue.isEmpty()) {
        try {
            File file = queue.pop();
            if (progress != null) {
                if (progress.get("processing.stop") != null) {
                    break;
                }
                progress.put("processing.file", file.getAbsolutePath());
            }
            if (file.isDirectory()) {
                queue.addAll(0, Arrays.asList(file.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File file) {
                        if (file.isHidden() || !file.canRead()) {
                            return false;
                        }

                        if (file.isDirectory())
                            return true;

                        String ext = Util.getFileExt(file).toLowerCase();
                        if (formats.contains(ext)) {
                            String name = Util.removeExt(file.getAbsolutePath()) + ".cue";
                            return !new File(name).exists();
                        }
                        return ext.equals("cue");
                    }
                })));
            } else {
                TrackData trackData = new TrackData(file.toURI(), 0);
                Track track = trackDatas.get(trackData);
                if (track != null) {
                    if (track.getTrackData().getLastModified() != file.lastModified()) {
                        track.getTrackData().clearTags();
                        TrackIO.getAudioFileReader(file.getName()).reload(track);
                    }
                    processed.add(track);
                } else {
                    temp.clear();
                    TrackIO.getAudioFileReader(file.getName()).read(file, temp);
                    for (Track newTrack : temp) {
                        trackData = newTrack.getTrackData();
                        if (trackDatas.containsKey(trackData)) {
                            // it must be the cue file, so  merge the track data
                            trackData.merge(newTrack.getTrackData());
                        }
                        processed.add(newTrack);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    data.clear();
    data.addAll(processed);
    processed.clear();
    trackDatas.clear();
    rebuildTree();
}

From source file:org.jdto.util.expression.Expression.java

private ExpressionTerm parsePostfixExpr(String postfix) {
    //split the string
    String[] tokens = StringUtils.split(postfix, ' ');

    LinkedList<ExpressionTerm> termStack = new LinkedList<ExpressionTerm>();

    for (String token : tokens) {
        //if is not an operator, then read a literal or variable
        if (!isOperator(token)) {
            termStack.push(buildTerm(token));
        } else {/*from   w ww.ja  v  a2 s  . c o  m*/
            //try to build a compound term and push it.
            Operator op = Operator.getOperaorByString(token);
            ExpressionTerm right = termStack.pop(); //first is the right side
            ExpressionTerm left = termStack.pop(); //and then the left side

            ExpressionTerm term = new CompoundTerm(op, left, right);
            termStack.push(term);
        }
    }

    //at this point the stack should have just one element.

    return termStack.pop();
}

From source file:org.eclipse.che.api.builder.internal.SourcesManagerImpl.java

private void download(String downloadUrl, java.io.File downloadTo) throws IOException {
    HttpURLConnection conn = null;
    try {//from w w  w .java 2s .  c  om
        final LinkedList<java.io.File> q = new LinkedList<>();
        q.add(downloadTo);
        final long start = System.currentTimeMillis();
        final List<Pair<String, String>> md5sums = new LinkedList<>();
        while (!q.isEmpty()) {
            java.io.File current = q.pop();
            java.io.File[] list = current.listFiles();
            if (list != null) {
                for (java.io.File f : list) {
                    if (f.isDirectory()) {
                        q.push(f);
                    } else {
                        md5sums.add(Pair.of(com.google.common.io.Files.hash(f, Hashing.md5()).toString(),
                                downloadTo.toPath().relativize(f.toPath()).toString().replace("\\", "/"))); //Replacing of "\" is need for windows support
                    }
                }
            }
        }
        final long end = System.currentTimeMillis();
        if (md5sums.size() > 0) {
            LOG.debug("count md5sums of {} files, time: {}ms", md5sums.size(), (end - start));
        }
        conn = (HttpURLConnection) new URL(downloadUrl).openConnection();
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        final EnvironmentContext context = EnvironmentContext.getCurrent();
        if (context.getUser() != null && context.getUser().getToken() != null) {
            conn.setRequestProperty(HttpHeaders.AUTHORIZATION, context.getUser().getToken());
        }
        if (!md5sums.isEmpty()) {
            conn.setRequestMethod(HttpMethod.POST);
            conn.setRequestProperty("Content-type", MediaType.TEXT_PLAIN);
            conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.MULTIPART_FORM_DATA);
            conn.setDoOutput(true);
            try (OutputStream output = conn.getOutputStream(); Writer writer = new OutputStreamWriter(output)) {
                for (Pair<String, String> pair : md5sums) {
                    writer.write(pair.first);
                    writer.write(' ');
                    writer.write(pair.second);
                    writer.write('\n');
                }
            }
        }
        final int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentType = conn.getHeaderField("content-type");
            if (contentType.startsWith(MediaType.MULTIPART_FORM_DATA)) {
                final HeaderParameterParser headerParameterParser = new HeaderParameterParser();
                final String boundary = headerParameterParser.parse(contentType).get("boundary");
                try (InputStream in = conn.getInputStream()) {
                    MultipartStream multipart = new MultipartStream(in, boundary.getBytes());
                    boolean hasMore = multipart.skipPreamble();
                    while (hasMore) {
                        final Map<String, List<String>> headers = parseChunkHeader(
                                CharStreams.readLines(new StringReader(multipart.readHeaders())));
                        final List<String> contentDisposition = headers.get("content-disposition");
                        final String name = headerParameterParser.parse(contentDisposition.get(0)).get("name");
                        if ("updates".equals(name)) {
                            int length = -1;
                            List<String> contentLengthHeader = headers.get("content-length");
                            if (contentLengthHeader != null && !contentLengthHeader.isEmpty()) {
                                length = Integer.parseInt(contentLengthHeader.get(0));
                            }
                            if (length < 0 || length > 204800) {
                                java.io.File tmp = java.io.File.createTempFile("tmp", ".zip", directory);
                                try {
                                    try (FileOutputStream fOut = new FileOutputStream(tmp)) {
                                        multipart.readBodyData(fOut);
                                    }
                                    ZipUtils.unzip(tmp, downloadTo);
                                } finally {
                                    if (tmp.exists()) {
                                        tmp.delete();
                                    }
                                }
                            } else {
                                final ByteArrayOutputStream bOut = new ByteArrayOutputStream(length);
                                multipart.readBodyData(bOut);
                                ZipUtils.unzip(new ByteArrayInputStream(bOut.toByteArray()), downloadTo);
                            }
                        } else if ("removed-paths".equals(name)) {
                            final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                            multipart.readBodyData(bOut);
                            final String[] removed = JsonHelper.fromJson(
                                    new ByteArrayInputStream(bOut.toByteArray()), String[].class, null);
                            for (String path : removed) {
                                java.io.File f = new java.io.File(downloadTo, path);
                                if (!f.delete()) {
                                    throw new IOException(String.format("Unable delete %s", path));
                                }
                            }
                        } else {
                            // To /dev/null :)
                            multipart.readBodyData(DEV_NULL);
                        }
                        hasMore = multipart.readBoundary();
                    }
                }
            } else {
                try (InputStream in = conn.getInputStream()) {
                    ZipUtils.unzip(in, downloadTo);
                }
            }
        } else if (responseCode != HttpURLConnection.HTTP_NO_CONTENT) {
            throw new IOException(
                    String.format("Invalid response status %d from remote server. ", responseCode));
        }
    } catch (ParseException | JsonParseException e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:org.nuxeo.ecm.platform.routing.core.impl.GraphRunner.java

/**
 * Runs the graph starting with the given node.
 *
 * @param graph the graph// www  . java  2 s.co m
 * @param initialNode the initial node to run
 */
protected void runGraph(CoreSession session, DocumentRouteElement element, GraphNode initialNode)
        throws DocumentRouteException {
    GraphRoute graph = (GraphRoute) element;
    List<GraphNode> pendingSubRoutes = new LinkedList<GraphNode>();
    LinkedList<GraphNode> pendingNodes = new LinkedList<GraphNode>();
    pendingNodes.add(initialNode);
    boolean done = false;
    int count = 0;
    while (!pendingNodes.isEmpty()) {
        GraphNode node = pendingNodes.pop();
        count++;
        if (count > MAX_LOOPS) {
            throw new DocumentRouteException("Execution is looping, node: " + node);
        }
        State jump = null;
        switch (node.getState()) {
        case READY:
            log.debug("Doing node " + node);
            if (node.isMerge()) {
                jump = State.WAITING;
            } else {
                jump = State.RUNNING_INPUT;
            }
            break;
        case WAITING:
            if (node.canMerge()) {
                recursiveCancelInput(graph, node, pendingNodes);
                jump = State.RUNNING_INPUT;
            }
            // else leave state to WAITING
            break;
        case RUNNING_INPUT:
            node.starting();
            node.executeChain(node.getInputChain());
            if (node.hasTask() || node.hasMultipleTasks()) {
                createTask(session, graph, node); // may create several
                node.setState(State.SUSPENDED);
            }
            if (node.hasSubRoute()) {
                if (!pendingSubRoutes.contains(node)) {
                    pendingSubRoutes.add(node);
                }
                node.setState(State.SUSPENDED);
            }
            if (node.getState() != State.SUSPENDED) {
                jump = State.RUNNING_OUTPUT;
            }
            // else this node is suspended,
            // remove it from queue of nodes to process
            break;
        case SUSPENDED:
            if (node != initialNode) {
                throw new DocumentRouteException("Executing unexpected SUSPENDED state");
            }
            // actor
            NuxeoPrincipal principal = (NuxeoPrincipal) session.getPrincipal();
            String actor = principal.getActingUser();
            node.setLastActor(actor);
            // resuming, variables have been set by resumeGraph
            jump = State.RUNNING_OUTPUT;
            break;
        case RUNNING_OUTPUT:
            node.executeChain(node.getOutputChain());
            List<Transition> trueTrans = node.evaluateTransitions();
            node.ending();
            node.setState(State.READY);
            if (node.isStop()) {
                if (!pendingNodes.isEmpty()) {
                    throw new DocumentRouteException(String
                            .format("Route %s stopped with still pending nodes: %s", graph, pendingNodes));
                }
                done = true;
            } else {
                if (trueTrans.isEmpty()) {
                    throw new DocumentRouteException("No transition evaluated to true from node " + node);
                }
                for (Transition t : trueTrans) {
                    node.executeTransitionChain(t);
                    GraphNode target = graph.getNode(t.target);
                    if (!pendingNodes.contains(target)) {
                        pendingNodes.add(target);
                    }
                }
            }
            break;
        }
        if (jump != null) {
            node.setState(jump);
            // loop again on this node
            count--;
            pendingNodes.addFirst(node);
        }
    }
    if (done) {
        element.setDone(session);
        /*
         * Resume the parent route if this is a sub-route.
         */
        if (graph.hasParentRoute()) {
            graph.resumeParentRoute(session);
        }
    }
    /*
     * Now run the sub-routes. If they are done, they'll call back into the routing service to resume the parent
     * node (above code).
     */
    for (GraphNode node : pendingSubRoutes) {
        DocumentRoute subRoute = node.startSubRoute();
    }
    session.save();
}

From source file:org.alfresco.module.versionsdiff.VersionsDifferenceWebscript.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    if (null == req) {
        logger.error("VersionsDifferenceWebscript.java: The request URL is not well formatted");
        throw new WebScriptException("VersionsDifferenceWebscript.java: The request URL is not well formatted");
    } else {/*from  w  w w.  ja  v a 2 s  .c  o m*/

        // generate the returned model object
        Map<String, Object> model = new HashMap<String, Object>();

        // node reference to the last version of the document
        NodeRef lastVersRef = getArgsNodeRef(req);

        // node reference to the selected version of the document
        NodeRef selectVersRef = getArgsVersRef(req);

        // Instantiate the diff_match_patch object
        diff_match_patch diffMatchPatch = new diff_match_patch();

        // selectedVersRef is the first parameter for INSERT and DELETE right computation
        LinkedList<Diff> diffList = diffMatchPatch.diff_main(getPlainTxtTrasformation(selectVersRef),
                getPlainTxtTrasformation(lastVersRef));

        // semantic cleanup post-processing for human readable differentiation
        diffMatchPatch.diff_cleanupSemantic(diffList);

        LinkedList<String[]> diffObjList = new LinkedList<String[]>();

        // loop through the Diffs LinkedList
        while (!diffList.isEmpty()) {
            // Pop of the first element in the list
            Diff element = diffList.pop();
            String[] obj = { element.operation.toString(), element.text.toString() };
            diffObjList.add(obj);
        }

        model.put("result", diffObjList);
        return model;
    }
}

From source file:org.wwscc.storage.SQLDataInterface.java

@Override
public void updateDriver(Driver d) throws SQLException {
    LinkedList<Object> vals = d.getValues();
    vals.add(vals.pop());
    executeUpdate(//from   w  w  w.  j  a  v a 2s.co  m
            "update drivers set firstname=?,lastname=?,email=?,password=?,membership=?,attr=?,modified=now() where driverid=?",
            vals);
}

From source file:org.wwscc.storage.SQLDataInterface.java

@Override
public void updateCar(Car c) throws SQLException {
    LinkedList<Object> vals = c.getValues();
    vals.add(vals.pop());
    executeUpdate(/*from ww  w . j av  a  2  s .  c  o  m*/
            "update cars set driverid=?,classcode=?,indexcode=?,number=?,useclsmult=?,attr=?,modified=now() where carid=?",
            vals);
}