Example usage for java.util Stack push

List of usage examples for java.util Stack push

Introduction

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

Prototype

public E push(E item) 

Source Link

Document

Pushes an item onto the top of this stack.

Usage

From source file:com.anite.zebra.hivemind.om.state.ZebraProcessInstance.java

/**
 * @param results/*from   ww  w  .  j a  v a2  s  .c  o  m*/
 * @param q
 * @throws HibernateException
 */
@Transient
private void recursivelyQueryChildProcesses(List<ZebraProcessInstance> results, Query q)
        throws HibernateException {
    // Recursive Process children
    Stack<ZebraProcessInstance> checkList = new Stack<ZebraProcessInstance>();
    checkList.push(this);
    while (!checkList.isEmpty()) {
        ZebraProcessInstance processInstance = checkList.pop();
        q.setLong("guid", processInstance.getProcessInstanceId().longValue());
        for (Iterator it = q.iterate(); it.hasNext();) {
            ZebraProcessInstance childProcess = (ZebraProcessInstance) it.next();
            results.add(childProcess);
            checkList.push(childProcess);
        }
    }
}

From source file:com.anite.antelope.zebra.om.AntelopeProcessInstance.java

/**
 * Looks for the first list of tasks that come from the child(ren) of this
 * processinstance This is used for finding the next screen. We don't do
 * this exaustively as it could be very large. The first is good enough for
 * determining the next screen//from   ww  w.  ja  v a2  s .co m
 */
public List getFirstTasksFromAChildProcess() throws NestableException {

    Stack checkList = new Stack();
    checkList.push(this);
    while (!checkList.isEmpty()) {
        try {
            AntelopeProcessInstance currentProcess = (AntelopeProcessInstance) checkList.pop();
            List childProcesses = currentProcess.getRunningChildProcesses();
            for (Iterator it = childProcesses.iterator(); it.hasNext();) {
                AntelopeProcessInstance child = (AntelopeProcessInstance) it.next();
                List allTasks = child.getUsersTasks();
                if (!allTasks.isEmpty()) {
                    return allTasks;
                }
                checkList.push(child);
            }
        } catch (Exception e) {
            String emsg = "Failed to retrieve child processes";
            log.error(emsg, e);
            throw new NestableException(emsg, e);
        }
    }
    return new ArrayList();
}

From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java

/**
 * Performs recursive group membership lookup.
 *
 * This was how we did the lookup traditionally until we discovered 1.2.840.113556.1.4.1941.
 * But various people reported that it slows down the execution tremendously to the point that it is unusable,
 * while others seem to report that it runs faster than recursive search (http://social.technet.microsoft.com/Forums/fr-FR/f238d2b0-a1d7-48e8-8a60-542e7ccfa2e8/recursive-retrieval-of-all-ad-group-memberships-of-a-user?forum=ITCG)
 *
 * This implementation is kept for Windows 2003 that doesn't support 1.2.840.113556.1.4.1941, but it can be also
 * enabled for those who are seeing the performance problem.
 *
 * See JENKINS-22830//from w  w  w.  j a va2  s  .c o  m
 */
private void recursiveGroupLookup(DirContext context, Attributes id, Set<GrantedAuthority> groups)
        throws NamingException {
    Stack<Attributes> q = new Stack<Attributes>();
    q.push(id);
    while (!q.isEmpty()) {
        Attributes identity = q.pop();
        LOGGER.finer("Looking up group of " + identity);

        Attribute memberOf = identity.get("memberOf");
        if (memberOf == null)
            continue;

        for (int i = 0; i < memberOf.size(); i++) {
            try {
                LOGGER.log(Level.FINE, "Trying to get the CN of {0}", memberOf.get(i));
                Attributes group = context.getAttributes(new LdapName(memberOf.get(i).toString()),
                        new String[] { "CN", "memberOf" });
                Attribute cn = group.get("CN");
                if (cn == null) {
                    LOGGER.fine("Failed to obtain CN of " + memberOf.get(i));
                    continue;
                }
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine(cn.get() + " is a member of " + memberOf.get(i));

                if (groups.add(new GrantedAuthorityImpl(cn.get().toString()))) {
                    q.add(group); // recursively look for groups that this group is a member of.
                }
            } catch (NameNotFoundException e) {
                LOGGER.fine("Failed to obtain CN of " + memberOf.get(i));
            }
        }
    }
}

From source file:FibonacciHeap.java

/**
 * Creates a String representation of this Fibonacci heap.
 *
 * @return String of this./*  w  w  w . j a  v  a  2  s. c  om*/
 */
public String toString() {
    if (minNode == null) {
        return "FibonacciHeap=[]";
    }

    // create a new stack and put root on it
    Stack<FibonacciHeapNode<T>> stack = new Stack<FibonacciHeapNode<T>>();
    stack.push(minNode);

    StringBuffer buf = new StringBuffer(512);
    buf.append("FibonacciHeap=[");

    // do a simple breadth-first traversal on the tree
    while (!stack.empty()) {
        FibonacciHeapNode<T> curr = stack.pop();
        buf.append(curr);
        buf.append(", ");

        if (curr.child != null) {
            stack.push(curr.child);
        }

        FibonacciHeapNode<T> start = curr;
        curr = curr.right;

        while (curr != start) {
            buf.append(curr);
            buf.append(", ");

            if (curr.child != null) {
                stack.push(curr.child);
            }

            curr = curr.right;
        }
    }

    buf.append(']');

    return buf.toString();
}

From source file:com.anite.zebra.hivemind.om.state.ZebraProcessInstance.java

/**
 * Looks for the first list of tasks that come from the child(ren) of this
 * processinstance This is used for finding the next screen. We don't do
 * this exaustively as it could be very large. The first is good enough for
 * determining the next screen//  w  w w. j a  va 2  s  .  c om
 */
@Transient
public List<ZebraTaskInstance> getFirstTasksFromAChildProcess() throws NestableException {

    Stack<ZebraProcessInstance> checkList = new Stack<ZebraProcessInstance>();
    checkList.push(this);
    while (!checkList.isEmpty()) {
        try {
            ZebraProcessInstance currentProcess = checkList.pop();
            List childProcesses = currentProcess.getRunningChildProcesses();
            for (Iterator it = childProcesses.iterator(); it.hasNext();) {
                ZebraProcessInstance child = (ZebraProcessInstance) it.next();
                List<ZebraTaskInstance> allTasks = child.getUsersTasks();
                if (!allTasks.isEmpty()) {
                    return allTasks;
                }
                checkList.push(child);
            }
        } catch (Exception e) {
            String emsg = "Failed to retrieve child processes";
            log.error(emsg, e);
            throw new NestableException(emsg, e);
        }
    }
    return new ArrayList<ZebraTaskInstance>();
}

From source file:com.unboundid.scim2.common.utils.Parser.java

/**
 * Close a grouping of filters enclosed by parenthesis.
 *
 * @param operators The stack of operators tokens.
 * @param output The stack of output tokens.
 * @param isAtTheEnd Whether the end of the filter string was reached.
 * @return The last operator encountered that signaled the end of the group.
 * @throws BadRequestException If the filter string could not be parsed.
 *//*w  w  w  . j  av a2s  .  c om*/
private static String closeGrouping(final Stack<String> operators, final Stack<Filter> output,
        final boolean isAtTheEnd) throws BadRequestException {
    String operator = null;
    String repeatingOperator = null;
    LinkedList<Filter> components = new LinkedList<Filter>();

    // Iterate over the logical operators on the stack until either there are
    // no more operators or an opening parenthesis or not is found.
    while (!operators.isEmpty()) {
        operator = operators.pop();
        if (operator.equals("(") || operator.equalsIgnoreCase(FilterType.NOT.getStringValue())) {
            if (isAtTheEnd) {
                throw BadRequestException.invalidFilter("Unexpected end of filter string");
            }
            break;
        }
        if (repeatingOperator == null) {
            repeatingOperator = operator;
        }
        if (!operator.equals(repeatingOperator)) {
            if (output.isEmpty()) {
                throw BadRequestException.invalidFilter("Unexpected end of filter string");
            }
            components.addFirst(output.pop());
            if (repeatingOperator.equalsIgnoreCase(FilterType.AND.getStringValue())) {
                output.push(Filter.and(components));
            } else {
                output.push(Filter.or(components));
            }
            components.clear();
            repeatingOperator = operator;
        }
        if (output.isEmpty()) {
            throw BadRequestException.invalidFilter("Unexpected end of filter string");
        }
        components.addFirst(output.pop());
    }

    if (repeatingOperator != null && !components.isEmpty()) {
        if (output.isEmpty()) {
            throw BadRequestException.invalidFilter("Unexpected end of filter string");
        }
        components.addFirst(output.pop());
        if (repeatingOperator.equalsIgnoreCase(FilterType.AND.getStringValue())) {
            output.push(Filter.and(components));
        } else {
            output.push(Filter.or(components));
        }
    }

    return operator;
}

From source file:forge.limited.SealedCardPoolGenerator.java

/**
 * <p>//w  w  w  . j a  v a  2  s .c  o m
 * Constructor for SealedDeck.
 * </p>
 * 
 * @param poolType
 *            a {@link java.lang.String} object.
 */
private SealedCardPoolGenerator(final LimitedPoolType poolType) {
    switch (poolType) {
    case Full:
        // Choose number of boosters
        if (!chooseNumberOfBoosters(new UnOpenedProduct(SealedProduct.Template.genericBooster))) {
            return;
        }
        landSetCode = CardEdition.Predicates.getRandomSetWithAllBasicLands(FModel.getMagicDb().getEditions())
                .getCode();
        break;

    case Block:
    case FantasyBlock:
        List<CardBlock> blocks = new ArrayList<CardBlock>();
        Iterable<CardBlock> src = poolType == LimitedPoolType.Block ? FModel.getBlocks()
                : FModel.getFantasyBlocks();
        for (CardBlock b : src) {
            blocks.add(b);
        }

        final CardBlock block = SGuiChoose.oneOrNone("Choose Block", blocks);
        if (block == null) {
            return;
        }

        final int nPacks = block.getCntBoostersSealed();
        final Stack<String> sets = new Stack<String>();

        for (CardEdition edition : block.getSets()) {
            sets.add(edition.getCode());
        }

        for (String ms : block.getMetaSetNames()) {
            sets.push(ms);
        }

        if (sets.size() > 1) {
            final List<String> setCombos = getSetCombos(sets, nPacks);
            if (setCombos == null || setCombos.isEmpty()) {
                throw new RuntimeException(
                        "Unsupported amount of packs (" + nPacks + ") in a Sealed Deck block!");
            }

            final String p = setCombos.size() > 1 ? SGuiChoose.oneOrNone("Choose packs to play with", setCombos)
                    : setCombos.get(0);
            if (p == null) {
                return;
            }

            for (String pz : TextUtil.split(p, ',')) {
                String[] pps = TextUtil.splitWithParenthesis(pz.trim(), ' ');
                String setCode = pps[pps.length - 1];
                int nBoosters = pps.length > 1 ? Integer.parseInt(pps[0]) : 1;
                while (nBoosters-- > 0) {
                    this.product.add(block.getBooster(setCode));
                }
            }
        } else {
            IUnOpenedProduct prod = block.getBooster(sets.get(0));
            for (int i = 0; i < nPacks; i++) {
                this.product.add(prod);
            }
        }

        landSetCode = block.getLandSet().getCode();
        break;

    case Custom:
        String[] dList;
        final List<CustomLimited> customs = new ArrayList<CustomLimited>();

        // get list of custom draft files
        final File dFolder = new File(ForgeConstants.SEALED_DIR);
        if (!dFolder.exists()) {
            throw new RuntimeException(
                    "GenerateSealed : folder not found -- folder is " + dFolder.getAbsolutePath());
        }

        if (!dFolder.isDirectory()) {
            throw new RuntimeException("GenerateSealed : not a folder -- " + dFolder.getAbsolutePath());
        }

        dList = dFolder.list();

        for (final String element : dList) {
            if (element.endsWith(FILE_EXT)) {
                final List<String> dfData = FileUtil.readFile(ForgeConstants.SEALED_DIR + element);
                final CustomLimited cs = CustomLimited.parse(dfData, FModel.getDecks().getCubes());
                if (cs.getSealedProductTemplate().getNumberOfCardsExpected() > 5) { // Do not allow too small cubes to be played as 'stand-alone'!
                    customs.add(cs);
                }
            }
        }

        // present list to user
        if (customs.isEmpty()) {
            SOptionPane.showMessageDialog("No custom sealed files found.");
            return;
        }

        final CustomLimited draft = SGuiChoose.oneOrNone("Choose Custom Sealed Pool", customs);
        if (draft == null) {
            return;
        }

        UnOpenedProduct toAdd = new UnOpenedProduct(draft.getSealedProductTemplate(), draft.getCardPool());
        toAdd.setLimitedPool(draft.isSingleton());
        if (!chooseNumberOfBoosters(toAdd)) {
            return;
        }

        landSetCode = draft.getLandSetCode();
        break;
    }
}

From source file:com.anite.zebra.core.Engine.java

public void transitionTask(ITaskInstance taskInstance) throws TransitionException {
    /*//from  www.  jav  a  2 s .  c o  m
     * we need to LOCK the ProcessInstance from changes by other Engine
     * instances 
     */

    IProcessInstance currentProcess = taskInstance.getProcessInstance();
    try {
        stateFactory.acquireLock(currentProcess, this);
    } catch (LockException e) {
        String emsg = "Failed to aquire an exclusive lock on the Process Instance (" + currentProcess
                + "). Transitioning aborted.";
        log.error(emsg, e);
        throw new TransitionException(emsg, e);
    }

    Stack taskStack = new Stack();
    taskStack.push(taskInstance);
    while (!taskStack.empty()) {
        // get the task from the Stack
        ITaskInstance currentTask = (ITaskInstance) taskStack.pop();
        Map createdTasks;
        try {
            createdTasks = transitionTaskFromStack(currentTask, currentProcess);
        } catch (Exception e) {
            String emsg = "Problem encountered transitioning task from Stack";
            log.error(emsg, e);
            throw new TransitionException(e);
        }
        for (Iterator it = createdTasks.values().iterator(); it.hasNext();) {
            ITaskInstance newTask = (ITaskInstance) it.next();
            ITaskDefinition td;
            try {
                td = newTask.getTaskDefinition();
            } catch (DefinitionNotFoundException e) {
                String emsg = "FATAL: Failed to access the Task Definition";
                log.error(emsg, e);
                // throwing an exception here will leave the process "locked", but that is a valid situation
                throw new TransitionException(emsg, e);
            }
            if (td.isAuto() || td.isSynchronised()) {
                /*
                 * is an Auto task, so add to the stack for processing.
                 * Also treat 
                 * check,
                 * to see if task is present in stack before adding it
                 */
                if (!taskStack.contains(newTask)) {
                    if (log.isInfoEnabled()) {
                        log.info("Added task to TaskStack - " + newTask);
                    }
                    taskStack.push(newTask);
                } else {
                    if (log.isInfoEnabled()) {
                        log.info("transitionTask - task already exists in stack " + newTask);
                    }
                }
            }
        }
    }
    try {
        if (currentProcess.getTaskInstances().size() == 0) {
            // mark process complete
            doProcessDestruct(currentProcess);
        }
        /*
         * release lock on process instance
         */
        stateFactory.releaseLock(currentProcess, this);
    } catch (Exception e) {
        String emsg = "FATAL: Couldnt release lock on Process Instance (" + currentProcess
                + ") after transitioning. Process will be left in an usuable state";
        log.fatal(emsg, e);
        throw new TransitionException(emsg, e);
    }
}

From source file:org.alfresco.filesys.repo.CifsHelper.java

/**
 * Finds the nodes being reference by the given directory and file paths.
 * <p>//from   w  w  w  . j a v  a2 s .  co m
 * Examples of the path are:
 * <ul>
 *   <li>\New Folder\New Text Document.txt</li>
 *   <li>\New Folder\Sub Folder</li>
 * </ul>
 * 
 * @param pathRootNodeRef the node from which to start the path search
 * @param path the search path to either a folder or file
 * @return Returns references to all matching nodes
 */
public List<NodeRef> getNodeRefs(NodeRef pathRootNodeRef, String path) {
    // tokenize the path and push into a stack in reverse order so that
    // the root directory gets popped first
    StringTokenizer tokenizer = new StringTokenizer(path, FileName.DOS_SEPERATOR_STR, false);
    String[] tokens = new String[tokenizer.countTokens()];
    int count = 0;
    while (tokenizer.hasMoreTokens()) {
        tokens[count] = tokenizer.nextToken();
        count++;
    }
    Stack<String> pathElements = new Stack<String>();
    for (int i = tokens.length - 1; i >= 0; i--) {
        pathElements.push(tokens[i]);
    }

    // start with a single parent node
    List<NodeRef> pathRootNodeRefs = Collections.singletonList(pathRootNodeRef);

    // result storage
    List<NodeRef> results = new ArrayList<NodeRef>(5);
    List<NodeRef> rubeResults = new ArrayList<NodeRef>(5);

    // kick off the path walking
    addDescendents(pathRootNodeRefs, pathElements, rubeResults);

    for (NodeRef nodeRef : rubeResults) {
        QName nodeType = nodeService.getType(nodeRef);
        if (!excludedTypes.contains(nodeType)) {
            results.add(nodeRef);
        }
    }

    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Retrieved node references for path: \n" + "   path root: " + pathRootNodeRef + "\n"
                + "   path: " + path + "\n" + "   results: " + results);
    }
    return results;
}

From source file:com.autentia.intra.bean.MenuBean.java

/**
 * Add non-leaf node to current node if it is accesible by current user
 *
 * @param path       path of current node
 * @param creds      current user//from  www.j  av  a  2s .com
 * @param neededRole role needed to render the node
 * @param parent     parent node
 * @param cmd        command name
 * @return true if node has been created
 */
private boolean openNode(Stack<TreeNode> path, Principal creds, GrantedAuthority neededRole, String cmd) {
    boolean added = false;

    if (neededRole == null || creds.hasAuthority(neededRole)) {
        String text;
        try {
            text = msg.getString("menu." + cmd);
        } catch (MissingResourceException e) {
            text = "MISSING : " + cmd + " : MISSING";
        }
        TreeNode child = new TreeNodeBase("folder", text, cmd, false);
        path.peek().getChildren().add(child);
        path.push(child);
        added = true;
    }

    log.debug("openNode - " + (added ? "OPEN  " : "IGNORE") + ": " + cmd);
    return added;
}