Example usage for java.util LinkedList isEmpty

List of usage examples for java.util LinkedList isEmpty

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

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

/**
 * Runs the graph starting with the given node.
 *
 * @param graph the graph//from  w w w.  j  av a2 s  . c om
 * @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:com.github.jknack.handlebars.internal.Partial.java

@Override
public void merge(final Context context, final Writer writer) throws IOException {
    TemplateLoader loader = handlebars.getLoader();
    try {//from   w ww.java  2s .co m
        LinkedList<TemplateSource> invocationStack = context.data(Context.INVOCATION_STACK);

        TemplateSource source = loader.sourceAt(path);

        if (exists(invocationStack, source.filename())) {
            TemplateSource caller = invocationStack.removeLast();
            Collections.reverse(invocationStack);

            final String message;
            final String reason;
            if (invocationStack.isEmpty()) {
                reason = String.format("infinite loop detected, partial '%s' is calling itself",
                        source.filename());

                message = String.format("%s:%s:%s: %s", caller.filename(), line, column, reason);
            } else {
                reason = String.format("infinite loop detected, partial '%s' was previously loaded",
                        source.filename());

                message = String.format("%s:%s:%s: %s\n%s", caller.filename(), line, column, reason,
                        "at " + join(invocationStack, "\nat "));
            }
            HandlebarsError error = new HandlebarsError(caller.filename(), line, column, reason, text(),
                    message);
            throw new HandlebarsException(error);
        }

        if (indent != null) {
            source = partial(source, indent);
        }

        Template template = handlebars.compile(source);
        if (this.context == null || this.context.equals("this")) {
            template.apply(context, writer);
        } else {
            template.apply(Context.newContext(context, context.get(this.context)), writer);
        }
    } catch (IOException ex) {
        String reason = String.format("The partial '%s' could not be found", loader.resolve(path));
        String message = String.format("%s:%s:%s: %s", filename, line, column, reason);
        HandlebarsError error = new HandlebarsError(filename, line, column, reason, text(), message);
        throw new HandlebarsException(error);
    }
}

From source file:bamboo.trove.full.FullReindexWarcManager.java

private boolean checkWorkComplete() throws InterruptedException, IOException {
    if (currentBatch == null || currentBatch.isEmpty()) {
        // Get a new batch
        LinkedList<ToIndex> newBatch = getNextBatchWithRetry();
        if (newBatch == null || newBatch.isEmpty()) {
            log.info("Retrieved empty batch from Bamboo. Work completed.");
            return true;
        }//w ww .  j  a v  a  2s. c o m
        // Including a separate reference just to ensure we know when to persist back to the DB
        LinkedList<ToIndex> persistTracking = new LinkedList<>();
        for (ToIndex w : newBatch) {
            persistTracking.add(w);
        }
        allBatches.add(persistTracking);
        // Update state
        endOfBatchId = newBatch.peekLast().getId();
        currentBatch = newBatch;
        return false;

    } else {
        // We are still in this batch
        return false;
    }
}

From source file:org.modeshape.web.jcr.rest.handler.ItemHandlerImpl.java

private void updateChildren(Node node, JsonNode jsonNode, VersionableChanges changes)
        throws RepositoryException {
    Session session = node.getSession();

    // Get the existing children ...
    Map<String, Node> existingChildNames = new LinkedHashMap<>();
    List<String> existingChildrenToUpdate = new ArrayList<>();
    NodeIterator childIter = node.getNodes();
    while (childIter.hasNext()) {
        Node child = childIter.nextNode();
        String childName = nameOf(child);
        existingChildNames.put(childName, child);
        existingChildrenToUpdate.add(childName);
    }/*from  w  ww .j ava 2 s .  com*/
    //keep track of the old/new order of children to be able to perform reorderings
    List<String> newChildrenToUpdate = new ArrayList<>();

    List<JSONChild> children = getChildren(jsonNode);
    for (JSONChild jsonChild : children) {
        String childName = jsonChild.getNameWithSNS();
        JsonNode child = jsonChild.getBody();
        // Find the existing node ...
        if (node.hasNode(childName)) {
            // The node exists, so get it and update it ...
            Node childNode = node.getNode(childName);
            String childNodeName = nameOf(childNode);
            newChildrenToUpdate.add(childNodeName);
            updateNode(childNode, child, changes);
            existingChildNames.remove(childNodeName);
        } else {
            //try to see if the child name is actually an identifier
            try {
                Node childNode = session.getNodeByIdentifier(childName);
                String childNodeName = nameOf(childNode);
                if (childNode.getParent().getIdentifier().equals(node.getIdentifier())) {
                    //this is an existing child of the current node, referenced via an identifier
                    newChildrenToUpdate.add(childNodeName);
                    updateNode(childNode, child, changes);
                    existingChildNames.remove(childNodeName);
                } else {
                    //this is a child belonging to another node
                    if (childNode.isNodeType("mix:shareable")) {
                        //if it's a shared node, we can't clone it because clone is not a session-scoped operation
                        logger.warn(
                                "The node {0} with the id {1} is a shared node belonging to another parent. It cannot be changed via the update operation",
                                childNode.getPath(), childNode.getIdentifier());
                    } else {
                        //move the node into this parent
                        session.move(childNode.getPath(), node.getPath() + "/" + childNodeName);
                    }
                }
            } catch (ItemNotFoundException e) {
                //the child name is not a valid identifier, so treat it as a new child
                addNode(node, childName, child);
            }
        }
    }

    // Remove the children in reverse order (starting with the last child to be removed) ...
    LinkedList<Node> childNodes = new LinkedList<Node>(existingChildNames.values());
    while (!childNodes.isEmpty()) {
        Node child = childNodes.removeLast();
        existingChildrenToUpdate.remove(child.getIdentifier());
        child.remove();
    }

    // Do any necessary reorderings
    if (newChildrenToUpdate.equals(existingChildrenToUpdate)) {
        //no order changes exist
        return;
    }

    for (int i = 0; i < newChildrenToUpdate.size() - 1; i++) {
        String startNodeName = newChildrenToUpdate.get(i);
        int startNodeOriginalPosition = existingChildrenToUpdate.indexOf(startNodeName);
        assert startNodeOriginalPosition != -1;

        for (int j = i + 1; j < newChildrenToUpdate.size(); j++) {
            String nodeName = newChildrenToUpdate.get(j);
            int nodeOriginalPosition = existingChildrenToUpdate.indexOf(nodeName);
            assert nodeOriginalPosition != -1;

            if (startNodeOriginalPosition > nodeOriginalPosition) {
                //the start node should be moved *before* this node
                node.orderBefore(startNodeName, nodeName);
            }
        }
    }
}

From source file:org.kitodo.production.forms.dataeditor.StructurePanel.java

void deleteSelectedStructure() {
    Optional<IncludedStructuralElement> selectedStructure = getSelectedStructure();
    if (!selectedStructure.isPresent()) {
        /*/*from  ww w  .ja v a  2 s.  co m*/
         * No element is selected or the selected element is not a structure
         * but, for example, a media unit.
         */
        return;
    }
    LinkedList<IncludedStructuralElement> ancestors = MetadataEditor
            .getAncestorsOfStructure(selectedStructure.get(), structure);
    if (ancestors.isEmpty()) {
        // The selected element is the root node of the tree.
        return;
    }
    IncludedStructuralElement parent = ancestors.getLast();
    parent.getChildren().remove(selectedStructure.get());
    show();
}

From source file:org.apache.http.HC4.conn.ssl.AbstractVerifier.java

public static String[] getCNs(X509Certificate cert) {
    LinkedList<String> cnList = new LinkedList<String>();
    /*//from   w w w .  j  av a 2 s.c o  m
      Sebastian Hauer's original StrictSSLProtocolSocketFactory used
      getName() and had the following comment:
            
        Parses a X.500 distinguished name for the value of the
        "Common Name" field.  This is done a bit sloppy right
         now and should probably be done a bit more according to
        <code>RFC 2253</code>.
            
       I've noticed that toString() seems to do a better job than
       getName() on these X500Principal objects, so I'm hoping that
       addresses Sebastian's concern.
            
       For example, getName() gives me this:
       1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
            
       whereas toString() gives me this:
       EMAILADDRESS=juliusdavies@cucbc.com
            
       Looks like toString() even works with non-ascii domain names!
       I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
    */
    String subjectPrincipal = cert.getSubjectX500Principal().toString();
    StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
    while (st.hasMoreTokens()) {
        String tok = st.nextToken();
        int x = tok.indexOf("CN=");
        if (x >= 0) {
            cnList.add(tok.substring(x + 3));
        }
    }
    if (!cnList.isEmpty()) {
        String[] cns = new String[cnList.size()];
        cnList.toArray(cns);
        return cns;
    } else {
        return null;
    }
}

From source file:android.net.http.Connection.java

/**
 * After a send/receive failure, any pipelined requests must be
 * cleared back to the mRequest queue/*from  w w  w . j  a v  a 2  s  .c  o m*/
 * @return true if mRequests is empty after pipe cleared
 */
private boolean clearPipe(LinkedList<Request> pipe) {
    boolean empty = true;
    if (HttpLog.LOGV)
        HttpLog.v("Connection.clearPipe(): clearing pipe " + pipe.size());
    synchronized (mRequestFeeder) {
        Request tReq;
        while (!pipe.isEmpty()) {
            tReq = (Request) pipe.removeLast();
            if (HttpLog.LOGV)
                HttpLog.v("clearPipe() adding back " + mHost + " " + tReq);
            mRequestFeeder.requeueRequest(tReq);
            empty = false;
        }
        if (empty)
            empty = !mRequestFeeder.haveRequest(mHost);
    }
    return empty;
}

From source file:com.mtgi.analytics.BehaviorTrackingManagerImpl.java

/**
 * Flush any completed events to the event persister.  This operation can be called
 * manually via JMX, or can be called on a fixed interval via the Quartz Scheduler.
 * This operation results in the logging of a "flush" event to the database.
 * /*from  ww  w  .j  a va 2s . co m*/
 * @return the number of events persisted
 */
@ManagedOperation(description = "Immediately flush all completed events to the behavior tracking database.  Returns the number of events written to the database (not counting the flush event that is also logged)")
public int flush() {

    LinkedList<BehaviorEvent> oldList = null;
    //rotate the buffer.
    synchronized (bufferSync) {
        oldList = writeBuffer;
        pendingFlush -= oldList.size();
        writeBuffer = new LinkedList<BehaviorEvent>();
        flushRequested = false;
    }

    //prevent no-ops from spewing a bunch of noise into the logs.
    if (oldList.isEmpty())
        return 0;

    //we log flush events, so that we can correlate flush events to system
    //resource spikes, and also see evidence of behavior tracking
    //churn in the database if tuning parameters aren't set correctly.

    //we don't call our own start/stop/createEvents methods, because that could
    //recursively lead to another flush() or other nasty problems if the flush 
    //threshold is set too small
    BehaviorEvent flushEvent = new FlushEvent(event.get());
    if (!warned && !flushEvent.isRoot()) {
        warned = true;
        log.warn(
                "Flush is being called from inside an application thread!  It is strongly advised the flush only be called from a dedicated, reduced-priority thread pool (are you using a SyncTaskExecutor in your spring configuration?).");
    }
    EventDataElement data = flushEvent.addData();
    flushEvent.start();

    int count = oldList.size();
    event.set(flushEvent);
    try {

        persister.persist(oldList);
        if (log.isDebugEnabled())
            log.debug("Flushed " + count + " events with " + pendingFlush + " remaining");

        return count;

    } finally {
        //restore stack state
        event.set(flushEvent.getParent());

        data.add("count", count);
        flushEvent.stop();

        //persist the flush event immediately.
        LinkedList<BehaviorEvent> temp = new LinkedList<BehaviorEvent>();
        temp.add(flushEvent);
        persister.persist(temp);
    }
}

From source file:org.kitodo.production.forms.dataeditor.StructurePanel.java

void deleteSelectedMediaUnit() {
    Optional<MediaUnit> selectedMediaUnit = getSelectedMediaUnit();
    if (!selectedMediaUnit.isPresent()) {
        return;/*w ww.j  ava  2 s.  c om*/
    }
    LinkedList<MediaUnit> ancestors = MetadataEditor.getAncestorsOfMediaUnit(selectedMediaUnit.get(),
            dataEditor.getWorkpiece().getMediaUnit());
    if (ancestors.isEmpty()) {
        // The selected element is the root node of the tree.
        return;
    }
    MediaUnit parent = ancestors.getLast();
    parent.getChildren().remove(selectedMediaUnit.get());
    show();
}

From source file:net.sourceforge.fenixedu.domain.reports.FlunkedReportFile.java

@Override
public void renderReport(Spreadsheet spreadsheet) {
    spreadsheet.setHeader("nmero aluno");
    spreadsheet.setHeader("ciclo estudos");
    setDegreeHeaders(spreadsheet);/*from  w  ww . ja  va  2  s  . co  m*/

    for (final Degree degree : Degree.readNotEmptyDegrees()) {
        if (checkDegreeType(getDegreeType(), degree)) {
            for (final Registration registration : degree.getRegistrationsSet()) {
                LinkedList<RegistrationState> states = new LinkedList<RegistrationState>();
                states.addAll(registration.getRegistrationStatesSet());
                CollectionUtils.filter(states, new Predicate() {
                    @Override
                    public boolean evaluate(Object item) {
                        return ((RegistrationState) item).getExecutionYear() != null
                                && ((RegistrationState) item).getExecutionYear().equals(getExecutionYear());
                    }
                });
                Collections.sort(states, RegistrationState.DATE_COMPARATOR);
                if (!states.isEmpty()
                        && states.getLast().getStateType().equals(RegistrationStateType.FLUNKED)) {
                    final Row row = spreadsheet.addRow();
                    row.setCell(registration.getNumber());
                    CycleType cycleType = registration.getCycleType(states.getLast().getExecutionYear());
                    row.setCell(cycleType != null ? cycleType.toString() : "");
                    setDegreeCells(row, degree);
                }
            }
        }
    }
}