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.olio.workload.driver.UIDriver.java

public Set<String> parseImages(StringBuilder buffer) {
    LinkedHashSet<String> urlSet = new LinkedHashSet<String>();
    //String elStart = "<img ";
    String elStart = "background: ";
    String attrStart = " url(";
    int elStartLen = elStart.length() - 1; // Don't include the trailing space
    int attrStartLen = attrStart.length();
    int idx = 0;// w ww .ja  v a 2s .co  m
    logger.finest("Parsing images from buffer");
    for (;;) {

        // Find and copy out the element.
        idx = buffer.indexOf(elStart, idx);
        if (idx == -1) {
            break;
        }
        idx += elStartLen;
        int endIdx = buffer.indexOf(")", idx) + 1; // +1 to include the '('
        if (endIdx == -1) {
            break;
        }
        String elText = buffer.substring(idx, endIdx);
        logger.finest(elText);
        idx = endIdx + 1;

        // Find the attribute
        int idx2 = elText.indexOf(attrStart);
        if (idx2 == -1) {
            logger.finer("No img src attribute. Weird! " + elText);
            continue;
        }
        endIdx = elText.indexOf(")", idx2 + attrStartLen);
        if (endIdx == -1) {
            logger.warning("No ) attribute ending. Weird! " + elText);
            continue;
        }

        String link = elText.substring(idx2 + attrStartLen, endIdx);
        if (link.startsWith("/uploaded_files")) {
            String url = baseURL + link;

            logger.finer("Adding " + url + " from idx " + idx);
            urlSet.add(url);
        }
    }
    return urlSet;
}

From source file:org.jasig.ssp.dao.EarlyAlertDao.java

/**
 * Returns string where clause of the HQL query based on parameters inputted
 *  NOTE: Includes the word where, so if already specified, replace with and!
 *    REQUIRES EarlyAlert with alias of ea and Campus with alias c elsewhere in HQL Query!
 * @param termCode//from  w  w w .  j av a  2s.com
 * @param createdDateFrom
 * @param createdDateTo
 * @param campus
 * @param status
 * @return
 */
private String createEarlyAlertReportHQLWhereClause(String termCode, Date createdDateFrom, Date createdDateTo,
        Campus campus, ObjectStatus status) {
    final StringBuilder whereClause = new StringBuilder("where ");
    String whereClauseToReturn = "";

    if (termCode != null) {
        whereClause.append("ea.courseTermCode = :courseTermCode and ");
    }

    if (createdDateFrom != null) {
        whereClause.append("ea.createdDate >= :createdDateFrom and ");
    }

    if (createdDateTo != null) {
        whereClause.append("ea.createdDate <= :createdDateTo and ");
    }

    if (campus != null) {
        whereClause.append("c.id = :campusId and ");
    }

    if (status != null) {
        whereClause.append("objectStatus = :objectStatus ");
    }

    if (StringUtils.countMatches(whereClause.toString(), "and") > 0) {
        final int endingAnd = whereClause.indexOf("and", whereClause.length() - 5);

        if (endingAnd < 0) {
            whereClauseToReturn = whereClause.toString();
        } else {
            whereClauseToReturn = whereClause.toString().substring(0, endingAnd - 1);
        }
    }
    return whereClauseToReturn;
}

From source file:org.eclipse.b3.p2.maven.loader.Maven2RepositoryLoader.java

private boolean robotSafe(String baseURL, String path) throws CoreException {
    String robotStr = baseURL + "/robots.txt";
    URL robotURL;// w ww . java2s .  c o  m
    try {
        robotURL = new URL(robotStr);
    } catch (MalformedURLException e) {
        throw ExceptionUtils.fromMessage(e.getMessage());
    }

    StringBuilder commands = new StringBuilder();
    InputStream robotStream = null;

    try {
        robotStream = robotURL.openStream();
        byte buffer[] = new byte[1024];
        int read;
        while ((read = robotStream.read(buffer)) != -1)
            commands.append(new String(buffer, 0, read));
    } catch (IOException e) {
        // no robots.txt file => safe to crawl
        return true;
    } finally {
        if (robotStream != null)
            try {
                robotStream.close();
            } catch (IOException e) {
                // ignore
            }
    }

    // search for "Disallow:" commands.
    int index = 0;
    String disallow = "Disallow:";
    while ((index = commands.indexOf(disallow, index)) != -1) {
        index += disallow.length();
        String commandPath = commands.substring(index);
        StringTokenizer tokenizer = new StringTokenizer(commandPath);

        if (!tokenizer.hasMoreTokens())
            break;

        String disallowedPath = tokenizer.nextToken();

        // if the URL starts with a disallowed path, it is not safe
        if (path.indexOf(disallowedPath) == 0)
            return false;
    }

    return true;
}

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

private StringBuilder putValue(String value, String type, int pointer, StringBuilder html) {
    // inserts value= into tag or textarea
    if (type == null)
        return html;
    if (type.equals("onclick") || type.equals("onclick_append")) {
        if (type.equals("onclick_append")) {
            if (html.charAt(pointer - 1) == '"')
                pointer -= 1;//from w w  w.jav a 2s.  c o  m
            if (html.charAt(pointer - 1) != ';')
                value = ";" + value;
        } else {
            value = "onclick=\"" + value + "\"";
        }
        html.insert(pointer, " " + value);
    } else if (type.equals(OPENER_VALUE)) {
        html.insert(pointer, " " + OPENER_VALUE + "=\"" + value + "\"");
    } else if (type.equals("text") || type.equals("hidden")) {
        html.insert(pointer, " value=\"" + value + "\"");
    } else if (type.equals("textarea")) {
        pointer = html.indexOf(">", pointer) + 1;
        int endPointer = html.indexOf("<", pointer);
        html.delete(pointer, endPointer);
        html.insert(pointer, value);
    } else if (type.equals("checkbox")) {
        html.insert(pointer, " checked");
    } else if (type.equals("select")) {
        int endindex = StringBuilderUtils.indexOfIgnoreCase(html, "</select>", pointer);
        if (endindex < 0)
            return html; // if closing tag not found

        int valueLoc = nextIndex(html, " value=" + value, " value=\"" + value, pointer);
        if (valueLoc < 0 || valueLoc > endindex)
            return html;

        pointer = nextSpot(html, valueLoc + 1);
        html.insert(pointer, " selected");
    } else if (type.equals("radio")) {
        int endindex = html.indexOf(">", pointer);
        int valindexS = nextIndex(html, " value=", " value=", pointer);
        if (valindexS < 0 || valindexS > endindex)
            return html; // if value= not found in tag

        valindexS += 7;
        if (html.charAt(valindexS) == '"')
            valindexS++;
        int valindexE = valindexS + value.length();
        if (html.substring(valindexS, valindexE).equals(value)) {
            pointer = nextSpot(html, valindexE);
            html.insert(pointer, " checked");
        }
    }
    return html;
}

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

private void saveFieldValue(StringBuilder html, int fieldIndex) {
    String header = getFieldHeader(html, fieldIndex);
    if (EFormUtil.blank(header))
        return;/*from   www  .  j  a v  a  2 s  .  c  o m*/

    String name = EFormUtil.removeQuotes(EFormUtil.getAttribute("name", header));
    String value = EFormUtil.removeQuotes(EFormUtil.getAttribute("value", header));
    if (EFormUtil.blank(name))
        return;

    if (header.toLowerCase().startsWith("<input ")) {
        String type = EFormUtil.removeQuotes(EFormUtil.getAttribute("type", header));
        if (EFormUtil.blank(type))
            return;

        if (type.equalsIgnoreCase("radio")) {
            String checked = EFormUtil.removeQuotes(EFormUtil.getAttribute("checked", header));
            if (EFormUtil.blank(checked) || !checked.equalsIgnoreCase("checked"))
                return;
        }
    } else if (header.toLowerCase().startsWith("<select ")) {
        String selects = html.substring(fieldIndex, html.indexOf("</select>", fieldIndex));
        int pos = selects.indexOf("<option ", 0);
        while (pos >= 0) {
            String option = getFieldHeader(selects, pos);
            String selected = EFormUtil.removeQuotes(EFormUtil.getAttribute("selected", option));
            if (!EFormUtil.blank(selected) && selected.equalsIgnoreCase("selected")) {
                value = EFormUtil.removeQuotes(EFormUtil.getAttribute("value", option));
                break;
            }
            pos = selects.indexOf("<option ", pos + 1);
        }
    } else if (header.toLowerCase().startsWith("<textarea ")) {
        int fieldEnd = html.indexOf("</textarea>", fieldIndex);
        value = html.substring(fieldIndex + header.length(), fieldEnd).trim();
        if (value.startsWith("\n"))
            value = value.substring(1); // remove 1st line break, UNIX style
        else if (value.startsWith("\r\n"))
            value = value.substring(2); // remove 1st line break, WINDOWS style
    }
    name = name.toLowerCase();
    if (!EFormUtil.blank(value))
        fieldValues.put(name, value);
}

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

private StringBuilder putValuesFromAP(DatabaseAP ap, String type, int pointer, StringBuilder html) {
    //prepare all sql & output
    String sql = ap.getApSQL();/*from   ww w.  j  ava  2s . c  o  m*/
    String output = ap.getApOutput();
    if (!EFormUtil.blank(sql)) {
        sql = replaceAllFields(sql);
        log.debug("SQL----" + sql);
        ArrayList<String> names = DatabaseAP.parserGetNames(output); // a list of ${apName} --> apName
        sql = DatabaseAP.parserClean(sql); // replaces all other ${apName} expressions with 'apName'

        if (ap.isJsonOutput()) {
            JSONArray values = EFormUtil.getJsonValues(names, sql);
            output = values.toString(); //in case of JsonOutput, return the whole JSONArray and let the javascript deal with it
        } else {
            ArrayList<String> values = EFormUtil.getValues(names, sql);
            if (values.size() != names.size()) {
                output = "";
            } else {
                for (int i = 0; i < names.size(); i++) {
                    output = DatabaseAP.parserReplace(names.get(i), values.get(i), output);
                }
            }
        }
    }

    //put values into according controls
    if (type.equals("textarea")) {
        pointer = html.indexOf(">", pointer) + 1;
        html.insert(pointer, output);
    } else if (type.equals("select")) {
        int selectEnd = StringBuilderUtils.indexOfIgnoreCase(html, "</select>", pointer);
        if (selectEnd >= 0) {
            int valueLoc = nextIndex(html, " value=" + output, " value=\"" + output, pointer);
            if (valueLoc < 0 || valueLoc > selectEnd)
                return html;
            pointer = nextSpot(html, valueLoc);
            html = html.insert(pointer, " selected");
        }
    } else {
        String quote = output.contains("\"") ? "'" : "\"";
        html.insert(pointer, " value=" + quote + output + quote);
    }
    return (html);
}

From source file:net.sourceforge.processdash.ev.ui.EVReport.java

private String fixChartHelpContent(String helpContent, String helpBaseUri, Map<String, String> chartHelp) {

    // discard headers and footers from the help content
    int cutStart = helpContent.indexOf("</h1>");
    if (cutStart != -1)
        helpContent = helpContent.substring(cutStart + 5);
    int cutEnd = helpContent.lastIndexOf("</body");
    if (cutEnd != -1)
        helpContent = helpContent.substring(0, cutEnd);

    // create a map of the chart help topics
    Map<String, String> chartUrls = new HashMap<String, String>();
    for (Map.Entry<String, String> e : chartHelp.entrySet()) {
        String chartId = e.getKey();
        String chartUrl = getChartDrillDownUrl(chartId);
        String helpUri = e.getValue();
        String helpName = hrefFileName(helpUri);
        chartUrls.put(helpName, chartUrl);
    }/*from  ww w  . j  a va  2s .c  o m*/

    // find and fix all the hrefs in this help topic:
    //   * If any hrefs point to the help topic for a different chart,
    //     rewrite the href so it actually loads the "drill-down page"
    //     for that chart instead.
    //   * For links that point to some non-chart help topic, rewrite the
    //     href to be absolute (so the help-relative URI won't break)

    StringBuilder html = new StringBuilder(helpContent);
    int pos = 0;
    while (true) {
        // find the next href in the document.
        pos = html.indexOf("href=", pos);
        if (pos == -1)
            break; // no more hrefs to fix

        pos += 6;
        int beg = pos; // the first character of the href value itself
        char delim = html.charAt(beg - 1);
        int end = html.indexOf(String.valueOf(delim), beg);
        if (end == -1)
            continue; // invalid href syntax.  Skip to the next one.

        // extract the href value
        String oneHref = html.substring(beg, end);
        // extract the final portion of the path name
        String oneName = hrefFileName(oneHref);
        // see if that name refers to one of the charts we can display
        String chartUrl = chartUrls.get(oneName);
        if (chartUrl != null) {
            // replace the href with a chart drill-down URL
            html.replace(beg, end, chartUrl);
            pos = beg + chartUrl.length();
        } else {
            try {
                // make the URL absolute, and set a "target" attribute
                // so it will open in another window.
                URI base = new URI(helpBaseUri);
                URI target = base.resolve(oneHref);
                String newUri = target.toString();
                html.replace(beg, end, newUri);
                html.insert(beg - 6, "target='evHelp' ");
                pos = beg + newUri.length() + 16;
            } catch (Exception e) {
                // problems resolving the URI?  Turn the link into an
                // anchor so it can't be clicked on anymore.
                html.replace(beg - 6, beg - 2, "name");
            }
        }
    }

    return html.toString();
}

From source file:com.flexive.shared.scripting.groovy.GroovyScriptExporterTools.java

/**
 * Write the script code to create a group
 *
 * @param ga                          the FxGroupAssignment to be scripted
 * @param childAssignments            a List of child assignments for the given group
 * @param groupAssignments            the map of FxGroupAssignments (keys) and their respective Lists of FxAssignments (values)
 * @param isDerived                   set to "true" if the assignment to be written is derived from another property
 * @param defaultsOnly                use only default settings provided by the GTB, no analysis of assignments will be performed
 * @param callOnlyGroups              a List of FxGroupAssignments for which no options should be generated
 * @param tabCount                    the number of tabs to be added to the code's left hand side
 * @param withoutDependencies         true = do not create assignment:xpath code
 * @param differingDerivedAssignments the List of assignment ids for derived assignments differing from their base assignments
 * @return returns the partial script as a String
 *//*from   ww  w. j  a va2  s.  c  om*/
public static String createGroup(FxGroupAssignment ga, List<FxAssignment> childAssignments,
        Map<FxGroupAssignment, List<FxAssignment>> groupAssignments, boolean isDerived, boolean defaultsOnly,
        List<FxGroupAssignment> callOnlyGroups, int tabCount, boolean withoutDependencies,
        List<Long> differingDerivedAssignments) {
    final StringBuilder script = new StringBuilder(200);

    if (!isDerived || withoutDependencies) {
        final FxGroup group = ga.getGroup();
        // NAME
        script.append(Indent.tabs(tabCount));
        final String groupName = keyWordNameCheck(group.getName().toUpperCase(), true);
        script.append(groupName).append("( "); // opening parenthesis + 1x \s

        // CHECK IF THIS GROUP WAS CREATED BEFOREHAND AND ONLY NEEDS TO BE CALLED FOR STRUCTURE CREATION
        if (callOnlyGroups == null || (callOnlyGroups != null && !callOnlyGroups.contains(ga))) {

            if (!defaultsOnly) {
                tabCount++; // add tabs for options
                script.append("\n");
                // label and hint
                script.append(getLabelAndHintStructure(group, true, true, tabCount));

                Map<String, String> sopts = new LinkedHashMap<String, String>();
                sopts.put("alias", "\"" + ga.getAlias() + "\"");
                sopts.put("defaultMultiplicity", ga.getDefaultMultiplicity() + "");
                sopts.put("overrideMultiplicity", group.mayOverrideBaseMultiplicity() + "");
                sopts.put("multiplicity", "new FxMultiplicity(" + group.getMultiplicity().getMin() + ","
                        + group.getMultiplicity().getMax() + ")");
                sopts.put("groupMode", "GroupMode." + ga.getMode().name());

                // FxStructureOptions via the GroovyOptionbuilder
                script.append(getStructureOptions(group, tabCount));

                // append options to script
                for (String option : sopts.keySet()) {
                    script.append(simpleOption(option, sopts.get(option), tabCount));
                }

                script.trimToSize();
                if (script.indexOf(",\n", script.length() - 2) != -1)
                    script.delete(script.length() - 2, script.length());

                --tabCount; // remove tab again
            }
        }

        script.append(") "); // closing parenthesis + 1x \s
        // if the difference analyser yields any data, change the assignment in the next line (only launch if defaultsOnly = false)
        if (!defaultsOnly) {
            final List<String> differences = AssignmentDifferenceAnalyser.analyse(ga, false);
            if (differences.size() > 0) {
                script.append(updateGroupAssignment(ga, false, differences, defaultsOnly, tabCount,
                        withoutDependencies, differingDerivedAssignments));
            }
        }
    } else { // DERIVED GROUP ASSIGNMENTS
        final List<String> differences = AssignmentDifferenceAnalyser.analyse(ga, true);
        script.append(updateGroupAssignment(ga, true, differences, defaultsOnly, tabCount, withoutDependencies,
                differingDerivedAssignments));
    }

    // add child assignments ******************************
    if (childAssignments != null && childAssignments.size() > 0) {
        script.append("{\n"); // closing parenthesis and curly bracket
        // if childAssignments != null && size() == 0, then we are calling for derived groups in derived types
        // --> remove current group from groupAssignments to avoid infinite recursions
        if (differingDerivedAssignments != null && differingDerivedAssignments.size() > 0) {
            groupAssignments.remove(ga);
        }
        script.append(createChildAssignments(childAssignments, groupAssignments, defaultsOnly, callOnlyGroups,
                ++tabCount, withoutDependencies, differingDerivedAssignments));
        script.append(Indent.tabs(--tabCount));
        script.append("}"); // closing curly bracket
    }

    script.append("\n");
    script.trimToSize();
    return script.toString();
}

From source file:com.opensource.frameworks.processframework.utils.PropertyPlaceholderHelper.java

protected String parseStringValue(String strVal, PlaceholderResolver placeholderResolver,
        Set<String> visitedPlaceholders) {

    StringBuilder buf = new StringBuilder(strVal);

    int startIndex = strVal.indexOf(this.placeholderPrefix);
    while (startIndex != -1) {
        int endIndex = findPlaceholderEndIndex(buf, startIndex);
        if (endIndex != -1) {
            String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex);
            if (!visitedPlaceholders.add(placeholder)) {
                throw new IllegalArgumentException(
                        "Circular placeholder reference '" + placeholder + "' in property definitions");
            }//from   ww w .  j  a va  2 s .co m
            // Recursive invocation, parsing placeholders contained in the placeholder key.
            placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);

            // Now obtain the value for the fully resolved key...
            String propVal = placeholderResolver.resolvePlaceholder(placeholder);
            if (propVal == null && this.valueSeparator != null) {
                int separatorIndex = placeholder.indexOf(this.valueSeparator);
                if (separatorIndex != -1) {
                    String actualPlaceholder = placeholder.substring(0, separatorIndex);
                    String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
                    propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
                    if (propVal == null) {
                        propVal = defaultValue;
                    }
                }
            }
            if (propVal != null) {
                // Recursive invocation, parsing placeholders contained in the
                // previously resolved placeholder value.
                propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
                buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
                if (logger.isTraceEnabled()) {
                    logger.trace("Resolved placeholder '" + placeholder + "'");
                }
                startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length());
            } else if (this.ignoreUnresolvablePlaceholders) {
                // Proceed with unprocessed value.
                startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
            } else {
                throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "'");
            }

            visitedPlaceholders.remove(placeholder);
        } else {
            startIndex = -1;
        }
    }

    return buf.toString();
}

From source file:com.harrywu.springweb.common.PropertyPlaceholderHelper.java

protected String parseStringValue(String strVal, StringValueResolver placeholderResolver,
        Set<String> visitedPlaceholders) {

    StringBuilder buf = new StringBuilder(strVal);

    int startIndex = strVal.indexOf(this.placeholderPrefix);
    while (startIndex != -1) {
        int endIndex = findPlaceholderEndIndex(buf, startIndex);
        if (endIndex != -1) {
            String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex);
            if (!visitedPlaceholders.add(placeholder)) {
                throw new IllegalArgumentException(
                        "Circular placeholder reference '" + placeholder + "' in property definitions");
            }/*  www.j a v a 2 s. co m*/
            // Recursive invocation, parsing placeholders contained in the placeholder key.
            placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);

            // Now obtain the value for the fully resolved key...
            String propVal = placeholderResolver.resolveStringValue(placeholder);
            if (propVal == null && this.valueSeparator != null) {
                int separatorIndex = placeholder.indexOf(this.valueSeparator);
                if (separatorIndex != -1) {
                    String actualPlaceholder = placeholder.substring(0, separatorIndex);
                    String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
                    propVal = placeholderResolver.resolveStringValue(actualPlaceholder);
                    if (propVal == null) {
                        propVal = defaultValue;
                    }
                }
            }
            if (propVal != null) {
                // Recursive invocation, parsing placeholders contained in the
                // previously resolved placeholder value.
                propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
                buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);

                if (logger.isTraceEnabled()) {
                    logger.trace("Resolved placeholder '" + placeholder + "'");
                }

                startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length());
            } else if (this.ignoreUnresolvablePlaceholders) {
                // Proceed with unprocessed value.
                startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
            } else {
                throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "'");
            }

            visitedPlaceholders.remove(placeholder);
        } else {
            startIndex = -1;
        }
    }

    return buf.toString();
}