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.pentaho.di.trans.steps.ivwloader.IngresVectorwiseLoader.java

private String replace(String string, String[] searchStrings, String[] replaceStrings) {
    StringBuilder builder = new StringBuilder(string);
    for (int e = 0; e < Math.min(searchStrings.length, replaceStrings.length); e++) {
        String chr = searchStrings[e];
        String rep = replaceStrings[e];
        int idx = builder.indexOf(chr, 0);
        while (idx > 0) {
            builder.replace(idx, idx + chr.length(), rep);
            idx = builder.indexOf(chr, idx + rep.length());
        }// w  w  w  . j  a  va 2  s.co m
    }
    return builder.toString();
}

From source file:org.sonar.plugins.kt.advance.util.XmlParser.java

/**
 * Fix the error occured when parsing a string containing unicode character
 * Example : &u20ac; will be replaced by &#x20ac;
 *//*  ww w .j  av a2 s .co  m*/
protected String fixUnicodeChar(String text) {
    final String unicode = "&u";
    final StringBuilder replace = new StringBuilder(text);
    if (text.indexOf(unicode) >= 0) {
        final Pattern p = Pattern.compile("&u([0-9a-fA-F]{1,4});");
        final Matcher m = p.matcher(replace.toString());
        int nbFind = 0;
        while (m.find()) {
            // Add one index each time because we add one character each
            // time (&u -> &#x)
            replace.replace(m.start() + nbFind, m.end() + nbFind, "&#x" + m.group(1) + ";");
            nbFind++;
        }
    }

    return replace.toString();
}

From source file:edu.chalmers.dat076.moviefinder.service.TitleParser.java

private TemporaryMedia getInformation(StringBuilder mySb) {

    TemporaryMedia returnMedia = new TemporaryMedia();
    StringBuilder wordSb = new StringBuilder();

    int tmpYear;//w  ww .  java 2  s . c om
    int year = -1;
    int thisYear = Calendar.getInstance().get(Calendar.YEAR);

    boolean deleteYear = false;
    boolean finalWord = true;

    for (int i = 0; i < mySb.length(); i++) {
        if (mySb.charAt(i) == '.' || mySb.charAt(i) == ' ' || mySb.charAt(i) == '-' || mySb.charAt(i) == '_') {

            if (Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
                mySb.delete(i - (wordSb.length() + 1), mySb.length());
                finalWord = false;
                // final useful word found. No point in continuing.
                break;
            }
            mySb.replace(i, i + 1, " ");

            tmpYear = checkForYear(wordSb);
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = true;
            }
            wordSb.setLength(0);

        } else if (wordSb.length() == 0
                && (mySb.charAt(i) == 'S' || mySb.charAt(i) == 's' || Character.isDigit(mySb.charAt(i)))) {
            // See if new word contains series and episode information.

            StringBuilder whatsLeft = new StringBuilder(mySb.subSequence(i, mySb.length()));
            if (getEpisodePotential(whatsLeft)) {
                TemporaryMedia tmpMedia = getEpisodeInfo(whatsLeft);
                returnMedia.setIsMovie(false);
                returnMedia.setSeason(tmpMedia.getSeason());
                returnMedia.setEpisode(tmpMedia.getEpisode());
                mySb.delete(i, mySb.length());
                // series and episode information saved. No point in continuing.
                break;

            } else {
                wordSb.append(mySb.charAt(i));
            }
        } else if (mySb.charAt(i) == '[' || mySb.charAt(i) == '(') {
            // Brackets shoudl usually be removed. They could possibly contain realease year.

            if (Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
                mySb.delete(i - (wordSb.length() + 1), mySb.length());
                finalWord = false;
                // final useful word found. No point in continuing.
                break;
            }
            tmpYear = checkForYear(wordSb);
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = true;
            }
            wordSb.setLength(0);

            if (mySb.charAt(i) == '[') {
                tmpYear = removeUntil(mySb, i, ']');
            } else if (mySb.charAt(i) == '(') {
                tmpYear = removeUntil(mySb, i, ')');
            }
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = false;
            }
            i--; // Need to compensate for removing bracket.

        } else {
            // Nothing useful here. Save the char and continue.
            wordSb.append(mySb.charAt(i));
        }
    }

    if (finalWord && Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
        mySb.delete(mySb.length() - wordSb.length(), mySb.length());
    } else {
        tmpYear = checkForYear(wordSb);
        if (tmpYear > 1900 && tmpYear <= thisYear) {
            year = tmpYear;
            deleteYear = true;
        }
    }
    if (deleteYear && returnMedia.IsMovie()) {
        int i = mySb.lastIndexOf(year + "");
        mySb.delete(i, i + 4);
    }

    returnMedia.setYear(year);
    returnMedia.setName(mySb.toString().trim());

    return returnMedia;
}

From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java

private URL createRequestUrl(Map<String, String> parameters) {
    UriBuilder ubu = UriBuilder.fromUri(protocol + "://" + baseUrl).port(port).path("api").path("xml");

    for (String key : parameters.keySet()) {
        ubu.queryParam(key, parameters.get(key));
    }/*from   w  w  w . ja  v  a  2  s . co m*/

    URL url = null;
    try {
        url = ubu.build().toURL();
    } catch (Exception e) {
        logWarn("Error while creating URL for Adobe Connect request.", e);
        // try to build the URL in a naiv way below
    }
    if (url == null) {
        // error case, try the naiv way
        try {
            StringBuilder sb = new StringBuilder(protocol + "://" + baseUrl + ":" + port + "/api/xml");
            if (!parameters.isEmpty())
                sb.append("?");
            for (String key : parameters.keySet()) {
                sb.append(key + "=" + parameters.get(key) + "&");
            }
            sb.replace(sb.length(), sb.length(), "");
            url = new URL(sb.toString());
        } catch (MalformedURLException e) {
            logError("Error while creating URL for Adobe Connect request. Please check the configuration!", e);
        }
    }

    return url;
}

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

/**
 * Return the result of the jth OBX at ith OBR.
 * /*  ww  w.  j a  va  2 s  .c  om*/
 * If it's an ITS^REPORT, the show nothing as this result will be fetched in the previous column.
 * 
 * @param i
 * @param j
 * @param its
 * @return
 */
@SuppressWarnings("unchecked")
public String getOBXResult(int i, int j, boolean its) {

    String result = "", newComment = "";
    int len = 80;

    try {
        OBX obx = null;
        Terser terser = new Terser(msg);
        result = getString(
                Terser.get((obx = (OBX) ((ArrayList) obrSegMap.get(obrSegKeySet.get(i))).get(j)), 5, 0, 1, 1));

        // format the result
        if (result.endsWith("."))
            result = result.substring(0, result.length() - 1);

        if (result.length() > len) {
            StringBuilder sb = new StringBuilder(result);

            int i1 = 0;
            while ((i1 = sb.indexOf(" ", i1 + len)) != -1) {
                sb.replace(i1, i1 + 1, "<br/>");
            }
            newComment = sb.toString();
            logger.info("Modified comment =" + newComment);
        } else {
            newComment = result;
            logger.info("Original comment =" + newComment);
        }

        //if true, then we're giving the report values to the function showing the "test name" per OBX
        if (its)
            return newComment; //return result;
        String name = "";
        //default behavior is for ITS^REPORT is to show now result as this will be in the "test name" field.
        if ((name = obx.getObservationIdentifier().getText().getValue()).indexOf("ITS") != -1
                || name.indexOf("DEPARTMENTAL") != -1)
            return "";
    } catch (Exception e) {
        logger.error("Exception returning result", e);
    }
    return result;
}

From source file:com.github.rwitzel.streamflyer.xml.XmlVersionModifier.java

/**
 * @see com.github.rwitzel.streamflyer.core.Modifier#modify(java.lang.StringBuilder, int, boolean)
 *//*from w  w  w  . j  a  v a 2  s  .c o  m*/
@Override
public AfterModification modify(StringBuilder characterBuffer, int firstModifiableCharacterInBuffer,
        boolean endOfStreamHit) {

    switch (state) {

    case NO_LONGER_MODIFYING:

        return factory.skipEntireBuffer(characterBuffer, firstModifiableCharacterInBuffer, endOfStreamHit);

    case INITIAL:

        state = XmlVersionModifierState.PROLOG_REQUEST;

        // you never know how many whitespace characters are in the prolog
        return factory.modifyAgainImmediately(INITIAL_NUMBER_OF_CHARACTERS, firstModifiableCharacterInBuffer);

    case PROLOG_REQUEST:

        // (Should we do aware of BOMs here? No. I consider it the
        // responsibility of the caller to provide characters without BOM.)

        Matcher matcher = Pattern.compile("<\\?xml[^>]*version\\s*=\\s*['\"]((1.0)|(1.1))['\"].*")
                .matcher(characterBuffer);
        if (matcher.matches()) {

            // replace version in prolog
            characterBuffer.replace(matcher.start(1), matcher.end(1), xmlVersion);
        } else {
            // is there a prolog that is too long?
            Matcher matcher2 = Pattern.compile("<\\?xml.*").matcher(characterBuffer);
            if (matcher2.matches()) {
                // this is not normal at all -> throw exception
                throw new XmlPrologRidiculouslyLongException(characterBuffer.toString());
            }

            // insert prolog
            characterBuffer.insert(0, "<?xml version='" + xmlVersion + "'>");
        }

        state = XmlVersionModifierState.NO_LONGER_MODIFYING;

        return factory.skipEntireBuffer(characterBuffer, firstModifiableCharacterInBuffer, endOfStreamHit);

    default:
        throw new IllegalStateException("state " + state + " not supported");

    }

}

From source file:com.haulmont.cuba.core.global.QueryTransformerRegex.java

@Override
public void addWhere(String where) {
    Matcher entityMatcher = FROM_ENTITY_PATTERN.matcher(buffer);
    String alias = findAlias(entityMatcher);

    int insertPos = buffer.length();
    Matcher lastClauseMatcher = LAST_CLAUSE_PATTERN.matcher(buffer);
    if (lastClauseMatcher.find(entityMatcher.end()))
        insertPos = lastClauseMatcher.start() - 1;

    StringBuilder sb = new StringBuilder();
    Matcher whereMatcher = WHERE_PATTERN.matcher(buffer);
    int whereEnd = -1;
    boolean needOpenBracket = false;
    if (whereMatcher.find(entityMatcher.end())) {
        whereEnd = whereMatcher.end();//  w w w  .ja va  2 s.  c  o  m

        Matcher orMatcher = OR_PATTERN.matcher(buffer);
        orMatcher.region(whereEnd + 1, insertPos);
        if (orMatcher.find()) { // surround with brackets if there is OR inside WHERE
            sb.append(")");
            needOpenBracket = true;
        }
        sb.append(" and ");
    } else {
        sb.append(" where ");
    }

    sb.append("(").append(where);
    int idx;
    while ((idx = sb.indexOf(ALIAS_PLACEHOLDER)) >= 0) {
        sb.replace(idx, idx + ALIAS_PLACEHOLDER.length(), alias);
    }
    sb.append(")");

    if (needOpenBracket) {
        buffer.insert(whereEnd + 1, "(");
        insertPos++;
    }

    buffer.insert(insertPos, sb);

    Matcher paramMatcher = PARAM_PATTERN.matcher(where);
    while (paramMatcher.find()) {
        addedParams.add(paramMatcher.group(1));
    }
}

From source file:org.bitbucket.mlopatkin.android.logviewer.TooltipGenerator.java

public String getTooltip() {
    StringBuilder result = new StringBuilder(text.length());
    result.append("<html>");
    String[] parts = splitWithHighlights();
    boolean shouldHighlight = false;
    int pos = 0;/*from  www . j a  v a2s  .  com*/
    for (String s : parts) {
        if (shouldHighlight) {
            result.append(SPAN_BEGIN);
        }
        String remain = s;
        while (pos + remain.length() > WIDTH) {
            int indexOfBr = WIDTH - pos;
            String onThisLine = remain.substring(0, indexOfBr);
            remain = remain.substring(indexOfBr);
            appendEnc(result, onThisLine);
            result.append(BR);
            pos = 0;
        }
        appendEnc(result, remain);
        pos += remain.length();
        if (shouldHighlight) {
            result.append(SPAN_END);
        }
        shouldHighlight = !shouldHighlight;
    }
    if (StringUtils.endsWith(result, BR)) {
        result.setLength(result.length() - BR.length());
    }
    if (StringUtils.endsWith(result, BR + SPAN_END)) {
        result.replace(result.length() - (BR + SPAN_END).length(), result.length(), SPAN_END);
    }
    result.append("</html>");
    return result.toString();
}

From source file:org.apache.oozie.tools.OozieDBCLI.java

private String getSelectQuery(String tableName, List<String> columnNames) {
    StringBuilder selectQuery = new StringBuilder();
    selectQuery.append("SELECT id,");
    for (String column : columnNames) {
        selectQuery.append(column);/*from   w  w w.j a v  a 2  s.  c  o m*/
        selectQuery.append(",");
    }
    selectQuery.replace(selectQuery.length() - 1, selectQuery.length(), "");
    selectQuery.append(" FROM ");
    selectQuery.append(tableName);
    return selectQuery.toString();
}

From source file:lcmc.data.DrbdXML.java

/** Gets short description for the parameter. */
public String getParamShortDesc(final String param) {
    final StringBuilder name = new StringBuilder(param.replaceAll("\\-", " "));
    name.replace(0, 1, name.substring(0, 1).toUpperCase());
    if (paramUnitLongMap.containsKey(param)) {
        name.append(" (" + paramUnitLongMap.get(param) + ")");
    }// ww w .  j  a va 2s .c  o m
    return name.toString();
}