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:org.apache.drill.common.expression.fn.JodaDateValidator.java

/**
 * Replaces all postgres patterns from {@param pattern},
 * available in postgresToJodaMap keys to jodaTime equivalents.
 *
 * @param pattern date pattern in postgres format
 * @return date pattern with replaced patterns in joda format
 *//* w ww. j  a v a  2  s.co m*/
public static String toJodaFormat(String pattern) {
    // replaces escape character for text delimiter
    StringBuilder builder = new StringBuilder(
            pattern.replaceAll(POSTGRES_ESCAPE_CHARACTER, JODA_ESCAPE_CHARACTER));

    int start = 0; // every time search of postgres token in pattern will start from this index.
    int minPos; // min position of the longest postgres token
    do {
        // finds first value with max length
        minPos = builder.length();
        PostgresDateTimeConstant firstMatch = null;
        for (PostgresDateTimeConstant postgresPattern : postgresToJodaMap.keySet()) {
            // keys sorted in length decreasing
            // at first search longer tokens to consider situation where some tokens are the parts of large tokens
            // example: if pattern contains a token "DDD", token "DD" would be skipped, as a part of "DDD".
            int pos;
            // some tokens can't be in upper camel casing, so we ignore them here.
            // example: DD, DDD, MM, etc.
            if (postgresPattern.hasCamelCasing()) {
                // finds postgres tokens in upper camel casing
                // example: Month, Mon, Day, Dy, etc.
                pos = builder.indexOf(StringUtils.capitalize(postgresPattern.getName()), start);
                if (pos >= 0 && pos < minPos) {
                    firstMatch = postgresPattern;
                    minPos = pos;
                    if (minPos == start) {
                        break;
                    }
                }
            }
            // finds postgres tokens in lower casing
            pos = builder.indexOf(postgresPattern.getName().toLowerCase(), start);
            if (pos >= 0 && pos < minPos) {
                firstMatch = postgresPattern;
                minPos = pos;
                if (minPos == start) {
                    break;
                }
            }
            // finds postgres tokens in upper casing
            pos = builder.indexOf(postgresPattern.getName().toUpperCase(), start);
            if (pos >= 0 && pos < minPos) {
                firstMatch = postgresPattern;
                minPos = pos;
                if (minPos == start) {
                    break;
                }
            }
        }
        // replaces postgres token, if found and it does not escape character
        if (minPos < builder.length() && firstMatch != null) {
            String jodaToken = postgresToJodaMap.get(firstMatch);
            // checks that token is not a part of escape sequence
            if (StringUtils.countMatches(builder.subSequence(0, minPos), JODA_ESCAPE_CHARACTER) % 2 == 0) {
                int offset = minPos + firstMatch.getName().length();
                builder.replace(minPos, offset, jodaToken);
                start = minPos + jodaToken.length();
            } else {
                int endEscapeCharacter = builder.indexOf(JODA_ESCAPE_CHARACTER, minPos);
                if (endEscapeCharacter >= 0) {
                    start = endEscapeCharacter;
                } else {
                    break;
                }
            }
        }
    } while (minPos < builder.length());
    return builder.toString();
}

From source file:org.moe.natjgen.XcodeFullDocumentation.java

private void replaceAll(StringBuilder builder, String from, String to) {
    int idx = 0;//from w  w  w.  java 2  s  .  c o  m
    int flen = from.length();
    while ((idx = builder.indexOf(from, idx)) != -1) {
        builder.replace(idx, idx + flen, to);
    }
}

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

public static String encodeAmpersands(String htmlString) {
    StringBuilder htmlBuffer = new StringBuilder(htmlString);
    int ampLoc = -1;
    while ((ampLoc = htmlBuffer.indexOf("&", ampLoc + 1)) != -1) {
        //NOTE: this should work fine, but if it doesn't could try making sure all characters between & and ; are letters, that would qualify as an entity

        // found ampersand, is it already and entity? if not change it to &amp;
        int semiLoc = htmlBuffer.indexOf(";", ampLoc);
        if (semiLoc != -1) {
            // found a semi colon, if it has another & or an = before it, don't count it as an entity, otherwise it may be an entity, so skip it
            int eqLoc = htmlBuffer.indexOf("=", ampLoc);
            int amp2Loc = htmlBuffer.indexOf("&", ampLoc + 1);
            if ((eqLoc == -1 || eqLoc > semiLoc) && (amp2Loc == -1 || amp2Loc > semiLoc)) {
                continue;
            }/*ww  w. j av  a  2 s  . c o m*/
        }

        // at this point not an entity, no substitute with a &amp;
        htmlBuffer.insert(ampLoc + 1, "amp;");
    }
    return htmlBuffer.toString();
}

From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv1Reader.java

/**
 * Create {@link Token} in the {@link CAS}. If the lemma and pos columns are not empty it will
 * create {@link Lemma} and {@link POS} annotations
 *//*from  w w w.  j  ava  2 s . c o m*/
private void createToken(JCas aJCas, StringBuilder text, Map<Integer, String> tokens, Map<Integer, String> pos,
        Map<Integer, String> lemma, Map<String, Token> tokensStored) {
    int tokenBeginPosition = 0;
    int tokenEndPosition = 0;

    for (int i = 1; i <= tokens.size(); i++) {
        tokenBeginPosition = text.indexOf(tokens.get(i), tokenBeginPosition);
        Token outToken = new Token(aJCas, tokenBeginPosition,
                text.indexOf(tokens.get(i), tokenBeginPosition) + tokens.get(i).length());
        tokenEndPosition = text.indexOf(tokens.get(i), tokenBeginPosition) + tokens.get(i).length();
        tokenBeginPosition = tokenEndPosition;
        outToken.addToIndexes();

        // Add pos to CAS if exist
        if (!pos.get(i).equals("_")) {
            POS outPos = new POS(aJCas, outToken.getBegin(), outToken.getEnd());
            outPos.setPosValue(pos.get(i));
            outPos.addToIndexes();
            outToken.setPos(outPos);
        }

        // Add lemma if exist
        if (!lemma.get(i).equals("_")) {
            Lemma outLemma = new Lemma(aJCas, outToken.getBegin(), outToken.getEnd());
            outLemma.setValue(lemma.get(i));
            outLemma.addToIndexes();
            outToken.setLemma(outLemma);
        }
        tokensStored.put("t_" + i, outToken);
    }
}

From source file:com.surveypanel.utils.PlaceHolderParser.java

protected static String parseStringValue(Form form, String strVal, Set<String> visitedPlaceholders) {

    StringBuilder buf = new StringBuilder(strVal);

    int startIndex = strVal.indexOf(DEFAULT_PLACEHOLDER_PREFIX);
    while (startIndex != -1) {
        int endIndex = findPlaceholderEndIndex(buf, startIndex);
        if (endIndex != -1) {
            String placeholder = buf.substring(startIndex + DEFAULT_PLACEHOLDER_PREFIX.length(), endIndex);
            if (!visitedPlaceholders.add(placeholder)) {
                logger.error("Circular placeholder reference '" + placeholder + "' in property definitions");
                return placeholder;
            }/*from w  w  w.ja va  2  s .c o  m*/
            // Recursive invocation, parsing placeholders contained in the
            // placeholder key.
            placeholder = parseStringValue(form, placeholder, visitedPlaceholders);
            // Now obtain the value for the fully resolved key...
            String propVal = resolvePlaceholder(form, placeholder);
            if (propVal != null) {
                // Recursive invocation, parsing placeholders contained in
                // the
                // previously resolved placeholder value.
                propVal = parseStringValue(form, propVal, visitedPlaceholders);
                buf.replace(startIndex, endIndex + DEFAULT_PLACEHOLDER_SUFFIX.length(), propVal);
                if (logger.isTraceEnabled()) {
                    logger.trace("Resolved placeholder '" + placeholder + "'");
                }
                startIndex = buf.indexOf(DEFAULT_PLACEHOLDER_PREFIX, startIndex + propVal.length());
            } else {
                // Proceed with unprocessed value.
                startIndex = buf.indexOf(DEFAULT_PLACEHOLDER_PREFIX,
                        endIndex + DEFAULT_PLACEHOLDER_SUFFIX.length());
            }
            visitedPlaceholders.remove(placeholder);
        } else {
            startIndex = -1;
        }
    }

    return buf.toString();
}

From source file:org.jts.docGenerator.PathInserter.java

/**
 *
 * @param hrefs String representations of hrefs for which paths need to be
 * inserted. it is assumed that file names in href are placed in the
 * destination root directory./*from  w ww .  j av a 2s.  com*/
 *
 */
void insertPaths(List<String> hrefs) {

    // get all HTML files at or under dest dir
    Collection<File> htmlFiles = FileUtils.listFiles(dest, FileFilterUtils.suffixFileFilter(".html"),
            TrueFileFilter.INSTANCE);

    FileReader reader = null;
    FileWriter writer = null;

    for (File htmlFile : htmlFiles) {

        try {
            reader = new FileReader(htmlFile);
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        char[] buf = new char[(int) htmlFile.length()];

        try {
            reader.read(buf);
            reader.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        StringBuilder builder = new StringBuilder();
        builder = builder.append(buf);

        // insert paths to specified hrefs
        for (int jj = 0; jj < hrefs.size(); jj++) {
            String path = getPath(htmlFile);
            String href = (String) hrefs.get(jj);
            int offset = 0;

            // find all incidences of href and insert path modification
            while ((offset = builder.indexOf(href, offset)) != -1) {
                builder = builder.insert(offset, path);
                offset += path.length() + href.length();
            }
        }

        try {
            writer = new FileWriter(htmlFile);
            writer.write(builder.toString().toCharArray());
            writer.close();
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

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

public String getOBXComment(int i, int j, int k) {
    String comment = "", newComment = "";
    int len = 80;
    String[] splitComment;// w w  w.  ja  v  a 2 s  . co  m
    String concatComment = "";

    try {
        Terser terser = new Terser(msg);
        comment = Terser.get(obxseg, 5, 0, 1, 1);
        comment = comment.replaceAll("<P\\s*/*>", "<br/>");
        splitComment = comment.split("<br/>");

        for (int l = 0; l < splitComment.length; l++) {
            if (splitComment[l].length() > len) {
                StringBuilder sb = new StringBuilder(splitComment[l]);
                int i1 = 0;
                while ((i1 = sb.indexOf(" ", i1 + len)) != -1) {
                    sb.replace(i1, i1 + 1, "<br/>");

                }

                concatComment = sb.toString();
            }

            if (!concatComment.equals("")) {
                newComment += "<br/>" + concatComment.toString();
            } else {
                newComment += "<br/>" + splitComment[l].toString();
            }
            concatComment = "";

        }

        logger.info("Modified comment =" + newComment);
        return newComment;

    } catch (Exception e) {
        logger.error("getOBRComment error", e);
        return "";
    }
    //return comment;
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.index.lucene.RepositoryAwareADMLuceneSearcherImpl.java

private String parameterise(String unparameterised, Map<QName, QueryParameterDefinition> map,
        QueryParameter[] queryParameters, NamespacePrefixResolver nspr) throws QueryParameterisationException {

    Map<QName, List<Serializable>> valueMap = new HashMap<QName, List<Serializable>>();

    if (queryParameters != null) {
        for (QueryParameter parameter : queryParameters) {
            List<Serializable> list = valueMap.get(parameter.getQName());
            if (list == null) {
                list = new ArrayList<Serializable>();
                valueMap.put(parameter.getQName(), list);
            }/* w  w w. j  a  va2  s  . c o m*/
            list.add(parameter.getValue());
        }
    }

    Map<QName, ListIterator<Serializable>> iteratorMap = new HashMap<QName, ListIterator<Serializable>>();

    List<QName> missing = new ArrayList<QName>(1);
    StringBuilder buffer = new StringBuilder(unparameterised);
    int index = 0;
    while ((index = buffer.indexOf("${", index)) != -1) {
        int endIndex = buffer.indexOf("}", index);
        String qNameString = buffer.substring(index + 2, endIndex);
        QName key = QName.createQName(qNameString, nspr);
        QueryParameterDefinition parameterDefinition = map.get(key);
        if (parameterDefinition == null) {
            missing.add(key);
            buffer.replace(index, endIndex + 1, "");
        } else {
            ListIterator<Serializable> it = iteratorMap.get(key);
            if ((it == null) || (!it.hasNext())) {
                List<Serializable> list = valueMap.get(key);
                if ((list != null) && (list.size() > 0)) {
                    it = list.listIterator();
                }
                if (it != null) {
                    iteratorMap.put(key, it);
                }
            }
            String value;
            if (it == null) {
                value = parameterDefinition.getDefault();
            } else {
                value = DefaultTypeConverter.INSTANCE.convert(String.class, it.next());
            }
            buffer.replace(index, endIndex + 1, value);
        }
    }
    if (missing.size() > 0) {
        StringBuilder error = new StringBuilder();
        error.append("The query uses the following parameters which are not defined: ");
        for (QName qName : missing) {
            error.append(qName);
            error.append(", ");
        }
        error.delete(error.length() - 1, error.length() - 1);
        error.delete(error.length() - 1, error.length() - 1);
        throw new QueryParameterisationException(error.toString());
    }
    return buffer.toString();
}

From source file:oscar.oscarRx.util.RxUtil.java

public static String replace(String expression, String searchFor, String replaceWith) {
    if (expression != null) {
        StringBuilder buf = new StringBuilder(expression);

        int pos = -1;

        while (true) {
            pos = buf.indexOf(searchFor, pos);

            if (pos > -1) {
                buf.delete(pos, pos + searchFor.length());
                buf.insert(pos, replaceWith);

                pos += replaceWith.length();
            } else {
                break;
            }//from  w ww .  j a  v a2  s. c  om
        }

        return buf.toString();
    } else {
        return null;
    }
}

From source file:org.opencms.db.jpa.CmsSqlManager.java

/**
 * Set numbers for parameters of giving JPQL query.<p>
 * /* w  w w .  ja v  a 2  s .  co  m*/
 * @param query - the query
 * @param cache if true, the query will be cached 
 * 
 * @return query with numbered parameter's placeholders
 */
private String prepareQueryParameters(String query, boolean cache) {

    String jpqlQuery = m_queriesWithParameters.get(query);
    if (jpqlQuery != null) {
        return jpqlQuery;
    }

    StringBuilder builder = new StringBuilder(query);
    int startPosition = 0;
    int currPosition = 0;
    int counter = 0;

    while ((currPosition = builder.indexOf(JPQL_PARAMETER_PLACEHOLDER, startPosition)) != -1) {
        builder.insert(currPosition + JPQL_PARAMETER_PLACEHOLDER_LENGTH, ++counter);
        startPosition = currPosition + JPQL_PARAMETER_PLACEHOLDER_LENGTH + (counter < 10 ? 1 : 2); // assumes we have not more than 99 parameters per query :)
    }

    jpqlQuery = builder.toString();
    if (cache) {
        m_queriesWithParameters.put(query, jpqlQuery);
    }
    return jpqlQuery;
}