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.aurel.track.lucene.search.associatedFields.AbstractAssociatedFieldSearcher.java

/**
 * Preprocess an explicit field/*from  w w  w  . j  a  va2 s  . c  om*/
 * @param analyzer
 * @param toBeProcessedString a part of the user entered query string
 * @param locale
 * @param indexStart the index to start looking for fieldName
 * @return
 */
@Override
public String preprocessExplicitField(Analyzer analyzer, String toBeProcessedString, Locale locale,
        int indexStart) {
    String fieldName = getLuceneFieldName();
    int indexFound = LuceneSearcher.fieldNameIndex(toBeProcessedString, fieldName, indexStart);
    if (indexFound == -1) {
        return toBeProcessedString;
    }
    int beginReplaceIndex = indexFound + fieldName.length() + 1;
    String originalFieldValue = LuceneSearcher.getFieldValue(toBeProcessedString.substring(beginReplaceIndex));
    if (originalFieldValue == null || "".equals(originalFieldValue)) {
        return toBeProcessedString;
    }
    String processedFieldValue = searchExplicitField(analyzer, fieldName, originalFieldValue, null, locale);
    if (processedFieldValue == null || "".equals(processedFieldValue)) {
        return toBeProcessedString;
    }
    StringBuilder original = new StringBuilder(toBeProcessedString);
    //get the user entered value of the field
    String issueNoFieldName = LuceneUtil.getFieldName(SystemFields.ISSUENO);
    original.replace(indexFound, beginReplaceIndex + originalFieldValue.length(),
            issueNoFieldName + LuceneSearcher.FIELD_NAME_VALUE_SEPARATOR + processedFieldValue);
    return preprocessExplicitField(analyzer, original.toString(), locale,
            beginReplaceIndex + processedFieldValue.length());
}

From source file:com.croer.javaorange.diviner.SimpleOrangeTextPane.java

protected void colorStyledDocument(final DefaultStyledDocument document) {
    EventQueue.invokeLater(new Runnable() {

        @Override//from  ww w. j  a  va 2 s .c  om
        public void run() {
            String input = "";
            try {
                input = document.getText(0, document.getLength());
            } catch (BadLocationException ex) {
                Logger.getLogger(SimpleOrangeTextPane.class.getName()).log(Level.SEVERE, null, ex);
            }

            StringBuilder inputMut = new StringBuilder(input);
            String[] split = StringUtils.split(inputMut.toString());
            int i = 0;
            for (String string : split) {
                int start = inputMut.indexOf(string);
                int end = start + string.length();
                inputMut.replace(start, end, StringUtils.repeat(" ", string.length()));
                document.setCharacterAttributes(start, string.length(), styles[i++ % styles.length], true);
            }
        }
    });
}

From source file:net.jforum.formatters.BBConfigFormatter.java

/**
 * Formats only the [code] tag/* w  w w.ja v  a 2s  . c  o  m*/
 *
 * @param text the text to format
 * @return the formatted text
 */
private String processCodeTag(String text) {
    for (BBCode bb : this.bbTags.values()) {
        // There is "code" and "code-highlight"
        if (bb.getTagName().startsWith("code")) {
            Matcher matcher = Pattern.compile(bb.getRegex()).matcher(text);
            StringBuilder sb = new StringBuilder(text);

            while (matcher.find()) {
                String lang = null;
                String contents = null;

                if ("code".equals(bb.getTagName())) {
                    contents = matcher.group(1);
                } else {
                    lang = matcher.group(1);
                    contents = matcher.group(2);
                }

                contents = StringUtils.replace(contents, "<br/> ", "\n");

                // XML-like tags
                contents = StringUtils.replace(contents, "<", "&lt;");
                contents = StringUtils.replace(contents, ">", "&gt;");

                // Note: there is no replacing for spaces and tabs as
                // we are relying on the Javascript SyntaxHighlighter library
                // to do it for us

                StringBuilder replace = new StringBuilder(bb.getReplace());
                int index = replace.indexOf("$1");

                if ("code".equals(bb.getTagName())) {
                    if (index > -1) {
                        replace.replace(index, index + 2, contents.toString());
                    }

                    index = sb.indexOf("[code]");
                } else {
                    if (index > -1) {
                        replace.replace(index, index + 2, lang.toString());
                    }

                    index = replace.indexOf("$2");

                    if (index > -1) {
                        replace.replace(index, index + 2, contents.toString());
                    }

                    index = sb.indexOf("[code=");
                }

                int lastIndex = sb.indexOf("[/code]", index) + "[/code]".length();

                if (lastIndex > index) {
                    sb.replace(index, lastIndex, replace.toString());
                }
            }

            text = sb.toString();
        }
    }

    return text;
}

From source file:org.jumpmind.db.model.Table.java

public static String getCommaDeliminatedColumns(Column[] cols) {
    StringBuilder columns = new StringBuilder();
    if (cols != null && cols.length > 0) {
        for (Column column : cols) {
            columns.append(column.getName());
            columns.append(",");
        }//w  w  w  .  j a  v  a2 s . c o m
        columns.replace(columns.length() - 1, columns.length(), "");
        return columns.toString();
    } else {
        return " ";
    }
}

From source file:com.cisco.oss.foundation.http.server.TraceWrapper.java

public static String toStringWithBody(String data, String ndsBodyStatusHeader, byte[] body, int bodyLimit,
        String contentType, List<String> contentTypes, String characterEncoding, String bodySuffix,
        boolean forceBinaryPrint) {

    int dataLength = data.length();
    final StringBuilder builder = new StringBuilder(dataLength + bodyLimit);
    builder.append(data);// ww  w.j a  v a2s .c  om
    builder.append("\n");
    boolean isText = false;
    if (body.length > 0) {
        boolean bodyEncrypted = (ndsBodyStatusHeader != null)
                && (ndsBodyStatusHeader.equalsIgnoreCase("Encrypted"));

        if (!forceBinaryPrint && !bodyEncrypted && contentType != null) {
            for (String type : contentTypes) {
                if (contentType.toLowerCase().contains(type)) {
                    String enc = characterEncoding;
                    if (enc == null) {
                        enc = "UTF-8";
                    }

                    try {
                        builder.append(new String(body, enc));
                        isText = true;
                        break;
                    } catch (UnsupportedEncodingException e) {
                        LOGGER.trace("problem appending string body with {} encoding. error is: {}", enc, e);
                        break;
                    }
                }
            }
        }

        if (!isText) {
            builder.append(Hex.encodeHex(body));
        }
        if (builder.length() > dataLength + bodyLimit) {
            builder.setLength(dataLength + bodyLimit);
            builder.replace(builder.length() - bodySuffix.length(), builder.length(), bodySuffix);
        }
    }
    return builder.toString();

}

From source file:com.untangle.app.web_filter.WebFilterDecisionEngine.java

/**
 * Encode a URL/*from  w  w  w.  ja v a  2 s . c  o  m*/
 * 
 * @param domain
 *        The domain
 * @param uri
 *        The URI
 * @return The encoded URL
 */
private static String encodeUrl(String domain, String uri) {
    // Remote trailing dots from domain
    Matcher matcher = trailingDotsPattern.matcher(domain);
    domain = matcher.replaceAll("");

    String url = domain + uri;

    // Remote trailing dots or slashes from URL
    matcher = trailingDotsSlashesPattern.matcher(url);
    url = matcher.replaceAll("");

    StringBuilder qBuilder = new StringBuilder(url);

    int i;
    int lastDot = 0;

    for (i = 0; i < qBuilder.length(); i++) {

        int numCharsAfterThisOne = (qBuilder.length() - i) - 1;

        // Must insert a null escape to divide long spans
        if (i > lastDot + 59) {
            qBuilder.insert(i, "_-0.");
            lastDot = i + 3;
            i += 4;
        }

        if (qBuilder.charAt(i) == '.') {
            lastDot = i;
        }
        // Take care of the rare, but possible case of _- being in the string
        else if (qBuilder.charAt(i) == '_' && numCharsAfterThisOne >= 1 && qBuilder.charAt(i + 1) == '-') {
            qBuilder.replace(i, i + 2, "_-_-");
            i += 4;
        }
        // Convert / to rfc compliant characters _-.
        else if (qBuilder.charAt(i) == '/') {
            qBuilder.replace(i, i + 1, "_-.");
            lastDot = i + 2;
            i += 3;
        }
        // Convert any dots next to each other
        else if (qBuilder.charAt(i) == '.' && numCharsAfterThisOne >= 1 && qBuilder.charAt(i + 1) == '.') {
            qBuilder.replace(i, i + 2, "._-2e");
            i += 5;
        }
        // Convert any dots at the end. (these should have already been stripped but the zvelo implementation has this here)
        else if (qBuilder.charAt(i) == '.' && numCharsAfterThisOne == 0) {
            qBuilder.replace(i, i + 1, "_-2e");
            i += 4;
        }
        // Convert : to _--
        else if (qBuilder.charAt(i) == ':') {
            qBuilder.replace(i, i + 1, "_--");
            i += 3;
        }
        // Drop everything after ? or #
        else if (qBuilder.charAt(i) == '?' || qBuilder.charAt(i) == '#') {
            qBuilder.delete(i, qBuilder.length());
            break;
        }
        // Convert %HEXHEX to encoded form
        else if (qBuilder.charAt(i) == '%' && numCharsAfterThisOne >= 2 && _isHex(qBuilder.charAt(i + 1))
                && _isHex(qBuilder.charAt(i + 2))) {
            //String hexString = new String(new char[] {qBuilder.charAt(i+1), qBuilder.charAt(i+2)});
            //char c = (char)( Integer.parseInt( hexString , 16) );
            //System.out.println("HEX: \"" + hexString +"\" -> \"" + Character.toString(c) + "\"");
            qBuilder.replace(i, i + 1, "_-");
            i += 4; // 2 for length of replacement + 2 for the hex characters
        }
        // Convert % charaters to encoded form
        else if (qBuilder.charAt(i) == '%') {
            qBuilder.replace(i, i + 1, "_-25");
            i += 4;
        }
        // Convert any remaining non-RFC characters.
        else if (!_isRfc(qBuilder.charAt(i))) {
            String replaceStr = String.format("_-%02X", ((byte) qBuilder.charAt(i)));
            qBuilder.replace(i, i + 1, replaceStr);
            i += 4;
        }
    }

    return qBuilder.toString();
}

From source file:ee.ioc.cs.vsle.synthesize.SpecParser.java

/**
 * Extracts the specification from the java file, also removing unnecessary
 * whitespaces//from ww  w . j  a  v a 2 s . co  m
 * 
 * @return specification text
 * @param fileString a (Java) file containing the specification
 * @throws SpecParseException 
 */
private static String refineSpec(String fileString) {
    Matcher matcher;

    // remove comments before removing line brake \n
    String[] s = fileString.split("\n");
    StringBuilder tmpBuf = new StringBuilder(fileString.length() / 2);
    for (int i = 0; i < s.length; i++) {
        if (!s[i].trim().startsWith("//")) {
            tmpBuf.append(s[i]);
        }
    }

    // remove unneeded whitespace
    matcher = PATTERN_WHITESPACE.matcher(tmpBuf);
    // This is broken as spaces should not be replaced in,
    // e.g. string literals. Keeping it now for compatibility.
    tmpBuf.replace(0, tmpBuf.length(), matcher.replaceAll(" "));

    // find spec
    matcher = PATTERN_SPEC.matcher(tmpBuf);
    if (matcher.find()) {
        StringBuilder sc = new StringBuilder();
        if (matcher.group(2) != null) {
            sc.append("super");
            String[] superclasses = matcher.group(2).split(",");
            for (int i = 0; i < superclasses.length; i++) {
                String t = superclasses[i].trim();
                if (t.length() > 0) {
                    sc.append("#");
                    sc.append(t);
                }
            }
            sc.append(";\n");
        }
        return sc.append(matcher.group(3)).toString();
    }

    throw new SpecParseException("Specification parsing error");
}

From source file:org.jenkinsmvn.jenkins.mvn.plugin.handler.EmailReportActionHandler.java

@Override
public void execute() throws IOException {
    FileWriter reportWriter = null;
    try {/*from ww  w.ja  v a  2  s  .  c  o m*/
        super.execute();
        printFooter();

        String content = stringWriter.toString();
        StringBuilder email = new StringBuilder(FileUtils.readFileToString(templateFile));

        Matcher matcher = VARIABLE.matcher(email);

        int index = 0;
        while (matcher.find(index)) {
            String variable = matcher.group().substring(1);

            if (StringUtils.equals(variable, "content")) {
                email.replace(matcher.start(), matcher.end(), content);
                index = matcher.start() + content.length();
            } else if (action.getProperties().containsKey(variable)) {
                String replacement = action.getProperties().getProperty(variable);
                email.replace(matcher.start(), matcher.end(), replacement);
                index = matcher.start() + replacement.length();
            } else {
                index = matcher.end();
            }
        }

        File baseReportFile = new File(jenkinsTargetDir, "email.html");

        reportWriter = new FileWriter(baseReportFile);
        IOUtils.write(email, reportWriter);
    } finally {
        IOUtils.closeQuietly(reportWriter);
        IOUtils.closeQuietly(stringWriter);
        IOUtils.closeQuietly(writer);
    }
}

From source file:net.jimj.automaton.Bot.java

@Subscribe
public void execute(HelpEvent event) {
    String cmdName = event.getCommandName();
    Command cmd = commandMap.get(cmdName);
    if (cmdName == null) {
        StringBuilder commandList = new StringBuilder();
        for (String command : commandMap.keySet()) {
            commandList.append(command).append(", ");
        }/*  w w  w .j  av  a  2 s. co m*/
        commandList.replace(commandList.length() - 2, commandList.length(), "");
        ircClient.sendPrivMsg(event.getTarget(), "Command list: " + commandList.toString());
    } else if (cmd == null) {
        ircClient.sendPrivMsg(event.getTarget(), "Unknown command: " + cmdName);
    } else {
        cmd.help(event.getUser());
    }
}