Example usage for java.lang StringBuilder replace

List of usage examples for java.lang StringBuilder replace

Introduction

In this page you can find the example usage for java.lang StringBuilder replace.

Prototype

@Override
public StringBuilder replace(int start, int end, String str) 

Source Link

Usage

From source file:Main.java

public static String replaceEntities(String s) {
    StringBuilder sb = new StringBuilder(s);
    int len = s.length();
    int skip = 0;
    int iSkip = 0;
    for (int i = 0; i < len; i++) {
        iSkip = i + skip;/* w  w  w.ja v  a2 s  .c  o  m*/
        char c = sb.charAt(iSkip);
        if (c == '&') {
            sb.replace(iSkip, iSkip + 1, "&amp;");
            skip += 4;
        } else if (c == '\'') {
            sb.replace(iSkip, iSkip + 1, "&apos;");
            skip += 5;
        } else if (c == '<') {
            sb.replace(iSkip, iSkip + 1, "&lt;");
            skip += 3;
        } else if (c == '>') {
            sb.replace(iSkip, iSkip + 1, "&gt;");
            skip += 3;
        } else if (c == '"') {
            sb.replace(iSkip, iSkip + 1, "&quot;");
            skip += 5;
        }
    }
    return sb.toString();
}

From source file:Main.java

public static String replace(String str, String[] targets, String[] replacements) {
    StringBuilder sb = new StringBuilder(str);

    int index, lenTarget;
    for (int i = 0; i < targets.length; i++) {
        index = sb.length();// w w  w.  j a  v a  2  s.co m
        lenTarget = targets[i].length();
        while ((index = sb.lastIndexOf(targets[i], index)) != -1) {
            sb.replace(index, index + lenTarget, replacements[i]);
            index -= lenTarget;
        }
    }

    return sb.toString();
}

From source file:org.medici.bia.common.util.UserRoleUtils.java

/**
 * /* ww w  .jav a2s .  co  m*/
 * @param userRoles
 * @return
 */
public static String toString(List<UserRole> userRoles) {
    StringBuilder stringBuilder = new StringBuilder("[");
    for (UserRole userRole : userRoles) {
        stringBuilder.append(userRole.getUserAuthority().toString());
        stringBuilder.append(',');
    }
    stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), "]");

    return stringBuilder.toString();
}

From source file:com.capitalone.dashboard.datafactory.jira.JiraDataFactoryImplTest.java

/**
 * Runs actions before test is initialized.
 * /*from  w  w w  .ja  v a  2  s .  co  m*/
 * @throws java.lang.Exception
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    logger.info("Beginning tests for com.capitalone.dashboard.datafactory.jira.JiraDataFactoryImpl");

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -3);
    yesterday = dateFormat.format(cal.getTime());
    StringBuilder canonicalYesterday = new StringBuilder(yesterday);
    canonicalYesterday.replace(10, 11, "%20");

    query = "search?jql=updatedDate%3E=%22" + canonicalYesterday + "%22+order+by+updated";
}

From source file:ext.sns.auth.OAuth2Client.java

/**
 * ??URI?Map/*from  w  w  w. j av a 2  s . c  o  m*/
 * 
 * @param uri ?URI
 * @return ?Map
 */
public static Map<String, String> getAuthBackParamByURI(String uri) {
    // ??URI1????&
    int countMatches = StringUtils.countMatches(uri, "?");
    if (countMatches > 1) {
        int firstIndex = uri.indexOf("?");

        StringBuilder uriBuilder = new StringBuilder(uri);
        for (int i = 0; i < countMatches - 1; ++i) {
            int start = uriBuilder.indexOf("?", firstIndex + 1);
            uriBuilder.replace(start, start + 1, "&");
        }
        uri = uriBuilder.toString();
    }

    String paramStr = uri.substring(uri.indexOf("?") + 1);

    Map<String, String> paramMap = new HashMap<String, String>();

    String[] pairArray = paramStr.split("&");
    for (String pair : pairArray) {
        String[] paramArray = pair.split("=");

        String val = paramArray.length == 2 ? paramArray[1] : "";
        paramMap.put(paramArray[0], val);
    }

    return paramMap;
}

From source file:wptools.cmds.FragToHtml.java

private static void gsub(StringBuilder buf, String old, String repl) {
    int len = old.length();
    int delta = repl.length();
    int pos = 0;/*from w w w  .  j a  v  a  2s  .c  o m*/
    while (true) {
        pos = buf.indexOf(old, pos);
        if (pos < 0)
            break;
        buf.replace(pos, pos + len, repl);
        pos += delta;
    }
}

From source file:Main.java

/**
 * Make a replacement of first "find" string by "replace" string into the StringBuilder
 * //www.j a v  a2s.c  o  m
 * @param builder
 * @param find
 * @param replace
 * @return True if one element is found
 */
public final static boolean replace(StringBuilder builder, String find, String replace) {
    if (find == null) {
        return false;
    }
    int start = builder.indexOf(find);
    if (start == -1) {
        return false;
    }
    int end = start + find.length();
    if (replace != null) {
        builder.replace(start, end, replace);
    } else {
        builder.replace(start, end, "");
    }
    return true;
}

From source file:oscar.eform.data.DatabaseAP.java

public static String parserClean(String str) {
    //removes left over ${...} in str; replaces with ""
    StringBuilder strb = new StringBuilder(str);
    int tagstart = -2;
    int tagend;// w w  w  .  ja  va 2s. com
    while ((tagstart = strb.indexOf("${", tagstart + 2)) >= 0) {
        strb.replace(tagstart, tagstart + 2, "\"");
        tagend = strb.indexOf("}", tagstart);
        strb.replace(tagend, tagend + 2, "\"");
    }
    return strb.toString();
}

From source file:com.zjy.mongo.splitter.MongoCollectionSplitter.java

/**
 * Takes an existing {@link MongoClientURI} and returns a new modified URI which replaces the original's server host + port with a
 * supplied new server host + port, but maintaining all the same original options. This is useful for generating distinct URIs for each
 * mongos instance so that large batch reads can all target them separately, distributing the load more evenly. It can also be used to
 * force a block of data to be read directly from the shard's servers directly, bypassing mongos entirely.
 *
 * @param originalUri  the URI to rewrite
 * @param newServerUri the new host(s) to target, e.g. server1:port1[,server2:port2,...]
 * @return the rewritten URI//from w  w  w  . ja  v a2s. c o  m
 */
protected static MongoClientURI rewriteURI(final MongoClientURI originalUri, final String newServerUri) {
    String originalUriString = originalUri.toString();
    originalUriString = originalUriString.substring(MongoURI.MONGODB_PREFIX.length());

    // uris look like: mongodb://fred:foobar@server1[,server2]/path?options
    //

    //Locate the last character of the original hostname
    int serverEnd;
    int idx = originalUriString.lastIndexOf("/");
    serverEnd = idx < 0 ? originalUriString.length() : idx;

    //Locate the first character of the original hostname
    idx = originalUriString.indexOf("@");
    int serverStart = idx > 0 ? idx + 1 : 0;

    StringBuilder sb = new StringBuilder(originalUriString);
    sb.replace(serverStart, serverEnd, newServerUri);
    return new MongoClientURI(MongoURI.MONGODB_PREFIX + sb);
}

From source file:org.apache.jmeter.protocol.http.util.ConversionUtils.java

/**
 * collapses absolute or relative URLs containing '/..' converting
 * <code>http://host/path1/../path2</code> to <code>http://host/path2</code>
 * or <code>/one/two/../three</code> to
 * <code>/one/three</code>//from   w  w  w. j  a  v  a  2 s. c  o  m
 * 
 * @param url in which the '/..'s should be removed
 * @return collapsed URL
 * @see <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=49083">Bug 49083 - collapse /.. in redirect URLs</a>
 */
public static String removeSlashDotDot(String url) {
    if (url == null || (url = url.trim()).length() < 4 || !url.contains(SLASHDOTDOT)) {
        return url;
    }

    /**
     * http://auth@host:port/path1/path2/path3/?query#anchor
     */

    // get to 'path' part of the URL, preserving schema, auth, host if
    // present

    // find index of path start

    int dotSlashSlashIndex = url.indexOf(COLONSLASHSLASH);
    final int pathStartIndex;
    if (dotSlashSlashIndex >= 0) {
        // absolute URL
        pathStartIndex = url.indexOf(SLASH, dotSlashSlashIndex + COLONSLASHSLASH.length());
    } else {
        // document or context-relative URL like:
        // '/path/to'
        // OR '../path/to'
        // OR '/path/to/../path/'
        pathStartIndex = 0;
    }

    // find path endIndex
    int pathEndIndex = url.length();

    int questionMarkIdx = url.indexOf('?');
    if (questionMarkIdx > 0) {
        pathEndIndex = questionMarkIdx;
    } else {
        int anchorIdx = url.indexOf('#');
        if (anchorIdx > 0) {
            pathEndIndex = anchorIdx;
        }
    }

    // path is between idx='pathStartIndex' (inclusive) and
    // idx='pathEndIndex' (exclusive)
    String currentPath = url.substring(pathStartIndex, pathEndIndex);

    final boolean startsWithSlash = currentPath.startsWith(SLASH);
    final boolean endsWithSlash = currentPath.endsWith(SLASH);

    StringTokenizer st = new StringTokenizer(currentPath, SLASH);
    List<String> tokens = new ArrayList<>();
    while (st.hasMoreTokens()) {
        tokens.add(st.nextToken());
    }

    for (int i = 0; i < tokens.size(); i++) {
        if (i < tokens.size() - 1) {
            final String thisToken = tokens.get(i);

            // Verify for a ".." component at next iteration
            if (thisToken.length() > 0 && !thisToken.equals(DOTDOT) && tokens.get(i + 1).equals(DOTDOT)) {
                tokens.remove(i);
                tokens.remove(i);
                i = i - 2;
                if (i < -1) {
                    i = -1;
                }
            }
        }

    }

    StringBuilder newPath = new StringBuilder();
    if (startsWithSlash) {
        newPath.append(SLASH);
    }
    for (int i = 0; i < tokens.size(); i++) {
        newPath.append(tokens.get(i));

        // append '/' if this isn't the last token or it is but the original
        // path terminated w/ a '/'
        boolean appendSlash = i < (tokens.size() - 1) ? true : endsWithSlash;
        if (appendSlash) {
            newPath.append(SLASH);
        }
    }

    // install new path
    StringBuilder s = new StringBuilder(url);
    s.replace(pathStartIndex, pathEndIndex, newPath.toString());
    return s.toString();
}