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:com.vladium.emma.report.html.ReportGenerator.java

private void addClassItemRow(final IItem item, final boolean odd, final HTMLTable table, final int[] columns,
        final String nameHREF, final boolean anchor) {
    if ($assert.ENABLED) {
        $assert.ASSERT(item != null, "null input: item");
        $assert.ASSERT(table != null, "null input: table");
        $assert.ASSERT(columns != null, "null input: columns");
    }/*from   w ww .  j a  v a 2s.  co  m*/

    final HTMLTable.IRow row = table.newRow();
    if (odd)
        row.setClass(CSS_ODDROW);

    final StringBuffer buf = new StringBuffer(11); // TODO: reuse a buffer

    for (int c = 0; c < columns.length; ++c) {
        final int attrID = columns[c];
        final IItemAttribute attr = item.getAttribute(attrID, m_settings.getUnitsType());

        if (attr != null) {
            final HTMLTable.ICell cell = row.newCell();

            boolean fail = false;
            if ((nameHREF != null) && (attrID == IItemAttribute.ATTRIBUTE_NAME_ID)) {
                buf.setLength(0);
                attr.format(item, buf);

                trimForDisplay(buf);

                final String fullHREFName = anchor ? "#".concat(nameHREF) : nameHREF;

                cell.add(new HyperRef(fullHREFName, buf.toString(), true));
            } else {
                fail = (m_metrics[attrID] > 0) && !attr.passes(item, m_metrics[attrID]);

                buf.setLength(0);
                attr.format(item, buf);

                trimForDisplay(buf);

                cell.setText(buf.toString(), true);
            }

            cell.setClass(dataCellStyle(c, fail));
        } else {
            // note: by design this puts empty cells for nonexistent attribute types

            final HTMLTable.ICell cell = row.newCell();
            cell.setText(" ", true);
            cell.setClass(dataCellStyle(c, false));
        }
    }
}

From source file:cc.siara.csv_ml_demo.MainActivity.java

/**
 * Evaluates given XPath from Input box against Document generated by
 * parsing csv_ml in input box and sets value or node list to output box.
 *///from  w  w  w . jav  a  2s . c o m
void processXPath() {
    EditText etInput = (EditText) findViewById(R.id.etInput);
    EditText etXPath = (EditText) findViewById(R.id.etXPath);
    CheckBox cbPretty = (CheckBox) findViewById(R.id.cbPretty);
    XPath xpath = XPathFactory.newInstance().newXPath();
    MultiLevelCSVParser parser = new MultiLevelCSVParser();
    Document doc = null;
    try {
        doc = parser.parseToDOM(new StringReader(etInput.getText().toString()), false);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    if (doc == null)
        return;
    StringBuffer out_str = new StringBuffer();
    try {
        XPathExpression expr = xpath.compile(etXPath.getText().toString());
        try {
            Document outDoc = Util.parseXMLToDOM("<output></output>");
            Element rootElement = outDoc.getDocumentElement();
            NodeList ret = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < ret.getLength(); i++) {
                Object o = ret.item(i);
                if (o instanceof String) {
                    out_str.append(o);
                } else if (o instanceof Node) {
                    Node n = (Node) o;
                    short nt = n.getNodeType();
                    switch (nt) {
                    case Node.TEXT_NODE:
                    case Node.ATTRIBUTE_NODE:
                    case Node.CDATA_SECTION_NODE: // Only one value gets
                                                  // evaluated?
                        if (out_str.length() > 0)
                            out_str.append(',');
                        if (nt == Node.ATTRIBUTE_NODE)
                            out_str.append(n.getNodeValue());
                        else
                            out_str.append(n.getTextContent());
                        break;
                    case Node.ELEMENT_NODE:
                        rootElement.appendChild(outDoc.importNode(n, true));
                        break;
                    }
                }
            }
            if (out_str.length() > 0) {
                rootElement.setTextContent(out_str.toString());
                out_str.setLength(0);
            }
            out_str.append(Util.docToString(outDoc, true));
        } catch (Exception e) {
            // Thrown most likely because the given XPath evaluates to a
            // string
            out_str.append(expr.evaluate(doc));
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    if (out_str.length() > 5 && out_str.substring(0, 5).equals("<?xml"))
        out_str.delete(0, out_str.indexOf(">") + 1);
    EditText etOutput = (EditText) findViewById(R.id.etOutput);
    etOutput.setText(out_str.toString());
    // tfOutputSize.setText(String.valueOf(xmlString.length()));
}

From source file:net.sourceforge.myvd.inserts.jdbc.JdbcInsert.java

private void createSELECT(ArrayList<Attribute> attributes, StringBuffer buf) {
    Iterator<Attribute> it = attributes.iterator();

    boolean foundRDN = false;
    boolean foundAttrib = false;
    if (attributes.size() == 0) {
        buf.append(" * ");
        return;//  ww  w .  j av a 2 s .c  om
    }

    while (it.hasNext()) {
        foundAttrib = false;
        String attrib = it.next().getAttribute().getName();

        if (attrib.equalsIgnoreCase(this.rdn)) {
            foundRDN = true;
        }

        if (attrib.equalsIgnoreCase("*")) {
            buf.append("* ");
        } else {

            String ldap2dbVal = ldap2db.get(attrib.toLowerCase());
            if (ldap2dbVal != null) {
                buf.append(ldap2dbVal).append(' ');
                foundAttrib = true;
            } else {
                continue;
            }
        }

        if ((it.hasNext() || !foundRDN) && foundAttrib) {
            buf.append(',');
        }
    }

    if (!foundRDN) {
        buf.append(this.ldap2db.get(this.rdn.toLowerCase())).append(" ,");
    }

    if (!foundAttrib) {
        buf.setLength(buf.lastIndexOf(",") - 1);
    }

    if (buf.charAt(buf.length() - 1) == ',') {
        buf.setLength(buf.length() - 1);
    }

}

From source file:org.pentaho.di.core.Const.java

/**
 * Right pad a StringBuffer: adds spaces to a string until a certain length. If the length is smaller then the limit
 * specified, the String is truncated./*from   w  w w . j av  a 2 s .  c  o m*/
 *
 * @param ret
 *          The StringBuffer to pad
 * @param limit
 *          The desired length of the padded string.
 * @return The padded String.
 */
public static final String rightPad(StringBuffer ret, int limit) {
    int len = ret.length();
    int l;

    if (len > limit) {
        ret.setLength(limit);
    } else {
        for (l = len; l < limit; l++) {
            ret.append(' ');
        }
    }
    return ret.toString();
}

From source file:com.pureinfo.srm.project.ProjectToFinishRemindJob.java

private void remindAdmins() throws PureException {
    for (Iterator iter = m_hRemindedPrjs.entrySet().iterator(); iter.hasNext();) {
        Map.Entry en = (Map.Entry) iter.next();
        Integer iDept = (Integer) en.getKey();
        SRMUser admin = (SRMUser) m_admins.get(iDept);
        if (admin == null)
            continue;
        StringBuffer sbuff = new StringBuffer();

        List[] prjs = (List[]) en.getValue();
        if (prjs == null || prjs[0].size() + prjs[1].size() == 0) {
            continue;
        }//from w  w  w  . j  a v  a 2  s. c  om
        sbuff.append(admin.getTrueName()).append(" \n\n");
        sbuff.append("");
        for (int ii = 0; ii < prjs.length; ii++) {
            if (prjs[ii].size() > 0) {
                sbuff.append("").append(ii == 0 ? 1 : 3).append("\n");
                sbuff.append("\t\t\t\t\n");
                sbuff.append("===================================================================\n");
                for (Iterator iterator = prjs[ii].iterator(); iterator.hasNext();) {
                    Object[] ele = (Object[]) iterator.next();
                    Project prj = (Project) ele[0];
                    SRMUser usr = (SRMUser) ele[1];
                    Organization oSection = prj.getAdminSectionObj();
                    String sSectionName = oSection == null ? "" : oSection.getName();
                    sbuff.append(DATE_FORMAT.format(prj.getFinishDate())).append('\t');
                    sbuff.append(usr == null ? "" : usr.getTrueName()).append('\t');
                    sbuff.append(prj.getProjectNumber()).append('\t');
                    sbuff.append(sSectionName).append('\t');
                    sbuff.append(prj.getProjectName()).append('\t');
                    sbuff.append('\n');
                }
                sbuff.append("\n\n");
            }
        }
        sbuff.append("\n");
        sbuff.append(TODAY);
        String sMsg = sbuff.toString();
        sendMail(admin, "", sMsg);
        sbuff.setLength(0);

    }
}

From source file:ValidateLicenseHeaders.java

/**
 * Read the first comment upto the package ...; statement
 * /*from   www.j a  v  a  2 s .  c om*/
 * @param javaFile
 */
static void parseHeader(File javaFile) throws IOException {
    totalCount++;
    RandomAccessFile raf = new RandomAccessFile(javaFile, "rw");
    String line = raf.readLine();
    StringBuffer tmp = new StringBuffer();
    long endOfHeader = 0;
    boolean packageOrImport = false;
    while (line != null) {
        long nextEOH = raf.getFilePointer();
        line = line.trim();
        // Ignore any single line comments
        if (line.startsWith("//")) {
            line = raf.readLine();
            continue;
        }

        // If this is a package/import/class/interface statement break
        if (line.startsWith("package") || line.startsWith("import") || line.indexOf("class") >= 0
                || line.indexOf("interface") >= 0) {
            packageOrImport = true;
            break;
        }

        // Update the current end of header marker
        endOfHeader = nextEOH;

        if (line.startsWith("/**"))
            tmp.append(line.substring(3));
        else if (line.startsWith("/*"))
            tmp.append(line.substring(2));
        else if (line.startsWith("*"))
            tmp.append(line.substring(1));
        else
            tmp.append(line);
        tmp.append(' ');
        line = raf.readLine();
    }
    raf.close();

    if (tmp.length() == 0 || packageOrImport == false) {
        addDefaultHeader(javaFile);
        return;
    }

    String text = tmp.toString();
    // Replace all duplicate whitespace with a single space
    text = text.replaceAll("[\\s*]+", " ");
    text = text.toLowerCase().trim();
    // Replace any copyright date0-date1,date2 with copyright ...
    text = text.replaceAll(COPYRIGHT_REGEX, "...");
    if (tmp.length() == 0) {
        addDefaultHeader(javaFile);
        return;
    }
    // Search for a matching header
    boolean matches = false;
    String matchID = null;
    Iterator iter = licenseHeaders.entrySet().iterator();
    escape: while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        String key = (String) entry.getKey();
        List list = (List) entry.getValue();
        Iterator jiter = list.iterator();
        while (jiter.hasNext()) {
            LicenseHeader lh = (LicenseHeader) jiter.next();
            if (text.startsWith(lh.text)) {
                matches = true;
                matchID = lh.id;
                lh.count++;
                lh.usage.add(javaFile);
                if (log.isLoggable(Level.FINE))
                    log.fine(javaFile + " matches copyright key=" + key + ", id=" + lh.id);
                break escape;
            }
        }
    }
    text = null;
    tmp.setLength(0);
    if (matches == false)
        invalidheaders.add(javaFile);
    else if (matchID.startsWith("jboss") && matchID.endsWith("#0") == false) {
        // This is a legacy jboss head that needs to be updated to the default
        replaceHeader(javaFile, endOfHeader);
        jbossCount++;
    }
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * <p>/* ww  w. j  a va 2 s .c om*/
 * Is the supplied {@linkplain File#getPath() path} a relative path, which, if
 * {@linkplain java.net.URI#resolve(String) resolved} against some other path/folder, would point to a location
 * <em>within</em> that path's folder.
 * </p>
 * 
 * <ul>
 * <li><code>"/hello/"</code> returns <code>false</code>.</li>
 * <li><code>"./"</code> returns <code>true</code>.</li>
 * <li><code>"./hello.txt"</code> returns <code>true</code>.</li>
 * <li><code>"hello/"</code> returns <code>true</code>.</li>
 * <li><code>"hello/../"</code> returns <code>true</code>.</li>
 * <li><code>"hello/world/../"</code> returns <code>true</code>.</li>
 * <li><code>"hello/world/../../"</code> returns <code>true</code>.</li>
 * <li><code>"hello/world/../.././"</code> returns <code>true</code>.</li>
 * <li><code>"hello/world/../../../"</code> returns <code>false</code>.</li>
 * <li><code>".."</code> returns <code>false</code>.</li>
 * <li><code>"../"</code> returns <code>false</code>.</li>
 * </ul>
 * 
 * @param path The {@linkplain File#getPath() path} to some file or directory.
 * @return <code>true</code> if the supplied <code>path</code> is a relative subpath.
 * @throws IllegalArgumentException If <code>path</code> is {@linkplain String#isEmpty() empty}.
 */
protected static final boolean isRelativeSubPath(final String path) throws IllegalArgumentException {
    if (path.isEmpty())
        throw new IllegalArgumentException("emtpy path");
    if (path.charAt(0) == '/')
        return false;
    int depth = 0;
    final StringBuffer currentComponent = new StringBuffer(path.length());
    for (int i = 0; i < path.length(); i++) {
        final char c = path.charAt(i);
        if (c != '/') {
            currentComponent.append(c);
        } else {
            final String currentComponentString = currentComponent.toString();
            if (currentComponentString.equals("..")) {
                depth--;
                if (depth < 0)
                    return false;
            } else if ((currentComponentString.length() > 0) && (!currentComponentString.equals("."))) {
                depth++;
            }
            currentComponent.setLength(0);
        }
    }
    if ((currentComponent.length() == 2) && (currentComponent.toString().equals("..")) && (depth <= 0))
        return false;
    return true;
}

From source file:com.ikanow.infinit.e.api.config.source.SourceHandler.java

/**
 * validateSourceKey/*from w w  w. ja  v  a 2 s. c  o m*/
 * Checks source key passed in for uniqueness, if the key is not
 * unique it adds a number to the end and increments the number
 * until it is unique
 * @param id
 * @param key
 * @return
 */
private String validateSourceKey(ObjectId id, String key) {
    ///////////////////////////////////////////////////////////////////////
    // Keep appending random numbers to the string until we get a unique
    // match

    int counter = 0;
    java.util.Random random = new java.util.Random(new Date().getTime());

    StringBuffer sb = new StringBuffer(key).append('.');
    key = sb.toString();
    int nBaseLen = sb.length();

    while (!hasUniqueSourceKey(id, key)) {
        counter++;
        if (0 == (counter % 50)) { // every 50 times another term to the expression
            sb.append('.');
            nBaseLen = sb.length();
        } //(TESTED)

        sb.setLength(nBaseLen);
        sb.append(random.nextInt(10000));

        key = sb.toString();
    }
    //(TESTED)
    return sb.toString();
}

From source file:org.apache.jetspeed.services.template.JetspeedTemplateLocatorService.java

/**
 * Helper function for template locator to find a localized (NLS) resource.
 * Considers both language and country resources as well as all the possible
 * media-types for the request/*  w w w  .ja  v  a2s  . c o  m*/
 * 
 * @param data
 *          The rundata for the request.
 * @param locale
 *          The locale for the request.
 * 
 * @return The possible paths to a localized template ordered by descending
 *         preference
 */
private List localizeTemplateName(RunData data, Locale inLocale) {
    List templates = new ArrayList();
    Locale tmplocale = null;

    if (inLocale != null) {
        tmplocale = inLocale;
    } else {
        CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil
                .getServiceByName(LocalizationService.SERVICE_NAME);
        tmplocale = locService.getLocale(data);
    }

    // Get the locale store it in the user object
    if (tmplocale == null) {
        tmplocale = new Locale(TurbineResources.getString("locale.default.language", "en"),
                TurbineResources.getString("locale.default.country", "US"));
    }

    if (data.getUser() != null) {
        data.getUser().setTemp("locale", tmplocale);
    }

    StringBuffer templatePath = new StringBuffer();

    // retrieve all the possible media types
    String type = data.getParameters().getString(Profiler.PARAM_MEDIA_TYPE, null);
    List types = new ArrayList();
    CapabilityMap cm = ((JetspeedRunData) data).getCapability();

    // Grab the Locale from the temporary storage in the User object
    Locale locale = data.getUser() != null ? (Locale) data.getUser().getTemp("locale") : tmplocale;
    String language = locale.getLanguage();
    String country = locale.getCountry();

    if (null != type) {
        types.add(type);
    } else {
        Iterator i = cm.listMediaTypes();
        while (i.hasNext()) {
            types.add(i.next());
        }
    }

    Iterator typeIterator = types.iterator();

    while (typeIterator.hasNext()) {
        type = (String) typeIterator.next();

        if ((type != null) && (type.length() > 0)) {
            templatePath.append(PATH_SEPARATOR).append(type);
        }

        if ((language != null) && (language.length() > 0)) {
            templatePath.append(PATH_SEPARATOR).append(language);
        }

        if ((country != null) && (country.length() > 0)) {
            templatePath.append(PATH_SEPARATOR).append(country);
        }

        templates.add(templatePath.toString());
        templatePath.setLength(0);
    }

    return templates;
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java

public void importParentDB(InputStream in) {
    try {/*ww  w  . j  av  a 2 s  . co m*/
        Connection conn = sessionFactory.getCurrentSession().connection();
        Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuffer query = new StringBuffer();
        boolean queryEnds = false;

        while ((line = reader.readLine()) != null) {
            if ((line.startsWith("#") || line.startsWith("--"))) {
                continue;
            }
            queryEnds = line.endsWith(";");
            query.append(line);
            if (queryEnds) {
                try {
                    statement.execute(query.toString());
                } catch (SQLException ex) {
                    log.warn(ex);
                    ex.printStackTrace();
                }
                query.setLength(0);
            }
        }
        in.close();

    } catch (IOException ex) {
        log.warn(ex);
        ex.printStackTrace();
    } catch (SQLException ex) {
        log.warn(ex);
        ex.printStackTrace();
    }
}