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:org.ambraproject.service.search.SolrSearchService.java

private String createFilterLimitForArticleTypes(String[] articleTypes) {
    Arrays.sort(articleTypes); // Consistent order so that each filter will only be cached once.
    StringBuilder fq = new StringBuilder();
    for (String articleType : articleTypes) {
        fq.append("article_type:\"").append(articleType).append("\" OR ");
    }/*from  www.ja v a2 s. c  o  m*/
    return fq.replace(fq.length() - 4, fq.length(), "").toString(); // Remove last " OR".
}

From source file:org.jahia.services.render.filter.cache.AggregateCacheFilter.java

private int replaceInContent(StringBuilder sb, int start, int end, String replacement) {
    if (replacement == null) {
        replacement = "";
    }//from  w  w w. ja  v  a 2  s. co  m
    sb.replace(start, end, replacement);
    return sb.indexOf(CACHE_ESI_TAG_START, start + replacement.length());
}

From source file:org.jivesoftware.util.StringUtils.java

/**
 * Reformats a string where lines that are longer than <tt>width</tt>
 * are split apart at the earliest wordbreak or at maxLength, whichever is
 * sooner. If the width specified is less than 5 or greater than the input
 * Strings length the string will be returned as is.
 * <p>//  w  ww  .  j  ava2 s .  c o  m
 * Please note that this method can be lossy - trailing spaces on wrapped
 * lines may be trimmed.</p>
 *
 * @param input the String to reformat.
 * @param width the maximum length of any one line.
 * @return a new String with reformatted as needed.
 */
public static String wordWrap(String input, int width, Locale locale) {
    // protect ourselves
    if (input == null) {
        return "";
    } else if (width < 5) {
        return input;
    } else if (width >= input.length()) {
        return input;
    }

    // default locale
    if (locale == null) {
        locale = JiveGlobals.getLocale();
    }

    StringBuilder buf = new StringBuilder(input);
    boolean endOfLine = false;
    int lineStart = 0;

    for (int i = 0; i < buf.length(); i++) {
        if (buf.charAt(i) == '\n') {
            lineStart = i + 1;
            endOfLine = true;
        }

        // handle splitting at width character
        if (i > lineStart + width - 1) {
            if (!endOfLine) {
                int limit = i - lineStart - 1;
                BreakIterator breaks = BreakIterator.getLineInstance(locale);
                breaks.setText(buf.substring(lineStart, i));
                int end = breaks.last();

                // if the last character in the search string isn't a space,
                // we can't split on it (looks bad). Search for a previous
                // break character
                if (end == limit + 1) {
                    if (!Character.isWhitespace(buf.charAt(lineStart + end))) {
                        end = breaks.preceding(end - 1);
                    }
                }

                // if the last character is a space, replace it with a \n
                if (end != BreakIterator.DONE && end == limit + 1) {
                    buf.replace(lineStart + end, lineStart + end + 1, "\n");
                    lineStart = lineStart + end;
                }
                // otherwise, just insert a \n
                else if (end != BreakIterator.DONE && end != 0) {
                    buf.insert(lineStart + end, '\n');
                    lineStart = lineStart + end + 1;
                } else {
                    buf.insert(i, '\n');
                    lineStart = i + 1;
                }
            } else {
                buf.insert(i, '\n');
                lineStart = i + 1;
                endOfLine = false;
            }
        }
    }

    return buf.toString();
}

From source file:org.meveo.admin.action.BaseBean.java

/**
 * TODO// ww w .  j  a va 2  s  .  c  o m
 */
public String getEditViewName() {
    String className = clazz.getSimpleName();
    StringBuilder sb = new StringBuilder(className);
    sb.append("Detail");
    char[] dst = new char[1];
    sb.getChars(0, 1, dst, 0);
    sb.replace(0, 1, new String(dst).toLowerCase());
    return sb.toString();
}

From source file:org.kuali.rice.krad.data.jpa.NativeJpaQueryTranslator.java

/**
 * Fixes the search pattern by converting all non-escaped lookup wildcards ("*" and "?") into their respective JPQL
 * wildcards ("%" and "_").//from   w  w  w.  ja v  a  2  s . co  m
  *
  * <p>Any lookup wildcards escaped by a backslash are converted into their non-backslashed equivalents.</p>
  *
  * @param value the search pattern to fix.
  * @return a fixed search pattern.
 */
protected String fixSearchPattern(String value) {
    StringBuilder fixedPattern = new StringBuilder(value);
    // Convert all non-escaped wildcards.
    for (int i = 0; i < LOOKUP_WILDCARDS.length; i++) {
        String lookupWildcard = LOOKUP_WILDCARDS[i];
        String escapedLookupWildcard = ESCAPED_LOOKUP_WILDCARDS[i];
        char jpqlWildcard = JPQL_WILDCARDS[i];
        int wildcardIndex = fixedPattern.indexOf(lookupWildcard);
        int escapedWildcardIndex = fixedPattern.indexOf(escapedLookupWildcard);
        while (wildcardIndex != -1) {
            if (wildcardIndex == 0 || escapedWildcardIndex != wildcardIndex - 1) {
                fixedPattern.setCharAt(wildcardIndex, jpqlWildcard);
                wildcardIndex = fixedPattern.indexOf(lookupWildcard, wildcardIndex);
            } else {
                fixedPattern.replace(escapedWildcardIndex, wildcardIndex + 1, lookupWildcard);
                wildcardIndex = fixedPattern.indexOf(lookupWildcard, wildcardIndex);
                escapedWildcardIndex = fixedPattern.indexOf(escapedLookupWildcard, wildcardIndex);
            }
        }
    }
    return fixedPattern.toString();
}

From source file:org.wso2.am.integration.ui.tests.APIMANAGER3272ExternalLogoutPageTestCase.java

private boolean editStoreConfig(String externalLogoutPage) {
    String serverRoot = System.getProperty(ServerConstants.CARBON_HOME);
    String deploymentPath = serverRoot + getStoreSiteConfPath();
    File file = new File(deploymentPath);
    StringBuilder content = new StringBuilder();
    try {/*from w w w  .  ja va 2 s  .  c om*/
        if (file.exists()) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file), "UTF-8"));
            try {
                while (reader.ready()) {
                    content.append(reader.readLine() + "\r\n");
                }
            } finally {
                reader.close();
            }

            int ssoConfigIndex = content.indexOf("ssoConfiguration");

            if (ssoConfigIndex > -1) {
                String ssoConfigElement = content.substring(ssoConfigIndex);
                log.debug("SSO Configuration before editing : " + ssoConfigElement);
                int originalLength = ssoConfigElement.length();
                ssoConfigElement = ssoConfigElement
                        .replaceFirst("\"enabled\" : \"false\"", "\"enabled\" : \"true\"")
                        .replaceAll("\"keyStorePassword\" : \"[a-zA-Z0-9]*\"", "\"keyStorePassword\" : \"\"");
                ssoConfigElement.concat("\"externalLogoutPage\" : " + externalLogoutPage);
                content.replace(ssoConfigIndex, originalLength, ssoConfigElement);
                String jsonConfig = content.toString();
                log.debug("SSO Configuration after editing : " + jsonConfig);

                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
                try {
                    writer.write(jsonConfig);
                } finally {
                    writer.close();
                }
                return true;
            }
        }

    } catch (IOException ex) {
        log.error("Exception occurred while file reading or writing " + ex);
    }

    return false;
}

From source file:by.heap.remark.convert.TextCleaner.java

/**
 * Configures the basic replacements based on the configured options.
 * @param options Options that will affect what is replaced.
 *//*from   ww  w.j a va 2  s . co m*/
@SuppressWarnings({ "OverlyLongMethod" })
private void setupReplacements(Options options) {
    this.replacements = new HashMap<String, String>();

    // build replacement regex
    StringBuilder entities = new StringBuilder(replacements.size() * 5);

    // this is a special case for double-encoded HTML entities.
    entities.append("&(?>amp;([#a-z0-9]++;)|(?>");
    addRepl(entities, "&amp;", "&");
    addRepl(entities, "&lt;", "<");
    addRepl(entities, "&gt;", ">");
    addRepl(entities, "&quot;", "\"");
    if (options.reverseHtmlSmartQuotes) {
        addRepl(entities, "&ldquo;", "\"");
        addRepl(entities, "&rdquo;", "\"");
        addRepl(entities, "&lsquo;", "\'");
        addRepl(entities, "&rsquo;", "\'");
        addRepl(entities, "&apos;", "\'");
        addRepl(entities, "&laquo;", "<<");
        addRepl(entities, "&raquo;", ">>");
    }
    if (options.reverseHtmlSmartPunctuation) {
        addRepl(entities, "&ndash;", "--");
        addRepl(entities, "&mdash;", "---");
        addRepl(entities, "&hellip;", "...");
    }
    entities.replace(entities.length() - 1, entities.length(), ");)");

    entityReplacementsPattern = Pattern.compile(entities.toString(), Pattern.CASE_INSENSITIVE);

    if (options.reverseUnicodeSmartPunctuation || options.reverseUnicodeSmartQuotes) {
        StringBuilder unicode = new StringBuilder("[\\Q");
        if (options.reverseUnicodeSmartQuotes) {
            addRepl(unicode, "\u201c", "\""); // left double quote: 
            addRepl(unicode, "\u201d", "\""); // right double quote: ?
            addRepl(unicode, "\u2018", "\'"); // left single quote: 
            addRepl(unicode, "\u2019", "\'"); // right single quote: 
            addRepl(unicode, "\u00ab", "<<"); // left angle quote: 
            addRepl(unicode, "\u00bb", ">>"); // right angle quote: 
        }
        if (options.reverseUnicodeSmartPunctuation) {
            addRepl(unicode, "\u2013", "--"); // en-dash: 
            addRepl(unicode, "\u2014", "---"); // em-dash: 
            addRepl(unicode, "\u2026", "..."); // ellipsis: 
        }
        unicode.append("\\E]");
        unicodeReplacementsPattern = Pattern.compile(unicode.toString());
    }
}

From source file:com.laxser.blitz.util.PlaceHolderUtils.java

public static String resolve(String text, Invocation inv) {
    if (StringUtils.isEmpty(text)) {
        return text;
    }//from  w  w w .  jav  a2  s .  com
    int startIndex = text.indexOf(PLACEHOLDER_PREFIX);
    if (startIndex == -1) {
        return text;
    }
    StringBuilder buf = new StringBuilder(text);
    while (startIndex != -1) {
        int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length());
        if (endIndex != -1) {
            String placeholder = null;
            String defaultValue = null;
            for (int i = startIndex + PLACEHOLDER_PREFIX.length(); i < endIndex; i++) {
                if (buf.charAt(i) == '?') {
                    placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), i);
                    defaultValue = buf.substring(i + 1, endIndex);
                    break;
                }
            }
            if (placeholder == null) {
                placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
            }
            int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length();
            try {
                int dot = placeholder.indexOf('.');
                String attributeName = dot == -1 ? placeholder : placeholder.substring(0, dot);
                String propertyPath = dot == -1 ? "" : placeholder.substring(dot + 1);
                Object propVal = inv.getModel().get(attributeName);
                if (propVal != null) {
                    if (propertyPath.length() > 0) {
                        propVal = new BeanWrapperImpl(propVal).getPropertyValue(propertyPath);
                    }
                } else {
                    if ("flash".equals(attributeName)) {
                        propVal = inv.getFlash().get(propertyPath);
                    } else {
                        propVal = inv.getParameter(placeholder);
                    }
                }
                //
                if (propVal == null) {
                    propVal = defaultValue;
                }
                if (propVal == null) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not resolve placeholder '" + placeholder + "' in [" + text + "].");
                    }
                } else {
                    String toString = propVal.toString();
                    buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), toString);
                    nextIndex = startIndex + toString.length();
                }
            } catch (Throwable ex) {
                logger.warn("Could not resolve placeholder '" + placeholder + "' in [" + text + "] : " + ex);
            }
            startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex);
        } else {
            startIndex = -1;
        }
    }

    return buf.toString();
}

From source file:org.colombbus.tangara.Configuration.java

private void addClassPathToScriptEngine(File jarFile) throws ConfigurationException {
    try {/*from   www . ja  v  a  2  s .co  m*/
        StringBuilder cmd = new StringBuilder(addClassPathCmd);
        int tagStartPos = cmd.indexOf(parameterTag);
        int tageEndPos = tagStartPos + parameterTag.length();
        cmd.replace(tagStartPos, tageEndPos, jarFile.getAbsolutePath().replace("\\", "/"));
        // System.out.println("cmd " + cmd.toString());
        engine.eval("add-classpath", 1, 1, cmd.toString()); //$NON-NLS-1$
    } catch (Exception ex) {
        String msg = String.format("Failed to load class path %s", jarFile.getName()); //$NON-NLS-1$
        System.err.println(msg + " " + ex);
        throw new ConfigurationException(msg, ex);
    }
}

From source file:org.colombbus.tangara.Configuration.java

/**
 * Imports a package into the script engine
 *
 * @param pkgName/*from ww w.j  a v  a 2  s. co m*/
 *            the name of the package
 * @throws ConfigurationException
 *             if the package cannot be imported
 */
private void importPkgToScriptEngine(String pkgName) throws ConfigurationException {
    try {
        StringBuilder cmd = new StringBuilder(importPackageCmd);
        int tagStartPos = cmd.indexOf(parameterTag);
        int tageEndPos = tagStartPos + parameterTag.length();
        cmd.replace(tagStartPos, tageEndPos, pkgName);
        // System.out.println("cmd " + cmd.toString());
        engine.eval("load-packages", 1, 1, cmd.toString()); //$NON-NLS-1$
    } catch (Exception ex) {
        String msg = String.format("Failed to import package %s", pkgName); //$NON-NLS-1$
        System.err.println(msg + " " + ex);
        throw new ConfigurationException(msg, ex);
    }
}