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:biz.astute.test.simulator.rest.RequestContext.java

/**
 * Return path portion of URL. The url may be modified to extract variables.
 *
 * @param globalProperties global properties
 * @return path portion of url//from ww w.  ja v  a 2  s.c  o  m
 * @throws UnsupportedEncodingException exception
 */
public final String getResourcePath(final Properties globalProperties) throws UnsupportedEncodingException {

    uriProperties.clear();
    String requestURI = URLDecoder.decode(request.getRequestURI(), "utf-8");
    Pattern[] currentPatterns = getPatterns(globalProperties);
    if (currentPatterns.length < 1) {
        return requestURI;
    }

    StringBuilder resourceName = new StringBuilder(requestURI);
    resourceName.append('/'); // Remove this later - need for matcher

    for (Pattern pattern : currentPatterns) {
        Matcher matcher = pattern.matcher(resourceName);
        if (matcher.matches() && (matcher.groupCount() > 0)) {
            for (int index = 1; index <= matcher.groupCount(); index++) {
                String matched = matcher.group(index);
                uriProperties.add(matched);
            }
            // Do so in reverse order so as to not affect offset
            for (int index = matcher.groupCount(); index > 0; index--) {
                resourceName.replace(matcher.start(index), matcher.end(index), StringUtils.EMPTY);
            }
            break;
        }
    }

    // remove '/' appended earlier
    resourceName.setLength(resourceName.length() - 1);
    // Remove any // that result from pattern replacement
    return resourceName.toString().replaceAll("//", "/");
}

From source file:com.impetus.client.cassandra.query.ResultIterator.java

/**
 * Appends where claues and prepare for next fetch. Method to be called in
 * case cql3 enabled.//from   w  w w .ja v a2 s . c  om
 * 
 * @param parsedQuery
 *            parsed query.
 * 
 * @return cql3 query to be executed.
 */
private String appendWhereClauseWithScroll(String parsedQuery) {

    String queryWithoutLimit = parsedQuery.replaceAll(
            parsedQuery.substring(parsedQuery.lastIndexOf(CQLTranslator.LIMIT), parsedQuery.length()), "");

    CQLTranslator translator = new CQLTranslator();

    final String tokenCondition = prepareNext(translator, queryWithoutLimit);

    StringBuilder builder = new StringBuilder(queryWithoutLimit);

    if (tokenCondition != null) {
        if (query.getKunderaQuery().getFilterClauseQueue().isEmpty()) {
            builder.append(CQLTranslator.ADD_WHERE_CLAUSE);
        } else {
            builder.append(CQLTranslator.AND_CLAUSE);
        }
        builder.append(tokenCondition);
    }

    String replaceQuery = replaceAndAppendLimit(builder.toString());
    builder.replace(0, builder.toString().length(), replaceQuery);
    translator.buildFilteringClause(builder);

    // in case of fetch by ID, token condition will be null and results will
    // not be empty.
    return checkOnEmptyResult() && tokenCondition == null ? null : builder.toString();
}

From source file:fr.landel.utils.scripts.ScriptsReplacer.java

private void replaceSimples(final StringBuilder sb, final String key, final String value) {
    String simple;//from   www .  j a  v a  2 s.c  om

    final int valueLen = value.length();
    final int startLen = this.template.getVariableOpen().length();
    final int stopLen = this.template.getVariableClose().length();

    // get first
    int index = sb.indexOf(this.template.getVariableOpen());
    int indexStop = sb.indexOf(this.template.getVariableClose(), index + startLen);

    for (; index > -1 && indexStop > -1;) {
        simple = sb.substring(index + startLen, indexStop);

        if (key.equals(simple.trim())) {
            sb.replace(index, indexStop + stopLen, value);
            index += valueLen;
        }

        // get next
        index = sb.indexOf(this.template.getVariableOpen(), index + startLen);
        if (index > -1) {
            indexStop = sb.indexOf(this.template.getVariableClose(), index + startLen);
        }
    }
}

From source file:edu.ku.brc.af.core.db.AutoNumberGeneric.java

/**
 * Builds a new string from a formatter.
 * @param formatter the formatter//from   ww w. j a  va  2 s .  co m
 * @param value the existing largest value
 * @param yearAndIncVal a year,incVal pair
 * @return the new formatted value
 */
protected String buildNewNumber(final UIFieldFormatterIFace formatter, final String value,
        final Pair<BigInteger, BigInteger> yearAndIncVal) {
    String trimmedValue = StringUtils.deleteWhitespace(value);
    int fmtLen = formatter.getLength();
    if (trimmedValue.length() == 0 || (StringUtils.isNotEmpty(value) && formatter.isLengthOK(value.length()))) {
        Pair<Integer, Integer> pos = formatter.getIncPosition();
        if (pos != null) {
            if (pos.second != null) {
                BigInteger incVal = yearAndIncVal.second.add(new BigInteger("1"));

                StringBuilder sb = new StringBuilder(value.substring(0, pos.first));
                String formatStr = "%0" + (pos.second - pos.first) + "d"; //$NON-NLS-1$ //$NON-NLS-2$
                sb.append(String.format(formatStr, incVal));
                if (fmtLen > pos.second) {
                    sb.append(value.substring(pos.second, fmtLen));
                }

                UIFieldFormatterField yearField = formatter.getYear();
                if (yearField != null) {
                    Pair<Integer, Integer> yrPos = formatter.getYearPosition();
                    if (yrPos != null) {
                        sb.replace(yrPos.first, yrPos.second, yearAndIncVal.first.toString());
                    }
                } // else
                  //throw new RuntimeException("There was an error trying to obtain the highest number, there may be a bad value in the database.");
                return sb.toString();
            } // else
              //errorMsg = "There was an error trying to obtain the highest number, there may be a bad value in the database."; //$NON-NLS-1$
        }
        // else
        errorMsg = "Formatter [" + formatter.getName() + "] doesn't have an incrementer field."; //$NON-NLS-1$ //$NON-NLS-2$
    }
    return null;
}

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

@Override
public Object formatToUI(Object... datas) {
    Object data = datas[0];/* w  ww. j  a va2s .  c o m*/
    boolean isStr = data instanceof String;

    if (autoNumber != null && isStr && isEmpty((String) data)) {
        String pattern = toPattern();
        UIFieldFormatterField yearField = getYear();
        if (yearField != null) {
            Pair<Integer, Integer> pos = getYearPosition();
            if (pos != null) {
                StringBuilder sb = new StringBuilder(pattern);
                Calendar cal = Calendar.getInstance();
                sb.replace(pos.first, pos.second, Integer.toString(cal.get(Calendar.YEAR)));
                return sb.toString();
            }
        }
        return pattern;

    } else if (data instanceof Number) {
        /*
         * This block modified to fix #10238
        * the entire block actually seems kind of unnecessary because
        * the same code for displaying values in view mode could be used instead.
        */

        //int    size = fields.get(0).getSize();
        //String fmt;
        if (data instanceof Float || data instanceof Double) {
            //fmt = "%" + (size-2) + ".2f";
            //this results in a display that matches the
            return String.valueOf(data);

        } else if (data instanceof BigDecimal) {
            //fmt = "%" + (size-2) + ".2f";

            /*
             * using doubleValue() eliminates trailing zeroes but 
             * that leads to conflict with the way big decimals are
             * displayed in view mode on forms and in query results
             */
            //return String.valueOf(((Number )data).doubleValue());

            return String.valueOf(data);
        } else {
            //fmt = "%d";
            return String.format("%d", data).trim();
        }

    } else if (data instanceof Calendar) {
        return scrDateFormat.format((Calendar) data);

    } else if (data instanceof Date) {
        return scrDateFormat.format((Date) data);
    }
    return data;
}

From source file:ru.gkpromtech.exhibition.db.Table.java

public List<Pair<Entity[], T>> selectJoined(Join[] joins, String selection, String[] selectionArgs,
        String orderBy, String groupBy)
        throws InvalidClassException, IllegalAccessException, InstantiationException {

    List<Pair<Entity[], T>> result = new ArrayList<>();
    Table<? extends Entity>[] tables = new Table<?>[joins.length];

    StringBuilder query = new StringBuilder();
    for (int i = 0; i < joins.length; ++i) {
        tables[i] = ((DbHelper) mSqlHelper).getTableFor(joins[i].entity);
        for (String column : tables[i].mColumns) {
            query.append(",f").append(i).append(".").append(column);
        }//w  w  w. j a va2  s  . c om
    }
    for (String column : mColumns)
        query.append(",t.").append(column);
    query.replace(0, 1, "SELECT "); // first comma -> select

    query.append("\nFROM ").append(mTableName).append(" t");
    for (int i = 0; i < joins.length; ++i) {
        Join join = joins[i];
        query.append("\n");
        if (join.type != null)
            query.append(join.type).append(" ");
        query.append("JOIN ").append(tables[i].mTableName).append(" f").append(i).append(" ON ");
        if (join.customJoinOn != null) {
            query.append(join.customJoinOn);
        } else {
            query.append("f").append(i).append(".").append(join.entityRow).append(" = t.").append(join.row);
        }
    }

    if (selection != null)
        query.append("\nWHERE ").append(selection);
    if (groupBy != null)
        query.append("\nGROUP BY ").append(groupBy);
    if (orderBy != null)
        query.append("\nORDER BY ").append(orderBy);

    String queryString = query.toString();
    if (BuildConfig.DEBUG)
        Log.d("PP", queryString);

    SQLiteDatabase db = mSqlHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(queryString, selectionArgs);

    //noinspection TryFinallyCanBeTryWithResources
    try {
        while (cursor.moveToNext()) {
            int col = 0;
            Entity[] entities = new Entity[joins.length];
            for (int i = 0; i < joins.length; ++i) {
                Table<? extends Entity> table = tables[i];
                entities[i] = joins[i].entity.newInstance();
                for (int j = 0; j < table.mFields.length; ++j, ++col)
                    fillFieldValue(table.mType[j], table.mFields[j], entities[i], cursor, col);
            }

            T entity = mEntityClass.newInstance();
            for (int j = 0; j < mFields.length; ++j, ++col)
                fillFieldValue(mType[j], mFields[j], entity, cursor, col);
            result.add(new Pair<>(entities, entity));
        }
    } finally {
        cursor.close();
        db.close();
    }

    return result;
}

From source file:com.l2jfree.gameserver.status.GameStatusThread.java

private String readLine() throws IOException {
    String line = _read.readLine();
    if (line == null)
        return null;

    StringBuilder sb = new StringBuilder(line);

    for (int index; (index = sb.indexOf("\b")) != -1;)
        sb.replace(Math.max(0, index - 1), index + 1, "");

    return sb.toString();
}

From source file:pl.nask.hsn2.normalizers.URLNormalizerUtils.java

public static String dnsToIDN(StringBuilder str, int startIndx, int endIndx) throws URLHostParseException {
    if (str.length() == 0) {
        throw new URLHostParseException("Cannot process empty string");
    }/*from   w w w  .ja  va2 s  . c  o  m*/
    if (endIndx > str.length()) {
        endIndx = str.length();
    }
    int dd = str.indexOf("..", startIndx);
    if (dd >= 0 && dd < endIndx) {
        throw new URLHostParseException(
                "Sequence '..' is forbidden in DNS: '" + str.substring(startIndx, endIndx) + "'");
    }

    String host;
    try {
        host = IDN.toASCII(str.substring(startIndx, endIndx), IDN.USE_STD3_ASCII_RULES & IDN.ALLOW_UNASSIGNED);
        if (host.startsWith(".")) {
            throw new URLHostParseException("DNS name cannot start with .");
        }
    } catch (IllegalArgumentException e) {
        throw new URLHostParseException("Error converting DNS:" + str.toString(), e);
    }

    if (host.length() == str.length() && !EncodingType.DNS_ALLOWED.allowed(host)) {
        throw new URLHostParseException("Error converting DNS: " + str.toString());
    }

    if (host.length() == 0) {
        return host;
    }
    host = host.toLowerCase();

    str.replace(startIndx, endIndx, host);
    return host;
}

From source file:com.mawujun.utils.string.StringUtils.java

/**
 *  ?/*from   w  w w. j  a  v a 2s .  c o  m*/
 * @author mawujun email:160649888@163.com qq:16064988
 * @param param
 * @return
 */
public static String underlineToCamel2(String param) {
    if (param == null || "".equals(param.trim())) {
        return "";
    }
    StringBuilder sb = new StringBuilder(param);
    Matcher mc = Pattern.compile("_").matcher(param);
    int i = 0;
    while (mc.find()) {
        int position = mc.end() - (i++);
        // String.valueOf(Character.toUpperCase(sb.charAt(position)));
        sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
    }
    return sb.toString();
}

From source file:org.jumpmind.metl.core.runtime.component.DataDiff.java

protected void appendColumns(StringBuilder sql, String prefix, ModelEntity entity) {
    for (ModelAttribute attribute : entity.getModelAttributes()) {

        Component component = context.getFlowStep().getComponent();
        ComponentAttributeSetting matchColumnSetting = component.getSingleAttributeSetting(attribute.getId(),
                DataDiff.ATTRIBUTE_COMPARE_ENABLED);
        boolean matchColumn = matchColumnSetting != null ? Boolean.parseBoolean(matchColumnSetting.getValue())
                : true;//w w  w.  j  a v  a2 s  .c om
        if (matchColumn) {
            sql.append(prefix).append(attribute.getName()).append(" /* ").append(entity.getName()).append(".")
                    .append(attribute.getName()).append(" */").append(",");
        }
    }
    sql.replace(sql.length() - 1, sql.length(), "");
}