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.g3net.tool.StringUtils.java

/**
 * src?regex??????? ?(handler)/*from   w  ww  .  j  a  v a 2s .co m*/
 * ?????
 * 
 * @param src
 * @param regex
 *            ??:&(\\d+;)([a-z)+)
 * @param handleGroupIndex
 *            ???
 * @param hander
 *            ?
 * @param reservesGroups
 *            ???,?hander?handleGroupIndex
 *            ?reservesGroups?hander?regex? 
 * @return
 */
public static String replaceAll(String src, String regex, int handleGroupIndex, GroupHandler hander,
        int[] reservesGroups) {

    if (src == null || src.trim().length() == 0) {
        return "";
    }
    Matcher m = Pattern.compile(regex).matcher(src);

    StringBuffer sbuf = new StringBuffer();
    String replacementFirst = "";
    String replacementTail = "";
    if (reservesGroups != null && reservesGroups.length > 0) {
        Arrays.sort(reservesGroups);
        for (int i = 0; i < reservesGroups.length; i++) {
            if (reservesGroups[i] < handleGroupIndex) {
                replacementFirst = replacementFirst + "$" + reservesGroups[i];
            } else {
                replacementTail = replacementTail + "$" + reservesGroups[i];
            }
        }
    }

    // perform the replacements:
    while (m.find()) {
        String value = m.group(handleGroupIndex);

        String group = m.group();

        String handledStr = hander.handler(value);
        String replacement = "";
        if (reservesGroups == null) {
            int start0 = m.start();
            int end0 = m.end();
            int start = m.start(handleGroupIndex);
            int end = m.end(handleGroupIndex);
            int relativeStart = start - start0;
            int relativeEnd = end - start0;
            StringBuilder sbgroup = new StringBuilder(group);
            sbgroup = sbgroup.replace(relativeStart, relativeEnd, handledStr);
            replacement = sbgroup.toString();
        } else {
            replacement = replacementFirst + handledStr + replacementTail;
        }

        m.appendReplacement(sbuf, replacement);

    }
    // Put in the remainder of the text:
    m.appendTail(sbuf);
    return sbuf.toString();
    // return null;
}

From source file:org.eclipse.mdht.uml.cda.core.util.CDACommonUtils.java

public static String getUmlContext(Class clazz, boolean abbr) {
    if (CDACommonUtils.isDatatypeModel(clazz)) {
        return "/datatypes:" + clazz.getName();
    }/*  w  w  w.j  a  v a2 s.  c o  m*/
    List<Property> propertyPath = CDACommonUtils.getPropertyPath(clazz);
    if (propertyPath.isEmpty()) {
        // is either clinical document itself or has no property path leading from a clinicial document
        return "/" + clazz.getName();
    }
    EObject eContainer = propertyPath.get(0).eContainer();
    StringBuilder umlContext = new StringBuilder(
            "/" + (eContainer instanceof Class ? ((Class) eContainer).getName() : "root"));
    for (Property property : propertyPath) {
        Class class1 = (Class) property.getType();
        umlContext.append("/" + property.getName());
        if (abbr && class1 != null && !(class1.eContainer() instanceof Class)) {
            umlContext.replace(0, umlContext.length(), "/" + class1.getName());
        }
    }
    return umlContext.toString();
}

From source file:org.jumpmind.db.sql.DmlStatement.java

protected void appendColumnQuestions(StringBuilder sql, Column[] columns) {
    if (columns != null) {
        for (int i = 0; i < columns.length; i++) {
            if (columns[i] != null) {
                appendColumnQuestion(sql, columns[i]);
            }//from  w  ww .  j a  va  2  s  .  com
        }

        if (columns.length > 0) {
            sql.replace(sql.length() - 1, sql.length(), "");
        }
    }
}

From source file:com.streamsets.pipeline.stage.processor.fieldmask.FieldMaskProcessor.java

@VisibleForTesting
String regExMask(Field field, FieldMaskConfig fieldMaskConfig) {
    String value = field.getValueAsString();
    Matcher matcher = regExToPatternMap.get(fieldMaskConfig.regex).matcher(value);
    if (matcher.matches()) {
        int groupCount = matcher.groupCount();
        //create a masked string of the same length as the original string
        StringBuilder resultString = new StringBuilder();
        for (int i = 0; i < value.length(); i++) {
            resultString.append(MASK_CHAR);
        }//ww  w .  ja  v a2s .c o  m
        //for each group that needs to be shown, replace the masked string with the original string characters at those
        //positions
        Set<Integer> groupsToShow = regexToGroupsToShowMap.get(fieldMaskConfig.regex);
        if (groupsToShow != null && !groupsToShow.isEmpty()) {
            for (int i = 1; i <= groupCount; i++) {
                if (groupsToShow.contains(i)) {
                    resultString.replace(matcher.start(i), matcher.end(i), matcher.group(i));
                }
            }
        }
        return resultString.toString();
    }
    return field.getValueAsString();
}

From source file:fr.landel.utils.commons.StringUtils.java

/**
 * Injects all arguments in the specified char sequence. The arguments are
 * injected by replacement of the braces. If no index is specified between
 * braces, an internal index is created and the index is automatically
 * incremented. The index starts from 0. To exclude braces, just double them
 * (like {{0}} will return {0}). If number greater than arguments number are
 * specified, they are ignored./*from ww w.j  a  v  a  2 s.c  o m*/
 * 
 * <p>
 * precondition: {@code charSequence} cannot be {@code null}
 * </p>
 * 
 * <pre>
 * StringUtils.inject("", "test"); // =&gt; ""
 * 
 * StringUtils.inject("I'll go to the {} this {}", "beach", "afternoon");
 * // =&gt; "I'll go to the beach this afternoon"
 * 
 * StringUtils.inject("I'll go to the {1} this {0}", "afternoon", "beach");
 * // =&gt; "I'll go to the beach this afternoon"
 * 
 * StringUtils.inject("I'll go to the {1} this {}", "afternoon", "beach");
 * // =&gt; "I'll go to the beach this afternoon"
 * 
 * StringUtils.inject("I'll go to {} {3} {} {2}", "the", "this", "afternoon", "beach");
 * // =&gt; "I'll go to the beach this afternoon"
 * 
 * StringUtils.inject("I'll go to {{}}{3} {} {2}{{0}} {4} {text}", "the", "this", "afternoon", "beach");
 * // =&gt; "I'll go to {}beach the afternoon{0} {4} {text}"
 * </pre>
 * 
 * @param charSequence
 *            the input char sequence
 * @param arguments
 *            the arguments to inject
 * @param <T>
 *            the arguments type
 * @return the result with replacements
 */
@SafeVarargs
public static <T> String inject(final CharSequence charSequence, final T... arguments) {
    if (charSequence == null) {
        throw new IllegalArgumentException("The input char sequence cannot be null");
    } else if (isEmpty(charSequence) || arguments == null || arguments.length == 0) {
        return charSequence.toString();
    }

    final StringBuilder output = new StringBuilder(charSequence);

    // if no brace, just returns the string
    if (output.indexOf(BRACE_OPEN) < 0) {
        return output.toString();
    }

    // replace the excluded braces by a temporary string
    replaceBrace(output, BRACE_OPEN_EXCLUDE, BRACE_OPEN_TMP);
    replaceBrace(output, BRACE_CLOSE_EXCLUDE, BRACE_CLOSE_TMP);

    // replace the braces without index by the arguments
    int i = 0;
    int index = 0;
    while ((index = output.indexOf(BRACES, index)) > -1 && i < arguments.length) {
        output.replace(index, index + BRACES.length(), String.valueOf(arguments[i++]));
        index += BRACES.length();
    }

    // replace braces with index by the arguments
    int len;
    String param;
    for (i = 0; i < arguments.length; ++i) {
        index = 0;
        param = new StringBuilder(BRACE_OPEN).append(i).append(BRACE_CLOSE).toString();
        len = param.length();
        while ((index = output.indexOf(param, index)) > -1) {
            output.replace(index, index + len, String.valueOf(arguments[i]));
            index += len;
        }
    }

    // replace the temporary brace by the simple brace
    replaceBrace(output, BRACE_OPEN_TMP, BRACE_OPEN);
    replaceBrace(output, BRACE_CLOSE_TMP, BRACE_CLOSE);

    return output.toString();
}

From source file:net.duckling.ddl.service.resource.dao.ResourceDAOImpl.java

@Override
public int batchDelete(final List<Integer> rids) {
    if (null == rids || rids.isEmpty()) {
        return 0;
    }//  w  w w .  ja va  2  s.c o  m
    String sql = "update a1_resource set status='" + LynxConstants.STATUS_DELETE + "' where rid in(";
    int size = rids.size();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < size; i++) {
        sb.append(rids.get(i) + ",");
    }
    sb.replace(sb.lastIndexOf(","), sb.length(), ")");
    sql += sb.toString();
    return this.getJdbcTemplate().update(sql);
}

From source file:net.duckling.ddl.service.resource.dao.ResourceDAOImpl.java

private String buildSphinxIdsSQL(List<Long> page_ids) {
    StringBuilder sb = new StringBuilder();
    sb.append("(");
    for (Long l : page_ids) {
        sb.append(l + ",");
    }// w ww.j  a  va  2  s. c om
    sb.replace(sb.lastIndexOf(","), sb.length(), ")");
    return sb.toString();
}

From source file:net.dmulloy2.swornrpg.commands.CmdStaffList.java

@Override
public void perform() {
    // Calculate online staff
    Map<String, List<String>> staffMap = new HashMap<>();

    int total = 0;

    for (Player player : Util.getOnlinePlayers()) {
        if (plugin.getPermissionHandler().hasPermission(player, Permission.STAFF)) {
            if (plugin.isVaultEnabled()) {
                String group = plugin.getVaultHandler().getGroup(player);
                if (group != null) {
                    if (!staffMap.containsKey(group)) {
                        staffMap.put(group, new ArrayList<String>());
                    }/*from w w  w .  jav  a2 s.c  om*/

                    staffMap.get(group).add((player.isOp() ? "&b" : "&e") + player.getName());
                }
            } else {
                if (!staffMap.containsKey("staff")) {
                    staffMap.put("staff", new ArrayList<String>());
                }

                staffMap.get("staff").add(player.isOp() ? "&b" : "&e" + player.getName());
            }

            total++;
        }
    }

    List<String> lines = new ArrayList<String>();

    StringBuilder line = new StringBuilder();
    line.append(FormatUtil.format(getMessage("stafflist_header"), total, plugin.getServer().getMaxPlayers()));
    lines.add(line.toString());

    // Specific Group

    String group = "all";
    if (args.length > 0) {
        group = args[0];
    }

    if (staffMap.containsKey(group)) {
        line = new StringBuilder();
        line.append("&3" + WordUtils.capitalize(group) + "&e: ");

        for (String player : staffMap.get(group)) {
            line.append("&e" + player + "&b, ");
        }

        if (line.lastIndexOf("&b, ") >= 0) {
            line.replace(line.lastIndexOf("&"), line.lastIndexOf(" "), "");
        }

        lines.add(line.toString());

        for (String string : lines)
            sendMessage(string);

        return;
    }

    // All online staff

    for (Entry<String, List<String>> entry : staffMap.entrySet()) {
        line = new StringBuilder();
        line.append("&3" + WordUtils.capitalize(entry.getKey()) + "&e: ");

        for (String player : entry.getValue()) {
            line.append("&e" + player + "&b, ");
        }

        if (line.lastIndexOf("&b, ") >= 0) {
            line.replace(line.lastIndexOf("&"), line.lastIndexOf(" "), "");
        }

        lines.add(line.toString());
    }

    for (String string : lines)
        sendMessage(string);
}

From source file:org.wso2.carbon.identity.authenticator.inbound.saml2sso.test.RequestSigningTests.java

/**
 * Test inbound authentication with redirect binding with invalid signature parameter.
 *///  w  w  w  .j  a v  a  2 s  .com
@Test
public void testAuthnRequestSignatureValidationWithInvalidSignatureForRedirect() {

    ServiceProviderConfig serviceProviderConfig = TestUtils
            .getServiceProviderConfigs(TestConstants.SAMPLE_ISSUER_NAME, bundleContext);
    serviceProviderConfig.getRequestValidationConfig().getRequestValidatorConfigs().get(0).getProperties()
            .setProperty(SAML2AuthConstants.Config.Name.AUTHN_REQUEST_SIGNED, "true");
    try {
        AuthnRequest samlRequest = TestUtils.buildAuthnRequest("https://localhost:9292/gateway", false, false,
                TestConstants.SAMPLE_ISSUER_NAME, TestConstants.ACS_URL);
        String samlRequestString = SAML2AuthUtils.encodeForRedirect(samlRequest);

        StringBuilder httpQueryString = new StringBuilder(
                SAML2AuthConstants.SAML_REQUEST + "=" + samlRequestString);
        httpQueryString.append("&" + SAML2AuthConstants.RELAY_STATE + "="
                + URLEncoder.encode("relayState", StandardCharsets.UTF_8.name()).trim());
        SAML2AuthUtils.addSignatureToHTTPQueryString(httpQueryString,
                "http://www.w3.org/2000/09/xmldsig#rsa-sha1", SAML2AuthUtils.getServerCredentials());

        httpQueryString.replace(httpQueryString.indexOf("Signature=") + 10, httpQueryString.length(),
                "invalid_signature");
        HttpURLConnection urlConnection = TestUtils.request(
                TestConstants.GATEWAY_ENDPOINT + "?" + httpQueryString.toString(), HttpMethod.GET, false);
        String postBody = TestUtils.getContent(urlConnection);
        //          Relay state must be returned for error scenarios as well
        //            Assert.assertTrue(postBody.contains(TestConstants.RELAY_STATE));

        Assert.assertEquals(urlConnection.getResponseCode(), 200);
        Assert.assertNotNull(postBody);
        String samlResponse = postBody.split("SAMLResponse' value='")[1].split("'>")[0];
        Response samlResponseObject = TestUtils.getSAMLResponse(samlResponse);
        Assert.assertEquals(samlResponseObject.getAssertions().size(), 0);

    } catch (IOException e) {
        Assert.fail("Error while running testSAMLInboundAuthentication test case", e);
    } catch (SAML2SSOServerException e) {
        Assert.fail("Error while building response object", e);
    } finally {
        serviceProviderConfig.getRequestValidationConfig().getRequestValidatorConfigs().get(0).getProperties()
                .setProperty(SAML2AuthConstants.Config.Name.AUTHN_REQUEST_SIGNED, "false");
    }
}

From source file:it.andreascarpino.ansible.inventory.type.AnsibleVariable.java

public String objToString(Object value) {
    final StringBuilder buf = new StringBuilder();

    for (Field f : value.getClass().getDeclaredFields()) {
        f.setAccessible(true);/* w w w. jav  a  2  s . c om*/

        try {
            buf.append("'" + f.getName() + "': ");
            if (ClassUtils.isPrimitiveOrWrapper(value.getClass()) || value instanceof String) {
                buf.append("'" + value + "'");
            } else {
                buf.append(valueToString(f.get(value)));
            }
            buf.append(", ");
        } catch (IllegalArgumentException | IllegalAccessException e) {
            // Silently ignore errors
            e.printStackTrace();
        }
    }
    buf.replace(buf.length() - 2, buf.length(), "");

    return buf.toString();
}