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:org.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultTreeView.java

private TreePath getTreePath(TreePath currentPath, ViewState state) {
    String lookingForPath = state.getCurrentMetGroup();
    Stack<DefaultMutableTreeNode> stack = new Stack<DefaultMutableTreeNode>();
    DefaultMutableTreeNode baseNode = (DefaultMutableTreeNode) currentPath.getLastPathComponent();
    for (int i = 0; i < baseNode.getChildCount(); i++) {
        stack.push((DefaultMutableTreeNode) baseNode.getChildAt(i));
    }//from  ww  w .  j av  a2  s. c om
    while (!stack.empty()) {
        DefaultMutableTreeNode node = stack.pop();
        if (node.getUserObject().equals("static-metadata")) {
            for (int i = 0; i < node.getChildCount(); i++) {
                stack.push((DefaultMutableTreeNode) node.getChildAt(i));
            }
        } else if (node.getUserObject() instanceof ConcurrentHashMap) {
            String key = (String) ((ConcurrentHashMap<String, String>) node.getUserObject()).keySet().iterator()
                    .next();
            if (lookingForPath.equals(key)) {
                return new TreePath(node.getPath());
            } else if (lookingForPath.startsWith(key + "/")) {
                lookingForPath = lookingForPath.substring(lookingForPath.indexOf("/") + 1);
                stack.clear();
                for (int i = 0; i < node.getChildCount(); i++) {
                    stack.add((DefaultMutableTreeNode) node.getChildAt(i));
                }
            }
        }
    }
    return currentPath;
}

From source file:nz.co.senanque.workflow.WorkflowManagerAbstract.java

@Transactional
public List<Audit> findHandlerTasks(ProcessInstance processInstance) {
    Stack<Audit> ret = new Stack<Audit>();
    for (Audit audit : processInstance.getAudits()) {
        if (audit.isHandler() && audit.getStatus() != null) {
            ret.push(audit);
        }/*from  www  . j  ava  2  s  . com*/
    }
    return ret;
}

From source file:org.apache.cocoon.components.treeprocessor.variables.PreparedVariableResolver.java

public final String resolve(InvokeContext context, Map objectModel) throws PatternException {
    List mapStack = null; // get the stack only when necessary - lazy inside the loop
    int stackSize = 0;

    if (needsMapStack) {
        if (context == null) {
            throw new PatternException("Need an invoke context to resolve " + this);
        }/* w w w.j  a  v  a 2  s  .c o  m*/
        mapStack = context.getMapStack();
        stackSize = mapStack.size();
    }

    Stack stack = new Stack();

    for (Iterator i = tokens.iterator(); i.hasNext();) {
        Token token = (Token) i.next();
        Token last;
        switch (token.getType()) {
        case TEXT:
            if (stack.empty()) {
                stack.push(new Token(EXPR, token.getStringValue()));
            } else {
                last = (Token) stack.peek();
                if (last.hasType(EXPR)) {
                    last.merge(token);
                } else {
                    stack.push(new Token(EXPR, token.getStringValue()));
                }
            }
            break;
        case CLOSE:
            Token expr = (Token) stack.pop();
            Token lastButOne = (Token) stack.pop();
            Token result;
            if (expr.hasType(COLON)) { // i.e. nothing was specified after the colon
                stack.pop(); // Pop the OPEN
                result = processModule(lastButOne, EMPTY_TOKEN, objectModel, context, mapStack, stackSize);
            } else if (lastButOne.hasType(COLON)) {
                Token module = (Token) stack.pop();
                stack.pop(); // Pop the OPEN
                result = processModule(module, expr, objectModel, context, mapStack, stackSize);
            } else {
                result = processVariable(expr, mapStack, stackSize);
            }
            if (stack.empty()) {
                stack.push(result);
            } else {
                last = (Token) stack.peek();
                if (last.hasType(EXPR)) {
                    last.merge(result);
                } else {
                    stack.push(result);
                }
            }
            break;
        case OPEN:
        case COLON:
        case ANCHOR_VAR:
        case THREADSAFE_MODULE:
        case STATEFUL_MODULE:
        case ROOT_SITEMAP_VARIABLE:
        default: {
            stack.push(token);
            break;
        }
        }
    }
    if (stack.size() != 1) {
        throw new PatternException("Evaluation error in expression: " + originalExpr);
    }
    return ((Token) stack.pop()).getStringValue();
}

From source file:com.bluepowermod.part.tube.TubeLogic.java

public void clearNodeCaches() {

    List<PneumaticTube> clearedTubes = new ArrayList<PneumaticTube>();
    Stack<PneumaticTube> todoTubes = new Stack<PneumaticTube>();

    clearNodeCache();// w  w w  .j  av a  2 s. c o  m
    boolean firstRun = true;
    todoTubes.push(tube);

    while (!todoTubes.isEmpty()) {
        PneumaticTube tube = todoTubes.pop();
        if (tube.getParent() != null && tube.getWorld() != null) {
            for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) {
                PneumaticTube neighbor = tube.getPartCache(d);
                if (neighbor != null) {
                    if (!clearedTubes.contains(neighbor)) {
                        neighbor.getLogic().clearNodeCache();
                        clearedTubes.add(neighbor);
                        if (firstRun || !neighbor.isCrossOver)
                            todoTubes.push(neighbor);
                    }
                }
            }
        }
        firstRun = false;
    }

}

From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePattern.java

/**
 * Gives fresh numbers to all nodes in a tree pattern.
 * //  ww w . j  ava 2s . c  o  m
 */
public void renumberNodes() {
    Stack<NavigationTreePatternNode> st = new Stack<NavigationTreePatternNode>();
    st.push(this.root);
    while (!st.empty()) {
        NavigationTreePatternNode pn = st.pop();
        if (pn.getNodeCode() == -1) {
            // nothing
            //Parameters.logger.debug("-1 node! Left unchanged");
        } else {
            pn.setNodeCode(NavigationTreePatternNode.globalNodeCounter.getAndIncrement());
        }
        Iterator<NavigationTreePatternEdge> ie = pn.getEdges().iterator();
        while (ie.hasNext()) {
            st.push(ie.next().n2);
        }
    }
}

From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePattern.java

/**
 * Same as {@link #renumberNodes()}, but it starts the numbering from the localCounter.
 * //from  w w  w  .ja  v a2 s .c  o  m
 * @author Konstantinos KARANASOS
 */
public void renumberNodes(int localCounter) {
    Stack<NavigationTreePatternNode> st = new Stack<NavigationTreePatternNode>();
    st.push(this.root);
    while (!st.empty()) {
        NavigationTreePatternNode pn = st.pop();
        if (pn.getNodeCode() == -1) {
            // nothing
            //Parameters.logger.debug("-1 node! Left unchanged");
        } else {
            pn.setNodeCode(localCounter);
            localCounter++;
        }
        Iterator<NavigationTreePatternEdge> ie = pn.getEdges().iterator();
        while (ie.hasNext()) {
            st.push(ie.next().n2);
        }
    }
}

From source file:alluxio.job.persist.PersistDefinition.java

@Override
public SerializableVoid runTask(PersistConfig config, SerializableVoid args, JobWorkerContext context)
        throws Exception {
    AlluxioURI uri = new AlluxioURI(config.getFilePath());
    String ufsPath = config.getUfsPath();

    // check if the file is persisted in UFS and delete it, if we are overwriting it
    UfsManager.UfsClient ufsClient = context.getUfsManager().get(config.getMountId());
    try (CloseableResource<UnderFileSystem> ufsResource = ufsClient.acquireUfsResource()) {
        UnderFileSystem ufs = ufsResource.get();
        if (ufs == null) {
            throw new IOException("Failed to create UFS instance for " + ufsPath);
        }//from   www.  j  av a 2s.co m
        if (ufs.exists(ufsPath)) {
            if (config.isOverwrite()) {
                LOG.info("File {} is already persisted in UFS. Removing it.", config.getFilePath());
                ufs.deleteFile(ufsPath);
            } else {
                throw new IOException("File " + config.getFilePath()
                        + " is already persisted in UFS, to overwrite the file, please set the overwrite flag"
                        + " in the config.");
            }
        }

        FileSystem fs = FileSystem.Factory.get();
        long bytesWritten;
        try (Closer closer = Closer.create()) {
            OpenFileOptions options = OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE);
            FileInStream in = closer.register(fs.openFile(uri, options));
            AlluxioURI dstPath = new AlluxioURI(ufsPath);
            // Create ancestor directories from top to the bottom. We cannot use recursive create
            // parents here because the permission for the ancestors can be different.
            Stack<Pair<String, MkdirsOptions>> ufsDirsToMakeWithOptions = new Stack<>();
            AlluxioURI curAlluxioPath = uri.getParent();
            AlluxioURI curUfsPath = dstPath.getParent();
            // Stop at the Alluxio root because the mapped directory of Alluxio root in UFS may not
            // exist.
            while (!ufs.isDirectory(curUfsPath.toString()) && curAlluxioPath != null) {
                URIStatus curDirStatus = fs.getStatus(curAlluxioPath);
                ufsDirsToMakeWithOptions.push(new Pair<>(curUfsPath.toString(),
                        MkdirsOptions.defaults().setCreateParent(false).setOwner(curDirStatus.getOwner())
                                .setGroup(curDirStatus.getGroup())
                                .setMode(new Mode((short) curDirStatus.getMode()))));
                curAlluxioPath = curAlluxioPath.getParent();
                curUfsPath = curUfsPath.getParent();
            }
            while (!ufsDirsToMakeWithOptions.empty()) {
                Pair<String, MkdirsOptions> ufsDirAndPerm = ufsDirsToMakeWithOptions.pop();
                // UFS mkdirs might fail if the directory is already created. If so, skip the mkdirs
                // and assume the directory is already prepared, regardless of permission matching.
                if (!ufs.mkdirs(ufsDirAndPerm.getFirst(), ufsDirAndPerm.getSecond())
                        && !ufs.isDirectory(ufsDirAndPerm.getFirst())) {
                    throw new IOException("Failed to create " + ufsDirAndPerm.getFirst() + " with permission "
                            + ufsDirAndPerm.getSecond().toString());
                }
            }
            URIStatus uriStatus = fs.getStatus(uri);
            OutputStream out = closer.register(
                    ufs.create(dstPath.toString(), CreateOptions.defaults().setOwner(uriStatus.getOwner())
                            .setGroup(uriStatus.getGroup()).setMode(new Mode((short) uriStatus.getMode()))));
            bytesWritten = IOUtils.copyLarge(in, out);
            incrementPersistedMetric(ufsClient.getUfsMountPointUri(), bytesWritten);
        }
        LOG.info("Persisted file {} with size {}", ufsPath, bytesWritten);
    }
    return null;
}

From source file:com.projecttango.examples.java.pointtopoint.PointToPointActivity.java

/**
 * Return the endpoints of the line as a Stack of Vector3 objects. Returns
 * null if the line is not visible.//from w  ww.  j a va 2  s  .co m
 */
private synchronized Stack<Vector3> generateEndpoints() {

    // Place the line based on the two points.
    if (mLinePoints[0] != null && mLinePoints[1] != null) {
        Stack<Vector3> points = new Stack<Vector3>();
        points.push(new Vector3(mLinePoints[0][0], mLinePoints[0][1], mLinePoints[0][2]));
        points.push(new Vector3(mLinePoints[1][0], mLinePoints[1][1], mLinePoints[1][2]));
        return points;
    }
    return null;
}

From source file:edu.uci.ics.jung.algorithms.scoring.BetweennessCentrality.java

protected void computeBetweenness(Queue<V> queue, Transformer<E, ? extends Number> edge_weights) {
    for (V v : graph.getVertices()) {
        // initialize the betweenness data for this new vertex
        for (V s : graph.getVertices())
            this.vertex_data.put(s, new BetweennessData());

        //         if (v.equals(new Integer(0)))
        //            System.out.println("pause");

        vertex_data.get(v).numSPs = 1;/*from   w  w w  . j  a  va 2 s .  c om*/
        vertex_data.get(v).distance = 0;

        Stack<V> stack = new Stack<V>();
        //            Buffer<V> queue = new UnboundedFifoBuffer<V>();
        //            queue.add(v);
        queue.offer(v);

        while (!queue.isEmpty()) {
            //                V w = queue.remove();
            V w = queue.poll();
            stack.push(w);
            BetweennessData w_data = vertex_data.get(w);

            for (E e : graph.getOutEdges(w)) {
                // TODO (jrtom): change this to getOtherVertices(w, e)
                V x = graph.getOpposite(w, e);
                if (x.equals(w))
                    continue;
                double wx_weight = edge_weights.transform(e).doubleValue();

                //                for(V x : graph.getSuccessors(w)) 
                //                {
                //                   if (x.equals(w))
                //                      continue;

                // FIXME: the other problem is that I need to 
                // keep putting the neighbors of things we've just 
                // discovered in the queue, if they're undiscovered or
                // at greater distance.

                // FIXME: this is the problem, right here, I think: 
                // need to update position in queue if distance changes
                // (which can only happen with weighted edges).
                // for each outgoing edge e from w, get other end x
                // if x not already visited (dist x < 0)
                //   set x's distance to w's dist + edge weight
                //   add x to queue; pri in queue is x's dist
                // if w's dist + edge weight < x's dist 
                //   update x's dist
                //   update x in queue (MapBinaryHeap)
                //   clear x's incoming edge list
                // if w's dist + edge weight = x's dist
                //   add e to x's incoming edge list

                BetweennessData x_data = vertex_data.get(x);
                double x_potential_dist = w_data.distance + wx_weight;

                if (x_data.distance < 0) {
                    //                        queue.add(x);
                    //                        vertex_data.get(x).distance = vertex_data.get(w).distance + 1;
                    x_data.distance = x_potential_dist;
                    queue.offer(x);
                }

                // note:
                // (1) this can only happen with weighted edges
                // (2) x's SP count and incoming edges are updated below 
                if (x_data.distance > x_potential_dist) {
                    x_data.distance = x_potential_dist;
                    // invalidate previously identified incoming edges
                    // (we have a new shortest path distance to x)
                    x_data.incomingEdges.clear();
                    // update x's position in queue
                    ((MapBinaryHeap<V>) queue).update(x);
                }
                //                  if (vertex_data.get(x).distance == vertex_data.get(w).distance + 1) 
                // 
                //                    if (x_data.distance == x_potential_dist) 
                //                    {
                //                        x_data.numSPs += w_data.numSPs;
                ////                        vertex_data.get(x).predecessors.add(w);
                //                        x_data.incomingEdges.add(e);
                //                    }
            }
            for (E e : graph.getOutEdges(w)) {
                V x = graph.getOpposite(w, e);
                if (x.equals(w))
                    continue;
                double e_weight = edge_weights.transform(e).doubleValue();
                BetweennessData x_data = vertex_data.get(x);
                double x_potential_dist = w_data.distance + e_weight;
                if (x_data.distance == x_potential_dist) {
                    x_data.numSPs += w_data.numSPs;
                    //                        vertex_data.get(x).predecessors.add(w);
                    x_data.incomingEdges.add(e);
                }
            }
        }
        while (!stack.isEmpty()) {
            V x = stack.pop();

            //              for (V w : vertex_data.get(x).predecessors) 
            for (E e : vertex_data.get(x).incomingEdges) {
                V w = graph.getOpposite(x, e);
                double partialDependency = vertex_data.get(w).numSPs / vertex_data.get(x).numSPs
                        * (1.0 + vertex_data.get(x).dependency);
                vertex_data.get(w).dependency += partialDependency;
                //                  E w_x = graph.findEdge(w, x);
                //                  double w_x_score = edge_scores.get(w_x).doubleValue();
                //                  w_x_score += partialDependency;
                //                  edge_scores.put(w_x, w_x_score);
                double e_score = edge_scores.get(e).doubleValue();
                edge_scores.put(e, e_score + partialDependency);
            }
            if (!x.equals(v)) {
                double x_score = vertex_scores.get(x).doubleValue();
                x_score += vertex_data.get(x).dependency;
                vertex_scores.put(x, x_score);
            }
        }
    }

    if (graph instanceof UndirectedGraph) {
        for (V v : graph.getVertices()) {
            double v_score = vertex_scores.get(v).doubleValue();
            v_score /= 2.0;
            vertex_scores.put(v, v_score);
        }
        for (E e : graph.getEdges()) {
            double e_score = edge_scores.get(e).doubleValue();
            e_score /= 2.0;
            edge_scores.put(e, e_score);
        }
    }

    vertex_data.clear();
}

From source file:com.wavemaker.json.AlternateJSONTransformer.java

private static Object toObjectInternal(JSONState jsonState, JSONObject obj, Object root,
        FieldDefinition fieldDefinition, TypeState typeState, int arrayLevel, Stack<String> setterQueue)
        throws InstantiationException, IllegalAccessException, InvocationTargetException,
        NoSuchMethodException {/*w w  w  . ja v  a2  s.c  om*/

    if (fieldDefinition == null) {
        throw new NullArgumentException("fieldDefinition");
    } else if (fieldDefinition.getTypeDefinition() == null) {
        throw new WMRuntimeException(MessageResource.JSON_TYPEDEF_REQUIRED);
    } else if (!(fieldDefinition.getTypeDefinition() instanceof ObjectTypeDefinition)) {
        throw new WMRuntimeException(MessageResource.JSON_OBJECTTYPEDEF_REQUIRED,
                fieldDefinition.getTypeDefinition(), fieldDefinition.getTypeDefinition().getClass());
    }

    ObjectTypeDefinition otd = (ObjectTypeDefinition) fieldDefinition.getTypeDefinition();

    Object instance = otd.newInstance();

    for (Object entryO : obj.entrySet()) {
        Entry<?, ?> entry = (Entry<?, ?>) entryO;
        String key = (String) entry.getKey();

        FieldDefinition nestedFieldDefinition = otd.getFields().get(key);
        if (nestedFieldDefinition == null) {
            throw new WMRuntimeException(MessageResource.JSON_NO_PROP_MATCHES_KEY, key, fieldDefinition);
        }
        if (!PropertyUtils.isWriteable(instance, key)) {
            logger.warn(MessageResource.JSON_NO_WRITE_METHOD.getMessage(fieldDefinition, key));
            continue;
        }

        // setter list support
        setterQueue.push(key);
        jsonState.getSettersCalled().add(getPropertyFromQueue(setterQueue));

        Object paramValue = toObjectInternal(jsonState, entry.getValue(), root, nestedFieldDefinition,
                typeState, 0, setterQueue);
        PropertyUtils.setProperty(instance, key, paramValue);

        // end setter list support
        setterQueue.pop();
    }

    return instance;
}