Example usage for java.lang StringBuffer length

List of usage examples for java.lang StringBuffer length

Introduction

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

Prototype

@Override
    public synchronized int length() 

Source Link

Usage

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);
    }/*from   ww  w.j av  a  2 s . co m*/
    return matches;
}

From source file:net.duckling.ddl.util.FileUtil.java

/**
 *  Runs a simple command in given directory.
 *  The environment is inherited from the parent process (e.g. the
 *  one in which this Java VM runs)./*from  www  . j a v a 2  s. com*/
 *
 *  @return Standard output from the command.
 *  @param  command The command to run
 *  @param  directory The working directory to run the command in
 *  @throws IOException If the command failed
 *  @throws InterruptedException If the command was halted
 */
public static String runSimpleCommand(String command, String directory)
        throws IOException, InterruptedException {
    StringBuffer result = new StringBuffer();

    LOG.info("Running simple command " + command + " in " + directory);

    Process process = Runtime.getRuntime().exec(command, null, new File(directory));

    BufferedReader stdout = null;
    BufferedReader stderr = null;

    try {
        stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
        stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        String line;

        while ((line = stdout.readLine()) != null) {
            result.append(line).append("\n");
        }

        StringBuffer error = new StringBuffer();
        while ((line = stderr.readLine()) != null) {
            error.append(line).append("\n");
        }

        if (error.length() > 0) {
            LOG.error("Command failed, error stream is: " + error);
        }

        process.waitFor();

    } finally {
        // we must close all by exec(..) opened streams: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
        process.getInputStream().close();
        if (stdout != null) {
            stdout.close();
        }
        if (stderr != null) {
            stderr.close();
        }
    }

    return result.toString();
}

From source file:ch.entwine.weblounge.common.url.UrlUtils.java

/**
 * Concatenates the url elements with respect to leading and trailing slashes.
 * The path will always end with a trailing slash.
 * //from ww  w  .j a v  a 2s  . c o m
 * @param urlElements
 *          the path elements
 * @return the concatenated url of the two arguments
 * @throws IllegalArgumentException
 *           if less than two path elements are provided
 */
public static String concat(String... urlElements) throws IllegalArgumentException {
    if (urlElements == null || urlElements.length < 1)
        throw new IllegalArgumentException("Prefix cannot be null or empty");
    if (urlElements.length < 2)
        throw new IllegalArgumentException("Suffix cannot be null or empty");

    StringBuffer b = new StringBuffer();
    for (String s : urlElements) {
        if (StringUtils.isBlank(s))
            throw new IllegalArgumentException("Path element cannot be null");
        String element = checkSeparator(s);
        element = removeDoubleSeparator(element);

        if (b.length() == 0) {
            b.append(element);
        } else if (b.lastIndexOf("/") < b.length() - 1 && !element.startsWith("/")) {
            b.append("/").append(element);
        } else if (b.lastIndexOf("/") == b.length() - 1 && element.startsWith("/")) {
            b.append(element.substring(1));
        } else {
            b.append(element);
        }
    }

    return b.toString();
}

From source file:Main.java

public static String parseNodeAsText(Node node) {
    if (node == null)
        return null;
    String text = null;/*from   ww w.  j a  v a  2 s  .  co m*/
    if (node.getNodeType() == 3) {
        text = node.getNodeValue();
    } else {
        StringBuffer sb = new StringBuffer();
        NodeList children = node.getChildNodes();
        for (int i = 0; children != null && i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child != null) {
                int childType = child.getNodeType();
                if (childType == 3 || childType == 4 || childType == 8) {
                    String childText = child.getNodeValue();
                    sb.append(childText);
                } else {
                    sb.append(parseNodeAsText(child));
                }
            }
        }

        if (sb.length() > 0)
            text = sb.toString();
    }
    return text;
}

From source file:com.edgenius.core.Global.java

public static void syncTo(GlobalSetting setting) {

    setting.setDefaultDirection(Global.DefaultDirection);
    setting.setDefaultLanguage(Global.DefaultLanguage);
    setting.setDefaultCountry(Global.DefaultCountry);
    setting.setDefaultTimeZone(Global.DefaultTimeZone);
    setting.setDefaultLoginKey(Global.DefaultLoginKey);
    setting.setHostProtocol(Global.SysHostProtocol);
    if (StringUtils.indexOf(Global.SysHostAddress, ':') != -1) {
        String[] addr = StringUtils.split(Global.SysHostAddress, ':');
        setting.setHostName(addr[0]);/*from   w  w w.  j a v  a2s .  c om*/
        setting.setHostPort(Integer.parseInt(addr[1]));
    } else {
        setting.setHostName(Global.SysHostAddress);
        if (Global.SysHostProtocol != null && Global.SysHostProtocol.startsWith("https:"))
            setting.setHostPort(443);
        else
            setting.setHostPort(80);
    }

    setting.setPublicSearchEngineAllow(Global.PublicSearchEngineAllow);
    setting.setContextPath(StringUtils.trim(Global.SysContextPath));
    setting.setEncryptAlgorithm(Global.PasswordEncodingAlgorithm);
    setting.setEncryptPassword(Global.EncryptPassword);
    setting.setSpaceQuota(Global.SpaceQuota);
    setting.setDelayRemoveSpaceHours(Global.DelayRemoveSpaceHours);
    setting.setEnableAdminPermControl(Global.EnableAdminPermControl);
    setting.setDelayOfflineSyncMinutes(Global.DelayOfflineSyncMinutes);
    setting.setRegisterMethod(Global.registerMethod);
    setting.setMaintainJobCron(Global.MaintainJobCron);
    setting.setCommentsNotifierCron(Global.CommentsNotifierCron);
    setting.setMaxCommentsNotifyPerDay(Global.MaxCommentsNotifyPerDay);
    setting.setAutoFixLinks(Global.AutoFixLinks);
    setting.setDefaultNotifyMail(Global.DefaultNotifyMail);
    setting.setCcToSystemAdmin(Global.ccToSystemAdmin);
    setting.setDefaultReceiverMailAddress(Global.DefaultReceiverMail);
    setting.setSystemTitle(Global.SystemTitle);

    setting.setAdsense(enable(Global.ADSENSE));
    setting.setTextnut(enable(Global.TEXTNUT));
    setting.setSkin(Global.Skin);

    setting.setWebservice(enable(Global.webServiceEnabled));
    setting.setWebserviceAuthenticaton(
            StringUtils.isBlank(Global.webServiceAuth) ? "basic" : Global.webServiceAuth);

    setting.setRestservice(enable(Global.restServiceEnabled));
    setting.setRestserviceAuthenticaton(
            StringUtils.isBlank(Global.restServiceAuth) ? "basic" : Global.restServiceAuth);

    setting.setDetectLocaleFromRequest(Global.DetectLocaleFromRequest);

    setting.setVersionCheck(Global.VersionCheck);
    setting.setVersionCheckCron(Global.VersionCheckCron);
    setting.setPurgeDaysOldActivityLog(Global.PurgeDaysOldActivityLog);

    //convert suppress value to names 
    StringBuffer supStr = new StringBuffer();
    if (Global.suppress > 0) {
        for (SUPPRESS sup : SUPPRESS.values()) {
            if ((sup.getValue() & Global.suppress) > 0) {
                supStr.append(sup.name()).append(",");
            }
        }
        if (supStr.length() > 0) {
            supStr.deleteCharAt(supStr.length() - 1);
        }
    }
    setting.setSuppress(supStr.toString());

    setting.setTwitterOauthConsumerKey(Global.TwitterOauthConsumerKey);
    setting.setTwitterOauthConsumerSecret(Global.TwitterOauthConsumerSecret);
}

From source file:com.tactfactory.harmony.utils.TactFileUtils.java

/**
 * Append String to at the end of a file
 * if it doesn't exists in the file yet.
 * @param content The content to append/*from   w w w .j a  va 2s.  c  om*/
 * @param file The file to write to
 * @return true if the content has been correctly appended
 */
public static boolean appendToFile(final String content, final File file) {
    boolean success = false;
    final StringBuffer buffer = TactFileUtils.fileToStringBuffer(file);
    //If content doesn't exists in the file yet
    if (buffer.indexOf(content) == -1) {
        final int offset = buffer.length();
        buffer.insert(offset, content);
        TactFileUtils.stringBufferToFile(buffer, file);
        success = true;
    }
    return success;
}

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);// w w w .j a  va  2  s  . c  o m
    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:com.bytelightning.opensource.pokerface.ScriptHelperImpl.java

/**
 * @see AddMimeEntry//  w w  w . j  a v a2  s .  c o m
 */
private static void AddMimeEntryImpl(String type, String extensions) {
    LinkedHashSet<String> extSet = new LinkedHashSet<String>();
    MimeEntry entry = MimeHashTable.find(type);
    if (entry == null)
        entry = new sun.net.www.MimeEntry(type.intern());
    // Ensure the type is an interned string
    entry.setType(type.intern());

    String[] existing = entry.getExtensions();
    if (existing != null)
        for (String ext : existing)
            extSet.add(ext);
    String[] additional = extensions.split(",");
    for (int i = 0; i < additional.length; i++) {
        additional[i] = additional[i].trim().toLowerCase();
        if (additional[i].length() == 0)
            throw new RuntimeException("Invalid mime extensions for: " + type);
        if (additional[i].charAt(0) != '.')
            throw new RuntimeException("mime extensions must start with a '.' (" + type + ")");
        extSet.add(additional[i]);
    }
    StringBuffer sb = new StringBuffer();
    for (String ext : extSet) {
        if (sb.length() > 0)
            sb.append(',');
        sb.append(ext);
    }
    entry.setExtensions(sb.toString());
    // This little hack ensures that the MimeEntry itself has interned strings in it's list.  Yes it's a trade off between bad practice and speed.
    String[] processed = entry.getExtensions();
    for (int i = 0; i < processed.length; i++)
        processed[i] = processed[i].intern();
}

From source file:com.mg.framework.utils.StringUtils.java

/**
 * Make sure the string starts with a forward slash but does not end with one; converts
 * back-slashes to forward-slashes; if in String is null or empty, returns zero length string.
 *///from  w  w w .ja v  a 2 s. c  om
public static String cleanUpPathPrefix(String prefix) {
    if (prefix == null || prefix.length() == 0)
        return "";

    StringBuffer cppBuff = new StringBuffer(prefix.replace('\\', '/'));

    if (cppBuff.charAt(0) != '/') {
        cppBuff.insert(0, '/');
    }
    if (cppBuff.charAt(cppBuff.length() - 1) == '/') {
        cppBuff.deleteCharAt(cppBuff.length() - 1);
    }
    return cppBuff.toString();
}

From source file:com.redhat.rhn.common.util.ServletUtils.java

/**
 * Creates a encoded URL query string with the parameters from the given request. If the
 * request is a GET, then the returned query string will simply consist of the query
 * string from the request. If the request is a POST, the returned query string will
 * consist of the form variables.//  w ww. j a  v  a 2 s . c  om
 *
 * <br/><br/>
 *
 * <strong>Note</strong>: This method does not support multi-value parameters.
 *
 * @param request The request for which the query string will be generated.
 *
 * @return An encoded URL query string with the parameters from the given request.
 */
public static String requestParamsToQueryString(ServletRequest request) {

    StringBuffer queryString = new StringBuffer();

    String paramName = null;
    String paramValue = null;

    Enumeration paramNames = request.getParameterNames();

    while (paramNames.hasMoreElements()) {
        paramName = (String) paramNames.nextElement();
        paramValue = request.getParameter(paramName);

        queryString.append(encode(paramName)).append("=").append(encode(paramValue)).append("&");
    }

    if (endsWith(queryString, '&')) {
        queryString.deleteCharAt(queryString.length() - 1);
    }

    return queryString.toString();
}