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:com.ferdi2005.secondgram.AndroidUtilities.java

public static SpannableStringBuilder replaceTags(String str, int flag) {
    try {// ww  w . j a va  2 s .  c o  m
        int start;
        int end;
        StringBuilder stringBuilder = new StringBuilder(str);
        if ((flag & FLAG_TAG_BR) != 0) {
            while ((start = stringBuilder.indexOf("<br>")) != -1) {
                stringBuilder.replace(start, start + 4, "\n");
            }
            while ((start = stringBuilder.indexOf("<br/>")) != -1) {
                stringBuilder.replace(start, start + 5, "\n");
            }
        }
        ArrayList<Integer> bolds = new ArrayList<>();
        if ((flag & FLAG_TAG_BOLD) != 0) {
            while ((start = stringBuilder.indexOf("<b>")) != -1) {
                stringBuilder.replace(start, start + 3, "");
                end = stringBuilder.indexOf("</b>");
                if (end == -1) {
                    end = stringBuilder.indexOf("<b>");
                }
                stringBuilder.replace(end, end + 4, "");
                bolds.add(start);
                bolds.add(end);
            }
        }
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder);
        for (int a = 0; a < bolds.size() / 2; a++) {
            spannableStringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")),
                    bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableStringBuilder;
    } catch (Exception e) {
        FileLog.e(e);
    }
    return new SpannableStringBuilder(str);
}

From source file:org.jahia.services.render.filter.AggregateFilter.java

/**
 * Aggregate the content that are inside the fragment to get a full HTML content with all sub modules embedded.
 *
 * @param content The fragment/*  w  w w . jav a2  s .c o m*/
 * @param renderContext The render context
 */
protected String aggregateContent(String content, RenderContext renderContext) throws RenderException {
    int esiTagStartIndex = content.indexOf(ESI_TAG_START);
    if (esiTagStartIndex == -1) {
        return content;
    } else {
        StringBuilder sb = new StringBuilder(content);
        while (esiTagStartIndex != -1) {
            int esiTagEndIndex = sb.indexOf(ESI_TAG_END, esiTagStartIndex);
            if (esiTagEndIndex != -1) {
                String replacement = generateContent(renderContext,
                        sb.substring(esiTagStartIndex + ESI_TAG_START.length(), esiTagEndIndex));
                if (replacement == null) {
                    replacement = "";
                }
                sb.replace(esiTagStartIndex, esiTagEndIndex + ESI_TAG_END_LENGTH, replacement);
                esiTagStartIndex = sb.indexOf(ESI_TAG_START, esiTagStartIndex + replacement.length());
            } else {
                // no closed esi end tag found
                return sb.toString();
            }
        }
        return sb.toString();
    }
}

From source file:dsfixgui.configs.DSFConfiguration.java

public void loadSettingsFromIniFile(String filePath) {

    File in = new File(filePath);
    String iniExt = DSF_FILES[1].substring(DSF_FILES[1].lastIndexOf('.'));
    int settingsChanged = 0;

    //Check for .ini file type
    if (iniExt.equals(filePath.substring(filePath.lastIndexOf('.')))) {
        try {/*from  www  .  j  a va  2  s. com*/
            fileInput = new Scanner(in);
            String line = " ";
            boolean verifiedIniFile = false;
            while (settingsChanged < TOTAL_SETTINGS && fileInput.hasNextLine()) {
                line = fileInput.nextLine();

                //Make sure it's a DSfix ini file and not just some random .ini
                if (settingsChanged == 0 && !verifiedIniFile && !line.equals(DSF_VERIFICATION)) {
                    ui.printConsole(in.getName() + INVALID_DSF_INI);
                    ui.printConsole(CONFIG_NOT_LOADED);
                    return;
                } else if (settingsChanged == 0 && !verifiedIniFile && line.equals(DSF_VERIFICATION)) {
                    verifiedIniFile = true;
                }

                if (line.length() > 1 && line.charAt(0) != '\n' && line.charAt(0) != '#') {
                    //Check for special settings that have special limitations
                    //This might actually be unecessary now (the mutator methods used to make changes based on certain limitations that I've since removed)
                    if (settingsChanged == 2 || settingsChanged == 3 || settingsChanged == 9) {
                        switch (settingsChanged) {
                        case 2:
                            setPresentWidth(
                                    Integer.parseInt(line.substring(line.indexOf(' ') + 1, line.length())));
                            break;
                        case 3:
                            setPresentHeight(
                                    Integer.parseInt(line.substring(line.indexOf(' ') + 1, line.length())));
                            break;
                        case 9:
                            setDOFOverride(
                                    Integer.parseInt(line.substring(line.indexOf(' ') + 1, line.length())));
                            break;
                        default:
                            break;
                        }
                        //Check for int valued setting
                    } else if (INT_VALUE_NAMES[settingsChanged] != null) {
                        //Change int value
                        AtomicInteger intVal = (AtomicInteger) settings.get(settingsChanged);
                        intVal.set(Integer.parseInt(line.substring(line.indexOf(' ') + 1, line.length())));
                        //Check for StringBuilder valued setting
                    } else {
                        //Change StringBuilder value
                        StringBuilder stringVal = (StringBuilder) settings.get(settingsChanged);
                        stringVal.replace(0, stringVal.length(), ("" + line.substring(line.indexOf(' ') + 1)));
                        if (settingsChanged == 11) {
                        }
                    }
                    settingsChanged++;
                }
            }

        } catch (FileNotFoundException ex) {
            //Logger.getLogger(DSFConfiguration.class.getName()).log(Level.SEVERE, null, ex);
            ui.printConsole(in.getName() + DSFGUI_FILE_NOT_FOUND);
        }
    } else {
        ui.printConsole(in.getName() + INVALID_FILETYPE_ERR + iniExt);
        ui.printConsole(CONFIG_NOT_LOADED);
    }

    if (settingsChanged != TOTAL_SETTINGS) {
        ui.printConsole(CONFIG_PARTIALLY_LOADED);
        ui.resetDSFConfigDefaults();
    } else {
        ui.printConsole(SETTINGS_LOADED);
    }

    if (fileInput != null) {
        fileInput.close();
    }

    if (dofOverrideResolution.get() == renderHeight.get() && presentWidth.get() == renderWidth.get()
            && presentHeight.get() == renderHeight.get() && disableDofScaling.get() == 1
            && dofBlurAmount.toString().equals("o")) {
        disableDOF = true;
    } else {
        disableDOF = false;
    }

    initSettingsList();
}

From source file:oscar.oscarLab.ca.all.parsers.MEDVUEHandler.java

public String getOBXComment(int i, int j, int k) {
    String comment = "", newComment = "";
    int len = 80;
    String[] splitComment;//from  ww w . java 2  s  .  com
    String concatComment = "";

    try {
        Terser terser = new Terser(msg);
        comment = Terser.get(obxseg, 5, 0, 1, 1);
        comment = comment.replaceAll("<P\\s*/*>", "<br/>");
        splitComment = comment.split("<br/>");

        for (int l = 0; l < splitComment.length; l++) {
            if (splitComment[l].length() > len) {
                StringBuilder sb = new StringBuilder(splitComment[l]);
                int i1 = 0;
                while ((i1 = sb.indexOf(" ", i1 + len)) != -1) {
                    sb.replace(i1, i1 + 1, "<br/>");

                }

                concatComment = sb.toString();
            }

            if (!concatComment.equals("")) {
                newComment += "<br/>" + concatComment.toString();
            } else {
                newComment += "<br/>" + splitComment[l].toString();
            }
            concatComment = "";

        }

        logger.info("Modified comment =" + newComment);
        return newComment;

    } catch (Exception e) {
        logger.error("getOBRComment error", e);
        return "";
    }
    //return comment;
}

From source file:com.amazonaws.services.kinesis.connectors.redshift.RedshiftManifestEmitter.java

/**
 * Format for Amazon Redshift Manifest File:
 * //from  w ww.  jav a 2  s .c  o m
 * <pre>
 * {
 *    "entries": [
 *       {"url":"s3://s3Bucket/file1","mandatory":true},
 *       {"url":"s3://s3Bucket/file2","mandatory":true},
 *       {"url":"s3://s3Bucket/file3","mandatory":true}
 *    ]
 * }
 * 
 * </pre>
 * 
 * 
 * @param files
 * @return String representation of Amazon S3 manifest file
 */
private String generateManifestFile(List<String> files) {
    StringBuilder s = new StringBuilder();
    s.append("{\n");
    s.append("\t\"entries\": [\n");
    for (String file : files) {
        s.append("\t\t{");
        s.append("\"url\":\"s3://");
        s.append(s3Bucket);
        s.append("/");
        s.append(file);
        s.append("\"");
        s.append(",");
        s.append("\"mandatory\":" + Boolean.toString(copyMandatory));
        s.append("},\n");
    }
    s.replace(s.length() - 2, s.length() - 1, "");
    s.append("\t]\n");
    s.append("}\n");
    return s.toString();
}

From source file:edu.ku.brc.af.ui.forms.BrowserLauncherBtn.java

protected void buildAndOpenURL() {
    StringBuilder urlBuilder = new StringBuilder(url);

    if (url.startsWith("[")) {
        // replace the URL prefix ([prefix]) at the start with the value from the DB 
        AppPreferences remotePrefs = AppPreferences.getRemote();

        int endingBracketIndex = urlBuilder.indexOf("]");
        String urlPrefix = urlBuilder.substring(1, endingBracketIndex);
        String urlPrefixValue = remotePrefs.get("URL_Prefix." + urlPrefix, null);

        if (urlPrefixValue == null) {
            String errorMsg = String.format(getResourceString("WLLB_CANNOT_BUILD_URL"),
                    new Object[] { urlPrefix });
            UIRegistry.getStatusBar().setErrorMessage(errorMsg);
            return;
        }/*from  w  ww  . j av  a 2s  .  co  m*/
        urlBuilder.replace(0, endingBracketIndex + 1, urlPrefixValue);
    }

    try {
        AttachmentUtils.openURI(new URI(urlBuilder.toString()));
    } catch (Exception e) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BrowserLauncherBtn.class, e);
        String errorMsg = String.format(getResourceString("ERROR_CANT_OPEN_URL"),
                new Object[] { urlBuilder.toString() });
        UIRegistry.getStatusBar().setErrorMessage(errorMsg, e);
    }
}

From source file:org.apache.sling.commons.cache.impl.AbstractCacheManagerService.java

protected InputStream processConfig(InputStream in, Map<String, Object> properties) throws IOException {
    if (in == null) {
        return null;
    }/*from   www .  ja va  2s . c o m*/
    StringBuilder config = new StringBuilder(IOUtils.toString(in, "UTF-8"));
    in.close();
    int pos = 0;
    for (;;) {
        int start = config.indexOf("${", pos);
        if (start < 0) {
            break;
        }
        int end = config.indexOf("}", start);
        if (end < 0) {
            throw new IllegalArgumentException("Config file malformed, unterminated variable "
                    + config.substring(start, Math.min(start + 10, config.length())));
        }
        String key = config.substring(start + 2, end);
        if (properties.containsKey(key)) {
            String replacement = (String) properties.get(key);
            config.replace(start, end + 1, replacement);
            pos = start + replacement.length();
        } else {
            throw new IllegalArgumentException("Missing replacement property " + key);
        }
    }
    return new ByteArrayInputStream(config.toString().getBytes("UTF-8"));

}

From source file:org.jspringbot.keyword.db.DbHelper.java

private String sqlSubstitute(String queryString) {
    StringBuilder buf = new StringBuilder(queryString);

    Matcher matcher = NAMED_PARAMETER_PATTERN.matcher(buf);

    int index = 0;
    while (matcher.find(index)) {
        String param = matcher.group().substring(1);
        if (literalSubstitution.containsKey(param)) {
            String replacement = literalSubstitution.get(param);
            buf.replace(matcher.start(), matcher.end(), replacement);

            index = matcher.start() + replacement.length();
        } else {/*from w  ww  . j  a  v a2 s .  c o  m*/
            index = matcher.end();
        }
    }

    return buf.toString();
}

From source file:com.coroptis.coidi.core.message.AbstractMessage.java

protected StringBuilder concatEntries(final String keyPrefix, final String separator, final String lineEnds)
        throws UnsupportedEncodingException {
    StringBuilder buff = new StringBuilder();
    for (Entry<String, String> entry : map.entrySet()) {
        if (keyPrefix != null) {
            buff.append(keyPrefix);/*w  ww . j av a 2  s . c om*/
        }
        buff.append(entry.getKey());
        buff.append(separator);
        if (isUrl) {
            if (entry.getValue() != null) {
                buff.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
        } else {
            if (entry.getValue() != null) {
                buff.append(entry.getValue());
            }
        }
        buff.append(lineEnds);
    }
    buff = buff.replace(buff.length() - lineEnds.length(), buff.length(), "");
    return buff;
}

From source file:au.org.ala.delta.util.Utils.java

/**
 * The main job of this method is to terminate RTF control words with {}
 * instead of a space.//from   ww w . j a  v a 2s. c o  m
 */
// Not all cases are handled correctly in the current code.
// For example, text with \bin might not always give correct results
// A few other things, such as \'xx, should perhaps also be given
// explicit treatment, but should not substantially affect the outcome.
public static String despaceRtf(String text, boolean quoteDelims) {
    if (StringUtils.isEmpty(text)) {
        return "";
    }
    int srcPos;
    boolean inRTF = false;
    boolean inParam = false;
    boolean inUnicode = false;
    boolean bracketed = text.charAt(0) == '<' && text.charAt(text.length() - 1) == '>';

    StringBuilder outputText = new StringBuilder(text);
    if (bracketed) // If a "comment", temporarily chop off the terminating
                   // bracket
        outputText.setLength(outputText.length() - 1);
    for (srcPos = 0; srcPos < outputText.length(); ++srcPos) {
        char ch = outputText.charAt(srcPos);
        // Always convert a tab character into a \tab control word
        if (ch == '\t') {
            outputText.replace(srcPos, srcPos + 1, "\\tab{}");
            ch = '\\';
        }
        if (inRTF) {
            if (Character.isDigit(ch) || (!inParam && ch == '-')) {
                if (!inParam && outputText.charAt(srcPos - 1) == 'u' && outputText.charAt(srcPos - 2) == '\\')
                    inUnicode = true;
                inParam = true;
            } else if (inParam || !Character.isLetter(ch)) {
                boolean wasInUnicode = inUnicode;
                inUnicode = inParam = inRTF = false;
                if (Character.isSpaceChar(ch)) {
                    // Check for the absence of a control; when this
                    // happens,
                    // the terminating character IS the control word!
                    if (srcPos > 0 && outputText.charAt(srcPos - 1) == '\\') {
                        // \<NEWLINE> is treated as a \par control. We make
                        // this
                        // change here explicitly, to make it more apparent.
                        // But should we keep the <NEWLINE> character around
                        // as well,
                        // as a clue for breaking lines during output?
                        if (ch == '\n' || ch == '\r') {
                            // text.replace(--srcPos, 2, "\\par{}");
                            outputText.insert(srcPos, "par{}");
                            srcPos += 5;
                        }
                        // (Note that if we don't catch this here, replacing
                        // "\ " could yield
                        // "\{}" which is WRONG. But rather than just get
                        // rid of this, it
                        // is probably better to replace with {} to ensure
                        // that any preceding
                        // RTF is terminated)
                        else if (ch == ' ') {
                            outputText.replace(srcPos - 1, 2, "{}");
                        }
                    }
                    // This is the chief condition we are trying to fix.
                    // Terminate the RTF
                    // control phrase with {} instead of white space...
                    // But if the terminator is a new line, we keep it
                    // around
                    // for assistance in wrapping output lines.
                    // else if (ch == '\n')
                    // {
                    // text.insert(srcPos, "{}");
                    // srcPos += 2;
                    // }
                    else if (ch != '\n') {
                        outputText.setCharAt(srcPos, '{');
                        outputText.insert(++srcPos, '}');
                    }
                }
                // No reason to do the following. Probably better to leave
                // the
                // character quoted.
                // Reinstated 8 December 1999 because we need to be sure
                // all text is in a consistent state when linking characters
                // One exception - if the quoted character is a Unicode
                // "replacement"
                // character, we'd better leave it quoted.
                else if (ch == '\'' && !wasInUnicode && srcPos + 2 < outputText.length()) {
                    char[] buff = new char[3];
                    buff[0] = outputText.charAt(srcPos + 1);
                    buff[1] = outputText.charAt(srcPos + 2);
                    buff[2] = 0;

                    int[] endPos = new int[1];
                    int value = strtol(new String(buff), endPos, 16);
                    if ((endPos[0] == 2) && value > 127 && outputText.charAt(srcPos - 1) == '\\') {

                        srcPos--;
                        outputText.replace(srcPos, srcPos + 4, new String(new char[] { (char) value }));

                    }
                } else if (ch == '\\' && outputText.charAt(srcPos - 1) != '\\') // Terminates
                                                                                // RTF,
                                                                                // but
                                                                                // starts
                                                                                // new
                                                                                // RTF
                {
                    inRTF = true;
                    if (wasInUnicode && srcPos + 1 < outputText.length()
                            && outputText.charAt(srcPos + 1) == '\'')
                        inUnicode = true;
                } else if (ch == '>') {
                    // Append a space after the RTF (it was probably
                    // stripped by the attribute parsing)
                    outputText.insert(srcPos, "{}");
                }
            }
        } else if (ch == '\\')
            inRTF = true;
        // TEST - to allow outputting of a "*" or "#" character in arbitrary
        // text...
        else if (quoteDelims && (ch == '*' || ch == '#')
                && (srcPos == 0 || Character.isSpaceChar(outputText.charAt(srcPos - 1)))) {
            // //char buffer[5];
            // Always build a 4-character replacement string, like:
            // \'20
            // //sprintf(buffer, "\\\'%2.2x", (int)ch);
            // //text.replace(srcPos, buffer, 4);
            // //srcPos += 3;
            outputText.insert(srcPos, "{}");
            srcPos += 2;
        }
    }
    if (inRTF)
        outputText.append("{}");
    if (bracketed)
        outputText.append('>');
    return outputText.toString();
}