Example usage for java.lang StringBuilder indexOf

List of usage examples for java.lang StringBuilder indexOf

Introduction

In this page you can find the example usage for java.lang StringBuilder indexOf.

Prototype

@Override
    public int indexOf(String str) 

Source Link

Usage

From source file:edu.cornell.med.icb.util.ICBStringUtils.java

/**
 * Highlight occurrences of highlightWords within
 * toHighlight. Place the value highlightStart before
 * the word and highlightEnd after it. You must provide
 * at least one of highlightStart & highlightEnd.
 * This WILL ignore the case of highlightWords when
 * marking the string./*from  ww  w .j  av a2  s .  c om*/
 * @param toHighlight the text to highlight
 * @param highlightWords the array of words to highlight
 * within toHighlight
 * @param highlightStart the text to place before highlightWords
 * @param highlightEnd the text to place before highlightWords
 * @return the highlighted text
 */
public static String highlightStrings(final String toHighlight, final String[] highlightWords,
        final String highlightStart, final String highlightEnd) {
    if (StringUtils.isBlank(toHighlight)) {
        // Source word is empty, nothing to do.
        return toHighlight;
    }
    final String[] cleanHighlightWords = cleanStringArray(highlightWords);
    if (cleanHighlightWords == null || cleanHighlightWords.length == 0) {
        // No words to highlight, nothing to do
        return toHighlight;
    }
    for (int i = 0; i < cleanHighlightWords.length; i++) {
        cleanHighlightWords[i] = cleanHighlightWords[i].toLowerCase();
    }
    if (StringUtils.isBlank(highlightStart) && StringUtils.isBlank(highlightEnd)) {
        // No markup tags, nothing to do.
        return toHighlight;
    }

    final StringBuilder input = new StringBuilder(toHighlight);
    final StringBuilder inputLC = new StringBuilder(toHighlight.toLowerCase());
    final StringBuilder output = new StringBuilder();
    final StringBuilder tagStart;
    final StringBuilder tagEnd;

    if (highlightStart == null) {
        tagStart = new StringBuilder();
    } else {
        tagStart = new StringBuilder(highlightStart);
    }

    if (highlightEnd == null) {
        tagEnd = new StringBuilder();
    } else {
        tagEnd = new StringBuilder(highlightEnd);
    }

    int pos;
    int size;
    while (true) {
        if (input.length() == 0) {
            // No more text to search.
            break;
        }

        pos = -1;
        size = -1;
        for (final String toFind : cleanHighlightWords) {
            // Find the FIRST of the highlight words
            final int curPos = inputLC.indexOf(toFind);
            if (curPos != -1) {
                // We have a match
                if (pos == -1) {
                    // First match, keep it
                    pos = curPos;
                    size = toFind.length();
                } else if (curPos < pos) {
                    // Earlier match that what we fond before,
                    // keep it
                    pos = curPos;
                    size = toFind.length();
                }
            }
        }
        if (pos == -1) {
            // We're done, no more matches.
            output.append(input);
            break;
        }
        assert size > 0;
        if (pos > 0) {
            // Copy before position
            output.append(input.substring(0, pos));
        }
        // Highlight and copy the text
        output.append(tagStart);
        output.append(input.substring(pos, pos + size));
        output.append(tagEnd);

        // Remove the text from the source so we can
        // find the next occurrence.
        input.delete(0, pos + size);
        inputLC.delete(0, pos + size);
    }
    return output.toString();
}

From source file:org.wso2.carbon.identity.governance.store.InMemoryIdentityDataStore.java

@Override
public UserIdentityClaim load(String userName, UserStoreManager userStoreManager) {

    try {/*w  w  w. ja va2  s.  co m*/
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        Cache<String, UserIdentityClaim> cache = getCache();
        if (userName != null && cache != null) {
            if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) {
                if (!IdentityUtil.isUserStoreCaseSensitive(
                        (org.wso2.carbon.user.core.UserStoreManager) userStoreManager)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Case insensitive user store found. Changing username from : " + userName
                                + " to : " + userName.toLowerCase());
                    }
                    userName = userName.toLowerCase();
                }
            }

            org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager) userStoreManager;

            String domainName = store.getRealmConfiguration()
                    .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

            UserIdentityClaim userIdentityDTO = cache
                    .get(domainName + userStoreManager.getTenantId() + userName);

            if (userIdentityDTO != null && log.isDebugEnabled()) {
                StringBuilder data = new StringBuilder("{");
                if (userIdentityDTO.getUserIdentityDataMap() != null) {
                    for (Map.Entry<String, String> entry : userIdentityDTO.getUserIdentityDataMap()
                            .entrySet()) {
                        data.append("[" + entry.getKey() + " = " + entry.getValue() + "], ");
                    }
                }
                if (data.indexOf(",") >= 0) {
                    data.deleteCharAt(data.lastIndexOf(","));
                }
                data.append("}");
                log.debug("Loaded UserIdentityClaimsDO from cache for user :" + userName + " with claims: "
                        + data);

            }
            return userIdentityDTO;
        }
    } catch (UserStoreException e) {
        log.error("Error while obtaining tenant ID from user store manager");
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    return null;
}

From source file:gool.generator.common.CommonCodeGenerator.java

/**
 * <pre>/*from w w w.  j  a  v a2 s .c o  m*/
 * Produce indented code in a manner similar to printf but with custom conversions.
 * %%  a single "%"
 * %s  Print an argument as a string, without indentation or newlines added.
 *     Similar to the corresponding flag of <i>String.format</i>.
 * %<i>n</i>  (where <i>n</i> is a digit)
 *     Print an argument as a bloc indented <i>n</i> times from the current indentation level.
 *     Newlines are inserted before and after the bloc.
 * %-<i>n</i> (where <i>n</i> is a digit)
 *     <i>n</i> times the indentation string, does not consumes a argument.
 *     %-0 becomes a empty string (it does nothing but is still parsed)
 * 
 * @param format
 *            the format string
 * @param arguments
 *            the objects to format, each one corresponding to a % code
 * @return the formated string
 */
protected String formatIndented(String format, Object... arguments) {
    StringBuilder sb = new StringBuilder(format);
    int pos = sb.indexOf("%");
    int arg = 0;
    while (pos != -1) {
        if (sb.charAt(pos + 1) == '%') {
            sb = sb.replace(pos, pos + 2, "%");
        } else if (sb.charAt(pos + 1) == 's') {
            sb = sb.replace(pos, pos + 2, arguments[arg].toString());
            pos += arguments[arg].toString().length() - 1;
            arg++;
        } else if (Character.isDigit(sb.charAt(pos + 1))) {
            String replacement = ("\n" + arguments[arg].toString().replaceFirst("\\s*\\z", "")).replace("\n",
                    "\n" + StringUtils.repeat(indentation, Character.digit(sb.charAt(pos + 1), 10))) + "\n";
            sb = sb.replace(pos, pos + 2, replacement);
            pos += replacement.length() - 1;
            arg++;
        } else if (sb.charAt(pos + 1) == '-' && Character.isDigit(sb.charAt(pos + 2))) {
            String replacement = StringUtils.repeat(indentation, Character.digit(sb.charAt(pos + 2), 10));
            sb = sb.replace(pos, pos + 3, replacement);
            pos += replacement.length();
        }
        pos = sb.indexOf("%", pos);
    }
    return sb.toString();
}

From source file:org.mule.endpoint.URIBuilder.java

private void removeRootTrailingSlash(StringBuilder buffer) {
    int lastIndex = buffer.length() - 1;

    if (lastIndex >= 0 && buffer.charAt(lastIndex) == SLASH.charAt(0)) {
        int start = 0;
        int index = buffer.indexOf(DOTS_SLASHES);

        if (index != -1) {
            start = index + DOTS_SLASHES.length();
        }// w w w . ja va  2 s  .  c o  m

        if (buffer.indexOf(SLASH, start) == lastIndex) {
            buffer.deleteCharAt(lastIndex);
        }
    }
}

From source file:io.wcm.caravan.io.http.request.RequestTemplate.java

/**
 * if there are any query params in the URL, this will extract them out.
 *///from  w  w  w .jav  a 2 s  .c om
private StringBuilder pullAnyQueriesOutOfUrl(StringBuilder url) {
    // parse out queries
    int queryIndex = url.indexOf("?");
    if (queryIndex != -1) {
        String queryLine = url.substring(queryIndex + 1);
        Map<String, Collection<String>> firstQueries = parseAndDecodeQueries(queryLine);
        if (!queries.isEmpty()) {
            firstQueries.putAll(queries);
            queries.clear();
        }
        //Since we decode all queries, we want to use the
        //query()-method to re-add them to ensure that all
        //logic (such as url-encoding) are executed, giving
        //a valid queryLine()
        for (String key : firstQueries.keySet()) {
            Collection<String> values = firstQueries.get(key);
            if (allValuesAreNull(values)) {
                //Queryies where all values are null will
                //be ignored by the query(key, value)-method
                //So we manually avoid this case here, to ensure that
                //we still fulfill the contract (ex. parameters without values)
                queries.put(urlEncode(key), values);
            } else {
                query(key, values);
            }

        }
        return new StringBuilder(url.substring(0, queryIndex));
    }
    return url;
}

From source file:org.rhq.enterprise.server.measurement.util.MeasurementDataManagerUtility.java

private void replaceNextPlaceHolders(StringBuilder sqlWithQuestionMarks, Object... valuesToReplace) {
    for (Object nextValue : valuesToReplace) {
        int index = sqlWithQuestionMarks.indexOf("?");
        sqlWithQuestionMarks.replace(index, index + 1, String.valueOf(nextValue));
    }/* w w  w  .  j  a  v a 2 s .c  o  m*/
}

From source file:kr.wdream.storyshop.AndroidUtilities.java

public static SpannableStringBuilder replaceTags(String str, int flag) {
    try {//from  w  w w  .  j a v  a 2 s  .c  o  m
        int start;
        int end;
        StringBuilder stringBuilder = new StringBuilder(str);
        if ((flag & FLAG_TAG_BR) != 0) {
            while ((start = stringBuilder.indexOf("<br>")) != -1) {
                stringBuilder.replace(start, start + 4, "\n");
            }
            while ((start = stringBuilder.indexOf("<br/>")) != -1) {
                stringBuilder.replace(start, start + 5, "\n");
            }
        }
        ArrayList<Integer> bolds = new ArrayList<>();
        if ((flag & FLAG_TAG_BOLD) != 0) {
            while ((start = stringBuilder.indexOf("<b>")) != -1) {
                stringBuilder.replace(start, start + 3, "");
                end = stringBuilder.indexOf("</b>");
                if (end == -1) {
                    end = stringBuilder.indexOf("<b>");
                }
                stringBuilder.replace(end, end + 4, "");
                bolds.add(start);
                bolds.add(end);
            }
        }
        ArrayList<Integer> colors = new ArrayList<>();
        if ((flag & FLAG_TAG_COLOR) != 0) {
            while ((start = stringBuilder.indexOf("<c#")) != -1) {
                stringBuilder.replace(start, start + 2, "");
                end = stringBuilder.indexOf(">", start);
                int color = Color.parseColor(stringBuilder.substring(start, end));
                stringBuilder.replace(start, end + 1, "");
                end = stringBuilder.indexOf("</c>");
                stringBuilder.replace(end, end + 4, "");
                colors.add(start);
                colors.add(end);
                colors.add(color);
            }
        }
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder);
        for (int a = 0; a < bolds.size() / 2; a++) {
            spannableStringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")),
                    bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        for (int a = 0; a < colors.size() / 3; a++) {
            spannableStringBuilder.setSpan(new ForegroundColorSpan(colors.get(a * 3 + 2)), colors.get(a * 3),
                    colors.get(a * 3 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableStringBuilder;
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
    return new SpannableStringBuilder(str);
}

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

private Pair<Integer, Integer> findDeepestCondition(final StringBuilder sb, final String inStr,
        final String outStr) {
    Pair<Integer, Integer> bounds = null;

    final int inStrLen = inStr.length();

    // get first//from  ww w  .  java  2  s.  com
    int index = sb.indexOf(inStr);
    int indexStop = sb.indexOf(outStr, index + inStrLen);

    if (index > -1 && indexStop > -1) {
        for (; index > -1 && index < indexStop;) {
            bounds = new MutablePair<Integer, Integer>(index + inStrLen, indexStop);

            // get next
            index = sb.indexOf(inStr, index + inStrLen);
        }
    }

    return bounds;
}

From source file:com.bazaarvoice.seo.sdk.BVManagedUIContent.java

public String getAggregateRating(BVParameters bvQueryParams) {
    long startTime = System.currentTimeMillis();
    postProcess(bvQueryParams);/*from   www .j a v a 2  s .  c o  m*/

    StringBuilder uiContent = null;
    if (StringUtils.isBlank(validationError)) {
        if (bvUiContentService.isSdkEnabled()) {
            uiContent = bvUiContentService.executeCall(reloadContent);
        } else {
            _logger.info(BVMessageUtil.getMessage("MSG0003"));
            uiContent = new StringBuilder();
        }

        if (uiContent != null) {
            int startIndex = uiContent.indexOf("<!--begin-reviews-->");
            if (startIndex != -1) {
                String endReviews = "<!--end-reviews-->";
                int endIndex = uiContent.indexOf(endReviews) + endReviews.length();
                uiContent.delete(startIndex, endIndex);

                startIndex = uiContent.indexOf("<!--begin-pagination-->");
                if (startIndex != -1) {
                    String endPagination = "<!--end-pagination-->";
                    endIndex = uiContent.indexOf(endPagination) + endPagination.length();
                    uiContent.delete(startIndex, endIndex);
                }
            }

            startIndex = uiContent.indexOf("<!--begin-aggregate-rating-->");
            if (startIndex == -1 && bvUiContentService.getMessage().length() == 0) {
                message.append(BVMessageUtil.getMessage("ERR0003"));
            }
        } else {
            uiContent = new StringBuilder();
        }

        bvFooter.addMessage(bvUiContentService.getMessage().toString());
    } else {
        uiContent = new StringBuilder();
        bvFooter.addMessage(validationError);
    }

    bvFooter.addMessage(message.toString());
    bvFooter.setExecutionTime(System.currentTimeMillis() - startTime);
    uiContent.append(bvFooter.displayFooter("getAggregateRating"));

    return uiContent.toString();
}