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:pl.nask.hsn2.normalizers.URLNormalizerUtils.java

public static String normlizePath(StringBuilder pathIn, int startIndx, int endIndx) throws URLParseException {

    int endSq = findFirstMatch(pathIn, "?#", startIndx);
    if (endSq < 0 || endSq > endIndx) {
        endSq = endIndx;/*  w  w w. j  av  a2s . co m*/
    }
    int endReplace = endSq;
    StringBuilder retPath = new StringBuilder(pathIn.substring(startIndx, endSq));

    String[] strPattern = new String[] { "/./" };

    int dotIndex = findFirstMatch(retPath, strPattern, 0);
    while (dotIndex > 0 && dotIndex < endSq) {
        retPath.delete(dotIndex, dotIndex + 2);
        endSq -= 2;
        dotIndex = findFirstMatch(retPath, strPattern, 0);
    }

    strPattern = new String[] { "/.." };
    while (findFirstMatch(retPath, strPattern, 0) == 0) {
        retPath.delete(0, 3);
        endSq -= 3;
    }

    int iDDot = findFirstMatch(retPath, strPattern, 0, endSq);
    if (iDDot < 0) {
        encodePath(retPath, 0, retPath.length());
        if (retPath.length() == 0 || retPath.codePointAt(0) != '/') {
            retPath.insert(0, '/');
        }
        pathIn.replace(startIndx, endReplace, retPath.toString());
        return retPath.toString();
    }
    int iSS = 0;
    iDDot = retPath.indexOf("/..");

    Stack<String> pathStack = new Stack<String>();
    while (iDDot >= 0) {
        int next = retPath.indexOf("/", iSS + 1);
        while (next <= iDDot && next >= 0) {
            pathStack.push(retPath.substring(iSS, next));
            iSS = next;
            next = retPath.indexOf("/", iSS + 1);

        }
        while (iSS == iDDot) {
            if (!pathStack.isEmpty()) {
                pathStack.pop();
            }
            iDDot = retPath.indexOf("/..", iSS + 1);

            if (iDDot < 0) {
                pathStack.push(retPath.substring(iSS + 3));
                break;
            }
            iSS = retPath.indexOf("/", iSS + 1);
        }
    }

    if (pathStack.isEmpty()) {
        encodePath(retPath, 0, retPath.length());
        if (retPath.codePointAt(0) != '/') {
            retPath.insert(0, '/');
        }
        pathIn.replace(startIndx, endReplace, retPath.toString());
        return retPath.toString();
    } else {
        retPath = new StringBuilder();
        for (int i = 0; i < pathStack.size(); i++) {
            retPath.append(pathStack.elementAt(i));
        }
    }
    if (retPath.length() == 0) {
        retPath.append("/");
    }
    encodePath(retPath, 0, retPath.length());
    if (retPath.indexOf("/") != 0) {
        retPath.insert(0, '/');
    }
    pathIn.replace(startIndx, endReplace, retPath.toString());
    return retPath.toString();
}

From source file:org.apache.shindig.gadgets.oauth.OAuthFetcher.java

/**
 * Builds the URL the client needs to visit to approve access.
 *//*from   w  ww  .java2  s  .  c o m*/
private void buildAznUrl() {
    // At some point we can be clever and use a callback URL to improve
    // the user experience, but that's too complex for now.
    OAuthAccessor accessor = accessorInfo.getAccessor();
    StringBuilder azn = new StringBuilder(accessor.consumer.serviceProvider.userAuthorizationURL);
    if (azn.indexOf("?") == -1) {
        azn.append('?');
    } else {
        azn.append('&');
    }
    azn.append(OAuth.OAUTH_TOKEN);
    azn.append('=');
    azn.append(OAuth.percentEncode(accessor.requestToken));
    responseParams.setAznUrl(azn.toString());
}

From source file:org.talend.designer.codegen.config.CamelEndpointBuilder.java

/**
 * Builds the param query./*w ww . j a  v  a  2s  .  c om*/
 * 
 * @return the char sequence, eg: +"?p="+v+"&p2="+v2
 */
private CharSequence buildParamQuery() {
    StringBuilder sb = new StringBuilder();
    for (Entry<String, String> entry : paramsMap.entrySet()) {
        StringBuilder paramSB = new StringBuilder();
        SBTool.appendDirectString(paramSB, "&");
        SBTool.appendExpression(paramSB, entry.getKey());
        SBTool.appendDirectString(paramSB, "=");
        SBTool.appendExpression(paramSB, entry.getValue());
        SBTool.mergeConstantStrings(paramSB);
        sb.append(paramSB);
    }
    if (sb.length() > 0) {
        // fix first & to ?.
        sb.setCharAt(sb.indexOf("&"), '?');
    }
    return sb;
}

From source file:org.apache.shindig.gadgets.oauth.OAuthRequest.java

/**
 * Builds the URL the client needs to visit to approve access.
 *//*from w  ww  .  jav  a2s .  com*/
private void buildAznUrl() throws OAuthRequestException {
    // We add the token, gadget is responsible for the callback URL.
    OAuthAccessor accessor = accessorInfo.getAccessor();
    if (accessor.consumer.serviceProvider.userAuthorizationURL == null) {
        throw new OAuthRequestException(OAuthError.BAD_OAUTH_TOKEN_URL, "authorization");
    }
    StringBuilder azn = new StringBuilder(accessor.consumer.serviceProvider.userAuthorizationURL);
    if (azn.indexOf("?") == -1) {
        azn.append('?');
    } else {
        azn.append('&');
    }
    azn.append(OAuth.OAUTH_TOKEN);
    azn.append('=');
    azn.append(OAuth.percentEncode(accessor.requestToken));
    responseParams.setAznUrl(azn.toString());
}

From source file:com.riq.LatitudeServlet.java

private Map<String, String> riqGeocode(Long deptId,
        //          Long alertId, 
        Long objectId, String objectType) {

    //    log.info("");
    //    log.info("Inside riqGeocode");
    //    log.info("ObjectType: " + objectType);
    //    log.info("ObjectId: " + objectId.toString());

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Map<String, String> latlngMap = new HashMap();

    Member m = null;//w w  w  .  ja  v a2  s  .  c o  m
    Location l = null;
    String latitudeId = "";

    if ("Member".equalsIgnoreCase(objectType)) {
        try {
            m = (Member) pm.getObjectById(Member.class, objectId);
            log.info("Member Last Name: " + m.getlastName());
            latitudeId = m.getlatitudeId();
        } catch (javax.jdo.JDOObjectNotFoundException mi) {
        }
    } else if ("Location".equalsIgnoreCase(objectType)) {
        try {
            l = (Location) pm.getObjectById(Location.class, objectId);
            latitudeId = l.getlatitudeId();
        } catch (javax.jdo.JDOObjectNotFoundException mi) {
        }
    } else {
        return null;
    }

    String geocodeURL = "http://www.google.com/latitude/apps/badge/api?user=" + latitudeId.trim()
            + "&type=json";

    try {

        URL url;
        Long gpsTimeStamp = null;
        String gpsAccuracy = "";

        url = new URL(geocodeURL);
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuilder tempString = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            tempString.append(line);
        }

        JSONObject obj = new JSONObject(tempString.toString());

        //      if ("FeatureCollection".equalsIgnoreCase(obj.getString("type"))) {
        JSONArray features = obj.getJSONArray("features");
        //        log.info("Just before Feature not null check inside geocode method");
        //        log.info("Geometry Position in tempString: " + tempString.indexOf("geometry"));

        if (tempString.indexOf("geometry") < 10) {

            return (null);

        } else {

            JSONObject feature = features.getJSONObject(0);
            JSONObject geometry = feature.getJSONObject("geometry");
            JSONArray coordinates = geometry.getJSONArray("coordinates");
            Double lat = (Double) coordinates.get(0);
            Double lng = (Double) coordinates.get(1);

            JSONObject properties = feature.getJSONObject("properties");
            gpsTimeStamp = properties.getLong("timeStamp");
            gpsAccuracy = String.valueOf(properties.getLong("accuracyInMeters"));

            //          log.info("gLat: " + lat);
            //          log.info("gLng: " + lng);
            //          log.info("gTimeStamp: " + gpsTimeStamp);  
            //          log.info("gAccuracy in Meters: " + gpsAccuracy);
            //          log.info("gLatitudeId: " + latitudeId.trim());

            latlngMap.put("lat", String.valueOf(lat));
            latlngMap.put("lng", String.valueOf(lng));
            latlngMap.put("timeStamp", gpsTimeStamp.toString());
            latlngMap.put("accuracyMeters", gpsAccuracy.toString());

            Coordinate c = new Coordinate(deptId,
                    //                  alertId,
                    objectId, objectType, latitudeId, System.currentTimeMillis(), gpsTimeStamp, lat, lng,
                    gpsAccuracy, "dist", null);
            pm.makePersistent(c);
        }
        //      }
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return (latlngMap);
}

From source file:pl.nask.hsn2.normalizers.URLNormalizerUtils.java

public static String decodeIPv6(StringBuilder sb) throws URLHostParseException, URLMalformedInputException {

    Stack<Long> values = new Stack<Long>();

    int endSq = getIPv6EndIndex(sb);
    int i = findFirstMatch(sb, "[", 0, endSq);
    int begSq = i >= 0 ? i : 0;
    while (true) {
        int prev = i;
        i = findFirstMatch(sb, ":]/.", prev + 1);
        try {//www .  ja va 2  s.  c  o m
            if (i - prev < 2) {
                if (i < 0 && prev + 1 < endSq) {
                    values.push(Long.parseLong(sb.substring(prev + 1, endSq), 16));
                }
                break;
            }
            if (sb.codePointAt(i) == '.') {
                i = prev;
                break;
            }
            values.push(Long.parseLong(sb.substring(prev + 1, i), 16));
        } catch (NumberFormatException e) {
            LOG.warn("cannot parse IPv6 ");
            LOG.warn(e.getMessage());
            throw new URLHostParseException("Cannot parse IPv6:" + sb.substring(begSq), e);
        }
        if (i == sb.indexOf("::")) {
            break;
        }
    }
    final int parsedValues = values.size();
    int ipv64 = sb.indexOf(".");
    i = sb.indexOf("::");
    if ((ipv64 >= 0 && ipv64 < i)) {
        throw new URLHostParseException("Error in parsing ipv4 in ipv6");
    }
    long[] ipv4tab = null;

    i++;
    while (i > 0) {
        int prev = i + 1;
        i = sb.indexOf(":", prev);
        //            if (i < 0 && ipv64 > 0) {
        //                break;
        //            }
        if (i < 0) {
            if (ipv64 > 0) {
                break;
            }
            i = endSq;
            if (i - prev < 1) {
                break;
            }
            try {
                values.push(Long.parseLong(sb.substring(prev, i), 16));
            } catch (NumberFormatException e) {
                LOG.warn("cannot parse IPv6 ");
                LOG.warn(e.getMessage());
                throw new URLHostParseException("Cannot parse IPv6:" + sb.substring(begSq, endSq), e);
            }
            break;
        }
        try {
            if (i <= endSq) {
                values.push(Long.parseLong(sb.substring(prev, i), 16));
            }
        } catch (NumberFormatException e) {
            LOG.warn("Cannot parse IPv6 " + e.getMessage());
            LOG.warn(e.getMessage());
            throw new URLHostParseException("Cannot parse IPv6:" + sb.substring(begSq, endSq), e);
        }
    }
    if (ipv64 > 0) {
        i = findLastMatch(sb, ":", 0, endSq);
        ipv4tab = decodeIPv4(sb.substring(i + 1, endSq));
        ipv64 = 4;
    } else {
        ipv64 = 0;
    }

    long[] ret = validateAndBuildArray(values, parsedValues, ipv64, ipv4tab);

    if (ret[0] > 0xfc00l) {
        LOG.warn("non routable address (ULA) {}", sb.toString());
    }
    StringBuilder retSb = arrayToIPv6(ret, ipv64 > 0);
    i = retSb.indexOf("::");
    if (i > 0) {
        if (retSb.indexOf("ffff") > 0) {
            retSb.replace(i, i + 1, "0:0:0:0:0");
        } else {
            retSb.replace(i, i + 1, "0:0:0:0:0:0");
        }
    }

    if (endSq == URLNormalizerUtils.findFirstMatch(sb, "]/", 0)) {
        endSq++;
    }
    sb.replace(begSq, endSq, retSb.toString().toLowerCase());
    return retSb.toString();
}

From source file:org.sonatype.nexus.testsuite.obr.ObrITSupport.java

private void waitFor(final InputStream input, final String expectedLine) throws Exception {
    final long startMillis = System.currentTimeMillis();
    final StringBuilder content = new StringBuilder();
    do {//from   w  w w.  j ava  2 s.  co m
        final int available = input.available();
        if (available > 0) {
            final byte[] bytes = new byte[available];
            input.read(bytes);
            final String current = new String(bytes);
            System.out.print(current);
            content.append(current);
            Thread.yield();
        } else if (System.currentTimeMillis() - startMillis > 5 * 60 * 1000) {
            throw new InterruptedException(); // waited for more than 5 minutes
        } else {
            try {
                Thread.sleep(100);
            } catch (final InterruptedException e) {
                // continue...
            }
        }
    } while (content.indexOf(expectedLine) == -1);
    System.out.println();
}

From source file:com.cyberninjas.invoice.pdf.InvoiceTextExtractionStrategy.java

/**
 * Parses the text with a PDF based on the given settings.
 *
 * @param settings settings used to parse the document.
 *///w  w  w. j  av  a 2 s.c om
public void parse(PdfInvoiceSettings settings) {
    cumulativeCostLocationMap = new HashMap();
    cumulativeCostSubtotalLocation = null;
    totalFundedAmountLocation = null;

    // locate the cumulative cost heading for aligning cumulative cost amounts
    TextChunk cumulativeCostHeadingTextChunk = matchText(settings.getCumulativeCostHeadingText());

    if (cumulativeCostHeadingTextChunk == null) {
        log.warn("Failed to locate the cumulative cost heading based on the text ["
                + settings.getCumulativeCostHeadingText() + "]");
    }

    // locate the ItemIds and their containing rows
    StringBuilder sb = new StringBuilder();

    TextChunk lastChunk = null;

    String lastItemId = null;

    for (TextChunk chunk : getTextChunks()) {
        if (lastChunk == null) {
            sb.append(chunk.getText());
        } else {
            if (chunk.sameLine(lastChunk)) {
                // we only insert a blank space if the trailing character of the previous string wasn't a space, and the leading character of the current string isn't a space
                if (isChunkAtWordBoundary(chunk, lastChunk) && !startsWithSpace(chunk.getText())
                        && !endsWithSpace(lastChunk.getText())) {
                    sb.append(' ');
                }

                sb.append(chunk.getText());
            } else {
                if (sb.indexOf(settings.getItemIdSeparator()) > 0) {
                    String itemId = sb.substring(0, sb.indexOf(settings.getItemIdSeparator()));

                    cumulativeCostLocationMap.put(itemId, null);

                    lastItemId = itemId;
                }

                if (lastItemId != null && sb.toString().matches(settings.getItemRowPattern())) {
                    cumulativeCostLocationMap.put(lastItemId,
                            new Vector(cumulativeCostHeadingTextChunk.getEndLocation().get(Vector.I1),
                                    lastChunk.getEndLocation().get(Vector.I2), 0));

                    lastItemId = null;
                }

                sb = new StringBuilder();

                sb.append(chunk.getText());
            }
        }

        lastChunk = chunk;
    }

    // check if all the ItemId rows have been located - if not, position based on the location of the ItemId text
    cumulativeCostLocationMap.keySet().stream()
            .filter((itemId) -> (cumulativeCostLocationMap.get(itemId) == null)).forEach((itemId) -> {
                TextChunk itemIdTextChunk = this.matchText(itemId);

                if (itemIdTextChunk != null) {
                    cumulativeCostLocationMap.replace(itemId,
                            new Vector(cumulativeCostHeadingTextChunk.getEndLocation().get(Vector.I1),
                                    itemIdTextChunk.getEndLocation().get(Vector.I2), 0));
                } else {
                    log.warn("Failed to locate row for itemId [" + itemId + "]");
                }
            });

    // locate where to write the cumulative cost subtotal
    TextChunk subTotalLabel = matchText(settings.getSubtotalLabelText());

    if (subTotalLabel != null) {
        cumulativeCostSubtotalLocation = new Vector(
                cumulativeCostHeadingTextChunk.getEndLocation().get(Vector.I1),
                subTotalLabel.getEndLocation().get(Vector.I2), 0);
    }

    // locate where to write the total funded amount
    TextChunk totalFundedAmountLabel = matchText(settings.getTotalFundedAmountLabelText());

    if (totalFundedAmountLabel != null) {
        totalFundedAmountLocation = new Vector(
                totalFundedAmountLabel.getEndLocation().get(Vector.I1) + settings.getTotalFundedAmountOffset(),
                totalFundedAmountLabel.getEndLocation().get(Vector.I2), 0);
    }
}

From source file:org.apache.olio.workload.driver.UIDriver.java

private String parseAuthToken(StringBuilder responseBuffer) throws IOException {

    int idx = responseBuffer.indexOf("authenticity_token");

    if (idx == -1) {
        logger.info("Trying to add event but authenticity token not found");
        return null;
    }//from  w ww  .j av a  2  s.  c o m

    int endIdx = responseBuffer.indexOf("\" />", idx);

    if (endIdx == -1) {
        throw new IOException("Invalid authenticity_token element. Buffer(100 chars) = "
                + responseBuffer.substring(idx, idx + 100));
    }

    String tmpString = responseBuffer.substring(idx, endIdx);
    String[] splitStr = tmpString.split("value=\"");

    if (splitStr.length < 2) {
        throw new IOException("Invalid authenticity_token element. Buffer(100 chars) = "
                + responseBuffer.substring(idx, idx + 100));
    }

    String token = splitStr[1];

    logger.finer("authenticity_token = " + token);

    return token;

}