Example usage for java.lang String regionMatches

List of usage examples for java.lang String regionMatches

Introduction

In this page you can find the example usage for java.lang String regionMatches.

Prototype

public boolean regionMatches(int toffset, String other, int ooffset, int len) 

Source Link

Document

Tests if two string regions are equal.

Usage

From source file:net.lightbody.bmp.proxy.jetty.http.PathMap.java

/**
 * @return true if match.// www  . j  ava2  s .  c o  m
 */
public static boolean match(String pathSpec, String path, boolean noDefault) throws IllegalArgumentException {
    char c = pathSpec.charAt(0);
    if (c == '/') {
        if (!noDefault && pathSpec.length() == 1 || pathSpec.equals(path))
            return true;

        if (pathSpec.endsWith("/*") && pathSpec.regionMatches(0, path, 0, pathSpec.length() - 2))
            return true;

        if (path.startsWith(pathSpec) && path.charAt(pathSpec.length()) == ';')
            return true;
    } else if (c == '*')
        return path.regionMatches(path.length() - pathSpec.length() + 1, pathSpec, 1, pathSpec.length() - 1);
    return false;
}

From source file:simplesqlformatter.formatter.SQLFormatter.java

/**
 * Replace all literals (string literals and comments) with a
 * place-holder. Maintain a list of literals substituted in this way.
 * //from   w w  w . j  a v  a 2s.co m
 * @param parseInformation
 *        the text to process
 */
private static PartialParseResult processLiterals(final PartialParseResult parseInformation) {

    String workingText = parseInformation.getText();

    final List<Token> tokens = new ArrayList<Token>();
    for (int i = 0; i < workingText.length(); i++) {
        for (final LiteralDelimiter delimiter : LiteralDelimiter.ALLDELIMITERS) {
            if (workingText.regionMatches(i, delimiter.getStart(), 0, delimiter.getStart().length())) {
                final int beforeStart = i;
                final int afterStart = beforeStart + delimiter.getStart().length();
                int afterEnd = workingText.indexOf(delimiter.getEnd(), afterStart);
                if (afterEnd == -1) {
                    afterEnd = workingText.indexOf("\n", afterStart);
                    if (afterEnd == -1) {
                        afterEnd = workingText.indexOf("\r", afterStart);
                        if (afterEnd == -1) {
                            afterEnd = workingText.length() - 1;
                        }
                    }
                    afterEnd++;
                } else {
                    afterEnd += delimiter.getEnd().length();
                }
                String escapedText = workingText.substring(beforeStart, afterEnd);
                if (delimiter == LiteralDelimiter.SQLCOMMENT) {
                    // Convert SQL comment to C-style comment.
                    escapedText = LiteralDelimiter.CSTYLECOMMENT.getStart() + escapedText.trim().substring(2)
                            + LiteralDelimiter.CSTYLECOMMENT.getEnd();
                }
                tokens.add(new LiteralToken(escapedText, delimiter));

                final String preEscape = workingText.substring(0, beforeStart);
                String postEscape = "";
                if (afterEnd < workingText.length()) {
                    postEscape = workingText.substring(afterEnd);
                }
                String escapePlaceholder = String.valueOf(PLACEHOLDER_TOKEN);
                if (delimiter != LiteralDelimiter.DOUBLEQUOTEDSTRING
                        && delimiter != LiteralDelimiter.SINGLEQUOTEDSTRING) {
                    if (!preEscape.endsWith(" ")) {
                        escapePlaceholder = " " + escapePlaceholder;
                    }
                    if (!postEscape.startsWith(" ")) {
                        escapePlaceholder += " ";
                    }
                }
                workingText = preEscape + escapePlaceholder + postEscape;
                break;
            }
        }
    }

    return new PartialParseResult(tokens, workingText);

}

From source file:Main.java

public static final String getRawQueryParameter(Uri uri, String queryParameterName) {
    String ret = null;/*  w  w  w .ja  va 2s.  c  om*/

    if ((uri != null) && (!TextUtils.isEmpty(queryParameterName))) {
        final String query = uri.getEncodedQuery();
        if (query == null) {
            return null;
        }

        final String encodedKey = Uri.encode(queryParameterName, null);
        final int length = query.length();
        int start = 0;
        do {
            int nextAmpersand = query.indexOf('&', start);
            int end = nextAmpersand != -1 ? nextAmpersand : length;

            int separator = query.indexOf('=', start);
            if (separator > end || separator == -1) {
                separator = end;
            }

            if (separator - start == encodedKey.length()
                    && query.regionMatches(start, encodedKey, 0, encodedKey.length())) {
                if (separator == end) {
                    ret = "";
                } else {
                    ret = query.substring(separator + 1, end);
                }
                break;
            }

            // Move start to end of name.
            if (nextAmpersand != -1) {
                start = nextAmpersand + 1;
            } else {
                break;
            }
        } while (true);
    }

    return ret;
}

From source file:gda.jython.translator.GeneralTranslator.java

public static String[] splitGroup(String during) {
    String[] output = new String[0];
    StringBuffer buf = new StringBuffer();
    int index = 0;
    String[] quoteTypes = new String[] { "'''", "r\"", "r\'", "\'", "\"" }; //put most complex first
    while (index < during.length()) {
        if (during.regionMatches(index, " ", 0, 1) || during.regionMatches(index, ",", 0, 1)) {
            if (buf.length() > 0) {
                output = (String[]) ArrayUtils.add(output, buf.toString());
                buf = new StringBuffer();
            }//from w w  w  .j  av a2s  .  c o  m
            index++;
            continue;
        }
        boolean quoteTypeFound = false;
        for (String quoteType : quoteTypes) {
            if (during.regionMatches(index, quoteType, 0, quoteType.length())) {
                if (buf.length() > 0) {
                    output = (String[]) ArrayUtils.add(output, buf.toString());
                    buf = new StringBuffer();
                }
                buf.append(quoteType);
                index += quoteType.length();
                //start of quote so go up to the matching quote - allowing for escaped versions
                String endQuote = quoteType;
                if (endQuote == "r\"")
                    endQuote = "\"";
                if (endQuote == "r\'")
                    endQuote = "\'";
                while (index < during.length()) {
                    if (during.regionMatches(index, endQuote, 0, endQuote.length())) {
                        buf.append(endQuote);
                        index += endQuote.length();
                        output = (String[]) ArrayUtils.add(output, buf.toString());
                        buf = new StringBuffer();
                        break;
                    }
                    char charAt = during.charAt(index);
                    buf.append(during.charAt(index));
                    index++;
                    if (charAt == '\\') {
                        if (index < during.length()) {
                            buf.append(during.charAt(index));
                            index++;
                        }
                    }
                }
                if (buf.length() > 0) {
                    output = (String[]) ArrayUtils.add(output, buf.toString());
                    buf = new StringBuffer();
                }
                quoteTypeFound = true;
                break;
            }
        }
        if (quoteTypeFound)
            continue;
        //add to StringBuffer
        char charAt = during.charAt(index);
        buf.append(charAt);
        index++;
        if (charAt == '\\') {
            if (index < during.length()) {
                buf.append(during.charAt(index));
                index++;
            }
        }
    }
    if (buf.length() > 0) {
        output = (String[]) ArrayUtils.add(output, buf.toString());
        buf = new StringBuffer();
    }
    //at end move over buf contents
    return output;
}

From source file:org.opencms.staticexport.CmsLinkManager.java

/**
 * Calculates a relative URI from "fromUri" to "toUri",
 * both URI must be absolute.<p>/*w w w .  ja v a 2s .c  om*/
 * 
 * @param fromUri the URI to start
 * @param toUri the URI to calculate a relative path to
 * @return a relative URI from "fromUri" to "toUri"
 */
public static String getRelativeUri(String fromUri, String toUri) {

    StringBuffer result = new StringBuffer();
    int pos = 0;

    while (true) {
        int i = fromUri.indexOf('/', pos);
        int j = toUri.indexOf('/', pos);
        if ((i == -1) || (i != j) || !fromUri.regionMatches(pos, toUri, pos, i - pos)) {
            break;
        }
        pos = i + 1;
    }

    // count hops up from here to the common ancestor
    for (int i = fromUri.indexOf('/', pos); i > 0; i = fromUri.indexOf('/', i + 1)) {
        result.append("../");
    }

    // append path down from common ancestor to there
    result.append(toUri.substring(pos));

    if (result.length() == 0) {
        // special case: relative link to the parent folder from a file in that folder
        result.append("./");
    }

    return result.toString();
}

From source file:org.openmrs.module.web.filter.ModuleFilterMapping.java

/**
 * Return <code>true</code> if the context-relative request path matches the patternToCheck
 * otherwise, return <code>false</code>.
 * //from  ww  w.  j  a  va 2 s . c  om
 * @param patternToCheck String pattern to check
 * @param requestPath to check
 * @should return false if the patternToCheck is null
 * @should return true if the pattern is *
 * @should return true if the pattern is /*
 * @should return true if the pattern matches the requestPath exactly
 * @should return true if the pattern matches everything up to a suffix of /*
 * @should return true if the pattern matches by extension
 * @should return false if no pattern matches
 */
public static boolean urlPatternMatches(String patternToCheck, String requestPath) {

    // Return false if patternToCheck is null
    if (patternToCheck == null) {
        return false;
    }

    log.debug("Checking URL <" + requestPath + "> against pattern <" + patternToCheck + ">");

    // Match exact or full wildcard
    if (patternToCheck.equals("*") || patternToCheck.equals("/*") || patternToCheck.equals(requestPath)) {
        return true;
    }

    // Match wildcard
    if (patternToCheck.endsWith("/*")) {
        int patternLength = patternToCheck.length() - 2;
        if (patternToCheck.regionMatches(0, requestPath, 0, patternLength)) {
            if (requestPath.length() == patternLength) {
                return true;
            } else if ('/' == requestPath.charAt(patternLength)) {
                return true;
            }
        }
        return false;
    }

    // Case 3 - Extension Match
    if (patternToCheck.startsWith("*.")) {
        int slash = requestPath.lastIndexOf('/');
        int period = requestPath.lastIndexOf('.');
        int reqLen = requestPath.length();
        int patLen = patternToCheck.length();

        if (slash >= 0 && period > slash && period != reqLen - 1 && reqLen - period == patLen - 1) {
            return (patternToCheck.regionMatches(2, requestPath, period + 1, patLen - 2));
        }
    }

    // If no match found by here, return false
    return false;
}

From source file:org.ireland.jnetty.dispatch.servlet.ServletMapper.java

/**
 * //from ww w .  j a  v  a 2 s .  c  o  m
 * @param requestPath
 * @param extensionPattern
 * @return
 */
private static boolean extensionPatternMatch(String requestPath, String extensionPattern) {

    if (extensionPattern == null)
        return (false);

    // Case 3 - Extension Match
    if (extensionPattern.startsWith("*.")) {
        int slash = requestPath.lastIndexOf('/');
        int period = requestPath.lastIndexOf('.');
        if ((slash >= 0) && (period > slash) && (period != requestPath.length() - 1)
                && ((requestPath.length() - period) == (extensionPattern.length() - 1))) {
            return (extensionPattern.regionMatches(2, requestPath, period + 1, extensionPattern.length() - 2));
        }
    }

    return (false);
}

From source file:Main.java

/**
 * Returns the path will relative path segments like ".." and "." resolved.
 * The returned path will not necessarily start with a "/" character. This
 * handles ".." and "." segments at both the beginning and end of the path.
 *
 * @param discardRelativePrefix true to remove leading ".." segments from
 *     the path. This is appropriate for paths that are known to be
 *     absolute.//w  w  w.j  a v  a  2 s.  c  o m
 */
public static String canonicalizePath(String path, boolean discardRelativePrefix) {
    // the first character of the current path segment
    int segmentStart = 0;

    // the number of segments seen thus far that can be erased by sequences of '..'.
    int deletableSegments = 0;

    for (int i = 0; i <= path.length();) {
        int nextSegmentStart;
        if (i == path.length()) {
            nextSegmentStart = i;
        } else if (path.charAt(i) == '/') {
            nextSegmentStart = i + 1;
        } else {
            i++;
            continue;
        }

        /*
         * We've encountered either the end of a segment or the end of the
         * complete path. If the final segment was "." or "..", remove the
         * appropriate segments of the path.
         */
        if (i == segmentStart + 1 && path.regionMatches(segmentStart, ".", 0, 1)) {
            // Given "abc/def/./ghi", remove "./" to get "abc/def/ghi".
            path = path.substring(0, segmentStart) + path.substring(nextSegmentStart);
            i = segmentStart;
        } else if (i == segmentStart + 2 && path.regionMatches(segmentStart, "..", 0, 2)) {
            if (deletableSegments > 0 || discardRelativePrefix) {
                // Given "abc/def/../ghi", remove "def/../" to get "abc/ghi".
                deletableSegments--;
                int prevSegmentStart = path.lastIndexOf('/', segmentStart - 2) + 1;
                path = path.substring(0, prevSegmentStart) + path.substring(nextSegmentStart);
                i = segmentStart = prevSegmentStart;
            } else {
                // There's no segment to delete; this ".." segment must be retained.
                i++;
                segmentStart = i;
            }
        } else {
            if (i > 0) {
                deletableSegments++;
            }
            i++;
            segmentStart = i;
        }
    }
    return path;
}

From source file:org.eclipse.mylyn.internal.jira.core.service.web.rss.JiraRssHandler.java

/**
 * Returns true if <code>unescaped</code> has HTML markup that can not be properly reverted to the original
 * representation./*from   www .j a  v a 2s  .co m*/
 * <p>
 * Public for testing.
 */
public static boolean hasMarkup(String unescaped) {
    // look for any tag that is not <br/> and not <a... or </a>
    int i = unescaped.indexOf("<"); //$NON-NLS-1$
    while (i != -1) {
        if (!(unescaped.regionMatches(i + 1, "br/>", 0, 4) || unescaped.regionMatches(i + 1, "a ", 0, 1) //$NON-NLS-1$//$NON-NLS-2$
                || unescaped.regionMatches(i + 1, "/a>", 0, 3))) { //$NON-NLS-1$
            return true;
        }
        i = unescaped.indexOf("<", i + 1); //$NON-NLS-1$
    }
    return false;
}

From source file:org.apache.sysml.runtime.io.IOUtilFunctions.java

/**
 * Counts the number of tokens defined by the given delimiter, respecting 
 * the rules for quotes and escapes defined in RFC4180.
 * //from www  .  ja  v a2s.  co  m
 * @param str string
 * @param delim delimiter
 * @return number of tokens split by the given delimiter
 */
public static int countTokensCSV(String str, String delim) {
    // check for empty input
    if (str == null || str.isEmpty())
        return 1;

    // scan string and compute num tokens
    int numTokens = 0;
    int from = 0, to = 0;
    int len = str.length();
    while (from < len) { // for all tokens
        if (str.charAt(from) == CSV_QUOTE_CHAR && str.indexOf(CSV_QUOTE_CHAR, from + 1) > 0) {
            to = str.indexOf(CSV_QUOTE_CHAR, from + 1);
            // handle escaped inner quotes, e.g. "aa""a"
            while (to + 1 < len && str.charAt(to + 1) == CSV_QUOTE_CHAR)
                to = str.indexOf(CSV_QUOTE_CHAR, to + 2); // to + ""
            to += 1; // last "
        } else if (str.regionMatches(from, delim, 0, delim.length())) {
            to = from; // empty string
        } else { // default: unquoted non-empty
            to = str.indexOf(delim, from + 1);
        }

        //increase counter and advance position
        to = (to >= 0) ? to : len;
        from = to + delim.length();
        numTokens++;
    }

    // handle empty string at end
    if (from == len)
        numTokens++;

    // return number of tokens
    return numTokens;
}