Example usage for java.util LinkedList push

List of usage examples for java.util LinkedList push

Introduction

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

Prototype

public void push(E e) 

Source Link

Document

Pushes an element onto the stack represented by this list.

Usage

From source file:org.openmeetings.axis.services.RoomWebService.java

/**
 * Returns current users for rooms ids/*from   ww  w. j  a  va 2 s  .  co  m*/
 * 
 * @param SID The SID of the User. This SID must be marked as Loggedin 
 * @param roomId1
 * @param roomId2
 * @param roomId3
 * @param roomId4
 * @param roomId5
 * @param roomId6
 * @param roomId7
 * @param roomId8
 * @param roomId9
 * @param roomId10
 * @return
 * @throws AxisFault
 */
public RoomCountBean[] getRoomCounters(String SID, Integer roomId1, Integer roomId2, Integer roomId3,
        Integer roomId4, Integer roomId5, Integer roomId6, Integer roomId7, Integer roomId8, Integer roomId9,
        Integer roomId10) throws AxisFault {
    try {
        Long users_id = sessionManagement.checkSession(SID);
        Long user_level = userManagement.getUserLevelByID(users_id);

        if (authLevelManagement.checkWebServiceLevel(user_level)) {

            LinkedList<Integer> roomIds = new LinkedList<Integer>();

            if (roomId1 != null && roomId1 > 0) {
                roomIds.push(roomId1);
            }
            if (roomId2 != null && roomId2 > 0) {
                log.debug("roomId2 :: " + roomId2);
                roomIds.push(roomId2);
            }
            if (roomId3 != null && roomId3 > 0) {
                roomIds.push(roomId3);
            }
            if (roomId4 != null && roomId4 > 0) {
                roomIds.push(roomId4);
            }
            if (roomId5 != null && roomId5 > 0) {
                roomIds.push(roomId5);
            }
            if (roomId6 != null && roomId6 > 0) {
                roomIds.push(roomId6);
            }
            if (roomId7 != null && roomId7 > 0) {
                roomIds.push(roomId7);
            }
            if (roomId8 != null && roomId8 > 0) {
                roomIds.push(roomId8);
            }
            if (roomId9 != null && roomId9 > 0) {
                roomIds.push(roomId9);
            }
            if (roomId10 != null && roomId10 > 0) {
                roomIds.push(roomId10);
            }

            List<Rooms> rooms = roommanagement.getRoomsByIds(roomIds);

            RoomCountBean[] roomsArray = new RoomCountBean[rooms.size()];

            int i = 0;
            for (Rooms room : rooms) {

                HashMap<String, RoomClient> map = clientListManager.getClientListByRoom(room.getRooms_id());

                // room.setCurrentusers(new LinkedList<RoomClient>());

                // for (Iterator<String> iter = map.keySet().iterator();
                // iter.hasNext(); ) {
                // room.getCurrentusers().add(map.get(iter.next()));
                // }

                RoomCountBean rCountBean = new RoomCountBean();
                rCountBean.setRoomId(room.getRooms_id());
                rCountBean.setRoomName(room.getName());
                rCountBean.setMaxUser(room.getNumberOfPartizipants().intValue());
                rCountBean.setRoomCount(map.size());

                roomsArray[i] = rCountBean;
                i++;
            }

            return roomsArray;
        }

    } catch (Exception err) {
        log.error("[getRoomTypes]", err);
        throw new AxisFault(err.getMessage());
    }
    return null;
}

From source file:org.apache.openmeetings.axis.services.RoomWebService.java

/**
 * Returns current users for rooms ids//from  w  w  w .  j a v a2s.  co  m
 * 
 * @param SID
 *            The SID of the User. This SID must be marked as Loggedin
 * @param roomId1
 * @param roomId2
 * @param roomId3
 * @param roomId4
 * @param roomId5
 * @param roomId6
 * @param roomId7
 * @param roomId8
 * @param roomId9
 * @param roomId10
 * @return - current users for rooms ids
 * @throws AxisFault
 */
public RoomCountBean[] getRoomCounters(String SID, Integer roomId1, Integer roomId2, Integer roomId3,
        Integer roomId4, Integer roomId5, Integer roomId6, Integer roomId7, Integer roomId8, Integer roomId9,
        Integer roomId10) throws AxisFault {
    try {
        Long users_id = sessiondataDao.checkSession(SID);
        Long user_level = userManager.getUserLevelByID(users_id);

        if (authLevelUtil.checkWebServiceLevel(user_level)) {

            LinkedList<Integer> roomIds = new LinkedList<Integer>();

            if (roomId1 != null && roomId1 > 0) {
                roomIds.push(roomId1);
            }
            if (roomId2 != null && roomId2 > 0) {
                log.debug("roomId2 :: " + roomId2);
                roomIds.push(roomId2);
            }
            if (roomId3 != null && roomId3 > 0) {
                roomIds.push(roomId3);
            }
            if (roomId4 != null && roomId4 > 0) {
                roomIds.push(roomId4);
            }
            if (roomId5 != null && roomId5 > 0) {
                roomIds.push(roomId5);
            }
            if (roomId6 != null && roomId6 > 0) {
                roomIds.push(roomId6);
            }
            if (roomId7 != null && roomId7 > 0) {
                roomIds.push(roomId7);
            }
            if (roomId8 != null && roomId8 > 0) {
                roomIds.push(roomId8);
            }
            if (roomId9 != null && roomId9 > 0) {
                roomIds.push(roomId9);
            }
            if (roomId10 != null && roomId10 > 0) {
                roomIds.push(roomId10);
            }

            List<Room> rooms = roomManager.getRoomsByIds(roomIds);

            RoomCountBean[] roomsArray = new RoomCountBean[rooms.size()];

            int i = 0;
            for (Room room : rooms) {
                RoomCountBean rCountBean = new RoomCountBean();
                rCountBean.setRoomId(room.getRooms_id());
                rCountBean.setRoomName(room.getName());
                rCountBean.setMaxUser(room.getNumberOfPartizipants().intValue());
                rCountBean.setRoomCount(sessionManager.getClientListByRoom(room.getRooms_id()).size());

                roomsArray[i] = rCountBean;
                i++;
            }

            return roomsArray;
        }

    } catch (Exception err) {
        log.error("[getRoomTypes]", err);
        throw new AxisFault(err.getMessage());
    }
    return null;
}

From source file:org.eclipse.che.vfs.impl.fs.FSMountPoint.java

private void doDelete(VirtualFileImpl virtualFile, String lockToken)
        throws ForbiddenException, ServerException {
    if (virtualFile.isFolder()) {
        final LinkedList<VirtualFile> q = new LinkedList<>();
        q.add(virtualFile);/*from  w w w .  ja v a 2 s  .  c o  m*/
        while (!q.isEmpty()) {
            for (VirtualFile child : doGetChildren((VirtualFileImpl) q.pop(), SERVICE_GIT_DIR_FILTER)) {
                // Check permission directly for current file only.
                // We already know parent may be deleted by current user otherwise we should not be here.
                if (!hasPermission((VirtualFileImpl) child, BasicPermissions.WRITE.value(), false)) {
                    throw new ForbiddenException(String
                            .format("Unable delete item '%s'. Operation not permitted. ", child.getPath()));
                }
                if (child.isFolder()) {
                    q.push(child);
                } else if (isLocked((VirtualFileImpl) child)) {
                    // Do not check lock token here. It checked only when remove file directly.
                    // If folder contains locked children it may not be deleted.
                    throw new ForbiddenException(
                            String.format("Unable delete item '%s'. Child item '%s' is locked. ",
                                    virtualFile.getPath(), child.getPath()));
                }
            }
        }
    }

    // unlock file
    if (virtualFile.isFile()) {
        final FileLock fileLock = checkIsLockValidAndGet(virtualFile);
        if (NO_LOCK != fileLock) {
            doUnlock(virtualFile, fileLock, lockToken);
        }
    }

    // clear caches
    clearAclCache();
    clearLockTokensCache();
    clearMetadataCache();

    final String path = virtualFile.getPath();
    boolean isFile = virtualFile.isFile();
    if (!deleteRecursive(virtualFile.getIoFile())) {
        LOG.error("Unable delete file {}", virtualFile.getIoFile());
        throw new ServerException(String.format("Unable delete item '%s'. ", path));
    }

    // delete ACL file
    final java.io.File aclFile = new java.io.File(ioRoot,
            toIoPath(getAclFilePath(virtualFile.getVirtualFilePath())));
    if (aclFile.delete()) {
        if (aclFile.exists()) {
            LOG.error("Unable delete ACL file {}", aclFile);
            throw new ServerException(String.format("Unable delete item '%s'. ", path));
        }
    }

    // delete metadata file
    final java.io.File metadataFile = new java.io.File(ioRoot,
            toIoPath(getMetadataFilePath(virtualFile.getVirtualFilePath())));
    if (metadataFile.delete()) {
        if (metadataFile.exists()) {
            LOG.error("Unable delete file metadata {}", metadataFile);
            throw new ServerException(String.format("Unable delete item '%s'. ", path));
        }
    }

    if (searcherProvider != null) {
        try {
            searcherProvider.getSearcher(this, true).delete(path, isFile);
        } catch (ServerException e) {
            LOG.error(e.getMessage(), e);
        }
    }
}

From source file:org.commoncrawl.service.parser.server.ParseWorker.java

@Override
public Document buildDocument(InstructionsPool instructionsPool, FileOutputStream optionalOutputStream)
        throws IOException {

    //LOG.info("Build Document Called");
    List<Integer> operations = instructionsPool.operations;
    List<String> arguments = instructionsPool.arguments;
    LinkedList<Integer> nodeStack = new LinkedList<Integer>();
    LinkedList<BlockObjectInContext> blockStack = new LinkedList<BlockObjectInContext>();
    HTMLMeta meta = null;//  w ww .j ava 2 s .co m

    for (int i = 0; i < operations.size(); i++) {
        int domOperation = operations.get(i);
        String domArgument = arguments.get(i);
        //System.out.println("Operation :" + ParserInstruction.getOperationString(domOperation)+" Arg:~" + domArgument+"~");
        switch (domOperation) {
        // Open node :
        case ParserInstruction.OpenNode:
        case ParserInstruction.AddLeaf: {
            activeLink = null;
            blockInConstruction = null;
            String nodeName = domArgument.toLowerCase();

            // append new-line of start of a block level tag ... 
            if (domOperation == ParserInstruction.OpenNode && blockLevelHTMLTags.contains(nodeName)) {
                if (textAccumulator.length() != 0
                        && textAccumulator.charAt(textAccumulator.length() - 1) != '\n')
                    textAccumulator.append("\n");
            }

            if (nodeName.equals("meta")) {
                meta = new HTMLMeta();
            } else if (linkTypeToSrcMap.containsKey(nodeName)) {
                //LOG.info("Node:" + nodeName + " is of type Link. Adding to LinksUnderConst");
                activeLink = new LinkUnderConstruction(nodeName, blockStack.peek());
                linksUnderConstruction.push(activeLink);
            } else if (nodeName.equals("head")) {
                inHeadTag++;
            } else if (nodeName.equals("base")) {
                if (inHeadTag != 0) {
                    inBase++;
                }
            } else if (nodeName.equals("table") || nodeName.equals("div")) {
                blockInConstruction = new BlockObjectInContext(blockStack.peek(), nodeName, ++blockId);
                blockStack.push(blockInConstruction);
            } else if (nodeName.equals("tr") || nodeName.equals("th")) {
                BlockObjectInContext table = blockStack.peek();
                if (table != null) {
                    table.rowNumber++;
                    table.cellNumber = -1;
                }
            } else if (nodeName.equals("td")) {
                BlockObjectInContext table = blockStack.peek();
                if (table != null) {
                    table.cellNumber++;
                }
            }
            nodeStack.push(i);
        }
            break;
        // Close node :
        case ParserInstruction.CloseNode:
        case ParserInstruction.CloseLeaf: {
            int arguementPos = nodeStack.pop();
            String nodeName = arguments.get(arguementPos).toLowerCase();

            // append new-line of start of a block level tag ... 
            if (domOperation == ParserInstruction.CloseNode && blockLevelHTMLTags.contains(nodeName)) {
                if (textAccumulator.length() != 0
                        && textAccumulator.charAt(textAccumulator.length() - 1) != '\n')
                    textAccumulator.append("\n");
            }

            //LOG.info("Close Node Called on Node:" + nodeName);
            if (nodeName.equals("head")) {
                inHeadTag--;
            } else if (nodeName.equals("base")) {
                if (inHeadTag != 0) {
                    inBase--;
                }
            } else if (linkTypeToSrcMap.containsKey(nodeName)) {
                //LOG.info("Node:" + nodeName + " is a Link Type");
                LinkUnderConstruction linkPartial = linksUnderConstruction.pop();
                if (linkPartial != null) {
                    //LOG.info("POPed a partial LinkObject of type:" + linkPartial.type);
                    Link link = linkPartial.buildLink();
                    if (link != null) {
                        activeParseResult.getExtractedLinks().add(link);
                    }
                }
            } else if (nodeName.equals("table") || nodeName.equals("div")) {
                blockStack.pop();
            } else if (nodeName.equals("meta")) {
                if (meta != null) {
                    activeParseResult.getMetaTags().add(meta);
                    meta = null;
                }
            }
            if (textAccumulator.length() != 0
                    && !Character.isWhitespace(textAccumulator.charAt(textAccumulator.length() - 1))) {
                textAccumulator.append(" ");
            }

        }
            break;
        case ParserInstruction.AddText: {
            Integer arguementPos = nodeStack.peek();
            String nodeName = (arguementPos != null) ? arguments.get(arguementPos).toLowerCase() : null;
            LinkUnderConstruction link = linksUnderConstruction.peek();

            if (link != null) {
                if (link.linkText.length() != 0)
                    link.linkText += " ";
                link.linkText += domArgument.trim();
            }
            if (nodeName == null || !ignoreTextTagSet.contains(nodeName.toLowerCase())) {
                textAccumulator.append(domArgument);
            }

        }
            break;
        //        case ParserInstruction.AddContent:
        //          System.out.println("AddContent:"+domArgument);
        //          break;

        case ParserInstruction.WriteAttributeKey: {

            // grab key name .. 
            String key = domArgument.toLowerCase();

            // and lookahead one to grab attribute value ... 
            i++;

            if (i < operations.size() && operations.get(i) == ParserInstruction.WriteAttributeValue) {
                // grab value ... 
                String value = arguments.get(i);

                // if metatag capture key/value ... 
                if (meta != null) {
                    // create a new attribute object  
                    HTMLMetaAttribute attribute = new HTMLMetaAttribute();

                    attribute.setName(key);
                    attribute.setValue(value);

                    // append to meta tag 
                    meta.getAttributes().add(attribute);
                } else {
                    if (key.equals("href") && inBase != 0) {
                        if (value.length() != 0) {
                            try {
                                baseURL = new URL(value);
                            } catch (Exception e) {
                                LOG.error(CCStringUtils.stringifyException(e));
                                throw new IOException(e);
                            }
                        }
                    } else if (activeLink != null) {
                        if (linkTypeToSrcMap.get(activeLink.type).equalsIgnoreCase(key)) {
                            activeLink.linkURL = value;
                        } else {
                            activeLink.jsonObject.addProperty(key, value);
                        }
                    } else if (blockInConstruction != null) {
                        if (key.equals("class")) {
                            blockInConstruction.classId = value;
                        } else if (key.equals("id")) {
                            blockInConstruction.htmlId = value;
                        }
                    }
                }
            } else {
                // rewind and let outer control block deal with it 
                --i;
            }
        }
            break;

        case ParserInstruction.SetTitle: {
            activeParseResult.setTitle(domArgument);
        }
            break;
        //        case ParserInstruction.AddEntity:
        //          System.out.println("AddEntity:" + domArgument);
        //            break;
        //        case ParserInstruction.AddComment:
        //          System.out.println("AddComment:" + domArgument); 
        //            break;        case ParserInstruction.SetTitle:
        //          System.out.println("SetTitle:" + domArgument);
        //            break;
        //        }
        }
    }
    return null;
}

From source file:de.betterform.agent.web.event.EventQueue.java

public List<XMLEvent> aggregateEventList() {
    // Stack is used to "navigate" through the event list
    LinkedList<XMLEvent> aggregatedFocusList = new LinkedList<XMLEvent>();
    Stack<XMLEvent> aggregatedInsertEventsStack = new Stack();
    Stack<XMLEvent> aggregatedEmbedEventsStack = new Stack();
    ArrayList<XMLEvent> aggregatedEventList = new ArrayList<XMLEvent>(eventList.size());

    for (XMLEvent xmlEvent : this.loadEmbedEventList) {
        aggregatedEventList.add(xmlEvent);
    }/*from ww  w .j  av a2s  . c o m*/

    this.loadEmbedEventList.clear();

    for (int i = 0; i < eventList.size(); i++) {
        XercesXMLEvent xmlEvent = (XercesXMLEvent) eventList.get(i);

        XercesXMLEvent xmlEventToAdd = new XercesXMLEvent();
        // Map PROTOTYPE_CLONED event to betterform-insert-repeatitem or betterform-insert-itemset event
        // and copy event properties to new created XMLEvent
        if (xmlEvent.getType().equals(BetterFormEventNames.PROTOTYPE_CLONED)) {
            if (xmlEvent.getContextInfo("targetName").equals(XFormsConstants.ITEMSET)) {
                xmlEventToAdd.initXMLEvent("betterform-insert-itemset", xmlEvent.getBubbles(),
                        xmlEvent.getCancelable(), xmlEvent.getContextInfo());
            } else {
                xmlEventToAdd.initXMLEvent("betterform-insert-repeatitem", xmlEvent.getBubbles(),
                        xmlEvent.getCancelable(), xmlEvent.getContextInfo());
            }
            xmlEventToAdd.target = xmlEvent.target;
            xmlEvent.addProperty("generatedIds", new HashMap());
            aggregatedEventList.add(xmlEventToAdd);
            // push XMLEvent to Stack for further processing
            aggregatedInsertEventsStack.push(xmlEventToAdd);

        }
        // add all generated ids to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
        else if (xmlEvent.getType().equals(BetterFormEventNames.ID_GENERATED)
                && aggregatedInsertEventsStack.size() > 0) {
            XMLEvent aggregatingInsertEvent = aggregatedInsertEventsStack.peek();
            ((HashMap) aggregatingInsertEvent.getContextInfo("generatedIds"))
                    .put(xmlEvent.getContextInfo("originalId"), xmlEvent.getContextInfo("targetId"));
        }
        // add insert position to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
        else if (xmlEvent.getType().equals(BetterFormEventNames.ITEM_INSERTED)) {
            XMLEvent tmpEvent = aggregatedInsertEventsStack.pop();
            tmpEvent.addProperty("position", xmlEvent.getContextInfo("position"));
            tmpEvent.addProperty("label", xmlEvent.getContextInfo("label"));
            tmpEvent.addProperty("value", xmlEvent.getContextInfo("value"));

        } else if (xmlEvent.getType().equals(BetterFormEventNames.EMBED)) {
            aggregatedEventList.add(xmlEvent);
            aggregatedEmbedEventsStack.push(xmlEvent);
        } else if (xmlEvent.getType().equals(BetterFormEventNames.EMBED_DONE)) {
            aggregatedEmbedEventsStack.pop().addProperty("targetElement",
                    xmlEvent.getContextInfo("targetElement"));
            aggregatedEventList.add(xmlEvent);
        } else if (xmlEvent.getType().equals(XFormsEventNames.FOCUS)) {
            aggregatedFocusList.push(xmlEvent);
        }
        /* else if(xmlEvent.getType().equals(BetterFormEventNames.INDEX_CHANGED)){
        aggregatedFocusList.push(xmlEvent);
        }*/
        // all other events within eventList are simply copied to the new eventlist
        else {
            aggregatedEventList.add(xmlEvent);
        }
    }

    while (!aggregatedFocusList.isEmpty()) {
        aggregatedEventList.add(aggregatedFocusList.pollLast());
    }
    return aggregatedEventList;
}

From source file:hudson.plugins.project_inheritance.projects.InheritanceProject.java

/**
 * Tests if this project's configuration leads to a cyclic, diamond or
 * multiple dependency.<br/>/*from ww  w.  j a  v  a 2 s  .c  o m*/
 * <br/>
 * See <a href="http://en.wikipedia.org/wiki/Cycle_detection">cycle detection</a> and
 * <a href="http://en.wikipedia.org/wiki/Diamond_problem">diamond problem</a>.
 * 
 * @return true, if there is a cyclic, diamond or repeated dependency among
 * this project's parents.
 */
public final boolean hasCyclicDependency(String... whenTheseProjectsAdded) {
    /* TODO: While this method runs reasonably fast, it is run very often
     * As such, find a way to buffer the result across all projects and
     * only rebuild if necessary.
     */

    /* TODO: Further more, this method is not space-optimal
     * See: http://en.wikipedia.org/wiki/Cycle_detection
     * But do note that any replacement algorithm also, by contract, needs
     * to detect multiple inheritance and its special case of diamond
     * inheritance.
     */

    //Preparing the set of project names that were seen at least once
    HashSet<String> closed = new HashSet<String>();

    //Creating the list of parent projects to still explore
    LinkedList<InheritanceProject> open = new LinkedList<InheritanceProject>();
    //And scheduling ourselves as the first to evaluate
    open.push(this);

    //And finally, creating a list of additional references the caller
    //wishes to eventually add to THIS project
    LinkedList<String> additionalRefs = new LinkedList<String>();
    for (String pName : whenTheseProjectsAdded) {
        //We need to ignore those, that we already refer to as parents
        //Do note that this makes direct multiple inheritance impossible
        //to detect in advance, but such errors should be obvious anyway
        boolean isAlreadyReferenced = false;
        for (AbstractProjectReference par : this.getParentReferences()) {
            if (par.getName().equals(pName)) {
                isAlreadyReferenced = true;
                break;
            }
        }
        if (!isAlreadyReferenced) {
            additionalRefs.add(pName);
        }
    }

    //Processing the open stack, checking if we're already met that parent
    //and if not, adding its parent to our open stack
    while (open.isEmpty() == false) {
        //Popping the first element
        InheritanceProject p = open.pop();
        //Checking if we've seen that parent already
        if (closed.contains(p.name)) {
            //Detected a cyclic dependency
            return true;
        }
        // Otherwise, we add all its parents to our open set
        for (AbstractProjectReference ref : p.getParentReferences()) {
            InheritanceProject refP = ref.getProject();
            if (refP != null) {
                open.push(refP);
            }
        }
        //And if the current object is active, we also need to check the
        //new future refs
        if (p == this && !additionalRefs.isEmpty()) {
            for (String ref : additionalRefs) {
                InheritanceProject ip = InheritanceProject.getProjectByName(ref);
                if (ip != null) {
                    open.push(ip);
                }
            }
        }
        closed.add(p.name);
    }
    // If we reach this spot, there is no such dependency
    return false;
}

From source file:hudson.plugins.project_inheritance.projects.InheritanceProject.java

public Map<InheritanceProject, Relationship> getRelationships() {
    Object obj = onInheritChangeBuffer.get(this, "getRelationships");
    if (obj != null && obj instanceof Map) {
        return (Map) obj;
    }//w  w w .ja va 2  s. com

    //Creating the returned map and pre-filling it with empty lists
    Map<InheritanceProject, Relationship> map = new HashMap<InheritanceProject, Relationship>();

    //Preparing the set of projects that were already explored
    HashSet<String> seenProjects = new HashSet<String>();

    //Fetching the map of all projects and their connections
    Map<String, ProjectGraphNode> connGraph = getConnectionGraph();

    //Fetching the node for the current (this) project
    ProjectGraphNode node = connGraph.get(this.getName());
    if (node == null) {
        return map;
    }

    //Mates can be filled quite easily
    for (String mate : node.mates) {
        InheritanceProject p = InheritanceProject.getProjectByName(mate);
        ProjectGraphNode mateNode = connGraph.get(mate);
        boolean isLeaf = (mateNode == null) ? true : mateNode.children.isEmpty();
        if (p == null) {
            continue;
        }
        //Checking if we've seen this mate already
        if (!seenProjects.contains(p.getName())) {
            map.put(p, new Relationship(Relationship.Type.MATE, 0, isLeaf));
            seenProjects.add(p.getName());
        }
    }

    //Exploring parents
    int distance = 1;
    seenProjects.clear();
    LinkedList<InheritanceProject> cOpen = new LinkedList<InheritanceProject>();
    LinkedList<InheritanceProject> nOpen = new LinkedList<InheritanceProject>();
    cOpen.add(this);
    while (!cOpen.isEmpty()) {
        InheritanceProject ip = cOpen.pop();
        if (ip == null || seenProjects.contains(ip.getName())) {
            continue;
        }
        seenProjects.add(ip.getName());

        node = connGraph.get(ip.getName());
        if (ip == null || node == null) {
            continue;
        }
        //Adding all parents
        for (String parent : node.parents) {
            InheritanceProject par = InheritanceProject.getProjectByName(parent);
            if (par == null || seenProjects.contains(parent)) {
                continue;
            }
            map.put(par, new Relationship(Relationship.Type.PARENT, distance, false));
            nOpen.push(par);
        }
        if (cOpen.isEmpty() && !nOpen.isEmpty()) {
            cOpen = nOpen;
            nOpen = new LinkedList<InheritanceProject>();
            distance++;
        }
    }

    //Exploring children
    distance = 1;
    seenProjects.clear();
    cOpen.clear();
    nOpen.clear();
    cOpen.add(this);
    while (!cOpen.isEmpty()) {
        InheritanceProject ip = cOpen.pop();
        if (ip == null || seenProjects.contains(ip.getName())) {
            continue;
        }
        seenProjects.add(ip.getName());

        node = connGraph.get(ip.getName());
        if (ip == null || node == null) {
            continue;
        }
        //Adding all parents
        for (String child : node.children) {
            InheritanceProject cProj = InheritanceProject.getProjectByName(child);
            if (cProj == null || seenProjects.contains(child)) {
                continue;
            }
            ProjectGraphNode childNode = connGraph.get(child);
            boolean isLeaf = (childNode == null) ? true : childNode.children.isEmpty();
            map.put(cProj, new Relationship(Relationship.Type.CHILD, distance, isLeaf));
            nOpen.push(cProj);
        }
        if (cOpen.isEmpty() && !nOpen.isEmpty()) {
            cOpen = nOpen;
            nOpen = new LinkedList<InheritanceProject>();
            distance++;
        }
    }

    onInheritChangeBuffer.set(this, "getRelationships", map);
    return map;
}

From source file:com.crushpaper.Servlet.java

/** Part of the JSON API. Handles many note operations. */
private void handleJsonNoteOp(RequestAndResponse requestAndResponse) throws IOException, ServletException {
    requestAndResponse.setResponseContentTypeJson();
    String type = null;/* w w  w . jav  a2  s.c o m*/
    String note = null;
    String quotation = null;
    String id = null;
    String ids = null;
    String noteop = null;
    String childrenAction = null;
    boolean insertAsFirstChild = false;
    boolean isPublic = false;
    String csrft = null;
    boolean unlinkOnly = false;

    try {
        final JsonNodeHelper json = getJsonNode(requestAndResponse);

        type = json.getString(DbLogic.Constants.type);

        note = json.getString(DbLogic.Constants.note);

        quotation = json.getString(DbLogic.Constants.quotation);

        id = json.getString(DbLogic.Constants.id);

        ids = json.getString("ids");

        noteop = json.getString("noteop");

        childrenAction = json.getString("childrenAction");

        insertAsFirstChild = json.getBoolean("insertAsFirstChild");

        isPublic = json.getBoolean("isPublic");

        unlinkOnly = json.getBoolean("unlinkOnly");

        csrft = json.getString("csrft");
    } catch (final IOException e) {
        returnJson400(requestAndResponse, servletText.errorJson());
        return;
    }

    if (isTheCsrftWrong(requestAndResponse, csrft)) {
        returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false));
        return;
    }

    if (!EntryAttributeValidator.isNoteValid(note)) {
        returnJson400(requestAndResponse, servletText.errorNoteIsInvalid());
        return;
    }

    if (type != null && type.equals(Constants.note) && !EntryAttributeValidator.isNoteValid(note)) {
        returnJson400(requestAndResponse, servletText.errorNoteIsInvalid());
        return;
    }

    if (type != null && type.equals(Constants.notebook)
            && !EntryAttributeValidator.isNotebookTitleValid(note)) {
        returnJson400(requestAndResponse, servletText.errorNoteIsInvalid());
        return;
    }

    if (!EntryAttributeValidator.isQuotationValid(quotation)) {
        returnJson400(requestAndResponse, servletText.errorQuotationIsInvalid());
        return;
    }

    try {
        final Long time = new Long(System.currentTimeMillis());
        final Errors errors = new Errors();
        final StringBuilder result = new StringBuilder();
        User user = dbLogic.getUserById(getEffectiveUserId(requestAndResponse));

        boolean userWasSignedIn = false;
        // Create the user if needed and possible.
        if (user == null) {
            if (allowSaveIfNotSignedIn && noteop != null && noteop.equals("newNotebook")) {
                user = createAnonUser();

                if (user == null) {
                    returnJson400(requestAndResponse, servletText.errorCouldNotCreateAccount());
                    return;
                } else {
                    mapSessionToUser(requestAndResponse, user.getId());
                    userWasSignedIn = true;
                }
            } else {
                returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false));
                return;
            }
        }

        if (user.getIsAccountClosed()) {
            returnJson400(requestAndResponse, servletText.errorAccountIsClosed());
            return;
        }

        result.append("{\"modTime\": " + time + "\n");
        Entry entry = null;
        boolean includeNote = false;
        boolean success = false;
        ArrayList<String> deletedEntryIds = null;
        if (noteop != null) {
            if (noteop.equals("edit") || noteop.equals("editNotebook") || noteop.equals("editSource")
                    || noteop.equals("editNoteText")) {
                if (id == null) {
                    returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat());
                    return;
                }

                final String[] idParts = id.split(":");
                final String trueId = idParts[idParts.length == 1 ? 0 : 1];

                if (!dbLogic.getIdGenerator().isIdWellFormed(trueId)) {
                    returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat());
                    return;
                }

                if (noteop.equals("editNoteText")) {
                    entry = dbLogic.getEntryById(trueId);
                    if (entry == null) {
                        Errors.add(errors, servletText.errorEntryCouldNotBeFound());
                    } else {
                        entry = dbLogic.editEntry(user, trueId, note, entry.getQuotation(), entry.getIsPublic(),
                                time, isUserAnAdmin(requestAndResponse), errors);
                    }
                } else {
                    entry = dbLogic.editEntry(user, trueId, note, quotation, isPublic, time,
                            isUserAnAdmin(requestAndResponse), errors);
                }

                includeNote = true;
                success = entry != null;
            } else if (noteop.equals("delete") || noteop.equals("deleteNotebook")
                    || noteop.equals("deleteSource")) {
                deletedEntryIds = new ArrayList<String>();

                if (ids == null) {
                    returnJson400(requestAndResponse, servletText.errorIdsAreInvalidFormat());
                    return;
                }

                final String[] idsArray = ids.split(",");

                // Do this here so that we don't need to delete the orphan
                // functionality or tests.
                // It has also been disabled in the UI because probably no
                // one will want this feature unless it is more polished.
                if (childrenAction != null && childrenAction.equals("orphan")) {
                    childrenAction = "parent";
                }

                if (noteop.equals("deleteNotebook") || noteop.equals("deleteSource")) {
                    childrenAction = "parent";
                }

                success = true;

                final LinkedList<EntryAndIsFromList> entriesToDeleteOrUnlink = new LinkedList<EntryAndIsFromList>();
                String errorMessage = validateEntriesParentsBeforeChildren(requestAndResponse, idsArray,
                        entriesToDeleteOrUnlink);

                for (final EntryAndIsFromList entryToDeleteOrUnlink : entriesToDeleteOrUnlink) {
                    if (entryToDeleteOrUnlink.entry.getType().equals(Constants.tableofcontents)
                            || entryToDeleteOrUnlink.entry.getType().equals(Constants.root)) {
                        errorMessage = servletText.errorEntryCanNotBeDeleted();
                    }
                }

                final LinkedList<Entry> entriesToOnlyUnlink = new LinkedList<Entry>();
                if (unlinkOnly) {
                    for (final EntryAndIsFromList entryToDeleteOrUnlink : entriesToDeleteOrUnlink) {
                        if (entryToDeleteOrUnlink.entry.isQuotation()
                                || entryToDeleteOrUnlink.entry.isSource()) {
                            entriesToOnlyUnlink.push(entryToDeleteOrUnlink.entry);
                            entryToDeleteOrUnlink.entry = null;
                        }
                    }
                }

                if (errorMessage != null) {
                    success = false;
                    errors.add(errorMessage);
                } else {
                    for (final Entry entryToUnlink : entriesToOnlyUnlink) {
                        success &= dbLogic.unlinkEntry(user, entryToUnlink, isUserAnAdmin(requestAndResponse),
                                errors);
                    }

                    for (final EntryAndIsFromList entryToDelete : entriesToDeleteOrUnlink) {
                        // Check to make sure the entry has not already been
                        // deleted.
                        if (entryToDelete.entry == null
                                || dbLogic.wasEntryDeletedInThisTransaction(entryToDelete.entry)) {
                            continue;
                        }

                        success &= dbLogic.deleteEntry(user, entryToDelete.entry, childrenAction,
                                isUserAnAdmin(requestAndResponse), deletedEntryIds, errors);
                    }
                }
                /**
                 * Disable for now because probably no one will want this
                 * feature unless it is more polished } else if
                 * (noteop.equals("makeNotebook")) { String[] idsArray =
                 * ids.split(",");
                 * 
                 * success = true;
                 * 
                 * final LinkedList<Entry> entriesToMakeNotebooks = new
                 * LinkedList<Entry>(); final String errorMessage =
                 * validateEntriesParentsBeforeChildren( requestAndResponse,
                 * idsArray, entriesToMakeNotebooks); if (errorMessage !=
                 * null) { success = false; errors.add(errorMessage); } else
                 * { for (Entry entryToMakeNotebook :
                 * entriesToMakeNotebooks) { success &=
                 * dbLogic.makeNotebookEntry( user, entryToMakeNotebook,
                 * isUserAnAdmin(requestAndResponse), errors); } }
                 */
            } else if (noteop.equals("insert")) {
                if (id == null || !dbLogic.getIdGenerator().isIdWellFormed(id)) {
                    returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat());
                    return;
                }

                entry = dbLogic.createSimpleEntry(user, note, time, id, TreeRelType.Child, false, false,
                        isPublic, isUserAnAdmin(requestAndResponse), type, errors, null);
                includeNote = true;
                success = entry != null;
            } else if (noteop.equals("putUnderneath")) {
                if (id == null || !dbLogic.getIdGenerator().isIdWellFormed(id)) {
                    returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat());
                    return;
                }

                entry = dbLogic.createSimpleEntry(user, note, time, id, TreeRelType.Parent, true, false,
                        isPublic, isUserAnAdmin(requestAndResponse), type, errors, null);
                includeNote = true;
                success = entry != null;
            } else if (noteop.equals("createChild")) {
                if (id == null || !dbLogic.getIdGenerator().isIdWellFormed(id)) {
                    returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat());
                    return;
                }

                entry = dbLogic.createSimpleEntry(user, note, time, id, TreeRelType.Parent, false,
                        insertAsFirstChild, isPublic, isUserAnAdmin(requestAndResponse), type, errors, null);
                includeNote = true;
                success = entry != null;
            } else if (noteop.equals("newNotebook")) {
                boolean addSampleNote = !doesUserHaveAnyNotebooks(requestAndResponse);
                entry = dbLogic.createEntryNoteBook(user, note, time, null, null, false, false, isPublic,
                        isUserAnAdmin(requestAndResponse), addSampleNote, errors);
                includeNote = true;
                success = entry != null;
            } else if (noteop.equals("putBefore")) {
                if (id == null || !dbLogic.getIdGenerator().isIdWellFormed(id)) {
                    returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat());
                    return;
                }

                entry = dbLogic.createSimpleEntry(user, note, time, id, TreeRelType.Next, false, false,
                        isPublic, isUserAnAdmin(requestAndResponse), type, errors, null);
                includeNote = true;
                success = entry != null;
            } else if (noteop.equals("putAfter")) {
                if (id == null || !dbLogic.getIdGenerator().isIdWellFormed(id)) {
                    returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat());
                    return;
                }

                entry = dbLogic.createSimpleEntry(user, note, time, id, TreeRelType.Previous, false, isPublic,
                        isUserAnAdmin(requestAndResponse), false, type, errors, null);
                includeNote = true;
                success = entry != null;
            } else {
                errors.add(servletText.errorInvalidOperation());
            }
        } else {
            errors.add(servletText.errorMissingOperation());
        }

        if (!success) {
            requestAndResponse.response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            result.append(",\"success\":false");
            result.append(",");
            errorsToJson(errors, result);
        } else {
            result.append(",\"success\":true");
        }

        if (entry != null) {
            result.append(",\"id\":\"" + entry.getId() + "\"\n");

            if (includeNote) {
                result.append(",");

                addJsonForEntry(result, entry,
                        noteop.equals("edit") || noteop.equals("editNotebook") || noteop.equals("editSource")
                                || noteop.equals("editNoteText"),
                        noteop.equals("newNotebook"), userWasSignedIn, true);
            }
        }

        if (deletedEntryIds != null) {
            result.append(", \"deleted\": [");
            boolean isFirst = true;
            for (final String deletedEntryId : deletedEntryIds) {
                if (!isFirst) {
                    result.append(",");
                }
                isFirst = false;
                result.append("\"" + deletedEntryId + "\"");
            }
            result.append("]");
        }

        result.append("}\n");
        dbLogic.commit();

        requestAndResponse.print(result.toString());
    } catch (final PersistenceException e) {
        logger.log(Level.INFO, "Exception", e);
        returnJson500(requestAndResponse, servletText.errorInternalDatabase());
    }
}