Example usage for java.util Stack Stack

List of usage examples for java.util Stack Stack

Introduction

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

Prototype

public Stack() 

Source Link

Document

Creates an empty Stack.

Usage

From source file:com.amalto.core.storage.StorageMetadataUtils.java

/**
 * <p>/*from   w  w w.  java  2s  .  co m*/
 * Find <b>a</b> path (<b>not necessarily the shortest</b>) from type <code>origin</code> to field
 * <code>target</code>.
 * </p>
 * <p>
 * Method is expected to run in linear time, depending on:
 * <ul>
 * <li>Number of fields in <code>origin</code>.</li>
 * <li>Number of references fields accessible from <code>origin</code>.</li>
 * </ul>
 * </p>
 *
 * @param type Point of entry in the metadata graph.
 * @param target Field to look for as end of path.
 * @return A path from type <code>origin</code> to field <code>target</code>. Returns empty list if no path could be
 * found.
 * @throws IllegalArgumentException If either <code>origin</code> or <code>path</code> is null.
 */
public static List<FieldMetadata> path(ComplexTypeMetadata type, FieldMetadata target,
        boolean includeReferences) {
    Stack<FieldMetadata> path = new Stack<FieldMetadata>();
    _path(type, target, path, new HashSet<ComplexTypeMetadata>(), includeReferences);
    return path;
}

From source file:ecar.util.HtmlSanitizer.java

public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern forbiddenTags) {
    SanitizeResult ret = new SanitizeResult();
    Stack<String> openTags = new Stack();

    List<String> tokens = tokenize(html);

    // ------------------- LOOP for every token --------------------------
    for (String token : tokens) {
        boolean isAcceptedToken = false;

        Matcher startMatcher = tagStartPattern.matcher(token);
        Matcher endMatcher = tagClosePattern.matcher(token);

        // --------------------------------------------------------------------------------
        // COMMENT <!-- ......... -->
        if (commentPattern.matcher(token).find()) {
            ret.val = ret.val + token + (token.endsWith("-->") ? "" : "-->");
            ret.invalidTags.add(token + (token.endsWith("-->") ? "" : "-->"));
            continue;

            // --------------------------------------------------------------------------------
            // OPEN TAG <tag .........>
        } else if (startMatcher.find()) {

            // tag name extraction
            String tag = startMatcher.group(1).toLowerCase();

            // -----------------------------------------------------
            // FORBIDDEN TAG <script .........>
            if (forbiddenTags.matcher(tag).find()) {
                ret.invalidTags.add("<" + tag + ">");
                continue;

                // -------------------------------------------------- WELL
                // KNOWN TAG
            } else if (allowedTags.matcher(tag).find()) {

                String cleanToken = "<" + tag;
                String tokenBody = startMatcher.group(2);

                // first test table consistency
                // table tbody tfoot thead th tr td
                if ("thead".equals(tag) || "tbody".equals(tag) || "tfoot".equals(tag) || "tr".equals(tag)) {
                    if (openTags.search("table") < 1) {
                        ret.invalidTags.add("<" + tag + ">");
                        continue;
                    }/*  w w w .  j  a va  2s  .co  m*/
                } else if ("td".equals(tag) || "th".equals(tag)) {
                    if (openTags.search("tr") < 1) {
                        ret.invalidTags.add("<" + tag + ">");
                        continue;
                    }
                }

                // then test properties
                Matcher attributes = attributesPattern.matcher(tokenBody);

                boolean foundURL = false; // URL flag
                while (attributes.find()) {

                    String attr = attributes.group(1).toLowerCase();
                    String val = attributes.group(2);

                    // we will accept href in case of <A>
                    if ("a".equals(tag) && "href".equals(attr)) { // <a
                        // href="......">
                        String[] customSchemes = { "http", "https" };
                        if (new UrlValidator(customSchemes).isValid(val)) {
                            foundURL = true;
                        } else {
                            // may be it is a mailto?
                            // case <a
                            // href="mailto:pippo@pippo.com?subject=...."
                            if (val.toLowerCase().startsWith("mailto:") && val.indexOf("@") >= 0) {
                                String val1 = "http://www." + val.substring(val.indexOf("@") + 1);
                                if (new UrlValidator(customSchemes).isValid(val1)) {
                                    foundURL = true;
                                } else {
                                    ret.invalidTags.add(attr + " " + val);
                                    val = "";
                                }
                            } else {
                                ret.invalidTags.add(attr + " " + val);
                                val = "";
                            }
                        }

                    } else if (tag.matches("img|embed") && "src".equals(attr)) { // <img src="......">
                        String[] customSchemes = { "http", "https" };
                        if (new UrlValidator(customSchemes).isValid(val)) {
                            foundURL = true;
                        } else {
                            ret.invalidTags.add(attr + " " + val);
                            val = "";
                        }

                    } else if ("href".equals(attr) || "src".equals(attr)) { // <tag
                        // src/href="......">
                        // skipped
                        ret.invalidTags.add(tag + " " + attr + " " + val);
                        continue;

                    } else if (attr.matches("width|height")) { // <tag
                        // width/height="......">
                        if (!val.toLowerCase().matches("\\d+%|\\d+$")) { // test
                            // numeric
                            // values
                            ret.invalidTags.add(tag + " " + attr + " " + val);
                            continue;
                        }

                    } else if ("style".equals(attr)) { // <tag
                        // style="......">

                        // then test properties
                        Matcher styles = stylePattern.matcher(val);
                        String cleanStyle = "";

                        while (styles.find()) {
                            String styleName = styles.group(1).toLowerCase();
                            String styleValue = styles.group(2);

                            // suppress invalid styles values
                            if (forbiddenStylePattern.matcher(styleValue).find()) {
                                ret.invalidTags.add(tag + " " + attr + " " + styleValue);
                                continue;
                            }

                            // check if valid url
                            Matcher urlStyleMatcher = urlStylePattern.matcher(styleValue);
                            if (urlStyleMatcher.find()) {
                                String[] customSchemes = { "http", "https" };
                                String url = urlStyleMatcher.group(1);
                                if (!new UrlValidator(customSchemes).isValid(url)) {
                                    ret.invalidTags.add(tag + " " + attr + " " + styleValue);
                                    continue;
                                }
                            }

                            cleanStyle = cleanStyle + styleName + ":" + encode(styleValue) + ";";

                        }
                        val = cleanStyle;

                    } else if (attr.startsWith("on")) { // skip all
                        // javascript events
                        ret.invalidTags.add(tag + " " + attr + " " + val);
                        continue;

                    } else { // by default encode all properies
                        val = encode(val);
                    }

                    cleanToken = cleanToken + " " + attr + "=\"" + val + "\"";
                }
                cleanToken = cleanToken + ">";

                isAcceptedToken = true;

                // for <img> and <a>
                if (tag.matches("a|img|embed") && !foundURL) {
                    isAcceptedToken = false;
                    cleanToken = "";
                }

                token = cleanToken;

                // push the tag if require closure and it is accepted
                // (otherwirse is encoded)
                if (isAcceptedToken && !(standAloneTags.matcher(tag).find() || selfClosed.matcher(tag).find()))
                    openTags.push(tag);

                // --------------------------------------------------------------------------------
                // UNKNOWN TAG
            } else {
                ret.invalidTags.add(token);
                ret.val = ret.val + token;
                continue;

            }

            // --------------------------------------------------------------------------------
            // CLOSE TAG </tag>
        } else if (endMatcher.find()) {
            String tag = endMatcher.group(1).toLowerCase();

            // is self closing
            if (selfClosed.matcher(tag).find()) {
                ret.invalidTags.add(token);
                continue;
            }
            if (forbiddenTags.matcher(tag).find()) {
                ret.invalidTags.add("/" + tag);
                continue;
            }
            if (!allowedTags.matcher(tag).find()) {
                ret.invalidTags.add(token);
                ret.val = ret.val + token;
                continue;
            } else {

                String cleanToken = "";

                // check tag position in the stack
                int pos = openTags.search(tag);
                // if found on top ok
                for (int i = 1; i <= pos; i++) {
                    // pop all elements before tag and close it
                    String poppedTag = openTags.pop();
                    cleanToken = cleanToken + "</" + poppedTag + ">";
                    isAcceptedToken = true;
                }

                token = cleanToken;
            }

        }

        ret.val = ret.val + token;

        if (isAcceptedToken) {
            ret.html = ret.html + token;
            // ret.text = ret.text + " ";
        } else {
            String sanToken = htmlEncodeApexesAndTags(token);
            ret.html = ret.html + sanToken;
            ret.text = ret.text + htmlEncodeApexesAndTags(removeLineFeed(token));
        }

    }

    // must close remaining tags
    while (openTags.size() > 0) {
        // pop all elements before tag and close it
        String poppedTag = openTags.pop();
        ret.html = ret.html + "</" + poppedTag + ">";
        ret.val = ret.val + "</" + poppedTag + ">";
    }

    // set boolean value
    ret.isValid = ret.invalidTags.size() == 0;

    return ret;
}

From source file:ch.zhaw.icclab.tnova.expressionsolver.OTFlyEval.java

String evaluateExpression(String exp, Stack<Double> param, double threshold) {
    String[] literals = exp.split("(?!^)"); //array of characters
    String tempVal = "";
    Stack<String> sTable = new Stack<String>();
    for (int i = 0; i < literals.length; i++) {
        if (literals[i].equals("(")) {
            if (tempVal.trim().length() != 0) {
                sTable.push("fn " + tempVal.trim());
                logger.info("pushed function [" + tempVal.trim() + "] into stack.");
            } else {
                //parsing error this stage is not allowed
            }//w  w w . j  a  v a  2  s  .  c o m
            tempVal = "";
        } else if (literals[i].equals(",")) {
            if (tempVal.trim().length() != 0) {
                sTable.push("pm " + tempVal.trim());
                logger.info("pushed parameter [" + tempVal.trim() + "] into stack.");
            } else {
                //parsing error this stage is not allowed
            }
            tempVal = "";
        } else if (literals[i].equals(")")) {
            if (tempVal.trim().length() != 0) {
                sTable.push("pm " + tempVal.trim());
                logger.info("pushed parameter [" + tempVal.trim() + "] into stack.");
            }

            logger.info("Proceeding for partial stack evaluation.");
            tempVal = "";
            //proceed to partial evaluation
            try {
                String output = partialEvaluation(sTable, param, threshold);
                //push the result back into stack as a literal
                sTable.push("pm " + output);
                logger.info("pushed parameter [" + output + "] into stack for further processing.");
            } catch (EmptyStackException emex) {
                logger.warn("Malformed expression and value set received.");
                if (App.showExceptions)
                    emex.printStackTrace();
                return null;
            }
        } else
            tempVal += literals[i];
    }
    //if stack has more than 1 element error, else the only element is the result
    String result = "";
    if (sTable.size() != 1) {
        //error
        result = null;
    } else {
        result = sTable.pop().split(" ")[1];
    }
    return result;
}

From source file:de.codesourcery.jasm16.ast.ASTUtils.java

public static Iterator<ASTNode> createDepthFirst(ASTNode node) {
    final Stack<ASTNode> stack = new Stack<ASTNode>();
    if (node != null) {
        stack.push(node);//ww w  . j  a v a 2 s  . c  o m
    }
    return new Iterator<ASTNode>() {

        @Override
        public boolean hasNext() {
            return !stack.isEmpty();
        }

        @Override
        public ASTNode next() {
            ASTNode n = stack.peek();
            for (ASTNode child : n.getChildren()) {
                stack.push(child);
            }
            return stack.pop();
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Not implemented");
        }
    };
}

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

@SuppressWarnings("rawtypes")
public static <T> List<T> generate(Class<T> clazz, String[] uniqueFields, int count, String[] excludeFields,
        int recursiveCycleLimit) {
    List<String> excludeFieldList = null;
    if (excludeFields != null && excludeFields.length > 0) {
        excludeFieldList = Arrays.asList(excludeFields);
    }//from  www .  j a  v  a2  s .c om
    if (recursiveCycleLimit <= 0) {
        recursiveCycleLimit = 0;
    }
    checkBeanValidity(clazz, excludeFieldList, recursiveCycleLimit);

    List<T> list = new ArrayList<T>(count);
    ControlParam cp = new ControlParam();
    cp.setExcludeFieldList(excludeFieldList);
    cp.setNumIndex(1);
    cp.setRandom(new Random(RANDOM_SEED));
    cp.setStrIndex(100000);
    cp.setStrStep(1111L);
    cp.setCharIndex(0);
    cp.setRecursiveCycleLimit(recursiveCycleLimit);
    Calendar time = Calendar.getInstance();
    time.setTime(START_TIME);
    cp.setTime(time);
    if (uniqueFields != null && uniqueFields.length > 0) {
        cp.setUniqueFieldList(Arrays.asList(uniqueFields));
    }

    for (int i = 0; i < count; i++) {
        Stack<Class> stack = new Stack<Class>();
        stack.push(clazz);
        list.add(produceBean(clazz, cp, stack));
    }
    return list;
}

From source file:ar.com.zauber.commons.spring.servlet.mvc.support.ZauberBeanNameBasedClassNameHandlerMapping.java

/**
 * <ul>/* w  ww  .j  av  a2  s  .c  o  m*/
 * <li>ChangePassword -> password/change</li>
 * <li>changePassword -> password/change</li>
 * <li>login -> login</li>
 * </ul>
 * 
 */
protected final String getCompoundPath(final String s) {
    final Stack<String> stack = new Stack<String>();
    final int n = s.length();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < n; i++) {
        final char c = s.charAt(i);

        if (Character.isUpperCase(c)) {
            if (sb.length() > 0) {
                stack.push(sb.toString());
                sb = new StringBuilder();
            }
            sb.append(Character.toLowerCase(c));
        } else {
            sb.append(c);
        }
    }

    if (sb.length() > 0) {
        stack.push(sb.toString());
        sb = new StringBuilder();
    }

    while (!stack.isEmpty()) {
        sb.append(stack.pop());
        sb.append('/');
    }

    return sb.toString();
}

From source file:de.codesourcery.jasm16.compiler.Main.java

private int run(String[] args) throws Exception {
    final List<ICompilationUnit> units = new ArrayList<ICompilationUnit>();

    final Stack<String> arguments = new Stack<String>();
    for (String arg : args) {
        arguments.push(arg);//from   w ww .j a v a2  s  .  c o m
    }
    Collections.reverse(arguments);

    while (!arguments.isEmpty()) {
        final String arg = arguments.peek();
        if (arg.startsWith("-") || arg.startsWith("--")) {
            try {
                handleCommandlineOption(arg, arguments);
            } catch (NoSuchElementException e) {
                printError("Invalid command line, option " + arg + " lacks argument.");
                return 1;
            }
        } else {
            units.add(createCompilationUnit(arguments.pop()));
        }
    }

    if (verboseOutput) {
        printVersionInfo();
    }

    if (units.isEmpty()) {
        printError("No input files.");
        return 1;
    }

    setupCompiler(units);

    final ICompilationListener listener;
    if (printDebugStats || verboseOutput) {
        listener = new DebugCompilationListener(printDebugStats);
    } else {
        listener = new CompilationListener();
    }

    if (printSourceCode) {
        compiler.insertCompilerPhaseAfter(new CompilerPhase("format-code") {
            @Override
            protected void run(ICompilationUnit unit, ICompilationContext context) throws IOException {
                if (unit.getAST() != null) {
                    ASTUtils.visitInOrder(unit.getAST(), new FormattingVisitor(context));
                }
            };

        }, ICompilerPhase.PHASE_GENERATE_CODE);
    }

    // invoke compiler
    compiler.compile(units, listener);

    boolean hasErrors = false;
    for (ICompilationUnit unit : units) {
        if (unit.hasErrors()) {
            Misc.printCompilationErrors(unit, Misc.readSource(unit), printStackTraces);
            hasErrors = true;
        }
    }

    if (dumpObjectCode) {
        dumpObjectCode();
    }
    return hasErrors ? 1 : 0;
}

From source file:com.baifendian.swordfish.execserver.parameter.placeholder.CalculateUtil.java

/**
 * ??//from w w  w  .j  ava  2s.co m
 *
 * @param postOrder
 * @return 
 */
private static Integer calculate(List<String> postOrder) {
    Stack<Integer> stack = new Stack<>();
    for (int i = 0; i < postOrder.size(); i++) {
        if (Character.isDigit(postOrder.get(i).charAt(0))) {
            stack.push(Integer.parseInt(postOrder.get(i)));
        } else {
            Integer back = stack.pop();
            Integer front = 0;
            char op = postOrder.get(i).charAt(0);
            if (!(op == 'P' || op == 'S')) { // ?? "?" 
                front = stack.pop();
            }

            Integer res = 0;
            switch (postOrder.get(i).charAt(0)) {
            case 'P':
                res = front + back;
                break;
            case 'S':
                res = front - back;
                break;
            case '+':
                res = front + back;
                break;
            case '-':
                res = front - back;
                break;
            case '*':
                res = front * back;
                break;
            case '/':
                res = front / back;
                break;
            }
            stack.push(res);
        }
    }

    return stack.pop();
}

From source file:SimpleCalcStreamTok.java

/** Construct from an existing Reader */
public SimpleCalcStreamTok(Reader rdr) throws IOException {
    tf = new StreamTokenizer(rdr);
    // Control the input character set:
    tf.slashSlashComments(true); // treat "//" as comments
    tf.ordinaryChar('-'); // used for subtraction
    tf.ordinaryChar('/'); // used for division

    s = new Stack();
}

From source file:com.itude.mobile.mobbl.core.model.parser.MBXmlDocumentParser.java

private void doParseFragment(byte[] data, MBDocument document, String rootPath, boolean copyRootAttributes) {
    if (data != null) {
        try {//w  ww .jav a 2 s  .c  om
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();

            _stack = new Stack<MBElementContainer>();
            _pathStack = new Stack<String>();
            _definition = document.getDefinition();
            _characters = new StringBuilder();
            _copyRootAttributes = copyRootAttributes;
            _ignoredPaths = new HashSet<String>();

            if (rootPath != null) {
                List<String> parts = MBPathUtil.splitPath(rootPath);
                for (String part : parts) {
                    _pathStack.add(NUMBERPATTERN.matcher(part).replaceAll(""));
                }

                _rootElementName = _pathStack.peek();
                _rootElement = (MBElementContainer) document.getValueForPath(rootPath);
            } else {
                _rootElement = document;
                _rootElementName = (_definition.getRootElement() != null) ? _definition.getRootElement()
                        : _definition.getName();
            }

            parser.parse(new ByteArrayInputStream(data), this);
        } catch (Exception e) {
            MBLog.d(MBConstants.APPLICATION_NAME, new String(data));
            MBLog.e(MBConstants.APPLICATION_NAME,
                    "MBXmlDocumentParser.doParseFragment (for the data, see debug log above)", e);
        }
    }
}