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:hudson.model.Items.java

/**
 * Computes the canonical full name of a relative path in an {@link ItemGroup} context, handling relative
 * positions ".." and "." as absolute path starting with "/". The resulting name is the item fullName from Jenkins
 * root./*from   w w  w  .j  a  v  a2s .  c o  m*/
 */
public static String getCanonicalName(ItemGroup context, String path) {
    String[] c = context.getFullName().split("/");
    String[] p = path.split("/");

    Stack<String> name = new Stack<String>();
    for (int i = 0; i < c.length; i++) {
        if (i == 0 && c[i].equals(""))
            continue;
        name.push(c[i]);
    }
    for (int i = 0; i < p.length; i++) {
        if (i == 0 && p[i].equals("")) {
            // Absolute path starting with a "/"
            name.clear();
            continue;
        }
        if (p[i].equals("..")) {
            if (name.size() == 0) {
                throw new IllegalArgumentException(String
                        .format("Illegal relative path '%s' within context '%s'", path, context.getFullName()));
            }
            name.pop();
            continue;
        }
        if (p[i].equals(".")) {
            continue;
        }
        name.push(p[i]);
    }
    return StringUtils.join(name, '/');
}

From source file:com.aurel.track.admin.customize.category.filter.tree.design.TreeFilterSaverBL.java

/**
 * Transform a list of QueryExpressions with parenthesis into a tree
 * @param expressionList//  ww  w. j a  v  a 2 s. c  om
 * @param node
 * @param operationStack
 */
public static QNode transformExpressionListToTree(List<FieldExpressionInTreeTO> expressionList,
        Stack<QNode> operationStack) throws Exception {
    if (expressionList == null || expressionList.isEmpty()) {
        return null;
    }
    QNode root = new QNode();
    root.setType(QNode.AND);
    operationStack.push(root);
    if (expressionList != null) {
        Iterator<FieldExpressionInTreeTO> iterator = expressionList.iterator();
        boolean first = true;
        while (iterator.hasNext()) {
            FieldExpressionInTreeTO fieldExpressionInTree = iterator.next();
            if (operationStack.isEmpty()) {
                throw new Exception("admin.customize.queryFilter.err.closedGtOpened");
            }
            QNode peekNode = operationStack.peek();
            if (!first) {
                //the first operation (the hidden one) is not significant
                Integer operation = fieldExpressionInTree.getSelectedOperation();
                if (operation != null) {
                    if (peekNode.isTypeAlreadySet()) {
                        if (!equalOperation(peekNode, operation)) {
                            throw new Exception(
                                    "admin.customize.queryFilter.err.differentOperationsInParenthesis");
                        }
                    } else {
                        //in the outermost level the second filter expression sets the operation,
                        //inside internal parenthesis the first one
                        setOperation(peekNode, operation.intValue());
                        peekNode.setTypeAlreadySet(true);
                    }
                }
            } else {
                first = false;
                if (!iterator.hasNext()) {
                    //it can be also AND, it doesn't have importance  because it is a single expression
                    peekNode.setType(QNode.OR);
                }
            }
            int leftParenthesis = fieldExpressionInTree.getParenthesisOpen();
            for (int i = 0; i < leftParenthesis; i++) {
                //unknown node type (AND or OR)
                QNode qNode = new QNode();
                peekNode.addChild(qNode);
                operationStack.push(qNode);
                peekNode = operationStack.peek();
            }
            peekNode.addChild(new QNodeExpression(fieldExpressionInTree));
            int rightParenthesis = fieldExpressionInTree.getParenthesisClosed();
            if (rightParenthesis > 0) {
                for (int i = 0; i < rightParenthesis; i++) {
                    if (operationStack.isEmpty()) {
                        throw new Exception("admin.customize.queryFilter.err.closedGtOpened");
                    }
                    operationStack.pop();
                }
            }
        }
        //pop the root
        if (operationStack.isEmpty()) {
            throw new Exception("admin.customize.queryFilter.err.closedGtOpened");
        }
        operationStack.pop();
        if (!operationStack.isEmpty()) {
            throw new Exception("admin.customize.queryFilter.err.closedLtOpened");
        }
    }
    return root;
}

From source file:gdt.data.entity.BaseHandler.java

/**
 * List all databases in the parent directory
 *  @param entiroot$ the parent directory.
 * @return The locator string./*from   w w w.  java  2  s  .c  om*/
 */
public static String[] bases(String entiroot$) {
    try {
        if (entiroot$ == null)
            return null;
        File entiroot = new File(entiroot$);
        File[] dirs = entiroot.listFiles();
        if (dirs == null)
            return null;
        File propertyIndex;
        Stack<String> s = new Stack<String>();
        for (int i = 0; i < dirs.length; i++) {
            if (!dirs[i].isDirectory())
                continue;
            propertyIndex = new File(dirs[i] + "/" + Entigrator.PROPERTY_INDEX);
            if (propertyIndex.exists() && propertyIndex.isFile())
                s.push(dirs[i].getPath());

        }
        int cnt = s.size();
        if (cnt < 1)
            return null;
        String[] sa = new String[cnt];
        for (int i = 0; i < cnt; i++)
            sa[i] = (String) s.pop();
        return sa;
    } catch (Exception e) {
        Logger.getLogger(BaseHandler.class.getName()).severe(e.toString());
        ;
        return null;
    }
}

From source file:ReversePolishNotation.java

/**
 * This method will calculate the answer of the given Reverse Polar Notation
 * equation. All exceptions are thrown to the parent for handling.
 * /*from  w w w.  j a  v a2s . c  o m*/
 * @param input
 *            is the equation entered by the user
 * @throws EmptyRPNException
 *             when there is no RPN equation to be evaluated.
 * @throws RPNDivideByZeroException
 *             when the RPN equation attempts to divide by zero.
 * @throws RPNUnderflowException
 *             when the RPN equation has a mathematical operator before
 *             there are enough numerical values for it to evaluate.
 * @throws InvalidRPNException
 *             when the RPN equation is a String which is unable to be
 *             manipulated.
 * @throws RPNOverflowException
 *             when the RPN equation has too many numerical values and not
 *             enough mathematical operators with which to evaluate them.
 * @return the top item of the stack; the calculated answer of the Reverse
 *         Polish Notation equation
 */
public static double calcRPN(String input) {
    // eliminate any leading or trailing whitespace from input
    input = input.trim();
    // scanner to manipulate input and stack to store double values
    String next;
    Stack<Double> stack = new Stack<Double>();
    Scanner scan = new Scanner(input);

    // loop while there are tokens left in scan
    while (scan.hasNext()) {
        // retrieve the next token from the input
        next = scan.next();

        // see if token is mathematical operator
        if (nextIsOperator(next)) {
            // ensure there are enough numbers on stack
            if (stack.size() > 1) {
                if (next.equals("+")) {
                    stack.push((Double) stack.pop() + (Double) stack.pop());
                } else if (next.equals("-")) {
                    stack.push(-(Double) stack.pop() + (Double) stack.pop());
                } else if (next.equals("*")) {
                    stack.push((Double) stack.pop() * (Double) stack.pop());
                } else if (next.equals("/")) {
                    double first = stack.pop();
                    double second = stack.pop();

                    if (first == 0) {
                        System.out.println("The RPN equation attempted to divide by zero.");
                    } else {
                        stack.push(second / first);
                    }
                }
            } else {
                System.out.println(
                        "A mathematical operator occured before there were enough numerical values for it to evaluate.");
            }
        } else {
            try {
                stack.push(Double.parseDouble(next));
            } catch (NumberFormatException c) {
                System.out.println("The string is not a valid RPN equation.");
            }
        }
    }

    if (stack.size() > 1) {
        System.out.println(
                "There too many numbers and not enough mathematical operators with which to evaluate them.");
    }

    return (Double) stack.pop();
}

From source file:de.mpg.escidoc.services.citationmanager.utils.XsltHelper.java

/**
 * Check of the balanced tags sup/sub//from   w  w  w  .j a  v  a  2  s. c  o m
 * @param snippet
 * @return <code>true</code> if balanced, <code>false</code> otherwise 
 */
public static boolean isBalanced(String snippet) {
    if (snippet == null)
        return true; //????

    Stack<String> s = new Stack<String>();
    Matcher m = SUBS_OR_SUPS.matcher(snippet);
    while (m.find()) {
        String tag = m.group(1);
        if (tag.toLowerCase().startsWith("su")) {
            s.push(tag);
        } else {
            if (s.empty() || !tag.equals("/" + s.pop())) {
                return false;
            }
        }
    }

    return s.empty();
}

From source file:com.holonplatform.core.internal.utils.TypeUtils.java

/**
 * Return the type parameter of a generic type.
 * @param clazz subClass of <code>baseClass</code> to analyze.
 * @param baseClass base class having the type parameter the value of which we need to retrieve
 * @return the parameterized type value/*from w  ww .j a  v a2 s  .  c o m*/
 */
@SuppressWarnings("rawtypes")
public static Type getTypeArgument(Class<?> clazz, Class<?> baseClass) {
    Stack<Type> superclasses = new Stack<>();
    Type currentType;
    Class<?> currentClass = clazz;

    if (clazz.getGenericSuperclass() == Object.class) {
        currentType = clazz;
        superclasses.push(currentType);
    } else {

        do {
            currentType = currentClass.getGenericSuperclass();
            superclasses.push(currentType);
            if (currentType instanceof Class) {
                currentClass = (Class) currentType;
            } else if (currentType instanceof ParameterizedType) {
                currentClass = (Class) ((ParameterizedType) currentType).getRawType();
            }
        } while (!currentClass.equals(baseClass));

    }

    // find which one supplies type argument and return it
    TypeVariable tv = baseClass.getTypeParameters()[0];
    while (!superclasses.isEmpty()) {
        currentType = superclasses.pop();

        if (currentType instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) currentType;
            Class<?> rawType = (Class) pt.getRawType();
            int argIndex = Arrays.asList(rawType.getTypeParameters()).indexOf(tv);
            if (argIndex > -1) {
                Type typeArg = pt.getActualTypeArguments()[argIndex];
                if (typeArg instanceof TypeVariable) {
                    // type argument is another type variable - look for the value of that
                    // variable in subclasses
                    tv = (TypeVariable) typeArg;
                    continue;
                } else {
                    // found the value - return it
                    return typeArg;
                }
            }
        }

        // needed type argument not supplied - break and throw exception
        break;
    }
    throw new IllegalArgumentException(currentType + " does not specify a type parameter");
}

From source file:com.w20e.socrates.servlet.ValidatorHelper.java

/**
 * Add single item to the stream or, if it's a group, add it's controls.
 * //from  ww  w  .j a  v  a2  s.  co m
 * @param rItem
 * @param context
 * @param pContext
 * @param bundle
 */
private static void addItem(Renderable rItem, Stack<Group> parents,
        final Map<String, Map<String, String>> props, final Instance inst, Model model, RenderConfig cfg,
        final UTF8ResourceBundle bundle, final Locale locale) {

    /**
     * If it's a group, just add it's controls to the context.
     */
    if (rItem instanceof Group) {

        parents.push((Group) rItem);

        for (Renderable rSubItem : ((Group) rItem).getItems()) {

            addItem(rSubItem, parents, props, inst, model, cfg, bundle, locale);
        }

        parents.pop();
    }

    if (!(rItem instanceof Control)) {
        return;
    }

    Control control = (Control) rItem;
    String bind = control.getBind();
    Node n;
    Map<String, String> localProps = new HashMap<String, String>();

    try {
        n = inst.getNode(bind);
    } catch (InvalidPathExpression e1) {
        return;
    }

    ItemProperties itemProps = model.getItemProperties(bind);

    if (itemProps == null) {
        itemProps = new ItemPropertiesImpl(bind);
    }

    try {
        // Is the item required?
        if (NodeValidator.isRequired(itemProps, inst, model)) {
            localProps.put("required", "true");
        } else {
            localProps.put("required", "false");
        }

        if (NodeValidator.isRelevant(itemProps, inst, model)) {
            localProps.put("relevant", "true");
            for (Group group : parents) {
                LOGGER.fine("Adding relevant to parent " + group.getId());
                Map<String, String> groupProps = new HashMap<String, String>();
                groupProps.put("relevant", "true");
                props.put("group:" + group.getId(), groupProps);
            }
        } else {
            localProps.put("relevant", "false");
            for (Group group : parents) {
                if (!props.containsKey("group:" + group.getId())) {
                    LOGGER.fine("Removing relevant of parent " + group.getId());
                    Map<String, String> groupProps = new HashMap<String, String>();
                    groupProps.put("relevant", "false");
                    props.put("group:" + group.getId(), groupProps);
                }
            }
        }

        if (NodeValidator.isReadOnly(itemProps, inst, model)) {
            localProps.put("readonly", "true");
        } else {
            localProps.put("readonly", "false");
        }

        // New values we might have
        if (itemProps.getCalculate() != null) {
            try {
                Object val = control.getDisplayValue(NodeValidator.getValue(n, itemProps, model, inst),
                        itemProps.getDatatype(), locale);
                localProps.put("value", val.toString());
            } catch (Exception e) {
                LOGGER.severe("Exception in resolve of value: " + e.getMessage());
            }
        }

        // Redo label if necessary
        if (control.getLabel().toString().indexOf("${") != -1) {
            String label = FillProcessor.processFills(control.getLabel().toString(), inst, model, cfg, locale);
            localProps.put("label", label);
        }

        // Redo hint if necessary
        if (control.getHint().toString().indexOf("${") != -1) {
            String hint = FillProcessor.processFills(control.getHint().toString(), inst, model, cfg, locale);
            localProps.put("hint", hint);
        }

        if (n.getValue() != null) {

            try {
                NodeValidator.validate(n, itemProps, inst, model);
                localProps.put("alert", "");
            } catch (Exception cv) {
                LOGGER.finest("Exception during validation" + cv.getMessage());
                LOGGER.finest("Node value: " + n.getValue() + "; type " + itemProps.getDatatype());
                String msg = "";

                if ("".equals(((Control) rItem).getAlert())) {
                    msg = translateError(cv.getMessage(), bundle);
                } else {
                    msg = ((Control) rItem).getAlert().toString();
                }
                localProps.put("alert", msg);
            }
        } else {
            localProps.put("alert", "");
        }
    } catch (Exception e) {
        LOGGER.severe("Couldn't resolve properties:" + e.getMessage());
    }

    props.put(rItem.getId(), localProps);
}

From source file:alluxio.job.move.MoveDefinition.java

/**
 * @param source an Alluxio URI/*from   www.j  a  v a2  s.c  om*/
 * @param fileSystem the Alluxio file system
 * @return whether the URI is a file or a directory which contains files (including recursively)
 * @throws Exception if an unexpected exception occurs
 */
private static boolean hasFiles(AlluxioURI source, FileSystem fileSystem) throws Exception {
    Stack<AlluxioURI> dirsToCheck = new Stack<>();
    dirsToCheck.add(source);
    while (!dirsToCheck.isEmpty()) {
        try {
            for (URIStatus status : fileSystem.listStatus(dirsToCheck.pop())) {
                if (!status.isFolder()) {
                    return true;
                }
                dirsToCheck.push(new AlluxioURI(status.getPath()));
            }
        } catch (FileDoesNotExistException e) {
            // This probably means another worker has deleted the directory already, so we can probably
            // return false here. To be safe though, we will fall through and complete the search.
        }
    }
    return false;
}

From source file:com.github.jasonruckman.sidney.generator.BeanBuilder.java

public static <R> BeanBuilder<R> stub(final Class<R> type) {
    InstanceFactory<R> fact = new DefaultInstanceFactory<>(type);
    R stub = fact.newInstance();//from w w w .  j a v a 2s .  c  om
    ProxyFactory factory = new ProxyFactory(stub);
    final Stack<Method> m = new Stack<>();
    factory.addAdvice(new MethodInterceptor() {
        @Override
        public Object invoke(MethodInvocation methodInvocation) throws Throwable {
            PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(methodInvocation.getMethod());
            if (descriptor == null) {
                throw new IllegalStateException(String.format("Method %s is not a getter or setter",
                        methodInvocation.getMethod().getName()));
            }
            m.push(methodInvocation.getMethod());
            return defaultReturnObjects.get(methodInvocation.getMethod().getReturnType());
        }
    });
    return new BeanBuilder<>((R) factory.getProxy(), fact, m);
}

From source file:org.apache.hadoop.tools.util.TestDistCpUtils.java

public static boolean checkIfFoldersAreInSync(FileSystem fs, String targetBase, String sourceBase)
        throws IOException {
    Path base = new Path(targetBase);

    Stack<Path> stack = new Stack<Path>();
    stack.push(base);
    while (!stack.isEmpty()) {
        Path file = stack.pop();//  w w  w . j  a  v  a  2 s  . c  om
        if (!fs.exists(file))
            continue;
        FileStatus[] fStatus = fs.listStatus(file);
        if (fStatus == null || fStatus.length == 0)
            continue;

        for (FileStatus status : fStatus) {
            if (status.isDirectory()) {
                stack.push(status.getPath());
            }
            Assert.assertTrue(fs.exists(new Path(
                    sourceBase + "/" + DistCpUtils.getRelativePath(new Path(targetBase), status.getPath()))));
        }
    }
    return true;
}