Example usage for java.util Stack search

List of usage examples for java.util Stack search

Introduction

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

Prototype

public synchronized int search(Object o) 

Source Link

Document

Returns the 1-based position where an object is on this stack.

Usage

From source file:Main.java

public static void main(String args[]) {

    Stack st = new Stack();

    st.push("Java");
    st.push("Source");
    st.push("from java2s.com");

    System.out.println(st.search("Source"));
}

From source file:StackExample.java

public static void main(String args[]) {
    Stack s = new Stack();
    s.push("Java");
    s.push("Source");
    s.push("and");

    System.out.println("Next: " + s.peek());
    s.push("Support");
    System.out.println(s.pop());/*from ww w.  ja va2  s  . c om*/
    s.push(".");
    int count = s.search("Java");
    while (count != -1 && count > 1) {
        s.pop();
        count--;
    }
    System.out.println(s.pop());
    System.out.println(s.empty());
}

From source file:MainClass.java

public static void main(String args[]) {
    Stack s = new Stack();
    s.push("A");/*from   w w w .j av  a  2 s  .  com*/
    s.push("B");
    s.push("C");

    System.out.println("Next: " + s.peek());
    s.push("D");

    System.out.println(s.pop());
    s.push("E");
    s.push("F");

    int count = s.search("E");
    while (count != -1 && count > 1) {
        s.pop();
        count--;
    }
    System.out.println(s);
}

From source file:Main.java

public static void main(String args[]) {
    Stack<String> s = new Stack<String>();
    s.push("A");/*from w  w  w.  ja  v  a2 s .com*/
    s.push("B");
    s.push("C");

    System.out.println("Next: " + s.peek());
    s.push("D");

    System.out.println(s.pop());
    s.push("E");
    s.push("F");

    int count = s.search("E");
    while (count != -1 && count > 1) {
        s.pop();
        count--;
    }
    System.out.println(s);
}

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

private static boolean isCycle(Object obj, Stack<Object> touchedObjects, String propertyName, JSONState js) {

    boolean cycle = -1 != touchedObjects.search(obj);
    if (cycle && js.getRequiredProperties() != null && js.getRequiredProperties().contains(propertyName)) {
        cycle = false;/*  w w w.j a  v a  2  s.co  m*/
    }
    return cycle;
}

From source file:hydrograph.engine.core.xmlparser.parametersubstitution.ParameterSubstitutor.java

private void substituteMutable(StringBuilder mutable, Stack<String> unresolvedParameters) {

    int startIndex = mutable.indexOf(VARIABLE_PREFIX);
    int endIndex = mutable.indexOf(VARIABLE_SUFFIX, startIndex);

    // return if nothing to substitute
    if (startIndex == -1 || endIndex == -1) {
        return;// w  w w  .j a  v a 2  s  . c  o m
    }

    // get parameter name
    String parameterName = mutable.substring(startIndex + VARIABLE_PREFIX.length(), endIndex);

    // raise exception if parameter name is blank
    if (parameterName == null || parameterName.trim().length() == 0) {
        throw new ParameterSubstitutorException("Parameter name can not be blank. Please correct.");
    }

    parameterName = parameterName.trim();

    String parameterValue = null;

    if (resolvedParameterCache.containsKey(parameterName)) {
        // obtain value from cache if already present
        parameterValue = resolvedParameterCache.get(parameterName);
        LOG.info("cache used for " + parameterName);
    } else {

        // check if the parameter is already on the stack then raise
        // exception
        // that it is circular substitution
        if (unresolvedParameters.search(parameterName) != -1) {
            throw new ParameterSubstitutorException("Found a circular depencency between parameter "
                    + parameterName + " and " + unresolvedParameters.peek()
                    + ". Both are referencing each other and cannot be resolved. Please correct.");
        }

        // get parameter value
        parameterValue = parameterBank.getParameter(parameterName);

        // if value is null then raise exception
        if (parameterValue == null) {
            throw new ParameterSubstitutorException(
                    "No value is found for the parameter " + parameterName + " to substitute");
        }

        // if parameter key to be substituted is in quotes("") then escape
        // special characters from its value
        if (isParameterPresentInQuotes(mutable, startIndex, endIndex)) {
            parameterValue = StringEscapeUtils.escapeXml(parameterValue);
        }

        // add current parameter to stack to check for circular loop later
        unresolvedParameters.push(parameterName);

        // check of substitution if there is a parameter reference in
        // parameter
        // value(internal substitution)
        parameterValue = substitute(parameterValue, unresolvedParameters);

        // remove parameter from stack as soon as it is resolved
        unresolvedParameters.pop();

        // add resolved value to cache
        resolvedParameterCache.put(parameterName, parameterValue);
    }
    // delete parameter syntax
    mutable.delete(startIndex, endIndex + VARIABLE_SUFFIX.length());

    // insert parameter value
    mutable.insert(startIndex, parameterValue);

    // check for next substitution and do it if available
    substituteMutable(mutable, unresolvedParameters);

}

From source file:com.tmh.web.filter.xss.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;

        } //  STYLE SCRIPT   style=xss:expression
        else if (styleScriptPattern.matcher(token).find()) {
            ret.val = ret.val + token;
            ret.invalidTags.add(token);/*w w  w . ja v  a2 s  .  c  om*/
            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;
                    }
                } 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: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;
                    }//ww w . ja  v  a 2 s .  c o 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:HtmlEncoder.java

/**
 *  Do "smart" encodging on a string. This means that valid HTML entities and tags,
 *  Helma macros and HTML comments are passed through unescaped, while
 *  other occurrences of '<', '>' and '&' are encoded to HTML entities.
 *
 *  @param str the string to encode//from  ww  w . java  2 s  .  co  m
 *  @param ret the string buffer to encode to
 *  @param paragraphs if true use p tags for paragraphs, otherwise just use br's
 *  @param allowedTags a set containing the names of allowed tags as strings. All other
 *                     tags will be escaped
 */
public final static void encode(String str, StringBuffer ret, boolean paragraphs, Set allowedTags) {
    if (str == null) {
        return;
    }

    int l = str.length();

    // where to insert the <p> tag in case we want to create a paragraph later on
    int paragraphStart = ret.length();

    // what kind of element/text are we leaving and entering?
    // this is one of TEXT|SEMIBLOCK|BLOCK|INTERNAL
    // depending on this information, we decide whether and how to insert
    // paragraphs and line breaks. "entering" a tag means we're at the '<'
    // and exiting means we're at the '>', not that it's a start or close tag.
    byte entering = TEXT;
    byte exiting = TEXT;

    Stack openTags = new Stack();

    // are we currently within a < and a > that consitute some kind of tag?
    // we use tag balancing to know whether we are inside a tag (and should
    // pass things through unchanged) or outside (and should encode stuff).
    boolean insideTag = false;

    // are we inside an HTML tag?
    boolean insideHtmlTag = false;
    boolean insideCloseTag = false;
    byte htmlTagMode = TAG_NAME;

    // if we are inside a <code> tag, we encode everything to make
    // documentation work easier
    boolean insideCodeTag = false;
    boolean insidePreTag = false;

    // are we within a Helma <% macro %> tag? We treat macro tags and
    // comments specially, since we can't rely on tag balancing
    // to know when we leave a macro tag or comment.
    boolean insideMacroTag = false;

    // are we inside an HTML comment?
    boolean insideComment = false;

    // the quotation mark we are in within an HTML or Macro tag, if any
    char htmlQuoteChar = '\u0000';
    char macroQuoteChar = '\u0000';

    // number of newlines met since the last non-whitespace character
    int linebreaks = 0;

    // did we meet a backslash escape?
    boolean escape = false;

    boolean triggerBreak = false;

    for (int i = 0; i < l; i++) {
        char c = str.charAt(i);

        // step one: check if this is the beginning of an HTML tag, comment or
        // Helma macro.
        if (c == '<') {
            if (i < (l - 2)) {
                if (!insideMacroTag && ('%' == str.charAt(i + 1))) {
                    // this is the beginning of a Helma macro tag
                    if (!insideCodeTag) {
                        insideMacroTag = insideTag = true;
                        macroQuoteChar = '\u0000';
                    }
                } else if (('!' == str.charAt(i + 1)) && ('-' == str.charAt(i + 2))) {
                    // the beginning of an HTML comment?
                    if (!insideCodeTag) {
                        insideComment = insideTag = ((i < (l - 3)) && ('-' == str.charAt(i + 3)));
                    }
                } else if (!insideTag) {
                    // check if this is a HTML tag.
                    insideCloseTag = ('/' == str.charAt(i + 1));
                    int tagStart = insideCloseTag ? (i + 2) : (i + 1);
                    int j = tagStart;

                    while ((j < l) && Character.isLetterOrDigit(str.charAt(j)))
                        j++;

                    if ((j > tagStart) && (j < l)) {
                        String tagName = str.substring(tagStart, j).toLowerCase();

                        if ("code".equals(tagName) && insideCloseTag && insideCodeTag) {
                            insideCodeTag = false;
                        }

                        if (((allowedTags == null) || allowedTags.contains(tagName))
                                && allTags.contains(tagName) && !insideCodeTag) {
                            insideHtmlTag = insideTag = true;
                            htmlQuoteChar = '\u0000';
                            htmlTagMode = TAG_NAME;

                            exiting = entering;
                            entering = TEXT;

                            if (internalTags.contains(tagName)) {
                                entering = INTERNAL;
                            } else if (blockTags.contains(tagName)) {
                                entering = BLOCK;
                            } else if (semiBlockTags.contains(tagName)) {
                                entering = paragraphs ? BLOCK : SEMIBLOCK;
                            }

                            if (entering > 0) {
                                triggerBreak = !insidePreTag;
                            }

                            if (insideCloseTag) {
                                int t = openTags.search(tagName);

                                if (t == -1) {
                                    i = j;
                                    insideHtmlTag = insideTag = false;

                                    continue;
                                } else if (t > 1) {
                                    for (int k = 1; k < t; k++) {
                                        Object tag = openTags.pop();
                                        if (!emptyTags.contains(tag)) {
                                            ret.append("</");
                                            ret.append(tag);
                                            ret.append(">");
                                        }
                                    }
                                }

                                openTags.pop();
                            } else {
                                openTags.push(tagName);
                            }

                            if ("code".equals(tagName) && !insideCloseTag) {
                                insideCodeTag = true;
                            }

                            if ("pre".equals(tagName)) {
                                insidePreTag = !insideCloseTag;
                            }
                        }
                    }
                }
            } // if (i < l-2)
        }

        if ((triggerBreak || linebreaks > 0) && !Character.isWhitespace(c)) {

            if (!insideTag) {
                exiting = entering;
                entering = TEXT;
                if (exiting >= SEMIBLOCK) {
                    paragraphStart = ret.length();
                }
            }

            if (entering != INTERNAL && exiting != INTERNAL) {
                int swallowBreaks = 0;
                if (paragraphs && (entering != BLOCK || exiting != BLOCK) && (exiting < BLOCK)
                        && (linebreaks > 1) && paragraphStart < ret.length()) {
                    ret.insert(paragraphStart, "<p>");
                    ret.append("</p>");
                    swallowBreaks = 2;
                }

                // treat entering a SEMIBLOCK as entering a TEXT 
                int _entering = entering == SEMIBLOCK ? TEXT : entering;
                for (int k = linebreaks - 1; k >= 0; k--) {
                    if (k >= swallowBreaks && k >= _entering && k >= exiting) {
                        ret.append("<br />");
                    }
                    ret.append(newLine);
                }
                if (exiting >= SEMIBLOCK || linebreaks > 1) {
                    paragraphStart = ret.length();
                }

            }

            linebreaks = 0;
            triggerBreak = false;
        }

        switch (c) {
        case '<':

            if (insideTag) {
                ret.append('<');
            } else {
                ret.append("&lt;");
            }

            break;

        case '&':

            // check if this is an HTML entity already,
            // in which case we pass it though unchanged
            if ((i < (l - 3)) && !insideCodeTag) {
                // is this a numeric entity?
                if (str.charAt(i + 1) == '#') {
                    int j = i + 2;

                    while ((j < l) && Character.isDigit(str.charAt(j)))
                        j++;

                    if ((j < l) && (str.charAt(j) == ';')) {
                        ret.append("&");

                        break;
                    }
                } else {
                    int j = i + 1;

                    while ((j < l) && Character.isLetterOrDigit(str.charAt(j)))
                        j++;

                    if ((j < l) && (str.charAt(j) == ';')) {
                        ret.append("&");

                        break;
                    }
                }
            }

            // we didn't reach a break, so encode the ampersand as HTML entity
            ret.append("&amp;");

            break;

        case '\\':
            ret.append(c);

            if (insideTag && !insideComment) {
                escape = !escape;
            }

            break;

        case '"':
        case '\'':
            ret.append(c);

            if (!insideComment) {
                // check if the quote is escaped
                if (insideMacroTag) {
                    if (escape) {
                        escape = false;
                    } else if (macroQuoteChar == c) {
                        macroQuoteChar = '\u0000';
                    } else if (macroQuoteChar == '\u0000') {
                        macroQuoteChar = c;
                    }
                } else if (insideHtmlTag) {
                    if (escape) {
                        escape = false;
                    } else if (htmlQuoteChar == c) {
                        htmlQuoteChar = '\u0000';
                        htmlTagMode = TAG_SPACE;
                    } else if (htmlQuoteChar == '\u0000') {
                        htmlQuoteChar = c;
                    }
                }
            }

            break;

        case '\n':
            if (insideTag || insidePreTag) {
                ret.append('\n');
            } else {
                linebreaks++;
            }

            break;
        case '\r':
            if (insideTag || insidePreTag) {
                ret.append('\r');
            }
            break;

        case '>':

            // For Helma macro tags and comments, we overrule tag balancing,
            // i.e. we don't require that '<' and '>' be balanced within
            // macros and comments. Rather, we check for the matching closing tag.
            if (insideComment) {
                ret.append('>');
                insideComment = !((str.charAt(i - 2) == '-') && (str.charAt(i - 1) == '-'));
            } else if (insideMacroTag) {
                ret.append('>');
                insideMacroTag = !((str.charAt(i - 1) == '%') && (macroQuoteChar == '\u0000'));
            } else if (insideHtmlTag) {
                ret.append('>');

                // only leave HTML tag if quotation marks are balanced
                // within that tag.
                insideHtmlTag = htmlQuoteChar != '\u0000';

                // Check if this is an empty tag so we don't generate an
                // additional </close> tag.
                if (str.charAt(i - 1) == '/') {
                    // this is to avoid misinterpreting tags like
                    // <a href=http://foo/> as empty
                    if (htmlTagMode != TAG_ATT_VAL && htmlTagMode != TAG_ATT_NAME) {
                        openTags.pop();
                    }
                }

                exiting = entering;
                if (exiting > 0) {
                    triggerBreak = !insidePreTag;
                }

            } else {
                ret.append("&gt;");
            }

            // check if we still are inside any kind of tag
            insideTag = insideComment || insideMacroTag || insideHtmlTag;
            insideCloseTag = insideTag;

            break;

        default:

            if (insideHtmlTag && !insideCloseTag) {
                switch (htmlTagMode) {
                case TAG_NAME:
                    if (!Character.isLetterOrDigit(c)) {
                        htmlTagMode = TAG_SPACE;
                    }
                    break;
                case TAG_SPACE:
                    if (Character.isLetterOrDigit(c)) {
                        htmlTagMode = TAG_ATT_NAME;
                    }
                    break;
                case TAG_ATT_NAME:
                    if (c == '=') {
                        htmlTagMode = TAG_ATT_VAL;
                    } else if (c == ' ') {
                        htmlTagMode = TAG_SPACE;
                    }
                    break;
                case TAG_ATT_VAL:
                    if (Character.isWhitespace(c) && htmlQuoteChar == '\u0000') {
                        htmlTagMode = TAG_SPACE;
                    }
                    break;
                }
            }
            if (c < 128) {
                ret.append(c);
            } else if ((c >= 128) && (c < 256)) {
                ret.append(transform[c - 128]);
            } else {
                ret.append("&#");
                ret.append((int) c);
                ret.append(";");
            }

            escape = false;
        }
    }

    // if tags were opened but not closed, close them.
    int o = openTags.size();

    if (o > 0) {
        for (int k = 0; k < o; k++) {
            Object tag = openTags.pop();
            if (!emptyTags.contains(tag)) {
                ret.append("</");
                ret.append(tag);
                ret.append(">");
            }
        }
    }

    // add remaining newlines we may have collected
    int swallowBreaks = 0;
    if (paragraphs && entering < BLOCK) {
        ret.insert(paragraphStart, "<p>");
        ret.append("</p>");
        swallowBreaks = 2;
    }

    if (linebreaks > 0) {
        for (int i = linebreaks - 1; i >= 0; i--) {
            if (i >= swallowBreaks && i > exiting) {
                ret.append("<br />");
            }
            ret.append(newLine);
        }
    }
}

From source file:com.taobao.tdhs.jdbc.sqlparser.ParseSQL.java

private boolean checkSpecialStr(String sqlstring, String searchStr) {

    //????searchStr
    Stack<String> stack = new Stack<String>();
    boolean exist_danyinhao = false;
    for (int i = 0; i < sqlstring.length(); i++) {
        ///*from www  .  j  a  va2  s  .c  o  m*/
        if (sqlstring.substring(i, i + 1).equals("'") == false) {
            stack.push(sqlstring.substring(i, i + 1));
        }

        //'
        if (sqlstring.substring(i, i + 1).equals("'")) {
            //?\,?,\,,??
            int count = 0;
            int k = i;
            boolean real_danyinhao;
            while (k - 1 >= 0 && sqlstring.substring(k - 1, k).equals("\\") == true) {
                k--;
                count++;
            }
            //System.out.println("\\:"+count);
            if (count % 2 == 0) {
                //??
                real_danyinhao = true;
            } else {
                //???,value
                real_danyinhao = false;
                stack.push(sqlstring.substring(i, i + 1));
            }
            if (real_danyinhao == true) {
                if (exist_danyinhao == false) {
                    exist_danyinhao = true;
                    stack.push(sqlstring.substring(i, i + 1));
                } else {
                    boolean find_real_danyinhao = false;
                    while (find_real_danyinhao == false) {
                        while (!stack.pop().equals("'")) {
                            ;
                        }
                        //???,??\
                        if (stack.isEmpty() == false && stack.peek().equals("\\")) {
                            //?,???
                            count = 0;
                            while (stack.peek().equals("\\")) {
                                stack.pop();
                                count++;
                            }
                            if (count % 2 == 0) {
                                //?
                                find_real_danyinhao = true;
                            } else {
                                //?
                                find_real_danyinhao = false;
                            }
                        } else {
                            //
                            find_real_danyinhao = true;
                        }

                    }

                    exist_danyinhao = false;
                }
            }

        }
    } //end for

    logger.debug(stack.toString());

    if (stack.isEmpty() == false && stack.search(searchStr) > -1) {
        stack.clear();
        return true;
    } else {
        return false;
    }
}