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:com.aurel.track.lucene.search.LuceneSearcher.java

/**
 * Preprocess a boolean field.//from  w w w .  j a  v a  2  s .c om
 * Looks up the matchings by the localized name of the boolean value 
 *    
 * @param toBeProcessedString a part of the user entered query string
 * @param fieldName the name of the user entered field
 * @param indexStart the index to start looking for fieldName
 * @param locale
 * @return
 */
private static String preprocessBoolean(String toBeProcessedString, String fieldName, int indexStart,
        Locale locale) {
    int indexFound = fieldNameIndex(toBeProcessedString, fieldName, indexStart);
    if (indexFound == -1) {
        return toBeProcessedString;
    }
    int beginReplaceIndex = indexFound + fieldName.length() + 1;
    //gets the user entered value of the field
    //this could be a normal date or a date range
    String originalFieldValue = getFieldValue(toBeProcessedString.substring(beginReplaceIndex));
    if (originalFieldValue == null || "".equals(originalFieldValue)) {
        return toBeProcessedString;
    }
    String processedFieldValue = transformBooleanFields(originalFieldValue, locale);

    if (processedFieldValue == null || "".equals(processedFieldValue)) {
        return toBeProcessedString;
    }
    StringBuffer original = new StringBuffer(toBeProcessedString);
    original.replace(beginReplaceIndex, beginReplaceIndex + originalFieldValue.length(), processedFieldValue);
    return preprocessBoolean(original.toString(), fieldName, beginReplaceIndex + processedFieldValue.length(),
            locale);
}

From source file:util.StripHTMLTags.java

/**
 * This strips any given complete pattern from the body.
 *
 * @StringBuffer the body to strip/*w w  w .  ja  v a2 s.  com*/
 * @String the pattern to apply
 * @return StringBuffer return the stripped body
 */
StringBuffer stripPattern(StringBuffer body, String pattern) {
    Pattern mypattern = Pattern.compile(pattern, Pattern.DOTALL);
    Matcher matcher = mypattern.matcher(body);
    while (matcher.find()) {
        body = body.replace(matcher.start(), matcher.end(), "");
    }
    return body;
}

From source file:com.aurel.track.lucene.search.LuceneSearcher.java

/**
 * Preprocess a composite field. /*from ww w  . ja v a2  s .c  o m*/
 * The composite string is separated into parts by the # character 
 * @param analyzer
 * @param toBeProcessedString a part of the user entered query string
 * @param fieldName the name of the user entered field
 * @param indexStart the index to start looking for fieldName
 * @param locale
 * @return
 */
private static String preprocessComposite(Analyzer analyzer, String toBeProcessedString, String fieldName,
        Integer fieldID, int indexStart, Locale locale) {
    int indexFound = fieldNameIndex(toBeProcessedString, fieldName, indexStart);
    if (indexFound == -1) {
        return toBeProcessedString;
    }
    int beginReplaceIndex = indexFound + fieldName.length() + 1;
    //gets the user entered value of the field
    String originalFieldValue = getFieldValue(toBeProcessedString.substring(beginReplaceIndex));
    if (originalFieldValue == null || "".equals(originalFieldValue)) {
        return toBeProcessedString;
    }
    String processedFieldValue;
    //get rid of parenthesis and quotation marks from both ends of the entire originalFieldValue (if it is the case) 
    //because otherwise they would be interpreted as part of the searched strings
    //TODO what if by pc:(p1#c11) somebody want to find the string "(p1" for the first part and "c11)" for the second part?
    //then delete the following two if-s and make sure that if such case happens than the parentheses are part of the searched string 
    String strippedFieldValue = originalFieldValue;
    if (originalFieldValue.startsWith("(") && originalFieldValue.endsWith(")")) {
        strippedFieldValue = originalFieldValue.substring(1, originalFieldValue.length() - 1);
    }
    if (originalFieldValue.startsWith("\"") && originalFieldValue.endsWith("\"")) {
        strippedFieldValue = originalFieldValue.substring(1, originalFieldValue.length() - 1);
    }
    processedFieldValue = transformCompositeFields(analyzer, fieldName, fieldID, strippedFieldValue, locale);
    if (processedFieldValue == null || "".equals(processedFieldValue)) {
        return toBeProcessedString;
    }
    StringBuffer original = new StringBuffer(toBeProcessedString);
    original.replace(beginReplaceIndex - fieldName.length() - 1,
            beginReplaceIndex + originalFieldValue.length(), processedFieldValue);
    return preprocessComposite(analyzer, original.toString(), fieldName, fieldID,
            beginReplaceIndex + processedFieldValue.length(), locale);
}

From source file:grails.plugin.springsecurity.web.filter.DebugFilter.java

protected void log(boolean dumpStack, String message, Object... args) {
    StringBuilder output = new StringBuilder(256);
    output.append("\n\n************************************************************\n\n");
    output.append(message).append("\n");

    if (dumpStack) {
        StringWriter os = new StringWriter();
        GrailsUtil.deepSanitize(new Exception()).printStackTrace(new PrintWriter(os));
        StringBuffer buffer = os.getBuffer();
        // Remove the exception in case it scares people.
        int start = buffer.indexOf("java.lang.Exception");
        buffer.replace(start, start + 19, "");
        output.append("\nCall stack: \n").append(os);
    }/*from ww w.j a  v  a  2 s  . com*/

    output.append("\n\n************************************************************\n\n");
    log.info(output.toString(), args);
}

From source file:com.wavemaker.common.util.StringUtils.java

/**
 * Return a String with all occurrences of the "from" String within "original" replaced with the "to" String. If the
 * "original" string contains no occurrences of "from", "original" is itself returned, rather than a copy.
 * /* w  w  w. ja v a2s  .  c o m*/
 * @param original the original String
 * @param from the String to replace within "original"
 * @param to the String to replace "from" with
 * 
 * @returns a version of "original" with all occurrences of the "from" parameter being replaced with the "to"
 *          parameter.
 */
public static String replacePlainStr(String original, String from, String to) {
    int from_length = from.length();

    if (from_length != to.length()) {
        if (from_length == 0) {
            if (to.length() != 0) {
                throw new IllegalArgumentException("Replacing the empty string with something was attempted");
            }
        }
        int start = original.indexOf(from);
        if (start == -1) {
            return original;
        }
        char[] original_chars = original.toCharArray();
        StringBuffer buffer = new StringBuffer(original.length());
        int copy_from = 0;
        while (start != -1) {
            buffer.append(original_chars, copy_from, start - copy_from);
            buffer.append(to);
            copy_from = start + from_length;
            start = original.indexOf(from, copy_from);
        }
        buffer.append(original_chars, copy_from, original_chars.length - copy_from);
        return buffer.toString();
    } else {
        if (from.equals(to)) {
            return original;
        }
        int start = original.indexOf(from);
        if (start == -1) {
            return original;
        }
        StringBuffer buffer = new StringBuffer(original);
        while (start != -1) {
            buffer.replace(start, start + from_length, to);
            start = original.indexOf(from, start + from_length);
        }
        return buffer.toString();
    }
}

From source file:net.wasdev.gameon.auth.github.GitHubCallback.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //ok, we have our code.. so the user has agreed to our app being authed.
    String code = request.getParameter("code");

    String state = (String) request.getSession().getAttribute("github");

    //now we need to invoke the access_token endpoint to swap the code for a token.
    StringBuffer callbackURL = request.getRequestURL();
    int index = callbackURL.lastIndexOf("/");
    callbackURL.replace(index, callbackURL.length(), "").append("/GitHubCallback");

    HttpRequestFactory requestFactory;//from  w w w .  java2 s .c o  m
    try {
        //we'll ignore the ssl cert of the github server for now.. 
        //eventually we may add this to the player truststore.. 
        requestFactory = new NetHttpTransport.Builder().doNotValidateCertificate().build()
                .createRequestFactory();

        //prepare the request.. 
        GenericUrl url = new GenericUrl("https://github.com/login/oauth/access_token");
        //set the client id & secret from the injected environment.
        url.put("client_id", key);
        url.put("client_secret", secret);
        //add the code we just got given.. 
        url.put("code", code);
        url.put("redirect_uri", callbackURL);
        url.put("state", state);

        //now place the request to github..
        HttpRequest infoRequest = requestFactory.buildGetRequest(url);
        HttpResponse r = infoRequest.execute();
        String resp = "failed.";
        if (r.isSuccessStatusCode()) {

            //response comes back as query param encoded data.. we'll grab the token from that...
            resp = r.parseAsString();

            //http client way to parse query params.. 
            List<NameValuePair> params = URLEncodedUtils.parse(resp, Charset.forName("UTF-8"));
            String token = null;
            for (NameValuePair param : params) {
                if ("access_token".equals(param.getName())) {
                    token = param.getValue();
                }
            }

            if (token != null) {
                //great, we have a token, now we can use that to request the user profile..                    
                GenericUrl query = new GenericUrl("https://api.github.com/user");
                query.put("access_token", token);

                HttpRequest userRequest = requestFactory.buildGetRequest(query);
                HttpResponse u = userRequest.execute();
                if (u.isSuccessStatusCode()) {
                    //user profile comes back as json..                         
                    resp = u.parseAsString();
                    System.out.println(resp);

                    //use om to parse the json, so we can grab the id & name from it.
                    ObjectMapper om = new ObjectMapper();
                    JsonNode jn = om.readValue(resp, JsonNode.class);

                    Map<String, String> claims = new HashMap<String, String>();
                    claims.put("valid", "true");
                    //github id is a number, but we'll read it as text incase it changes in future.. 
                    claims.put("id", "github:" + jn.get("id").asText());
                    claims.put("name", jn.get("login").textValue());

                    String jwt = createJwt(claims);

                    //log for now, we'll clean this up once it's all working =)
                    System.out.println("New User Authed: " + claims.get("id") + " jwt " + jwt);
                    response.sendRedirect(callbackSuccess + "/" + jwt);

                } else {
                    System.out.println(u.getStatusCode());
                    response.sendRedirect("http://game-on.org/#/game");
                }
            } else {
                System.out.println("did not find token in github response " + resp);
                response.sendRedirect("http://game-on.org/#/game");
            }
        } else {
            response.sendRedirect("http://game-on.org/#/game");
        }

    } catch (GeneralSecurityException e) {
        throw new ServletException(e);
    }

}

From source file:com.aurel.track.lucene.search.LuceneSearcher.java

/**
 * Preprocess a date field. /*from  w w  w.  j av  a2  s  .  c o m*/
 * It could be a normal date or a date range
 * In both cases the user entered date will be parsed to a date and then
 * converted with DateTools.dateToString(date, Resolution.DAY);
 * @param toBeProcessedString a part of the user entered query string
 * @param fieldName the name of the user entered field
 * @param indexStart the index to start looking for fieldName
 * @param locale
 * @return
 */
private static String preprocessDate(String toBeProcessedString, String fieldName, int indexStart,
        Locale locale) {
    int indexFound = fieldNameIndex(toBeProcessedString, fieldName, indexStart);
    if (indexFound == -1) {
        return toBeProcessedString;
    }
    int beginReplaceIndex = indexFound + fieldName.length() + 1;
    //gets the user entered value of the field
    //this could be a normal date or a date range
    String originalFieldValue = getFieldValue(toBeProcessedString.substring(beginReplaceIndex));
    if (originalFieldValue == null || "".equals(originalFieldValue)) {
        return toBeProcessedString;
    }
    String processedFieldValue;
    if ((originalFieldValue.startsWith("[") || originalFieldValue.startsWith("{"))
            && (originalFieldValue.endsWith("]") || originalFieldValue.endsWith("}"))) {
        String rangeBegin = originalFieldValue.substring(0, 1);
        String rangeEnd = originalFieldValue.substring(originalFieldValue.length() - 1);
        String strippedFieldValue = originalFieldValue.substring(1, originalFieldValue.length() - 1);

        //if date range query we need two dates
        String[] dates;
        String date1 = null;
        String date2 = null;
        String splitString = " TO ";
        dates = strippedFieldValue.split(splitString);
        int i;
        String tmp;
        for (i = 0; i < dates.length; i++) {
            tmp = transformDateFields(dates[i], locale);
            //parses to a date?
            if (!dates[i].equals(tmp)) {
                date1 = tmp;
                break;
            }
        }
        for (int j = i + 1; j < dates.length; j++) {
            tmp = transformDateFields(dates[j], locale);
            //parses to a date?
            if (!dates[j].equals(tmp)) {
                date2 = tmp;
                break;
            }
        }
        if (date1 != null && date2 != null) {
            processedFieldValue = rangeBegin + date1 + splitString + date2 + rangeEnd;
        } else {
            processedFieldValue = originalFieldValue;
        }
    } else {
        processedFieldValue = transformDateFields(originalFieldValue, locale);
    }
    if (processedFieldValue == null || "".equals(processedFieldValue)) {
        return toBeProcessedString;
    }
    StringBuffer original = new StringBuffer(toBeProcessedString);
    original.replace(beginReplaceIndex, beginReplaceIndex + originalFieldValue.length(), processedFieldValue);
    return preprocessDate(original.toString(), fieldName, beginReplaceIndex + processedFieldValue.length(),
            locale);
}

From source file:com.aurel.track.lucene.search.listFields.ExternalListSearcher.java

/**
 * Preprocess a not localized lookup field
 * @param analyzer /*from   w  w w  .j  a v a2s. c om*/
 * @param toBeProcessedString a part of the user entered query string
 * @param workItemFieldName the workItem field name (like CRM Contact)
 * @param luceneFieldName the name of the user entered lucene field (like Company from CRM Contact)
 * @param indexStart the index to start looking for fieldName 
 * @return
 */
@Override
protected String replaceExplicitFieldValue(Analyzer analyzer, String toBeProcessedString,
        String workItemFieldName, String luceneFieldName, Integer fieldID, Locale locale, int indexStart) {
    int indexFound = LuceneSearcher.fieldNameIndex(toBeProcessedString, luceneFieldName, indexStart);
    if (indexFound == -1) {
        return toBeProcessedString;
    }
    int beginReplaceIndex = indexFound + luceneFieldName.length() + 1;
    String originalFieldValue = LuceneSearcher.getFieldValue(toBeProcessedString.substring(beginReplaceIndex));
    if (originalFieldValue == null || "".equals(originalFieldValue)) {
        return toBeProcessedString;
    }
    String processedFieldValue = searchExplicitField(analyzer, luceneFieldName, originalFieldValue, fieldID,
            locale);
    if (processedFieldValue == null || "".equals(processedFieldValue)) {
        return toBeProcessedString;
    }
    StringBuffer original = new StringBuffer(toBeProcessedString);
    original.replace(indexFound, beginReplaceIndex + originalFieldValue.length(),
            workItemFieldName + LuceneSearcher.FIELD_NAME_VALUE_SEPARATOR + processedFieldValue);
    return replaceExplicitFieldValue(analyzer, original.toString(), workItemFieldName, luceneFieldName, fieldID,
            locale, beginReplaceIndex + processedFieldValue.length());
}

From source file:org.springframework.security.config.annotation.web.builders.DebugFilter.java

void log(String message, boolean dumpStack) {
    StringBuilder output = new StringBuilder(256);
    output.append("\n\n************************************************************\n\n");
    output.append(message).append("\n");

    if (dumpStack) {
        StringWriter os = new StringWriter();
        new Exception().printStackTrace(new PrintWriter(os));
        StringBuffer buffer = os.getBuffer();
        // Remove the exception in case it scares people.
        int start = buffer.indexOf("java.lang.Exception");
        buffer.replace(start, start + 19, "");
        output.append("\nCall stack: \n").append(os.toString());
    }/*w  w w. j  a  va  2 s . c o  m*/

    output.append("\n\n************************************************************\n\n");

    logger.info(output.toString());
}

From source file:org.exoplatform.wiki.rendering.render.confluence.ConfluenceSyntaxEscapeHandler.java

private void escapeFirstMatchedCharacter(Pattern pattern, StringBuffer accumulatedBuffer) {
    Matcher matcher = pattern.matcher(accumulatedBuffer);
    if (matcher.lookingAt()) {
        // Escape the first character
        accumulatedBuffer.replace(matcher.start(1), matcher.start(1) + 1,
                ESCAPE_CHAR + matcher.group(1).charAt(0));
    }/* w  ww  .  j ava  2  s.  c om*/
}