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, int fromIndex) 

Source Link

Usage

From source file:de.tudarmstadt.ukp.dkpro.core.io.pdf.Pdf2CasConverter.java

private StringBuilder sanitize(final StringBuilder aContent) {
    int i = 0;//from w ww  .  j  a  v a  2  s  . c o m
    int lastBreak = 0;
    while (i < aContent.length()) {
        // Check valid unicode char
        if (!isValidXMLChar(aContent.codePointAt(i))) {
            aContent.setCharAt(i, ' ');
            i++;
            continue;
        }

        // Set up how many characters we want to skip
        int seek = i + 1;

        // Do we maybe have an entity?
        if (aContent.charAt(i) == '&') {
            // REC 2006-10-21 Some PDFs seem to have entities and others
            // don't
            // so we may encounter &'s that do not introduce an entity and
            // just ignore them.
            final int end = aContent.indexOf(";", i);
            if (end != -1) {
                final String cand = aContent.substring(i, end + 1);
                String r = null;
                try {
                    if (cand.startsWith("&#x")) {
                        final int cp = Integer.parseInt(cand.substring(2, cand.length() - 1), 16);
                        r = isValidXMLChar(cp) ? String.valueOf(Character.toChars(cp)) : " ";
                    } else if (cand.startsWith("&#")) {
                        final int cp = Integer.parseInt(cand.substring(2, cand.length() - 1));
                        r = isValidXMLChar(cp) ? String.valueOf(Character.toChars(cp)) : " ";
                    } else {
                        // RE 2006-10-22 The chance that there is a & and a
                        // ;
                        // together in a string is quite big. Let's be
                        // tolerant.
                    }
                } catch (final NumberFormatException e) {
                    log.warn("Invalid numeric entity in fragment [" + cand + "] - Dropping it.");
                }

                // Expand the entity and set proper skip (if found)
                if (r != null) {
                    aContent.replace(i, i + cand.length(), r);
                    seek = i + r.length();
                }
            }
        }

        // Match against the Trie after numeric entity expansion is over
        if (substitutionTable != null) {
            final Trie<String>.Node match = substitutionTable.getNode(aContent, i);
            if (match != null) {
                aContent.replace(i, i + match.level, match.value);
                seek = i + match.value.length();
            }
        }

        // Check line breaks
        while (i < seek) {
            if (aContent.charAt(i) == '\n') {
                lastBreak = i;
            } else if (Character.isWhitespace(aContent.codePointAt(i)) && (i > (lastBreak + 79))) {
                lastBreak = i;
                aContent.replace(i, i + 1, "\n");
            }
            i++;
        }
    }

    return aContent;
}

From source file:org.pentaho.di.trans.steps.ivwloader.IngresVectorwiseLoader.java

private String replace(String string, String[] searchStrings, String[] replaceStrings) {
    StringBuilder builder = new StringBuilder(string);
    for (int e = 0; e < Math.min(searchStrings.length, replaceStrings.length); e++) {
        String chr = searchStrings[e];
        String rep = replaceStrings[e];
        int idx = builder.indexOf(chr, 0);
        while (idx > 0) {
            builder.replace(idx, idx + chr.length(), rep);
            idx = builder.indexOf(chr, idx + rep.length());
        }/*from   w  w w. j  a v  a 2s. c o  m*/
    }
    return builder.toString();
}

From source file:oscar.eform.data.EForm.java

public void setAction(boolean unset) {
    // sets action= in the form
    StringBuilder html = new StringBuilder(this.formHtml);
    int index = StringBuilderUtils.indexOfIgnoreCase(html, "<form", 0);
    int endtag = html.indexOf(">", index + 1);
    // --remove all previous actions, methods and names from the form tag
    if (index < 0)
        return;/*from   www  . j  a v a 2  s  .co m*/

    int pointer, pointer2;
    while (((pointer = StringBuilderUtils.indexOfIgnoreCase(html, " action=", index)) >= 0)
            && (pointer < endtag)) {
        pointer2 = nextSpot(html, pointer + 1);
        html = html.delete(pointer, pointer2);
        endtag = html.indexOf(">", index + 1);
    }
    while (((pointer = StringBuilderUtils.indexOfIgnoreCase(html, " method=", index)) >= 0)
            && (pointer < endtag)) {
        pointer2 = nextSpot(html, pointer + 1);
        html = html.delete(pointer, pointer2);
        endtag = html.indexOf(">", index + 1);
    }
    pointer = StringBuilderUtils.indexOfIgnoreCase(html, " name=", index);
    String name = "name=\"saveEForm\" ";
    if ((pointer >= 0) && (pointer < endtag)) {
        pointer2 = nextSpot(html, pointer + 1);
        endtag = html.indexOf(">", index + 1);
        name = "";
    }
    if (index < 0)
        return;
    if (unset) {
        this.formHtml = html.toString();
        return;
    }
    index += 5;
    StringBuilder action = new StringBuilder(
            "action=\"../eform/addEForm.do?efmfid=" + this.fid + "&efmdemographic_no=" + this.demographicNo
                    + "&efmprovider_no=" + this.providerNo + "&eform_link=" + this.eform_link);
    if (this.parentAjaxId != null)
        action.append("&parentAjaxId=" + this.parentAjaxId);

    action.append("\"");

    String method = "method=\"POST\"";
    html.insert(index, " " + action.toString() + " " + name + method);
    this.formHtml = html.toString();
}

From source file:oscar.oscarLab.ca.all.parsers.TDISHandler.java

/**
 * Return the result of the jth OBX at ith OBR.
 * /*  w  w w .  ja v a 2  s .  c  o  m*/
 * If it's an ITS^REPORT, the show nothing as this result will be fetched in the previous column.
 * 
 * @param i
 * @param j
 * @param its
 * @return
 */
@SuppressWarnings("unchecked")
public String getOBXResult(int i, int j, boolean its) {

    String result = "", newComment = "";
    int len = 80;

    try {
        OBX obx = null;
        Terser terser = new Terser(msg);
        result = getString(
                Terser.get((obx = (OBX) ((ArrayList) obrSegMap.get(obrSegKeySet.get(i))).get(j)), 5, 0, 1, 1));

        // format the result
        if (result.endsWith("."))
            result = result.substring(0, result.length() - 1);

        if (result.length() > len) {
            StringBuilder sb = new StringBuilder(result);

            int i1 = 0;
            while ((i1 = sb.indexOf(" ", i1 + len)) != -1) {
                sb.replace(i1, i1 + 1, "<br/>");
            }
            newComment = sb.toString();
            logger.info("Modified comment =" + newComment);
        } else {
            newComment = result;
            logger.info("Original comment =" + newComment);
        }

        //if true, then we're giving the report values to the function showing the "test name" per OBX
        if (its)
            return newComment; //return result;
        String name = "";
        //default behavior is for ITS^REPORT is to show now result as this will be in the "test name" field.
        if ((name = obx.getObservationIdentifier().getText().getValue()).indexOf("ITS") != -1
                || name.indexOf("DEPARTMENTAL") != -1)
            return "";
    } catch (Exception e) {
        logger.error("Exception returning result", e);
    }
    return result;
}

From source file:org.jivesoftware.community.util.StringUtils.java

public static StringBuilder replaceAll(StringBuilder text, String token, String repl) {
    int tokSize = token.length();
    int i = 0;//  w  ww .  j a  va  2  s.co m
    do {
        if (i == -1)
            break;
        i = text.indexOf(token, i);
        if (i != -1) {
            text.replace(i, i + tokSize, repl);
            i += repl.length();
        }
    } while (true);
    return text;
}

From source file:com.qwazr.crawler.web.driver.BrowserDriver.java

public String getSnippet(SearchContext searchContext, int sizeLimit) {
    List<WebElement> elements = searchContext.findElements(By.tagName("p"));
    if (elements == null)
        return null;
    StringBuilder sb = new StringBuilder();
    for (WebElement element : elements) {
        String text = null;//  w w  w  .  j  av a 2s  .  co m
        try {
            text = getTextSafe(element);
        } catch (CSSException e) {
            if (logger.isWarnEnabled())
                logger.warn("Cannot extract snippet: " + e.getMessage(), e);
        }
        if (text == null)
            continue;
        text = StringUtils.join(StringUtils.split(text, " \r\n\t"), ' ');
        sb.append(text);
        if (!text.endsWith("."))
            sb.append(' ');
        sb.append(' ');
        if (sb.length() > sizeLimit)
            break;
    }
    if (sb.length() <= sizeLimit)
        return sb.toString().trim();
    int i = 0;
    int last = -1;
    for (;;) {
        i = sb.indexOf(" ", i + 1);
        if (i == -1 || i > sizeLimit)
            break;
        last = i;
    }
    if (last == -1)
        last = sizeLimit;
    return sb.substring(0, last) + "";
}

From source file:oscar.eform.data.EForm.java

private int nextIndex(StringBuilder text, String option1, String option2, int pointer) {
    // converts text content to lowercase
    text = new StringBuilder(text.toString().toLowerCase());
    option1 = option1.toLowerCase();//from   w ww.ja v  a  2 s.c o  m
    option2 = option2.toLowerCase();

    // returns the index of option1 or option2 whichever one is closer and exists
    int index;
    int option1i = text.indexOf(option1, pointer);
    int option2i = text.indexOf(option2, pointer);
    if (option1i < 0)
        index = option2i;
    else if (option2i < 0 || option1i < option2i)
        index = option1i;
    else
        index = option2i;
    return index;
}

From source file:ch.randelshofer.cubetwister.HTMLExporter.java

/**
 * Reads the content of the input stream into a list of token.
 * If a token start with "${", its a placeholder.
 * If a token doesn't start with "${" its a literal text.
 *//*  www  .  j av  a 2s.  c o m*/
private String[] toTokens(String filename, InputStream in) throws IOException {
    InputStreamReader reader = new InputStreamReader(in, "UTF8");
    StringBuilder buf = new StringBuilder();
    char[] cbuf = new char[256];
    int len;
    while (-1 != (len = reader.read(cbuf, 0, cbuf.length))) {
        buf.append(cbuf, 0, len);
    }

    int p1 = 0;
    int p2 = 0;
    LinkedList<String> tokens = new LinkedList<String>();
    while (true) {
        p1 = buf.indexOf("${", p2);
        if (p1 == -1) {
            break;
        }
        tokens.add(buf.substring(p2, p1));
        p2 = buf.indexOf("}", p1 + 2);
        if (p2 == -1) {
            throw new IOException("Closing curly bracket missing in " + filename + " after position " + p1);
        }
        p2++;
        tokens.add(buf.substring(p1, p2));
    }
    if (p2 != buf.length()) {
        tokens.add(buf.substring(p2));
    }
    return tokens.toArray(new String[tokens.size()]);
}

From source file:org.jahia.services.render.filter.cache.AggregateCacheFilter.java

private int replaceInContent(StringBuilder sb, int start, int end, String replacement) {
    if (replacement == null) {
        replacement = "";
    }/*w  w  w .j  av a  2s . co m*/
    sb.replace(start, end, replacement);
    return sb.indexOf(CACHE_ESI_TAG_START, start + replacement.length());
}

From source file:org.jahia.services.render.filter.cache.AggregateCacheFilter.java

/**
 * Aggregate the content that are inside the cached fragment to get a full HTML content with all sub modules
 * embedded./*from   w ww. j a v  a 2 s  .  c  om*/
 *
 * @param cache          The cache
 * @param cachedContent  The fragment, as it is stored in the cache
 * @param renderContext  The render context
 * @param areaIdentifier
 * @param cacheKeyStack
 * @param allPaths
 * @return
 */
protected String aggregateContent(Cache cache, String cachedContent, RenderContext renderContext,
        String areaIdentifier, Stack<String> cacheKeyStack, Set<String> allPaths) throws RenderException {

    int esiTagStartIndex = cachedContent.indexOf(CACHE_ESI_TAG_START);
    if (esiTagStartIndex == -1) {
        return cachedContent;
    } else {
        StringBuilder sb = new StringBuilder(cachedContent);
        while (esiTagStartIndex != -1) {
            int esiTagEndIndex = sb.indexOf(CACHE_ESI_TAG_END, esiTagStartIndex);
            if (esiTagEndIndex != -1) {
                String cacheKey = sb.substring(esiTagStartIndex + CACHE_ESI_TAG_START.length(), esiTagEndIndex);
                String replacedCacheKey = replacePlaceholdersInCacheKey(renderContext, cacheKey);

                if (logger.isDebugEnabled()) {
                    logger.debug("Check if {} is in cache", replacedCacheKey);
                }

                boolean cacheable = true;
                CacheKeyGenerator keyGenerator = cacheProvider.getKeyGenerator();
                Map<String, String> keyAttrbs = keyGenerator.parse(cacheKey);
                final String ecParameter = renderContext.getRequest().getParameter(EC);
                if ((ecParameter != null && ecParameter.equals(keyAttrbs.get("resourceID")))
                        || (renderContext.getRequest().getParameter(V) != null && renderContext.isLoggedIn())) {
                    cacheable = false;
                }

                if (cacheable && cache.isKeyInCache(replacedCacheKey)) {
                    // If fragment is in cache, get it from there and aggregate recursively
                    final Element element = cache.get(replacedCacheKey);
                    if (element != null && element.getObjectValue() != null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("It has been found in cache");
                        }
                        @SuppressWarnings("unchecked")
                        final CacheEntry<String> cacheEntry = (CacheEntry<String>) element.getObjectValue();
                        String content = cacheEntry.getObject();

                        // Avoid loops
                        if (cacheKeyStack.contains(cacheKey)) {
                            // replace by empty
                            esiTagStartIndex = replaceInContent(sb, esiTagStartIndex,
                                    esiTagEndIndex + CACHE_ESI_TAG_END_LENGTH, StringUtils.EMPTY);
                            continue;
                        }
                        cacheKeyStack.push(cacheKey);

                        try {
                            if (!cachedContent.equals(content)) {
                                try {
                                    if (cacheEntry.getProperty("requestAttributes") != null) {
                                        Map<String, Serializable> requestAttributesToCache = (Map<String, Serializable>) cacheEntry
                                                .getProperty("requestAttributes");
                                        for (Map.Entry<String, Serializable> entry : requestAttributesToCache
                                                .entrySet()) {
                                            renderContext.getRequest().setAttribute(entry.getKey(),
                                                    entry.getValue());
                                        }
                                    }

                                    esiTagStartIndex = replaceInContent(sb, esiTagStartIndex,
                                            esiTagEndIndex + CACHE_ESI_TAG_END_LENGTH,
                                            aggregateContent(cache, content, renderContext,
                                                    (String) cacheEntry.getProperty("areaResource"),
                                                    cacheKeyStack,
                                                    (Set<String>) cacheEntry.getProperty("allPaths")));
                                } catch (RenderException e) {
                                    throw new RuntimeException(e.getMessage(), e);
                                }
                            } else {
                                // TODO: need to investigate here, seem's that the if condition is always true.
                                esiTagStartIndex = replaceInContent(sb, esiTagStartIndex,
                                        esiTagEndIndex + CACHE_ESI_TAG_END_LENGTH, content);
                            }
                        } finally {
                            cacheKeyStack.pop();
                        }
                    } else {
                        cache.put(new Element(replacedCacheKey, null));
                        if (logger.isDebugEnabled()) {
                            logger.debug("Content is expired");
                        }
                        // The fragment is not in the cache, generate it
                        try {
                            esiTagStartIndex = replaceInContent(sb, esiTagStartIndex,
                                    esiTagEndIndex + CACHE_ESI_TAG_END_LENGTH,
                                    generateContent(renderContext, cacheKey, areaIdentifier, allPaths));
                        } catch (RenderException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Content is missing from cache");
                    }
                    // The fragment is not in the cache, generate it
                    try {
                        esiTagStartIndex = replaceInContent(sb, esiTagStartIndex,
                                esiTagEndIndex + CACHE_ESI_TAG_END_LENGTH,
                                generateContent(renderContext, cacheKey, areaIdentifier, allPaths));
                    } catch (RenderException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            } else {
                // no closed esi end tag found
                return sb.toString();
            }
        }
        return sb.toString();
    }
}