Example usage for java.lang StringBuilder charAt

List of usage examples for java.lang StringBuilder charAt

Introduction

In this page you can find the example usage for java.lang StringBuilder charAt.

Prototype

char charAt(int index);

Source Link

Document

Returns the char value at the specified index.

Usage

From source file:com.funambol.foundation.items.dao.DataBaseFileDataObjectMetadataDAO.java

/**
 * Updates metadata fields when FileDataObject body changes, like crc, size,
 * localname etc and the properties associated to it.
 *
 * @param fdow the wrapper with the new body file
 * @throws DAOException if an error occurs
 *///from w w w  .j a v  a  2 s.c  om
public void updateItemWhenBodyChanges(FileDataObjectWrapper fdow) throws DAOException {

    Connection con = null;
    PreparedStatement ps = null;

    try {

        Long fdoId = Long.valueOf(fdow.getId());

        FileDataObject fdo = fdow.getFileDataObject();

        Timestamp currentTime = new Timestamp(System.currentTimeMillis());

        StringBuilder updateQuery = new StringBuilder();

        updateQuery.append(SQL_UPDATE_FNBL_FILE_DATA_OBJECT_BEGIN);

        updateQuery.append(SQL_FIELD_LAST_UPDATE).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        String localName = fdow.getLocalName();
        if (localName != null) {
            updateQuery.append(SQL_FIELD_LOCAL_NAME).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        updateQuery.append(SQL_FIELD_UPLOAD_STATUS).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        Long crc = Long.valueOf(fdow.getFileDataObject().getCrc());
        updateQuery.append(SQL_FIELD_CRC).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        Long size = fdo.getSize();
        if (size != null) {
            updateQuery.append(SQL_FIELD_SIZE).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Long sizeOnStorage = fdow.getSizeOnStorage();
        if (sizeOnStorage != null) {
            updateQuery.append(SQL_FIELD_SIZE_ON_STORAGE).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        // set always created and modified dates
        updateQuery.append(SQL_FIELD_CREATED).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        updateQuery.append(SQL_FIELD_MODIFIED).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        if (updateQuery.charAt(updateQuery.length() - 2) == ',') {
            updateQuery.deleteCharAt(updateQuery.length() - 2);
        }

        updateQuery.append(SQL_UPDATE_FNBL_FILE_DATA_OBJECT_END);

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        ps = con.prepareStatement(updateQuery.toString());

        int k = 1;

        Timestamp lastUpdate = (fdow.getLastUpdate() == null) ? currentTime : fdow.getLastUpdate();
        ps.setLong(k++, lastUpdate.getTime());

        if (localName != null) {
            ps.setString(k++, StringUtils.left(localName, SQL_LOCAL_NAME_DIM));
        }

        ps.setString(k++, "" + fdo.getUploadStatus());
        ps.setLong(k++, crc);

        if (size != null) {
            ps.setLong(k++, size);
        }

        if (sizeOnStorage != null) {
            ps.setLong(k++, sizeOnStorage);
        }

        MediaUtils.setFDODates(fdo, fdo.getCreated(), fdo.getModified());

        Timestamp created = timestamp(fdo.getCreated());
        if (created != null) {
            ps.setTimestamp(k++, created);
        } else {
            ps.setTimestamp(k++, currentTime);
        }

        Timestamp modified = timestamp(fdo.getModified());
        if (modified != null) {
            ps.setTimestamp(k++, modified);
        } else {
            ps.setTimestamp(k++, currentTime);
        }

        ps.setLong(k++, fdoId);
        ps.setString(k++, userId);
        ps.setString(k++, sourceURI);

        ps.executeUpdate();

        DBTools.close(con, ps, null);

        // delete and add the properties associated to the new FDO
        removeAllProperties(fdow.getId());
        addProperties(fdow);

    } catch (Exception e) {
        throw new DAOException("Error updating file data object and its properties.", e);
    } finally {
        DBTools.close(con, ps, null);
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.xml.XMLSerializer.java

private void toXml(final int indent, final DomNode node, final StringBuilder buffer,
        final String foredNamespace) {
    final String nodeName = node.getNodeName();
    buffer.append('<').append(nodeName);

    String optionalPrefix = "";
    final String namespaceURI = node.getNamespaceURI();
    final String prefix = node.getPrefix();
    if (namespaceURI != null && prefix != null) {
        boolean sameNamespace = false;
        for (DomNode parentNode = node
                .getParentNode(); parentNode instanceof DomElement; parentNode = parentNode.getParentNode()) {
            if (namespaceURI.equals(parentNode.getNamespaceURI())) {
                sameNamespace = true;//ww  w . jav a2 s . c  om
            }
        }
        if (node.getParentNode() == null || !sameNamespace) {
            ((DomElement) node).setAttribute("xmlns:" + prefix, namespaceURI);
        }
    } else if (foredNamespace != null) {
        buffer.append(" xmlns=\"").append(foredNamespace).append('"');
        optionalPrefix = " ";
    }

    final NamedNodeMap attributesMap = node.getAttributes();
    for (int i = 0; i < attributesMap.getLength(); i++) {
        final DomAttr attrib = (DomAttr) attributesMap.item(i);
        buffer.append(' ').append(attrib.getQualifiedName()).append('=').append('"').append(attrib.getValue())
                .append('"');
    }
    boolean startTagClosed = false;
    for (final DomNode child : node.getChildren()) {
        if (!startTagClosed) {
            buffer.append(optionalPrefix).append('>');
            startTagClosed = true;
        }
        switch (child.getNodeType()) {
        case Node.ELEMENT_NODE:
            toXml(indent + 1, child, buffer, null);
            break;

        case Node.TEXT_NODE:
            String value = child.getNodeValue();
            value = StringUtils.escapeXmlChars(value);
            buffer.append(value);
            break;

        case Node.CDATA_SECTION_NODE:
        case Node.COMMENT_NODE:
            buffer.append(child.asXml());
            break;

        default:

        }
    }
    if (!startTagClosed) {
        final String tagName = nodeName.toLowerCase(Locale.ROOT);
        final boolean nonEmptyTagsSupported = getBrowserVersion().hasFeature(JS_XML_SERIALIZER_NON_EMPTY_TAGS);
        if (nonEmptyTagsSupported && NON_EMPTY_TAGS.contains(tagName)) {
            buffer.append('>');
            buffer.append("</").append(nodeName).append('>');
        } else {
            buffer.append(optionalPrefix);
            if (buffer.charAt(buffer.length() - 1) != ' '
                    && getBrowserVersion().hasFeature(JS_XML_SERIALIZER_BLANK_BEFORE_SELF_CLOSING)) {
                buffer.append(" ");
            }
            buffer.append("/>");
        }
    } else {
        buffer.append('<').append('/').append(nodeName).append('>');
    }
}

From source file:org.cesecore.util.CertTools.java

/** Removes any unescaped '\' character from the provided StringBuilder. Assumes that escaping quotes have been stripped. 
 * Special treatment of the # sign, which if not escaped will be treated as hex encoded DER value by BC. */
private static StringBuilder unescapeValue(final StringBuilder sb) {
    boolean esq = false;
    int index = 0;
    while (index < (sb.length() - 1)) {
        if (!esq && sb.charAt(index) == '\\' && sb.charAt(index + 1) != '#') {
            esq = true;/*from  ww  w. j av a2  s .  c  o m*/
            sb.deleteCharAt(index);
        } else {
            esq = false;
            index++;
        }
    }
    return sb;
}

From source file:org.cesecore.util.CertTools.java

public static String getUnescapedPlus(final String value) {
    StringBuilder buf = new StringBuilder(value);
    int index = 0;
    int end = buf.length();
    while (index < end) {
        if (buf.charAt(index) == '\\' && index + 1 != end) {
            char c = buf.charAt(index + 1);
            if (c == '+') {
                buf.deleteCharAt(index);
                end--;//from ww w . j  a  v  a 2  s . c  om
            }
        }
        index++;
    }
    return buf.toString();
}

From source file:com.quartzdesk.executor.common.db.DatabaseScriptExecutor.java

/**
 * Split an SQL script into separate statements delimited by the provided delimiter
 * string. Each individual statement will be added to the provided {@code List}.
 * <p>Within a statement, the provided {@code commentPrefix} will be honored;
 * any text beginning with the comment prefix and extending to the end of the
 * line will be omitted from the statement. In addition, multiple adjacent
 * whitespace characters will be collapsed into a single space.
 *
 * @param script the SQL script//from  w  w  w .j a  v  a  2s. co  m
 * @param delim character delimiting each statement (typically a ';' character)
 * @param commentPrefix the prefix that identifies line comments in the SQL script &mdash; typically "--"
 * @param statements the List that will contain the individual statements
 */
private void splitSqlScript(String script, String delim, String commentPrefix, List<String> statements) {
    String statementSeparatorStart = commentPrefix + ' ' + STATEMENT_SEPARATOR_START;
    String statementSeparatorEnd = commentPrefix + ' ' + STATEMENT_SEPARATOR_END;

    StringBuilder sb = new StringBuilder();
    boolean inLiteral = false;
    boolean inEscape = false;
    boolean inStatementEscape = false;

    char[] content = script.toCharArray();

    for (int i = 0; i < script.length(); i++) {
        char c = content[i];

        if (inEscape) {
            inEscape = false;
            sb.append(c);
            continue;
        }

        // MySQL style escapes
        if (c == '\\') {
            inEscape = true;
            sb.append(c);
            continue;
        }

        if (c == '\'') {
            inLiteral = !inLiteral;
        }

        if (!inLiteral) {
            // normal statements ending with ;
            if (script.startsWith(delim, i) && !inStatementEscape) {
                // we've reached the end of the current statement
                if (sb.length() > 0) {
                    statements.add(sb.toString());
                    sb = new StringBuilder();
                }
                i += delim.length() - 1;
                continue;
            } else if (script.startsWith(commentPrefix, i)) {
                // -- [statement]
                if (script.startsWith(statementSeparatorStart, i)) {
                    inStatementEscape = true;
                }

                // -- [/statement]
                if (script.startsWith(statementSeparatorEnd, i)) {
                    inStatementEscape = false;

                    // we've reached the end of the escaped statement
                    if (sb.length() > 0) {
                        statements.add(sb.toString());
                        sb = new StringBuilder();
                    }
                }

                // skip over any content from the start of the comment to the EOL
                int indexOfNextNewline = script.indexOf("\n", i);
                if (indexOfNextNewline > i) {
                    i = indexOfNextNewline;
                    continue;
                } else {
                    // if there's no newline after the comment, we must be at the end
                    // of the script, so stop here.
                    break;
                }
            } else if (c == ' ' || c == '\n' || c == '\t') {
                // avoid multiple adjacent whitespace characters
                if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') {
                    c = ' ';
                } else {
                    continue;
                }
            }
        }
        sb.append(c);
    }

    String statement = sb.toString();
    if (StringUtils.isNotBlank(statement)) {
        statements.add(statement);
    }
}

From source file:org.cesecore.util.CertTools.java

/**
 * Check if the String contains any unescaped '+'. RFC 2253, section 2.2 states that '+' is used for multi-valued RelativeDistinguishedName.
 * BC (version 1.45) did not support multi-valued RelativeDistinguishedName, and automatically escaped them instead.
 * Even though it is now (BC 1.49b15) supported, we want to keep ecaping '+' chars and warn that this might not be supported in the future.
 *//*w ww  .j a  v  a2s .c  om*/
public static String handleUnescapedPlus(final String dn) {
    if (dn == null) {
        return dn;
    }
    final StringBuilder buf = new StringBuilder(dn);
    int index = 0;
    final int end = buf.length();
    while (index < end) {
        if (buf.charAt(index) == '+') {
            // Found an unescaped '+' character.
            log.warn("DN \"" + dn
                    + "\" contains an unescaped '+'-character that will be automatically escaped. RFC 2253 reservs this "
                    + "for multi-valued RelativeDistinguishedNames. Encourage clients to use '\\+' instead, since future behaviour might change.");
            buf.insert(index, '\\');
            index++;
        } else if (buf.charAt(index) == '\\') {
            // Found an escape character.
            index++;
        }
        index++;
    }
    return buf.toString();
}

From source file:org.apache.hadoop.yarn.server.webapp.AppsBlock.java

protected void renderData(Block html) {
    TBODY<TABLE<Hamlet>> tbody = html.table("#apps").thead().tr().th(".id", "ID").th(".user", "User")
            .th(".name", "Name").th(".type", "Application Type").th(".queue", "Queue")
            .th(".priority", "Application Priority").th(".starttime", "StartTime")
            .th(".finishtime", "FinishTime").th(".state", "State").th(".finalstatus", "FinalStatus")
            .th(".progress", "Progress").th(".ui", "Tracking UI")._()._().tbody();

    StringBuilder appsTableData = new StringBuilder("[\n");
    for (ApplicationReport appReport : appReports) {
        // TODO: remove the following condition. It is still here because
        // the history side implementation of ApplicationBaseProtocol
        // hasn't filtering capability (YARN-1819).
        if (!reqAppStates.isEmpty() && !reqAppStates.contains(appReport.getYarnApplicationState())) {
            continue;
        }/* ww w  .  j a  v a2 s  .co  m*/
        AppInfo app = new AppInfo(appReport);
        String percent = StringUtils.format("%.1f", app.getProgress());
        appsTableData.append("[\"<a href='").append(url("app", app.getAppId())).append("'>")
                .append(app.getAppId()).append("</a>\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app.getUser())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app.getName())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app.getType())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app.getQueue())))
                .append("\",\"").append(String.valueOf(app.getPriority())).append("\",\"")
                .append(app.getStartedTime()).append("\",\"").append(app.getFinishedTime()).append("\",\"")
                .append(app.getAppState() == null ? UNAVAILABLE : app.getAppState()).append("\",\"")
                .append(app.getFinalAppStatus()).append("\",\"")
                // Progress bar
                .append("<br title='").append(percent).append("'> <div class='").append(C_PROGRESSBAR)
                .append("' title='").append(join(percent, '%')).append("'> ").append("<div class='")
                .append(C_PROGRESSBAR_VALUE).append("' style='").append(join("width:", percent, '%'))
                .append("'> </div> </div>").append("\",\"<a ");

        String trackingURL = app.getTrackingUrl() == null || app.getTrackingUrl().equals(UNAVAILABLE) ? null
                : app.getTrackingUrl();

        String trackingUI = app.getTrackingUrl() == null || app.getTrackingUrl().equals(UNAVAILABLE)
                ? "Unassigned"
                : app.getAppState() == YarnApplicationState.FINISHED
                        || app.getAppState() == YarnApplicationState.FAILED
                        || app.getAppState() == YarnApplicationState.KILLED ? "History" : "ApplicationMaster";
        appsTableData.append(trackingURL == null ? "#" : "href='" + trackingURL).append("'>").append(trackingUI)
                .append("</a>\"],\n");

    }
    if (appsTableData.charAt(appsTableData.length() - 2) == ',') {
        appsTableData.delete(appsTableData.length() - 2, appsTableData.length() - 1);
    }
    appsTableData.append("]");
    html.script().$type("text/javascript")._("var appsTableData=" + appsTableData)._();

    tbody._()._();
}

From source file:com.funambol.foundation.items.dao.PIMNoteDAO.java

public String updateItem(NoteWrapper nw) throws DAOException {

    Connection con = null;// ww  w  .ja va2 s .c  o m
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {

        //
        // Note fields
        //
        Note note = nw.getNote();

        StringBuilder updateQuery = new StringBuilder();

        updateQuery.append(SQL_UPDATE_FNBL_PIM_NOTE_BEGIN);

        updateQuery.append(SQL_FIELD_LAST_UPDATE + SQL_EQUALS_QUESTIONMARK_COMMA);
        updateQuery.append(SQL_FIELD_STATUS + SQL_EQUALS_QUESTIONMARK_COMMA);

        String subject = note.getSubject().getPropertyValueAsString();
        if (subject != null) {
            updateQuery.append(SQL_FIELD_SUBJECT + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String textDescription = note.getTextDescription().getPropertyValueAsString();
        if (textDescription != null) {
            updateQuery.append(SQL_FIELD_TEXTDESCRIPTION + SQL_EQUALS_QUESTIONMARK_COMMA);

            updateQuery.append(SQL_FIELD_CRC + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String categories = note.getCategories().getPropertyValueAsString();
        if (categories != null) {
            updateQuery.append(SQL_FIELD_CATEGORIES + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String folder = note.getFolder().getPropertyValueAsString();
        if (folder != null) {
            updateQuery.append(SQL_FIELD_FOLDER + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        String color = note.getColor().getPropertyValueAsString();
        if (color != null) {
            updateQuery.append(SQL_FIELD_COLOR + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String height = note.getHeight().getPropertyValueAsString();
        if (height != null) {
            updateQuery.append(SQL_FIELD_HEIGHT + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String width = note.getWidth().getPropertyValueAsString();
        if (width != null) {
            updateQuery.append(SQL_FIELD_WIDTH + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String top = note.getTop().getPropertyValueAsString();
        if (top != null) {
            updateQuery.append(SQL_FIELD_TOP + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        String left = note.getLeft().getPropertyValueAsString();
        if (left != null) {
            updateQuery.append(SQL_FIELD_LEFT_MARGIN + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        if (updateQuery.charAt(updateQuery.length() - 2) == ',') {
            updateQuery.deleteCharAt(updateQuery.length() - 2);
        }

        updateQuery.append(SQL_UPDATE_FNBL_PIM_NOTE_END);

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        ps = con.prepareStatement(updateQuery.toString());

        int k = 1;

        //
        // last update
        //
        Timestamp lastUpdate = (nw.getLastUpdate() == null) ? new Timestamp(System.currentTimeMillis())
                : nw.getLastUpdate();
        ps.setLong(k++, lastUpdate.getTime());

        //
        // status
        //
        ps.setString(k++, String.valueOf(Def.PIM_STATE_UPDATED));

        //
        // subject
        //
        if (subject != null) {
            ps.setString(k++, StringUtils.left(subject, SQL_SUBJECT_DIM));
        }

        //
        // textDescription
        //
        if (textDescription != null) {
            textDescription = textDescription.replace('\0', ' ');
            String truncatedTextDescription = StringUtils.left(textDescription, SQL_TEXTDESCRIPTION_DIM);

            ps.setString(k++, truncatedTextDescription);
            ps.setLong(k++, calculateCrc(truncatedTextDescription));
        }

        //
        // categories
        //
        if (categories != null) {
            ps.setString(k++, truncateCategoriesField(categories, SQL_CATEGORIES_DIM));
        }

        //
        // folder
        //
        if (folder != null) {
            ps.setString(k++, truncateFolderField(folder, SQL_FOLDER_DIM));
        }

        //
        // color
        //
        if (color != null) {
            if (color.length() == 0) {
                ps.setNull(k++, Types.INTEGER);
            } else {
                ps.setInt(k++, Integer.parseInt(color));
            }
        }

        //
        // height
        //
        if (height != null) {
            if (height.length() == 0) {
                ps.setNull(k++, Types.INTEGER);
            } else {
                ps.setInt(k++, Integer.parseInt(height));
            }
        }

        //
        // width
        //
        if (width != null) {
            if (width.length() == 0) {
                ps.setNull(k++, Types.INTEGER);
            } else {
                ps.setInt(k++, Integer.parseInt(width));
            }
        }

        //
        // top
        //
        if (top != null) {
            if (top.length() == 0) {
                ps.setNull(k++, Types.INTEGER);
            } else {
                ps.setInt(k++, Integer.parseInt(top));
            }
        }

        //
        // left
        //
        if (left != null) {
            if (left.length() == 0) {
                ps.setNull(k++, Types.INTEGER);
            } else {
                ps.setInt(k++, Integer.parseInt(left));
            }
        }

        //
        // id
        //
        ps.setLong(k++, Long.parseLong(nw.getId()));
        //
        // userId
        //
        ps.setString(k++, userId);

        ps.executeUpdate();

        DBTools.close(null, ps, null);
    } catch (Exception e) {
        throw new DAOException("Error updating note.", e);
    } finally {
        DBTools.close(con, ps, rs);
    }

    return nw.getId();
}

From source file:org.apache.hadoop.yarn.server.webapp.AppBlock.java

protected void generateApplicationTable(Block html, UserGroupInformation callerUGI,
        Collection<ApplicationAttemptReport> attempts) {
    // Application Attempt Table
    TBODY<TABLE<Hamlet>> tbody = html.table("#attempts").thead().tr().th(".id", "Attempt ID")
            .th(".started", "Started").th(".node", "Node").th(".logs", "Logs")._()._().tbody();

    StringBuilder attemptsTableData = new StringBuilder("[\n");
    for (final ApplicationAttemptReport appAttemptReport : attempts) {
        AppAttemptInfo appAttempt = new AppAttemptInfo(appAttemptReport);
        ContainerReport containerReport;
        try {// w  w w.  j a v  a2s. c  om
            final GetContainerReportRequest request = GetContainerReportRequest
                    .newInstance(appAttemptReport.getAMContainerId());
            if (callerUGI == null) {
                containerReport = appBaseProt.getContainerReport(request).getContainerReport();
            } else {
                containerReport = callerUGI.doAs(new PrivilegedExceptionAction<ContainerReport>() {
                    @Override
                    public ContainerReport run() throws Exception {
                        ContainerReport report = null;
                        if (request.getContainerId() != null) {
                            try {
                                report = appBaseProt.getContainerReport(request).getContainerReport();
                            } catch (ContainerNotFoundException ex) {
                                LOG.warn(ex.getMessage());
                            }
                        }
                        return report;
                    }
                });
            }
        } catch (Exception e) {
            String message = "Failed to read the AM container of the application attempt "
                    + appAttemptReport.getApplicationAttemptId() + ".";
            LOG.error(message, e);
            html.p()._(message)._();
            return;
        }
        long startTime = 0L;
        String logsLink = null;
        String nodeLink = null;
        if (containerReport != null) {
            ContainerInfo container = new ContainerInfo(containerReport);
            startTime = container.getStartedTime();
            logsLink = containerReport.getLogUrl();
            nodeLink = containerReport.getNodeHttpAddress();
        }
        attemptsTableData.append("[\"<a href='").append(url("appattempt", appAttempt.getAppAttemptId()))
                .append("'>").append(appAttempt.getAppAttemptId()).append("</a>\",\"").append(startTime)
                .append("\",\"<a ").append(nodeLink == null ? "#" : "href='" + nodeLink).append("'>")
                .append(nodeLink == null ? "N/A"
                        : StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(nodeLink)))
                .append("</a>\",\"<a ").append(logsLink == null ? "#" : "href='" + logsLink).append("'>")
                .append(logsLink == null ? "N/A" : "Logs").append("</a>\"],\n");
    }
    if (attemptsTableData.charAt(attemptsTableData.length() - 2) == ',') {
        attemptsTableData.delete(attemptsTableData.length() - 2, attemptsTableData.length() - 1);
    }
    attemptsTableData.append("]");
    html.script().$type("text/javascript")._("var attemptsTableData=" + attemptsTableData)._();

    tbody._()._();
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.FairSchedulerAppsBlock.java

@Override
public void render(Block html) {
    TBODY<TABLE<Hamlet>> tbody = html.table("#apps").thead().tr().th(".id", "ID").th(".user", "User")
            .th(".name", "Name").th(".type", "Application Type").th(".queue", "Queue")
            .th(".fairshare", "Fair Share").th(".starttime", "StartTime").th(".finishtime", "FinishTime")
            .th(".state", "State").th(".finalstatus", "FinalStatus")
            .th(".runningcontainer", "Running Containers").th(".allocatedCpu", "Allocated CPU VCores")
            .th(".allocatedMemory", "Allocated Memory MB").th(".progress", "Progress").th(".ui", "Tracking UI")
            ._()._().tbody();/*from   w  w w  .j  a  v a  2s .com*/
    Collection<YarnApplicationState> reqAppStates = null;
    String reqStateString = $(APP_STATE);
    if (reqStateString != null && !reqStateString.isEmpty()) {
        String[] appStateStrings = reqStateString.split(",");
        reqAppStates = new HashSet<YarnApplicationState>(appStateStrings.length);
        for (String stateString : appStateStrings) {
            reqAppStates.add(YarnApplicationState.valueOf(stateString));
        }
    }
    StringBuilder appsTableData = new StringBuilder("[\n");
    for (RMApp app : apps.values()) {
        if (reqAppStates != null && !reqAppStates.contains(app.createApplicationState())) {
            continue;
        }
        AppInfo appInfo = new AppInfo(rm, app, true, WebAppUtils.getHttpSchemePrefix(conf));
        String percent = StringUtils.format("%.1f", appInfo.getProgress());
        ApplicationAttemptId attemptId = app.getCurrentAppAttempt().getAppAttemptId();
        long fairShare = fsinfo.getAppFairShare(attemptId);
        if (fairShare == FairSchedulerInfo.INVALID_FAIR_SHARE) {
            // FairScheduler#applications don't have the entry. Skip it.
            continue;
        }
        appsTableData.append("[\"<a href='").append(url("app", appInfo.getAppId())).append("'>")
                .append(appInfo.getAppId()).append("</a>\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(appInfo.getUser())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(appInfo.getName())))
                .append("\",\"")
                .append(StringEscapeUtils
                        .escapeJavaScript(StringEscapeUtils.escapeHtml(appInfo.getApplicationType())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(appInfo.getQueue())))
                .append("\",\"").append(fairShare).append("\",\"").append(appInfo.getStartTime())
                .append("\",\"").append(appInfo.getFinishTime()).append("\",\"").append(appInfo.getState())
                .append("\",\"").append(appInfo.getFinalStatus()).append("\",\"")
                .append(appInfo.getRunningContainers() == -1 ? "N/A"
                        : String.valueOf(appInfo.getRunningContainers()))
                .append("\",\"")
                .append(appInfo.getAllocatedVCores() == -1 ? "N/A"
                        : String.valueOf(appInfo.getAllocatedVCores()))
                .append("\",\"")
                .append(appInfo.getAllocatedMB() == -1 ? "N/A" : String.valueOf(appInfo.getAllocatedMB()))
                .append("\",\"")
                // Progress bar
                .append("<br title='").append(percent).append("'> <div class='").append(C_PROGRESSBAR)
                .append("' title='").append(join(percent, '%')).append("'> ").append("<div class='")
                .append(C_PROGRESSBAR_VALUE).append("' style='").append(join("width:", percent, '%'))
                .append("'> </div> </div>").append("\",\"<a href='");

        String trackingURL = !appInfo.isTrackingUrlReady() ? "#" : appInfo.getTrackingUrlPretty();

        appsTableData.append(trackingURL).append("'>").append(appInfo.getTrackingUI()).append("</a>\"],\n");

    }
    if (appsTableData.charAt(appsTableData.length() - 2) == ',') {
        appsTableData.delete(appsTableData.length() - 2, appsTableData.length() - 1);
    }
    appsTableData.append("]");
    html.script().$type("text/javascript")._("var appsTableData=" + appsTableData)._();

    tbody._()._();
}