Example usage for java.lang StringBuffer setLength

List of usage examples for java.lang StringBuffer setLength

Introduction

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

Prototype

@Override
public synchronized void setLength(int newLength) 

Source Link

Usage

From source file:io.gravitee.reporter.file.FileReporter.java

private StringBuilder format(Metrics metrics) {
    StringBuilder buf = accessLogBuffer;
    StringBuffer dateBuffer = dateFormatBuffer;
    buf.setLength(0);/*from   ww  w. j  av  a 2  s . c  o  m*/
    dateBuffer.setLength(0);

    // Append request timestamp
    buf.append('[');
    dateFormatter.format(metrics.timestamp().toEpochMilli(), dateBuffer);
    buf.append(dateBuffer);
    buf.append("] ");

    // Append request id
    buf.append(metrics.getRequestId());
    buf.append(" ");

    // Append transaction id
    buf.append(metrics.getTransactionId());
    buf.append(" ");

    // Append local IP
    buf.append('(');
    buf.append(metrics.getLocalAddress());
    buf.append(") ");

    // Append remote IP
    buf.append(metrics.getRemoteAddress());
    buf.append(' ');

    // Append Api name
    String apiName = metrics.getApi();
    if (apiName == null) {
        apiName = NO_STRING_DATA_VALUE;
    }

    buf.append(apiName);
    buf.append(' ');

    // Append security type
    SecurityType securityType = metrics.getSecurityType();
    if (securityType == null) {
        buf.append(NO_STRING_DATA_VALUE);
    } else {
        buf.append(securityType.name());
    }
    buf.append(' ');

    // Append security token
    String securityToken = metrics.getSecurityToken();
    if (securityToken == null) {
        securityToken = NO_STRING_DATA_VALUE;
    }
    buf.append(securityToken);
    buf.append(' ');

    // Append request method and URI
    buf.append(metrics.getHttpMethod());
    buf.append(' ');
    buf.append(metrics.getUri());
    buf.append(' ');

    // Append response status
    int status = metrics.getStatus();
    if (status <= 0) {
        status = 404;
    }
    buf.append((char) ('0' + ((status / 100) % 10)));
    buf.append((char) ('0' + ((status / 10) % 10)));
    buf.append((char) ('0' + (status % 10)));
    buf.append(' ');

    // Append response length
    long responseLength = metrics.getResponseContentLength();
    if (responseLength >= 0) {
        if (responseLength > 99999) {
            buf.append(responseLength);
        } else {
            if (responseLength > 9999)
                buf.append((char) ('0' + ((responseLength / 10000) % 10)));
            if (responseLength > 999)
                buf.append((char) ('0' + ((responseLength / 1000) % 10)));
            if (responseLength > 99)
                buf.append((char) ('0' + ((responseLength / 100) % 10)));
            if (responseLength > 9)
                buf.append((char) ('0' + ((responseLength / 10) % 10)));
            buf.append((char) ('0' + (responseLength) % 10));
        }
    } else {
        buf.append(NO_INTEGER_DATA_VALUE);
    }
    buf.append(' ');

    // Append total response time
    buf.append(metrics.getProxyResponseTimeMs());
    buf.append(' ');

    // Append proxy latency
    buf.append(metrics.getProxyLatencyMs());

    buf.append(System.lineSeparator());

    return buf;
}

From source file:org.apache.marmotta.platform.core.services.prefix.PrefixServiceImpl.java

@Override
public String serializePrefixMapping() {
    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, String> mapping : cache.entrySet()) {
        sb.append(mapping.getKey()).append(": ").append(mapping.getValue()).append("\n");
    }//from ww w  .jav  a2s. c  o  m
    sb.setLength(sb.length() - 1);
    return sb.toString();
}

From source file:com.ikanow.infinit.e.data_model.store.config.source.SourcePojo.java

public static Collection<String> getDistributedKeys(String key, Integer highestDistributionFactorStored) {
    int numShards = 1;
    if (null != highestDistributionFactorStored) {
        numShards = highestDistributionFactorStored;
    }/*from  ww  w  .j a va2s  . com*/
    ArrayList<String> distributedKeys = new ArrayList<String>(numShards);
    StringBuffer keySb = new StringBuffer(key).append("#");
    int originalLength = keySb.length();
    for (int i = 0; i < numShards; i++) {
        if (0 == i) {
            distributedKeys.add(key);
        } else {
            keySb.append(i);
            distributedKeys.add(keySb.toString());
            keySb.setLength(originalLength);
        }
    }
    return distributedKeys;
}

From source file:com.fiveamsolutions.nci.commons.web.struts2.validator.HibernateValidator.java

private void addFieldError(String fieldName, InvalidValue message) {
    StringBuffer errorField = new StringBuffer(fieldName);
    StringBuffer errorFieldKey = new StringBuffer(fieldName);
    if (StringUtils.isNotBlank(getResourceKeyBase())) {
        errorFieldKey.setLength(0); // clear
        errorFieldKey.append(getResourceKeyBase());
    }/*from   w  w  w  .j  a v  a 2 s .  co  m*/
    errorField.append('.').append(message.getPropertyPath());
    errorFieldKey.append('.').append(message.getPropertyPath());
    String msg = StringUtils.replace(message.getMessage(), "(fieldName)",
            getValidatorContext().getText(errorFieldKey.toString(), message.getPropertyPath()));
    String errorFieldName = errorField.toString();
    getValidatorContext().addFieldError(errorFieldName, msg);

}

From source file:com.stimulus.archiva.language.LanguageIdentifier.java

/**
 * Identify language of content.// w  w  w  . j av a 2s . c  o m
 * 
 * @param content is the content to analyze.
 * @return The 2 letter
 *         <a href="http://www.w3.org/WAI/ER/IG/ert/iso639.htm">ISO 639
 *         language code</a> (en, fi, sv, ...) of the language that best
 *         matches the specified content.
 */
public synchronized String identify(StringBuffer content) {
    //logger.debug("language identification sample:");
    //logger.debug(content.toString());
    StringBuffer text = content;
    if ((analyzeLength > 0) && (content.length() > analyzeLength)) {
        text = new StringBuffer().append(content);
        text.setLength(analyzeLength);
    }

    suspect.analyze(text);
    Iterator iter = suspect.getSorted().iterator();
    float topscore = Float.MIN_VALUE;
    String lang = null;
    HashMap scores = new HashMap();
    NGramEntry searched = null;

    while (iter.hasNext()) {
        searched = (NGramEntry) iter.next();
        NGramEntry[] ngrams = (NGramEntry[]) ngramsIdx.get(searched.getSeq());
        if (ngrams != null) {
            for (int j = 0; j < ngrams.length; j++) {
                NGramProfile profile = ngrams[j].getProfile();
                Float pScore = (Float) scores.get(profile);
                if (pScore == null) {
                    pScore = new Float(0);
                }
                float plScore = pScore.floatValue();
                plScore += ngrams[j].getFrequency() + searched.getFrequency();
                scores.put(profile, new Float(plScore));
                if (plScore > topscore) {
                    topscore = plScore;
                    lang = profile.getName();
                }
            }
        }
    }
    logger.debug("document language identified {language='" + lang + "'}");
    return lang;
}

From source file:com.netease.qa.emmagee.utils.CpuInfo.java

/**
 * read the status of CPU.//from  w ww.  j  a  v  a2 s  .  c o  m
 * 
 * @throws FileNotFoundException
 */
public void readCpuStat() {
    String processPid = Integer.toString(pid);
    String cpuStatPath = "/proc/" + processPid + "/stat";
    try {
        // monitor cpu stat of certain process
        RandomAccessFile processCpuInfo = new RandomAccessFile(cpuStatPath, "r");
        String line = "";
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.setLength(0);
        while ((line = processCpuInfo.readLine()) != null) {
            stringBuffer.append(line + "\n");
        }
        String[] tok = stringBuffer.toString().split(" ");
        processCpu = Long.parseLong(tok[13]) + Long.parseLong(tok[14]);
        processCpuInfo.close();
    } catch (FileNotFoundException e) {
        Log.w(LOG_TAG, "FileNotFoundException: " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    }
    readTotalCpuStat();
}

From source file:Main.java

/**
 * <p>This helper method loads the XML properties from a specific
 *   XML element, or set of elements.</p>
 *
 * @param nodeList <code>List</code> of elements to load from.
 * @param baseName the base name of this property.
 *//*from   ww  w . j av a 2  s  .co m*/
private static void loadFromElements(Map<String, String> result, NodeList nodeList, StringBuffer baseName) {
    // Iterate through each element
    for (int s = 0; s < nodeList.getLength(); s++) {
        Node current = nodeList.item(s);
        if (current.getNodeType() == Node.ELEMENT_NODE) {
            String name = current.getNodeName();
            String text = null;
            NodeList childNodes = current.getChildNodes();

            if (childNodes.getLength() > 0) {
                text = current.getChildNodes().item(0).getNodeValue();
            }

            // String text = current.getAttributeValue("value");            

            // Don't add "." if no baseName
            if (baseName.length() > 0) {
                baseName.append(".");
            }
            baseName.append(name);

            // See if we have an element value
            if ((text == null) || (text.equals(""))) {
                // If no text, recurse on children
                loadFromElements(result, current.getChildNodes(), baseName);
            } else {
                // If text, this is a property
                result.put(baseName.toString(), text);
            }

            // On unwind from recursion, remove last name
            if (baseName.length() == name.length()) {
                baseName.setLength(0);
            } else {
                baseName.setLength(baseName.length() - (name.length() + 1));
            }
        }
    }
}

From source file:com.adito.boot.ReplacementEngine.java

private void replaceInto(Pattern pattern, String replacementPattern, Replacer replacer, StringBuffer input,
        StringBuffer work) {
    work.ensureCapacity(input.length());
    work.setLength(0);
    if (log.isDebugEnabled())
        log.debug("Getting matcher for " + pattern.pattern());
    Matcher m = pattern.matcher(input);
    log.debug("Got matcher, finding first occurence.");
    while (m.find()) {
        if (log.isDebugEnabled())
            log.debug("Found occurence '" + m.group() + "'");
        String repl = replacer.getReplacement(pattern, m, replacementPattern);
        if (repl != null) {
            if (log.isDebugEnabled())
                log.debug("Found replacement, appending '" + repl + "'");
            if (encoder == null) {
                m.appendReplacement(work, Util.escapeForRegexpReplacement(repl));
            } else {
                m.appendReplacement(work, encoder.encode(Util.escapeForRegexpReplacement(repl)));
            }/*ww w  .  j av  a2  s  . co  m*/
        }
    }
    if (log.isDebugEnabled())
        log.debug("Processed matches, appending replacement.");
    m.appendTail(work);
}

From source file:corner.payment.services.impl.view.AlipayViewHelper.java

/**
 * @see corner.payment.services.ViewHelper#sign()
 *//*from  w  ww.j a  v  a  2s . c o m*/
@Override
public void sign() {
    String[] signParameter = new String[] { "charset", "description", "defaultbank", "notify_url", "order",
            "account", "payment_type", "paymethod", "return_url", "seller", "service", "show_url", "subject",
            "total_fee" };
    StringBuffer sb = new StringBuffer();

    for (String p : signParameter) {
        String v = this.getOptionValue(p);
        if (v == null) {
            continue;
        }
        sb.append(this.getFieldNameMapped(p));
        sb.append("=");
        sb.append(v);
        sb.append("&");
    }
    sb.setLength(sb.length() - 1);
    sb.append(this.key);
    System.out.println("from corner:");
    System.out.println(sb.toString());
    this.addField("sign", DigestUtils.md5Hex(sb.toString()));
    this.addField("sign_type", "MD5");
}

From source file:charvax.swing.JLabel.java

public void draw() {

    // Draw the border if it exists
    super.draw();

    /* Get the absolute origin of this component.
     *//*  w w  w.  j a  va 2s  .co  m*/
    Point origin = getLocationOnScreen();
    Insets insets = super.getInsets();
    origin.translate(insets.left, insets.top);

    Toolkit term = Toolkit.getDefaultToolkit();
    term.setCursor(origin);

    // we'll sort out justification and video-attributes etc later.
    StringBuffer buf = new StringBuffer(_labeltext);
    int textlength = _labeltext.length();
    if (_width > textlength) {
        for (int i = textlength; i < _width; i++)
            buf.append(' ');
    } else if (_width < textlength)
        buf.setLength(_width); // truncate

    int colorpair = getCursesColor();
    int attribute = (getFont().getStyle() == Font.BOLD) ? Toolkit.A_BOLD : Toolkit.A_NORMAL;
    term.addString(buf.toString(), attribute, colorpair);
}