Example usage for java.lang StringBuffer indexOf

List of usage examples for java.lang StringBuffer indexOf

Introduction

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

Prototype

@Override
public synchronized int indexOf(String str, int fromIndex) 

Source Link

Usage

From source file:org.pssframework.xsqlbuilder.XsqlBuilder.java

private List getKeys(StringBuffer xsql, int start, int end, String keyPrifix, String keySuffix) {
    List results = new ArrayList();
    int keyStart = start;
    int keyEnd = keyStart;
    while (true) {
        //get keyStart
        keyStart = xsql.indexOf(keyPrifix, keyStart);
        if (keyStart > end || keyStart < 0) {
            break;
        }/*w w  w  . j a v a  2s . co  m*/

        //get keyEnd
        keyEnd = xsql.indexOf(keySuffix, keyStart + 1);
        if (keyEnd > end || keyEnd < 0) {
            break;
        }

        //get key string
        String key = xsql.substring(keyStart + 1, keyEnd);
        results.add(key);
        keyStart = keyEnd + 1;
    }
    return results;
}

From source file:com.openedit.util.URLUtilities.java

/**
 * This is the server name only /* w w w.j a v  a  2s.  c o m*/
 *
 * returns http://www.acme.com/
 */
public String buildRoot() {
    if (fieldRequest == null) {
        return null;
    }

    StringBuffer ctx = fieldRequest.getRequestURL();
    String servername = ctx.substring(0, ctx.indexOf("/", 8));

    return servername + "/";
}

From source file:eu.europa.esig.dss.DSSUtils.java

/**
 * This method replaces in a string one pattern by another one without using regexp.
 *
 * @param string/* w  w w  .j  a  v a 2s  . c  om*/
 * @param oldPattern
 * @param newPattern
 * @return
 */
public static StringBuffer replaceStrStr(final StringBuffer string, final String oldPattern,
        final String newPattern) {
    if ((string == null) || (oldPattern == null) || oldPattern.equals("") || (newPattern == null)) {
        return string;
    }

    final StringBuffer replaced = new StringBuffer();
    int startIdx = 0;
    int idxOld;
    while ((idxOld = string.indexOf(oldPattern, startIdx)) >= 0) {
        replaced.append(string.substring(startIdx, idxOld));
        replaced.append(newPattern);
        startIdx = idxOld + oldPattern.length();
    }
    replaced.append(string.substring(startIdx));
    return replaced;
}

From source file:net.mlw.vlh.adapter.hibernate3.util.StatementBuilder.java

/**
 * Usage of filters: {key} -> :keyName add to query's parameter map keyValue
 * [key] -> keyValue//from  w w w .j  a v a 2  s  .  c om
 * 
 * @param hql
 * @param whereClause
 * @return Query for ordinary list
 * @throws HibernateException
 * @throws ParseException
 */
public Query generate(Session session, StringBuffer hql, Map whereClause, boolean isRemoveEmptyStrings)
        throws HibernateException, ParseException {
    if (whereClause == null) {
        whereClause = Collections.EMPTY_MAP;
    }

    Map arguments = new HashMap();

    // Include or exclude the filters.
    for (int i = 0, end = 0, start; ((start = hql.toString().indexOf("/~", end)) >= 0); i++) {
        end = hql.toString().indexOf("~/", start);
        String key = hql.substring(start + 2, hql.indexOf(":", start));

        Object value = whereClause.get(key);
        if (isValuePopulated(value, isRemoveEmptyStrings)) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("The filter key=[" + key + "] with the value=[" + value
                        + "] is accepted by the hql preprocesor");
            }
            hql.replace(start, end + 2, hql.substring(hql.indexOf(":", start) + 1, end));
        } else {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("The filter key=[" + key + "] is removed from the query by the hql preprocesor.");
            }
            hql.replace(start, end + 2, "");

        }
        end -= start;
    }

    // Replace any [key] with the value in the whereClause Map.
    for (int i = 0, end = 0, start; ((start = hql.toString().indexOf('[', end)) >= 0); i++) {
        end = hql.toString().indexOf(']', start);
        String key = hql.substring(start + 1, end);

        Object value = whereClause.get(key);
        hql.replace(start, end + 1, (value == null) ? "" : value.toString());
        end -= (key.length() + 2);
    }

    // Replace any "{key}" with the value in the whereClause Map,
    // then placing the value in the partameters list.
    for (int i = 0, end = 0, start; ((start = hql.toString().indexOf('{', end)) >= 0); i++) {
        end = hql.toString().indexOf('}', start);

        String key = hql.substring(start + 1, end);

        Object value = whereClause.get(key);
        if (value == null) {
            throw new NullPointerException("Property '" + key + "' was not provided.");
        }
        arguments.put(key, value);
        hql.replace(start, end + 1, ":" + key);
        end -= (key.length() + 2);
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("The final query is " + hql);
    }
    Query query = session.createQuery(hql.toString());
    // Now set all the patameters on the statement.

    if (setters == null) {
        for (Iterator keys = arguments.keySet().iterator(); keys.hasNext();) {
            String key = (String) keys.next();
            Object value = arguments.get(key);
            if (value instanceof List) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Setting a paremeterList to the query.");
                }
                query.setParameterList(key, ((List) value).toArray());
            } else {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "Using the default setter for key=[" + key + "] with the value=[" + value + "]");
                }
                getDefaultSetter().set(query, key, value);
            }
        }
    } else {
        for (Iterator keys = arguments.keySet().iterator(); keys.hasNext();) {
            String key = (String) keys.next();
            Object value = arguments.get(key);
            getSetter(key).set(query, key, value);
        }
    }

    return query;
}

From source file:org.apache.axis2.builder.XFormURLEncodedBuilder.java

/**
 * Here is what I will try to do here. I will first try to identify the location of the first
 * template element in the request URI. I am trying to deduce the location of that location
 * using the httpLocation element of the binding (it is passed in to this
 * method)./*from www.jav a  2s . co  m*/
 * If there is a contant part in the httpLocation, then I will identify it. For this, I get
 * the index of {, from httpLocation param, and whatever to the left of it is the contant part.
 * Then I search for this constant part inside the url. This will give us the access to the first
 * template parameter.
 * To find the end of this parameter, we need to get the index of the next constant, from
 * httpLocation attribute. Likewise we keep on discovering parameters.
 * <p/>
 * Assumptions :
 * 1. User will always append the value of httpLocation to the address given in the
 * endpoint.
 * 2. I was talking about the constants in the httpLocation. Those constants will not occur,
 * to a reasonable extend, before the constant we are looking for.
 *
 * @param templatedPath
 * @param parameterMap
 */
protected String extractParametersUsingHttpLocation(String templatedPath, MultipleEntryHashMap parameterMap,
        String requestURL, String queryParameterSeparator) throws AxisFault, UnsupportedEncodingException {

    if (templatedPath != null && !"".equals(templatedPath) && templatedPath.indexOf("{") > -1) {
        StringBuffer pathTemplate = new StringBuffer(templatedPath);

        // this will hold the index, from which we need to process the request URI
        int startIndex = 0;
        int templateStartIndex = 0;
        int templateEndIndex = 0;
        int indexOfNextConstant = 0;

        StringBuffer requestURIBuffer = new StringBuffer(requestURL);

        while (startIndex < requestURIBuffer.length()) {
            // this will always hold the starting index of a template parameter
            templateStartIndex = pathTemplate.indexOf("{", templateStartIndex);

            if (templateStartIndex > 0) {
                // get the preceding constant part from the template
                String constantPart = pathTemplate.substring(templateEndIndex + 1, templateStartIndex);
                constantPart = constantPart.replaceAll("\\{\\{", "{");
                constantPart = constantPart.replaceAll("}}", "}");

                // get the index of the end of this template param
                templateEndIndex = pathTemplate.indexOf("}", templateStartIndex);
                if ((pathTemplate.length() - 1) > templateEndIndex
                        && pathTemplate.charAt(templateEndIndex + 1) == '}') {
                    templateEndIndex = pathTemplate.indexOf("}", templateEndIndex + 2);
                }

                String parameterName = pathTemplate.substring(templateStartIndex + 1, templateEndIndex);
                // next try to find the next constant
                templateStartIndex = pathTemplate.indexOf("{", templateEndIndex);
                if (pathTemplate.charAt(templateStartIndex + 1) == '{') {
                    templateStartIndex = pathTemplate.indexOf("{", templateStartIndex + 2);
                }

                int endIndexOfConstant = requestURIBuffer.indexOf(constantPart, indexOfNextConstant)
                        + constantPart.length();

                if (templateStartIndex == -1) {
                    if (templateEndIndex == pathTemplate.length() - 1) {

                        // We may have occations where we have templates of the form foo/{name}.
                        // In this case the next connstant will be ? and not the
                        // queryParameterSeparator
                        indexOfNextConstant = requestURIBuffer.indexOf("?", endIndexOfConstant);
                        if (indexOfNextConstant == -1) {
                            indexOfNextConstant = requestURIBuffer.indexOf(queryParameterSeparator,
                                    endIndexOfConstant);
                        }
                        if (indexOfNextConstant > 0) {
                            addParameterToMap(parameterMap, parameterName,
                                    requestURIBuffer.substring(endIndexOfConstant, indexOfNextConstant));
                            return requestURL.substring(indexOfNextConstant);
                        } else {

                            addParameterToMap(parameterMap, parameterName,
                                    requestURIBuffer.substring(endIndexOfConstant));
                            return "";
                        }

                    } else {

                        constantPart = pathTemplate.substring(templateEndIndex + 1, pathTemplate.length());
                        constantPart = constantPart.replaceAll("\\{\\{", "{");
                        constantPart = constantPart.replaceAll("}}", "}");
                        indexOfNextConstant = requestURIBuffer.indexOf(constantPart, endIndexOfConstant);

                        addParameterToMap(parameterMap, parameterName,
                                requestURIBuffer.substring(endIndexOfConstant, indexOfNextConstant));

                        if (requestURIBuffer.length() > indexOfNextConstant + 1) {
                            return requestURIBuffer.substring(indexOfNextConstant + 1);
                        }
                        return "";
                    }
                } else {

                    // this is the next constant from the template
                    constantPart = pathTemplate.substring(templateEndIndex + 1, templateStartIndex);
                    constantPart = constantPart.replaceAll("\\{\\{", "{");
                    constantPart = constantPart.replaceAll("}}", "}");

                    indexOfNextConstant = requestURIBuffer.indexOf(constantPart, endIndexOfConstant);
                    addParameterToMap(parameterMap, parameterName,
                            requestURIBuffer.substring(endIndexOfConstant, indexOfNextConstant));
                    startIndex = indexOfNextConstant;

                }

            }

        }
    }

    return requestURL;
}

From source file:org.ops4j.pax.scanner.file.internal.FileScanner.java

/**
 * Reads the bundles from the file specified by the urlSpec.
 * {@inheritDoc}/*from w w  w.j a  v a2 s .  c  om*/
 */
public List<ScannedBundle> scan(final ProvisionSpec provisionSpec)
        throws MalformedSpecificationException, ScannerException {
    NullArgumentException.validateNotNull(provisionSpec, "Provision spec");

    LOGGER.debug("Scanning [" + provisionSpec.getPath() + "]");
    List<ScannedBundle> scannedBundles = new ArrayList<ScannedBundle>();
    ScannerConfiguration config = createConfiguration();
    BufferedReader bufferedReader = null;
    try {
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(
                    URLUtils.prepareInputStream(provisionSpec.getPathAsUrl(), !config.getCertificateCheck())));
            Integer defaultStartLevel = getDefaultStartLevel(provisionSpec, config);
            Boolean defaultStart = getDefaultStart(provisionSpec, config);
            Boolean defaultUpdate = getDefaultUpdate(provisionSpec, config);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String trimmedLine = line.trim();
                if (trimmedLine.length() > 0 && !trimmedLine.startsWith(COMMENT_SIGN)) {
                    if (trimmedLine.startsWith(PROPERTY_PREFIX)) {
                        Matcher matcher = PROPERTY_PATTERN.matcher(trimmedLine);
                        if (!matcher.matches() || matcher.groupCount() != 2) {
                            throw new ScannerException("Invalid property: " + line);
                        }
                        String key = matcher.group(1);
                        String value = matcher.group(2);
                        StringBuffer stringBuffer = new StringBuffer(value.length());
                        for (matcher = QUOTED_PROPERTY_VALUE_PATTERN.matcher(value); matcher.find(); matcher
                                .appendReplacement(stringBuffer, value)) {
                            String group = matcher.group();
                            value = group.substring(1, group.length() - 1).replace("\\\"", "\"").replace("$",
                                    "\\$");
                        }
                        int index = stringBuffer.length();
                        matcher.appendTail(stringBuffer);
                        if (index < stringBuffer.length() && !(stringBuffer.indexOf(" ", index) < 0
                                && stringBuffer.indexOf("\"", index) < 0)) {
                            throw new ScannerException("Invalid property: " + line);
                        }
                        value = SystemPropertyUtils.resolvePlaceholders(stringBuffer.toString());
                        System.setProperty(key, value);
                    } else {
                        line = SystemPropertyUtils.resolvePlaceholders(line);
                        final ScannedFileBundle scannedFileBundle = new ScannedFileBundle(line,
                                defaultStartLevel, defaultStart, defaultUpdate);
                        scannedBundles.add(scannedFileBundle);
                        LOGGER.debug("Installing bundle [" + scannedFileBundle + "]");
                    }
                }
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
    } catch (IOException e) {
        throw new ScannerException("Could not parse the provision file", e);
    }
    return scannedBundles;
}

From source file:architecture.common.util.TextUtils.java

/**
 * Given a string, and the index to start looking at, find the index of the
 * start of the scheme. Eg.//from  ww w.  j  a va 2 s .c om
 * 
 * <pre>
 * getSchemeIndex("notes://abc", 0) -> 0
 * getSchemeIndex("abc notes://abc", 0) -> 4
 * </pre>
 * 
 * @param str
 *            The string to search for
 * @param startIndex
 *            Where to start looking at
 * @return The location the string was found, ot -1 if the string was not
 *         found.
 */
private static int getSchemeIndex(StringBuffer str, int startIndex) {
    int schemeIndex = str.indexOf(SCHEME_URL, startIndex + 1);

    // if it was not found, or found at the start of the string, then return
    // 'not found'
    if (schemeIndex <= 0) {
        return -1;
    }

    // walk backwards through the scheme until we find the first non valid
    // character
    int schemeStart;

    for (schemeStart = schemeIndex - 1; schemeStart >= 0; schemeStart--) {
        char currentChar = str.charAt(schemeStart);

        if (!isValidSchemeChar(currentChar)) {
            break;
        }
    }

    // reset the scheme to the starting character
    schemeStart++;

    // we don't want to do this, otherwise an invalid scheme would ruin the
    // linking for later schemes
    // if (UrlUtils.isValidScheme(str.substring(schemeStart, schemeIndex)))
    // return schemeStart;
    // else
    // return -1;
    return schemeStart;
}

From source file:architecture.common.util.TextUtils.java

/**
 * Get the starting index of a URL (either 'abc://' or 'www.')
 *///w w w . j a  va2 s.c  om
private static final int getStartUrl(StringBuffer str, int startIndex) {
    int schemeIndex = getSchemeIndex(str, startIndex);
    final int wwwIndex = str.indexOf("www.", startIndex + 1);

    if ((schemeIndex == -1) && (wwwIndex == -1)) {
        return -1;
    } else if (schemeIndex == -1) {
        return wwwIndex;
    } else if (wwwIndex == -1) {
        return schemeIndex;
    }

    return Math.min(schemeIndex, wwwIndex);
}

From source file:org.sakaiproject.nakamura.http.usercontent.ServerProtectionServiceImpl.java

private void redirectToContent(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException, IOException {
    StringBuffer requestURL = request.getRequestURL();
    String queryString = request.getQueryString();
    if (queryString != null) {
        requestURL.append("?").append(queryString);
    }//from   w w  w .j  a  va 2s  .  c om
    String url = requestURL.toString();
    // replace the protocol and host with the CDN host.
    int pathStart = requestURL.indexOf("/", requestURL.indexOf(":") + 3);
    url = getTransferUrl(request, url.substring(pathStart));
    // send via the session establisher
    LOGGER.debug("Sending redirect for {} {} ", request.getMethod(), url);
    response.sendRedirect(url);
}

From source file:com.isecpartners.gizmo.HttpRequest.java

private void setContentEncodings(StringBuffer contents) {
    if (contents.toString().toUpperCase().indexOf(ACCEPT_ENCODING) != -1) {
        int valStart = contents.toString().toUpperCase().indexOf(ACCEPT_ENCODING) + ACCEPT_ENCODING.length()
                + 2;//from www .j a va 2  s .  c om
        int valEnd = contents.indexOf("\r\n", valStart);
        contents.replace(valStart, valEnd, "gzip, deflate");
    }
}