Example usage for java.lang StringBuffer substring

List of usage examples for java.lang StringBuffer substring

Introduction

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

Prototype

@Override
public synchronized String substring(int start, int end) 

Source Link

Usage

From source file:Main.java

/**
 * convert the reference of the numerical value letter into ths substance.
 * @param xml//from  w w  w.j a v a  2  s. c  om
 * @return
 */
public static String resolveNumEntities(String xml) {
    StringBuffer strb = new StringBuffer(xml);

    int index;
    int index2 = 0;
    int index3 = 0;

    while ((index = strb.toString().indexOf("&#", index2)) != -1) {
        index2 = strb.toString().indexOf(';', index + 1);
        index3 = strb.toString().indexOf("&#", index + 1);
        if (index2 == -1) {
            break;
        } else if (index3 != -1 && index2 > index3) {
            //We pass the entity description that is not right.
            index2 = index3;
        } else {
            try {
                char numericChar = (char) Integer.parseInt(strb.substring(index + 2, index2));
                String numericStr = String.valueOf(numericChar);
                strb.replace(index, index2 + 1, numericStr);
                index2 = index + numericStr.length();
            } catch (NumberFormatException e) {
                //We pass reference of the numerical value letter that is not right.
            }
        }
    }

    return strb.toString();
}

From source file:Main.java

/**
 * Return true if the string starting at offset in sb matches with xmlTag.
 * @param sb StringBuffer/*from   w w  w  .ja v a 2s  .  co  m*/
 * @param offset int
 * @param xmlTag String The XML tag name to check without '<' and '>'
 * @return
 */
private static boolean matchXMLTag(StringBuffer sb, int offset, String xmlTag) {
    if (offset >= sb.length()) {
        return false;
    }
    if (sb.charAt(offset) != '<') {
        return false;
    }
    int indexOfSpace = sb.indexOf(" ", offset);
    int indexOfGt = sb.indexOf(">", offset);
    int indexOfEndTag = Integer.MAX_VALUE;
    if (indexOfSpace >= 0) {
        indexOfEndTag = indexOfSpace;
    }
    if (indexOfGt >= 0 && indexOfGt < indexOfEndTag) {
        indexOfEndTag = indexOfGt;
    }
    if (indexOfEndTag == Integer.MAX_VALUE) {
        return false;
    }
    String potentialTag = sb.substring(offset + 1, indexOfEndTag);
    return potentialTag.equals(xmlTag);
}

From source file:org.compass.core.util.SystemPropertyUtils.java

/**
 * Resolve ${...} placeholders in the given text,
 * replacing them with corresponding system property values.
 *
 * @param text the String to resolve/*from  www. j  a  v  a2s  .c  o m*/
 * @return the resolved String
 * @see #PLACEHOLDER_PREFIX
 * @see #PLACEHOLDER_SUFFIX
 */
public static String resolvePlaceholders(String text) {
    if (text == null) {
        return null;
    }

    StringBuffer buf = new StringBuffer(text);

    // The following code does not use JDK 1.4's StringBuffer.indexOf(String)
    // method to retain JDK 1.3 compatibility. The slight loss in performance
    // is not really relevant, as this code will typically just run on startup.

    int startIndex = text.indexOf(PLACEHOLDER_PREFIX);
    while (startIndex != -1) {
        int endIndex = buf.toString().indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length());
        if (endIndex != -1) {
            String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
            int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length();
            try {
                String propVal = System.getProperty(placeholder);
                if (propVal == null) {
                    // Fall back to searching the system environment.
                    propVal = System.getenv(placeholder);
                }
                if (propVal != null) {
                    buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal);
                    nextIndex = startIndex + propVal.length();
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Could not resolve placeholder '" + placeholder + "' in [" + text
                                + "] as system property: neither system property nor environment variable found");
                    }
                }
            } catch (Throwable ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not resolve placeholder '" + placeholder + "' in [" + text
                            + "] as system property: " + ex);
                }
            }
            startIndex = buf.toString().indexOf(PLACEHOLDER_PREFIX, nextIndex);
        } else {
            startIndex = -1;
        }
    }

    return buf.toString();
}

From source file:opennlp.tools.util.Span.java

  public static String[] spansToStrings(Span[] spans, String[] tokens) {
  String[] chunks = new String[spans.length];
  StringBuffer cb = new StringBuffer();
  for (int si = 0, sl = spans.length; si < sl; si++) {
    cb.setLength(0);/* www  .  j  a v  a 2 s  .  c om*/
    for (int ti=spans[si].getStart();ti<spans[si].getEnd();ti++) {
      cb.append(tokens[ti]).append(" ");
    }
    chunks[si]=cb.substring(0, cb.length()-1);
  }
  return chunks;
}

From source file:org.exoplatform.platform.common.software.register.UnlockService.java

private static int decodeKey(String productCode, String Key) {
    try {/*from  w w  w . j  a  va  2s. com*/
        StringBuffer keyBuffer = new StringBuffer(new String(Base64.decodeBase64(Key.getBytes())));
        String keyLengthString = keyBuffer.substring(8, 10);
        int length = Integer.parseInt(keyBuffer.substring(4, 6));
        keyBuffer.replace(4, 6, "");
        String productCodeHashed = keyBuffer.substring(0, length);
        if (!productCodeHashed.equals(Utils.getModifiedMD5Code(productCode.getBytes()))) {
            keyBuffer.replace(6, 8, "");
            productCodeHashed = keyBuffer.substring(0, length);
            if (!productCodeHashed.equals(Utils.getModifiedMD5Code(productCode.getBytes()))) {
                return 0;
            }
        }
        String productInfoString = keyBuffer.substring(length);
        String[] productInfo = productInfoString.split(",");

        if ((productInfo.length == 3)) {
            int keyLength = Integer.parseInt(keyLengthString);
            boolean validLicence = (keyLength == keyBuffer.toString().length() + 4);
            if (!validLicence)
                return 0;
            String nbUser = productInfo[0];
            String duration = productInfo[1];
            String keyDate = productInfo[2];
            DateFormat d = new SimpleDateFormat("dd/MM/yyyy");
            try {
                d.parse(keyDate);
            } catch (ParseException e) {
                LOG.info("UNVALID KEY");
                return 0;
            }
            String edition = "";
            int period = 0;
            try {
                period = Integer.parseInt(duration);
            } catch (NumberFormatException exp) {
                LOG.info("INVALID KAY");
                return 0;
            }
            if (period == -1) {
                duration = Utils.UNLIMITED;
                nbUser = new String(Base64.decodeBase64(nbUser.getBytes()));
                int userNumber = 0;
                try {
                    userNumber = Integer.parseInt(nbUser) / 3;
                } catch (NumberFormatException exp) {
                    LOG.info("INVALID KAY");
                    return 0;
                }
                if (userNumber == -1) {
                    edition = ProductInformations.ENTERPRISE_EDITION;
                    nbUser = Utils.UNLIMITED;
                } else {
                    edition = ProductInformations.EXPRESS_EDITION;
                    nbUser = String.valueOf(userNumber);
                }
            }
            persistInfo(edition, nbUser, keyDate, duration, productCode, Key);
            return period;
        } else if ((productInfo.length == 1) || (productInfo.length == 0)) {
            String periodString = new String(Base64.decodeBase64(productInfoString.getBytes()));
            int period = Integer.parseInt(periodString) / 3;
            return period;
        } else
            return 0;
    } catch (Exception e) {
        return 0;
    }

}

From source file:de.j4velin.mapsmeasure.Util.java

/**
 * Get the altitude data for a specific point
 * /*  w w w .j  a v  a2s.  co  m*/
 * @param p
 *            the point to get the altitude for
 * @param httpClient
 *            can be null if no network query should be performed
 * @param localContext
 *            can be null if no network query should be performed
 * @return the altitude at point p or -Float.MAX_VALUE if no valid data
 *         could be fetched
 * @throws IOException
 */
static float getAltitude(final LatLng p, final HttpClient httpClient, final HttpContext localContext)
        throws IOException {
    if (elevationCache == null) {
        elevationCache = new HashMap<LatLng, Float>(30);
    }
    if (elevationCache.containsKey(p)) {
        return elevationCache.get(p);
    } else if (httpClient != null && localContext != null) {
        float altitude = -Float.MAX_VALUE;
        String url = "http://maps.googleapis.com/maps/api/elevation/xml?locations=" + String.valueOf(p.latitude)
                + "," + String.valueOf(p.longitude) + "&sensor=true";
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            int r = -1;
            StringBuffer respStr = new StringBuffer();
            while ((r = instream.read()) != -1)
                respStr.append((char) r);
            String tagOpen = "<elevation>";
            String tagClose = "</elevation>";
            if (respStr.indexOf(tagOpen) != -1) {
                int start = respStr.indexOf(tagOpen) + tagOpen.length();
                int end = respStr.indexOf(tagClose);
                altitude = Float.parseFloat(respStr.substring(start, end));
                elevationCache.put(p, altitude);
            }
            instream.close();
        }
        return altitude;
    } else {
        return elevationCache.get(p);
    }
}

From source file:org.objectweb.proactive.extensions.vfsprovider.client.ProActiveFileNameParser.java

private static String extractServicePath(StringBuffer path) throws FileSystemException {
    if (path.length() > 0 && path.charAt(0) != FileName.SEPARATOR_CHAR) {
        throw new FileSystemException(
                "Invalid path in URI: service path after host name does not begin with slash");
    }/* w w  w .  j av a2 s  .  c  o  m*/

    int idx = path.indexOf(ProActiveFileName.SERVICE_AND_FILE_PATH_SEPARATOR);
    if (idx == -1) {
        // simply assume that whole path is a service path
        final String servicePath = path.toString();
        path.delete(0, path.length());
        return servicePath;
    }
    final String servicePath = path.substring(0, idx);
    path.delete(0, idx + ProActiveFileName.SERVICE_AND_FILE_PATH_SEPARATOR.length());
    return servicePath;
}

From source file:org.proxydroid.Profile.java

public static String encodeAddrs(String[] addrs) {

    if (addrs.length == 0)
        return "";

    StringBuffer sb = new StringBuffer();
    for (String addr : addrs) {
        String ta = validateAddr(addr);
        if (ta != null)
            sb.append(ta + "|");
    }// www . j  a  va  2  s  . co  m
    String ret = sb.substring(0, sb.length() - 1);
    return ret;
}

From source file:com.niki.normalizer.Metaphone.java

private static boolean regionMatch(StringBuffer string, int index, String test) {
    boolean matches = false;
    if (index >= 0 && (index + test.length() - 1) < string.length()) {
        String substring = string.substring(index, index + test.length());
        matches = substring.equals(test);
    }/* w  ww. jav  a 2  s.  c o  m*/
    return matches;
}

From source file:com.anyi.gp.license.RegisterTools.java

public static String getKeyString(String encodeType) {
    StringBuffer sb = new StringBuffer();
    sb.append("Host[" + getHostName() + "];");
    sb.append("Ip[");
    Set entrySet = getInetAddresses().entrySet();
    java.util.Map.Entry entry;//  w ww . j  a v  a  2s  .c om
    for (Iterator iterator = entrySet.iterator(); iterator.hasNext(); sb.append(entry.getValue() + ",")) {
        entry = (java.util.Map.Entry) iterator.next();
    }

    if (!entrySet.isEmpty()) {
        sb = new StringBuffer(sb.substring(0, sb.length() - 1));
    }
    sb.append("];");
    sb.append("ENCODETYPE[" + encodeType + "];");
    sb.append("Mac[");
    List macList = getMacAddresses();
    for (int i = 0; i < macList.size(); i++) {
        if (i != 0) {
            sb.append(",");
        }
        sb.append(macList.get(i));
    }

    sb.append("]");
    return sb.toString();
}