Example usage for java.lang StringBuffer replace

List of usage examples for java.lang StringBuffer replace

Introduction

In this page you can find the example usage for java.lang StringBuffer replace.

Prototype

@Override
public synchronized StringBuffer replace(int start, int end, String str) 

Source Link

Usage

From source file:org.apache.zeppelin.elasticsearch.ElasticsearchInterpreter.java

private String buildSearchHitsResponseMessage(ActionResponse response) {

    if (response.getHits() == null || response.getHits().size() == 0) {
        return "";
    }/*from  w  w  w .  j  a  v  a  2s .c  o m*/

    //First : get all the keys in order to build an ordered list of the values for each hit
    //
    final List<Map<String, Object>> flattenHits = new LinkedList<>();
    final Set<String> keys = new TreeSet<>();
    for (final HitWrapper hit : response.getHits()) {

        final String json = hit.getSourceAsString();

        final Map<String, Object> flattenJsonMap = JsonFlattener.flattenAsMap(json);
        final Map<String, Object> flattenMap = new HashMap<>();
        for (final Iterator<String> iter = flattenJsonMap.keySet().iterator(); iter.hasNext();) {
            // Replace keys that match a format like that : [\"keyname\"][0]
            final String fieldName = iter.next();
            final Matcher fieldNameMatcher = FIELD_NAME_PATTERN.matcher(fieldName);
            if (fieldNameMatcher.matches()) {
                flattenMap.put(fieldNameMatcher.group(1) + fieldNameMatcher.group(2),
                        flattenJsonMap.get(fieldName));
            } else {
                flattenMap.put(fieldName, flattenJsonMap.get(fieldName));
            }
        }
        flattenHits.add(flattenMap);

        for (final String key : flattenMap.keySet()) {
            keys.add(key);
        }
    }

    // Next : build the header of the table
    //
    final StringBuffer buffer = new StringBuffer();
    for (final String key : keys) {
        buffer.append(key).append('\t');
    }
    buffer.replace(buffer.lastIndexOf("\t"), buffer.lastIndexOf("\t") + 1, "\n");

    // Finally : build the result by using the key set
    //
    for (final Map<String, Object> hit : flattenHits) {
        for (final String key : keys) {
            final Object val = hit.get(key);
            if (val != null) {
                buffer.append(val);
            }
            buffer.append('\t');
        }
        buffer.replace(buffer.lastIndexOf("\t"), buffer.lastIndexOf("\t") + 1, "\n");
    }

    return buffer.toString();
}

From source file:com.enonic.vertical.engine.PresentationEngine.java

public Document getFusionBotQuery(String fusionBotUrl, String query, int siteNum, int page) {
    final String MESSAGE_00 = "Failed to query FusionBot search engine";

    Document doc;//  ww  w . ja  v  a  2 s  .com
    try {
        StringBuffer urlStr = new StringBuffer(fusionBotUrl);
        urlStr.append("?keys=");
        StringBuffer sb = new StringBuffer(query.replace(' ', '+'));
        for (int i = 0; i < sb.length(); i++) {
            char c = sb.charAt(i);
            if (c == '<') {
                sb.replace(i, i + 1, "&#x3c;");
                i += 5;
            }
        }
        urlStr.append(sb.toString());
        urlStr.append("&sitenbr=");
        urlStr.append(siteNum);
        urlStr.append("&ct=0&xml=1&pos=");
        urlStr.append(page);

        URL url = new URL(urlStr.toString());
        URLConnection urlConn = url.openConnection();
        InputStream in = urlConn.getInputStream();

        doc = XMLTool.domparse(in);
    } catch (Exception e) {
        VerticalEngineLogger.error(getClass(), 0, MESSAGE_00, e);
        doc = null;
    }

    if (doc == null) {
        doc = XMLTool.createDocument("noresult");
    }

    return doc;
}

From source file:org.openhie.openempi.report.impl.AbstractReportGenerator.java

private void insertParamValue(StringBuffer queryStr, String paramValue, ReportQueryParameter queryParam) {
    String clause = queryParam.getParameterName() + paramValue;
    if (queryParam.getSubstitutionKey() != null && queryParam.getSubstitutionKey().length() > 0
            && queryStr.indexOf("$" + queryParam.getSubstitutionKey()) >= 0) {
        log.debug("Before replacing substitution key " + queryParam.getSubstitutionKey() + " the query was: "
                + queryStr);/*from  w  w w.j  a v a 2 s.  c o m*/
        int start = queryStr.indexOf("$" + queryParam.getSubstitutionKey());
        int end = start + queryParam.getSubstitutionKey().length() + 2;
        queryStr.replace(start, end, clause);
        log.debug("After replacing substitution key " + queryParam.getSubstitutionKey() + " the query is: "
                + queryStr);
    } else {
        if (queryStr.indexOf("WHERE") < 0 && queryStr.indexOf("where") < 0) {
            queryStr.append(" WHERE 1=1");
        }
        queryStr.append(" AND ").append(clause);
    }
}

From source file:com.spinn3r.api.BaseClient.java

/**
 * Set a parameter in the HTTP URL.//from   www.  j  a v  a 2s.  co m
 *
 */
protected String setParam(String v, String key, Object value) {

    int start = v.indexOf(String.format("%s=", key));

    if (start != -1) {
        int end = v.indexOf("&", start);

        if (end == -1)
            end = v.length();

        StringBuffer buff = new StringBuffer(v);

        buff.replace(start, end, String.format("%s=%s", key, value));
        return buff.toString();
    }

    return v;

}

From source file:org.apache.phoenix.parse.HintNode.java

public HintNode(String hint) {
    Map<Hint, String> hints = new HashMap<Hint, String>();
    // Split on whitespace or parenthesis. We do not need to handle escaped or
    // embedded whitespace/parenthesis, since we are parsing what will be HBase
    // table names which are not allowed to contain whitespace or parenthesis.
    String[] hintWords = hint.split(SPLIT_REGEXP);
    for (int i = 0; i < hintWords.length; i++) {
        String hintWord = hintWords[i];
        if (hintWord.isEmpty()) {
            continue;
        }//from   w  w  w  . j  av  a 2s.  c om
        try {
            Hint key = Hint.valueOf(hintWord.toUpperCase());
            String hintValue = "";
            if (i + 1 < hintWords.length && PREFIX.equals(hintWords[i + 1])) {
                StringBuffer hintValueBuf = new StringBuffer(hint.length());
                hintValueBuf.append(PREFIX);
                i += 2;
                while (i < hintWords.length && !SUFFIX.equals(hintWords[i])) {
                    hintValueBuf.append(SchemaUtil.normalizeIdentifier(hintWords[i++]));
                    hintValueBuf.append(SEPARATOR);
                }
                // Replace trailing separator with suffix
                hintValueBuf.replace(hintValueBuf.length() - 1, hintValueBuf.length(), SUFFIX);
                hintValue = hintValueBuf.toString();
            }
            String oldValue = hints.put(key, hintValue);
            // Concatenate together any old value with the new value
            if (oldValue != null) {
                hints.put(key, oldValue + hintValue);
            }
        } catch (IllegalArgumentException e) { // Ignore unknown/invalid hints
        }
    }
    this.hints = ImmutableMap.copyOf(hints);
}

From source file:com.sun.faces.application.ViewHandlerImpl.java

/**
 * <p>Adjust the viewID per the requirements of {@link #renderView}.</p>
 *
 * @param context current {@link FacesContext}
 * @param viewId  incoming view ID//from ww  w. j  a  v  a  2s .co  m
 * @return the view ID with an altered suffix mapping (if necessary)
 */
private String convertViewId(FacesContext context, String viewId) {
    synchronized (this) {
        if (contextDefaultSuffix == null) {
            contextDefaultSuffix = context.getExternalContext()
                    .getInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME);
            if (contextDefaultSuffix == null) {
                contextDefaultSuffix = ViewHandler.DEFAULT_SUFFIX;
            }
            if (log.isDebugEnabled()) {
                log.debug("contextDefaultSuffix " + contextDefaultSuffix);
            }
        }
    }
    String convertedViewId = viewId;
    // if the viewId doesn't already use the above suffix,
    // replace or append.
    if (!convertedViewId.endsWith(contextDefaultSuffix)) {
        StringBuffer buffer = new StringBuffer(convertedViewId);
        int extIdx = convertedViewId.lastIndexOf('.');
        if (extIdx != -1) {
            buffer.replace(extIdx, convertedViewId.length(), contextDefaultSuffix);
        } else {
            // no extension in the provided viewId, append the suffix
            buffer.append(contextDefaultSuffix);
        }
        convertedViewId = buffer.toString();
        if (log.isDebugEnabled()) {
            log.debug("viewId after appending the context suffix " + convertedViewId);
        }

    }
    return convertedViewId;
}

From source file:org.jboss.dashboard.commons.text.StringUtil.java

/**
 * Replaces the characters in a substring of a String with characters in
 * the specified new substring.//from   www .  j av a2 s. co  m
 *
 * @param origStr original string
 * @param oldStr  substring to search in the orig String
 * @param newStr  new substring
 * @return if the parameters are correct returns the new string; otherwise
 *         if orig parameter is null returns null. If str or newstr parameters are
 *         null returns orig parameter
 */
public static String replaceAll(String origStr, String oldStr, String newStr) {

    if (origStr == null) {
        return null;
    } else if (oldStr == null || newStr == null) {
        return origStr;
    }

    StringBuffer buf = new StringBuffer(origStr);
    int inicio = origStr.indexOf(oldStr);

    if (inicio == -1) {
        return origStr;
    }

    while (inicio != -1) {
        buf.replace(inicio, inicio + oldStr.length(), newStr);
        inicio = buf.toString().indexOf(oldStr, inicio + newStr.length());
    }

    return buf.toString();
}

From source file:net.sourceforge.dvb.projectx.xinput.ftp.XInputFileImpl.java

/**
 * @return String, checked of arg1 and replaced with arg2 JDK 1.2.2
 *         compatibility, replacement of newer String.replaceAll()
 *///from  w  w w.  j av a  2  s. c  o m
private String replaceStringByString(String name, String arg1, String arg2) {

    if (name == null)
        return name;

    StringBuffer sb = new StringBuffer(name);

    for (int i = 0; (i = sb.toString().indexOf(arg1, i)) != -1;)
        sb.replace(i, i + 2, arg2);

    return sb.toString();
}

From source file:com.krawler.common.notification.handlers.NotificationExtractorManager.java

private void replaceExtraPlaceHolders(StringBuffer htmlMsg, Map<String, Object> extraParams) {
    try {//from w  w  w .j  a va  2s  .c  o m
        Set keySets = extraParams.keySet();
        for (Object key : keySets) {
            String value = extraParams.get(key).toString();
            int i1 = htmlMsg.indexOf(key.toString());
            while (i1 >= 0) {
                int i2 = i1 + key.toString().length();
                if (StringUtil.isNullOrEmpty(value)) {
                    value = "";
                }
                htmlMsg.replace(i1, i2, value);
                i1 = htmlMsg.indexOf(key.toString());
            }
        }
    } catch (Exception ex) {
        LOG.info(ex.getMessage(), ex);
        ex.printStackTrace();
    }
}

From source file:org.jboss.dashboard.commons.text.StringUtil.java

/**
 * Replaces the characters in all substrings of a String with a String.
 *
 * @param str original string// www . j av  a 2 s.  com
 * @param in  substrings to search in the orig String
 * @param out new String
 * @return if the parameters are correct returns the new string; otherwise
 *         if some of the parameters is null returns the original string
 */
private static String replaceAll(String str, String[] in, String out) {
    if (str == null || in == null || out == null) {
        return str; // for the sake of robustness
    }

    StringBuffer buffer = new StringBuffer(str);

    int idx = 0;
    for (int i = 0; i < in.length; i++) {
        idx = 0;
        while ((idx = indexOf(in[i], idx, buffer)) != -1) {
            buffer.replace(idx, idx + in[i].length(), out);
        }
    }
    return buffer.toString();
}