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:Main.java

public static Pair<String, String> ReorderRTLTextForPebble(String source, int charLimit) {
    if (source == null || source.equals(""))
        return new Pair<>("", "");

    if (!hebrewPattern.matcher(source).find()) {
        return new Pair<>(source, "");
    } else {/*from  w  w  w  . ja  va 2s  .  co  m*/

        StringBuilder sbResult = new StringBuilder();
        StringBuilder sbExtraResult = new StringBuilder();
        StringBuilder sbTemp = new StringBuilder();
        String[] words = source.split(" ");
        int charCount = 0;

        for (int wordIndex = 0; wordIndex < words.length; wordIndex++, sbTemp.setLength(0)) {
            sbTemp.append(words[wordIndex]);
            charCount += sbTemp.length();
            Matcher hebrewWord = hebrewPattern.matcher(words[wordIndex]);

            if (hebrewWord.find()) {
                sbTemp.reverse();
                if (sbTemp.charAt(0) == ')') {
                    sbTemp.replace(0, 1, "(");
                }
                if (sbTemp.charAt(sbTemp.length() - 1) == '(') {
                    sbTemp.replace(sbTemp.length() - 1, sbTemp.length(), ")");
                }
            }

            if (charCount <= charLimit) {
                sbResult.insert(0, sbTemp + " ");
            } else {
                sbExtraResult.insert(0, sbTemp + " ");
            }

            charCount++;
        }

        if (sbExtraResult.length() > charLimit) {
            sbExtraResult.replace(0, sbExtraResult.length() - charLimit, "...");
        }

        return new Pair<>(sbResult.toString().trim(), sbExtraResult.toString().trim());
    }
}

From source file:com.google.visualization.datasource.render.CsvRenderer.java

/**
 * Generates a csv string representation of a data table.
 *
 * @param dataTable The data table.//ww  w .j a v  a2 s. c o  m
 * @param locale The locale. If null, uses the default from
 *     {@code LocaleUtil#getDefaultLocale}.
 * @param separator The separator string used to delimit row values. 
 *     If the separator is {@code null}, comma is used as a separator.
 *
 * @return The char sequence with the csv string.
 */
public static CharSequence renderDataTable(DataTable dataTable, ULocale locale, String separator) {
    if (separator == null) {
        separator = ",";
    }

    // Deal with empty data table.
    if (dataTable.getColumnDescriptions().isEmpty()) {
        return "";
    }

    // Deal with non-empty data table.
    StringBuilder sb = new StringBuilder();
    List<ColumnDescription> columns = dataTable.getColumnDescriptions();
    // Append column labels
    for (ColumnDescription column : columns) {
        sb.append(escapeString(column.getLabel())).append(separator);
    }

    Map<ValueType, ValueFormatter> formatters = ValueFormatter.createDefaultFormatters(locale);

    // Remove last comma.
    int length = sb.length();
    sb.replace(length - 1, length, "\n");

    // Append the data cells.
    List<TableRow> rows = dataTable.getRows();
    for (TableRow row : rows) {
        List<TableCell> cells = row.getCells();
        for (TableCell cell : cells) {
            String formattedValue = cell.getFormattedValue();
            if (formattedValue == null) {
                formattedValue = formatters.get(cell.getType()).format(cell.getValue());
            }
            if (cell.isNull()) {
                sb.append("null");
            } else {
                ValueType type = cell.getType();
                // Escape the string with quotes if its a text value or if it contains a comma.
                if (formattedValue.indexOf(',') > -1 || type.equals(ValueType.TEXT)) {
                    sb.append(escapeString(formattedValue));
                } else {
                    sb.append(formattedValue);
                }
            }
            sb.append(separator);
        }

        // Remove last comma.
        length = sb.length();
        sb.replace(length - 1, length, "\n");
    }
    return sb.toString();
}

From source file:org.apache.ofbiz.base.util.UtilIO.java

private static StringBuilder filterLineEndings(StringBuilder sb) {
    String nl = System.getProperty("line.separator");
    if (!nl.equals("\n")) {
        int r = 0;
        while (r < sb.length()) {
            int i = sb.indexOf(nl, r);
            if (i == -1) {
                break;
            }/*from  w ww  .  j  av  a2 s  .  co m*/
            sb.replace(i, i + nl.length(), "\n");
            r = i + 1;
        }
    }
    return sb;
}

From source file:org.eclipse.jubula.client.core.utils.RefToken.java

/**
 * @param repl replacement (guid or reference name)
 * @param str base string//from w w w  .  j a  v  a2 s . com
 * @return replaced string
 */
public static String replaceCore(String repl, String str) {
    int start = -1;
    int end = -1;
    StringBuilder builder = new StringBuilder(str);
    if (str.startsWith(PREFIX)) {
        start = 2;
        end = str.length() - 1;
    } else {
        start = 1;
        end = str.length();
    }
    if (start < end) {
        builder.replace(start, end, repl);
        return builder.toString();
    }
    Assert.notReached(Messages.UnexpectedProblemWithStringReplacement);
    return str;
}

From source file:com.google.publicalerts.cap.CapUtil.java

static String toCase(String s, boolean camel) {
    String[] parts = s.split("_");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < parts.length; i++) {
        String part = parts[i];//www .  ja  v  a  2s . co m
        if (part.length() > 0) {
            sb.append(part.substring(0, 1).toUpperCase()).append(part.substring(1).toLowerCase());
        }
    }
    if (!camel && sb.length() > 0) {
        sb.replace(0, 1, String.valueOf(Character.toLowerCase(sb.charAt(0))));
    }
    return sb.toString();
}

From source file:com.foglyn.fogbugz.Utils.java

static String transformNumericAndCommonEntities(String input) {
    StringBuilder sb = new StringBuilder(input);

    int start = 0;
    for (int ampIndex = sb.indexOf("&", start); ampIndex >= 0; ampIndex = sb.indexOf("&", start)) {
        int semicolon = sb.indexOf(";", ampIndex + 1);
        if (semicolon < 0) {
            break;
        }//from  w  w w.ja v a 2 s  .  com

        start = semicolon + 1;

        String entity = sb.substring(ampIndex + 1, semicolon);

        if ("amp".equals(entity)) {
            sb.replace(ampIndex, semicolon + 1, "&");
            start = ampIndex + 1;
            continue;
        }

        if (entity.startsWith("#")) {
            try {
                int v = Integer.valueOf(entity.substring(1));
                if (v >= 0 && v <= 65535) {
                    char c = (char) v;
                    sb.replace(ampIndex, semicolon + 1, "" + c);

                    start = ampIndex + 1;
                    continue;
                }
            } catch (NumberFormatException ex) {
                // ignore
            }
        }
    }

    return sb.toString();
}

From source file:org.wso2.carbon.apimgt.rest.api.store.utils.mappings.APIMappingUtil.java

private static List<APIEndpointURLsDTO> extractEnpointURLs(API api, String tenantDomain)
        throws APIManagementException {
    List<APIEndpointURLsDTO> apiEndpointsList = new ArrayList<>();

    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration();
    Map<String, Environment> environments = config.getApiGatewayEnvironments();

    Set<String> environmentsPublishedByAPI = new HashSet<String>(api.getEnvironments());
    environmentsPublishedByAPI.remove("none");

    Set<String> apiTransports = new HashSet<>(Arrays.asList(api.getTransports().split(",")));
    APIConsumer apiConsumer = RestApiUtil.getLoggedInUserConsumer();

    for (String environmentName : environmentsPublishedByAPI) {
        Environment environment = environments.get(environmentName);
        if (environment != null) {
            APIEnvironmentURLsDTO environmentURLsDTO = new APIEnvironmentURLsDTO();
            String[] gwEndpoints = environment.getApiGatewayEndpoint().split(",");

            Map<String, String> domains = new HashMap<String, String>();
            if (tenantDomain != null) {
                domains = apiConsumer.getTenantDomainMappings(tenantDomain,
                        APIConstants.API_DOMAIN_MAPPINGS_GATEWAY);
            }/*from  w  w w.jav a2  s .  c o m*/

            String customGatewayUrl = null;
            if (domains != null) {
                customGatewayUrl = domains.get(APIConstants.CUSTOM_URL);
            }

            for (String gwEndpoint : gwEndpoints) {
                StringBuilder endpointBuilder = new StringBuilder(gwEndpoint);

                if (customGatewayUrl != null) {
                    int index = endpointBuilder.indexOf("//");
                    endpointBuilder.replace(index + 2, endpointBuilder.length(), customGatewayUrl);
                    endpointBuilder.append(api.getContext().replace("/t/" + tenantDomain, ""));
                } else {
                    endpointBuilder.append(api.getContext());
                }

                if (gwEndpoint.contains("http:") && apiTransports.contains("http")) {
                    environmentURLsDTO.setHttp(endpointBuilder.toString());
                } else if (gwEndpoint.contains("https:") && apiTransports.contains("https")) {
                    environmentURLsDTO.setHttps(endpointBuilder.toString());
                }
            }

            APIEndpointURLsDTO apiEndpointURLsDTO = new APIEndpointURLsDTO();
            apiEndpointURLsDTO.setEnvironmentURLs(environmentURLsDTO);

            apiEndpointURLsDTO.setEnvironmentName(environment.getName());
            apiEndpointURLsDTO.setEnvironmentType(environment.getType());

            apiEndpointsList.add(apiEndpointURLsDTO);
        }
    }

    return apiEndpointsList;
}

From source file:com.ephesoft.dcma.util.EphesoftStringUtil.java

/**
 * Replace if contains oldString with newString in String Builder object.
 *
 * @param builder String on which replacement needs to be performed.
 * @param oldString the old string pattern
 * @param newString the new string pattern
 *//*  www  . j  av  a 2  s  .  com*/
public static void replaceIfContains(StringBuilder builder, final String oldString, final String newString) {
    String tempString = builder.toString();
    if (tempString.contains(oldString)) {
        tempString = tempString.replaceAll(oldString, newString);
        builder = builder.replace(0, builder.length(), tempString);
    }
}

From source file:org.wso2.carbon.apimgt.rest.api.store.v1.mappings.APIMappingUtil.java

/**
 * Extracts the API environment details with access url for each endpoint
 * /*w w w . j a v a2  s  . c om*/
 * @param api API object
 * @param tenantDomain Tenant domain of the API
 * @return the API environment details
 * @throws APIManagementException error while extracting the information
 */
private static List<APIEndpointURLsDTO> extractEnpointURLs(API api, String tenantDomain)
        throws APIManagementException {
    List<APIEndpointURLsDTO> apiEndpointsList = new ArrayList<>();

    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration();
    Map<String, Environment> environments = config.getApiGatewayEnvironments();

    Set<String> environmentsPublishedByAPI = new HashSet<>(api.getEnvironments());
    environmentsPublishedByAPI.remove("none");

    Set<String> apiTransports = new HashSet<>(Arrays.asList(api.getTransports().split(",")));
    APIConsumer apiConsumer = RestApiUtil.getLoggedInUserConsumer();

    for (String environmentName : environmentsPublishedByAPI) {
        Environment environment = environments.get(environmentName);
        if (environment != null) {
            APIEnvironmentURLsDTO environmentURLsDTO = new APIEnvironmentURLsDTO();
            String[] gwEndpoints = environment.getApiGatewayEndpoint().split(",");

            Map<String, String> domains = new HashMap<>();
            if (tenantDomain != null) {
                domains = apiConsumer.getTenantDomainMappings(tenantDomain,
                        APIConstants.API_DOMAIN_MAPPINGS_GATEWAY);
            }

            String customGatewayUrl = null;
            if (domains != null) {
                customGatewayUrl = domains.get(APIConstants.CUSTOM_URL);
            }

            for (String gwEndpoint : gwEndpoints) {
                StringBuilder endpointBuilder = new StringBuilder(gwEndpoint);

                if (customGatewayUrl != null) {
                    int index = endpointBuilder.indexOf("//");
                    endpointBuilder.replace(index + 2, endpointBuilder.length(), customGatewayUrl);
                    endpointBuilder.append(api.getContext().replace("/t/" + tenantDomain, ""));
                } else {
                    endpointBuilder.append(api.getContext());
                }

                if (gwEndpoint.contains("http:") && apiTransports.contains("http")) {
                    environmentURLsDTO.setHttp(endpointBuilder.toString());
                } else if (gwEndpoint.contains("https:") && apiTransports.contains("https")) {
                    environmentURLsDTO.setHttps(endpointBuilder.toString());
                }
            }

            APIEndpointURLsDTO apiEndpointURLsDTO = new APIEndpointURLsDTO();
            apiEndpointURLsDTO.setEnvironmentURLs(environmentURLsDTO);

            apiEndpointURLsDTO.setEnvironmentName(environment.getName());
            apiEndpointURLsDTO.setEnvironmentType(environment.getType());

            apiEndpointsList.add(apiEndpointURLsDTO);
        }
    }

    return apiEndpointsList;
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.html.HtmlWriter.java

private static String convertTags(String s) {
    if (s == null) {
        return null;
    }//from   w  ww.jav a  2 s . co  m

    StringBuilder result = new StringBuilder(s);

    int temp;

    temp = 0;
    while ((temp = result.indexOf("<", temp)) != -1) {
        result.replace(temp, temp + 1, "&lt;");
    }

    temp = 0;
    while ((temp = result.indexOf(">", temp)) != -1) {
        result.replace(temp, temp + 1, "&gt;");
    }

    return result.toString();
}