List of usage examples for java.lang StringBuilder charAt
char charAt(int index);
From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java
public void htmlUnescapeInto(StringBuilder source, StringBuilder dest) { boolean inEntity = false; StringBuilder entity = new StringBuilder(10); int sourceLength = source.length(); for (int i = 0; i < sourceLength; ++i) { char c = source.charAt(i); if (inEntity) { if (c == ';') { // first see if this is a special sequence SpecialEntity special = org.htmlcleaner.SpecialEntity.getEntity(entity.toString()); if (special != null) { dest.append(special.getCharacter()); }/* ww w .ja va2s . co m*/ // next try hex starting with #x else if (entity.length() > 1 && entity.charAt(0) == '#' && entity.charAt(1) == 'x') { int value = 0; for (int j = 2; j < entity.length(); ++j) { value *= 16; char e = entity.charAt(j); if (e >= '0' && e <= '9') { value += (int) (e - '0'); } else if (e >= 'a' && e <= 'f') { value += 10 + (int) (e - 'a'); } else if (e >= 'A' && e <= 'F') { value += 10 + (int) (e - 'A'); } else { value = 0; break; } } if (value != 0) { dest.append((char) value); } } // next try decimal starting with # else if (entity.length() > 0 && entity.charAt(0) == '#') { int value = 0; for (int j = 1; j < entity.length(); ++j) { value *= 10; char e = entity.charAt(j); if (e >= '0' && e <= '9') { value += (int) (e - '0'); } else { value = 0; break; } } if (value != 0) { dest.append((char) value); } } inEntity = false; entity.setLength(0); } else { entity.append(c); } } else { if (c == '&') { inEntity = true; } else { dest.append(c); } } } }
From source file:com.gargoylesoftware.htmlunit.CodeStyleTest.java
/** * Converts the given alerts definition to an array of expressions. *//*from w ww. j a v a 2s. c om*/ private static List<String> alertsToList(final String string) { final List<String> list = new ArrayList<>(); if ("\"\"".equals(string)) { list.add(string); } else { final StringBuilder currentToken = new StringBuilder(); boolean insideString = true; boolean startsWithBraces = false; for (final String token : string.split("(?<!\\\\)\"")) { insideString = !insideString; if (currentToken.length() != 0) { currentToken.append('"'); } else { startsWithBraces = token.toString().contains("{"); } if (!insideString && token.startsWith(",") && !startsWithBraces) { list.add(currentToken.toString()); currentToken.setLength(0); startsWithBraces = token.toString().contains("{"); } if (!insideString && token.contains("}")) { final int curlyIndex = token.indexOf('}') + 1; currentToken.append(token.substring(0, curlyIndex)); list.add(currentToken.toString()); currentToken.setLength(0); currentToken.append(token.substring(curlyIndex)); } else { if (!insideString && token.contains(",") && !startsWithBraces) { final String[] expressions = token.split(","); currentToken.append(expressions[0]); if (currentToken.length() != 0) { list.add(currentToken.toString()); } for (int i = 1; i < expressions.length - 1; i++) { list.add(',' + expressions[i]); } currentToken.setLength(0); currentToken.append(',' + expressions[expressions.length - 1]); } else { currentToken.append(token); } } } if (currentToken.length() != 0) { if (!currentToken.toString().contains("\"")) { currentToken.insert(0, '"'); } int totalQuotes = 0; for (int i = 0; i < currentToken.length(); i++) { if (currentToken.charAt(i) == '"' && (i == 0 || currentToken.charAt(i - 1) != '\\')) { totalQuotes++; } } if (totalQuotes % 2 != 0) { currentToken.append('"'); } list.add(currentToken.toString()); } } return list; }
From source file:au.org.ala.delta.editor.slotfile.directive.DirOutDefault.java
private void writeIntItemCharSetArgs(int argType, DirectiveArguments directiveArgs, StringBuilder textBuffer) { if (directiveArgs.size() > 0) { State curState = State.IN_MODIFIERS; List<Integer> dataList = new ArrayList<Integer>(); for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) { BigDecimal curVal = vectIter.getValue(); if (curState == State.IN_MODIFIERS && !BigDecimal.ZERO.equals(curVal)) { if (curVal.compareTo(BigDecimal.ZERO) > 0) break; // No taxa present, so nothing else matters curState = State.IN_TAXA; dataList.clear();/* w w w . jav a 2 s . c o m*/ textBuffer.append(" ("); } if (curState == State.IN_TAXA && curVal.compareTo(BigDecimal.ZERO) > 0) { if (vectIter.getData().size() >= 0) appendRange(dataList, ' ', true, textBuffer); textBuffer.append(')'); curState = State.IN_CHARS; dataList.clear(); } if (curState == State.IN_CHARS && curVal.compareTo(BigDecimal.ZERO) >= 0) break; // Should never happen, unless arguments were somehow reordered if ((Integer) vectIter.getId() > 0) dataList.add((Integer) vectIter.getId()); else appendKeyword(textBuffer, vectIter.getText(), false, !(curState == State.IN_TAXA && textBuffer.charAt(textBuffer.length() - 1) == '(')); } if (dataList.size() > 0) { textBuffer.append(' '); appendRange(dataList, ' ', true, textBuffer); } } }
From source file:org.apache.hadoop.mapreduce.v2.app.webapp.TasksBlock.java
@Override protected void render(Block html) { if (app.getJob() == null) { html.h2($(TITLE));/*from w w w . ja v a 2s.co m*/ return; } TaskType type = null; String symbol = $(TASK_TYPE); if (!symbol.isEmpty()) { type = MRApps.taskType(symbol); } TBODY<TABLE<Hamlet>> tbody = html.table("#tasks").thead().tr().th("Task").th("Progress").th("Status") .th("State").th("Start Time").th("Finish Time").th("Elapsed Time")._()._().tbody(); StringBuilder tasksTableData = new StringBuilder("[\n"); for (Task task : app.getJob().getTasks().values()) { if (type != null && task.getType() != type) { continue; } String taskStateStr = $(TASK_STATE); if (taskStateStr == null || taskStateStr.trim().equals("")) { taskStateStr = "ALL"; } if (!taskStateStr.equalsIgnoreCase("ALL")) { try { // get stateUI enum MRApps.TaskStateUI stateUI = MRApps.taskState(taskStateStr); if (!stateUI.correspondsTo(task.getState())) { continue; } } catch (IllegalArgumentException e) { continue; // not supported state, ignore } } TaskInfo info = new TaskInfo(task); String tid = info.getId(); String pct = StringUtils.format("%.2f", info.getProgress()); tasksTableData.append("[\"<a href='").append(url("task", tid)).append("'>").append(tid) .append("</a>\",\"") //Progress bar .append("<br title='").append(pct).append("'> <div class='").append(C_PROGRESSBAR) .append("' title='").append(join(pct, '%')).append("'> ").append("<div class='") .append(C_PROGRESSBAR_VALUE).append("' style='").append(join("width:", pct, '%')) .append("'> </div> </div>\",\"") .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(info.getStatus()))) .append("\",\"") .append(info.getState()).append("\",\"").append(info.getStartTime()).append("\",\"") .append(info.getFinishTime()).append("\",\"").append(info.getElapsedTime()).append("\"],\n"); } //Remove the last comma and close off the array of arrays if (tasksTableData.charAt(tasksTableData.length() - 2) == ',') { tasksTableData.delete(tasksTableData.length() - 2, tasksTableData.length() - 1); } tasksTableData.append("]"); html.script().$type("text/javascript")._("var tasksTableData=" + tasksTableData)._(); tbody._()._(); }
From source file:org.exoplatform.outlook.OutlookServiceImpl.java
/** * Make JCR compatible item name./* w w w .j a v a2 s . c o m*/ * * @param name {@link String} * @return {@link String} JCR compatible name of local file */ public static String cleanName(String name) { String str = accentsConverter.transliterate(name.trim()); // the character ? seems to not be changed to d by the transliterate function StringBuilder cleanedStr = new StringBuilder(str.trim()); // delete special character if (cleanedStr.length() == 1) { char c = cleanedStr.charAt(0); if (c == '.' || c == '/' || c == ':' || c == '[' || c == ']' || c == '*' || c == '\'' || c == '"' || c == '|') { // any -> _<NEXNUM OF c> cleanedStr.deleteCharAt(0); cleanedStr.append('_'); cleanedStr.append(Integer.toHexString(c).toUpperCase()); } } else { for (int i = 0; i < cleanedStr.length(); i++) { char c = cleanedStr.charAt(i); if (c == '/' || c == ':' || c == '[' || c == ']' || c == '*' || c == '\'' || c == '"' || c == '|') { cleanedStr.deleteCharAt(i); cleanedStr.insert(i, '_'); } else if (!(Character.isLetterOrDigit(c) || Character.isWhitespace(c) || c == '.' || c == '-' || c == '_')) { cleanedStr.deleteCharAt(i--); } } // XXX finally ensure the name doesn't hava a dot at the end // https://github.com/exo-addons/outlook/issues/5 // https://jira.exoplatform.org/browse/COMMONS-510 int lastCharIndex = cleanedStr.length() - 1; char c = cleanedStr.charAt(lastCharIndex); if (c == '.') { cleanedStr.deleteCharAt(lastCharIndex); } } return cleanedStr.toString().trim(); // finally trim also }
From source file:org.operamasks.faces.render.graph.ChartRenderer.java
private void encodeItemTips(FacesContext context, UIChart comp, ChartRenderingInfo info) throws IOException { StringBuilder buf = new StringBuilder(); buf.append("Ext.om.AreaTips.init();\n"); buf.append("Ext.om.AreaTips.register({"); buf.append("target:'").append(comp.getClientId(context)).append("'"); buf.append(",trackMouse:true"); buf.append(",areas:["); EntityCollection entities = info.getEntityCollection(); Iterator it = entities.iterator(); while (it.hasNext()) { ChartEntity entity = (ChartEntity) it.next(); String tooltip = entity.getToolTipText(); if (tooltip != null) { buf.append("{"); buf.append("shape:'").append(entity.getShapeType()).append("'"); buf.append(",coords:[").append(entity.getShapeCoords()).append("]"); buf.append(",text:").append(HtmlEncoder.enquote(tooltip)); buf.append("},"); }//from w w w . ja va2 s .co m } if (buf.charAt(buf.length() - 1) == ',') { buf.setLength(buf.length() - 1); } buf.append("]});\n"); ResourceManager rm = ResourceManager.getInstance(context); if (isAjaxResponse(context)) { AjaxResponseWriter out = (AjaxResponseWriter) context.getResponseWriter(); out.writeScript("OM.ajax.loadScript('" + rm.getResourceURL("/ext/om/AreaTips.js") + "');\n"); out.writeScript(buf.toString()); } else { YuiExtResource resource = YuiExtResource.register(rm, "Ext.om.AreaTips"); resource.addInitScript(buf.toString()); } }
From source file:org.ngrinder.perftest.service.PerfTestService.java
/** * Get the test report data as a json string. * * @param targetFile target file//from w w w . j a va2 s .co m * @param interval interval to collect data * @return json string */ private String getFileDataAsJson(File targetFile, int interval) { if (!targetFile.exists()) { return "[]"; } StringBuilder reportData = new StringBuilder("["); FileReader reader = null; BufferedReader br = null; try { reader = new FileReader(targetFile); br = new BufferedReader(reader); String data = br.readLine(); int current = 0; while (StringUtils.isNotBlank(data)) { if (0 == current) { reportData.append(data); reportData.append(","); } if (++current >= interval) { current = 0; } data = br.readLine(); } if (reportData.charAt(reportData.length() - 1) == ',') { reportData.deleteCharAt(reportData.length() - 1); } } catch (IOException e) { LOGGER.error("Report data retrieval is failed: {}", e.getMessage()); LOGGER.debug("Trace is : ", e); } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(br); } return reportData.append("]").toString(); }
From source file:com.taobao.tddl.interact.rule.VirtualTable.java
private void showTopology(boolean showMap) { int crossIndex, endIndex, maxcolsPerRow = showColsPerRow, maxtbnlen = 1, maxdbnlen = 1; for (Map.Entry<String, Set<String>> e : this.actualTopology.entrySet()) { int colsPerRow = colsPerRow(e.getValue(), showColsPerRow); if (colsPerRow > maxcolsPerRow) { maxcolsPerRow = colsPerRow;//from w w w .j a v a 2 s. c o m } if (e.getKey().length() > maxdbnlen) { maxdbnlen = e.getKey().length(); //dbIndex } for (String tbn : e.getValue()) { if (tbn.length() > maxtbnlen) { maxtbnlen = tbn.length(); //tableName } } } crossIndex = maxdbnlen + 1; endIndex = crossIndex + (maxtbnlen + 1) * maxcolsPerRow + 1; StringBuilder sb = new StringBuilder("The topology of the virtual table " + this.virtualTbName); addLine(sb, crossIndex, endIndex); for (Map.Entry<String/**/, Set<String/**/>> e : this.actualTopology.entrySet()) { sb.append("\n|"); sb.append(fillAfter(e.getKey(), maxdbnlen)).append("|"); int i = 0, n = e.getValue().size(); for (String tb : e.getValue()) { sb.append(fillAfter(tb, maxtbnlen)).append(","); i++; if (i % maxcolsPerRow == 0 && i < n) { sb.append("|\n|").append(fillAfter(" ", maxdbnlen)).append("|");// } } if (i % maxcolsPerRow != 0) { int taillen = (maxcolsPerRow - (i % maxcolsPerRow)) * (maxtbnlen + 1) + 1; sb.append(fillBefore("|", taillen)); } else { sb.append("|"); } addLine(sb, crossIndex, endIndex); } sb.append("\n"); logger.warn(sb); if (!showMap) { return; } sb = new StringBuilder("\nYou could add below segement as the actualTopology property to "); sb.append(this.virtualTbName + "'s TableRule bean in the rule file\n\n"); sb.append(" <property name=\"actualTopology\">\n"); sb.append(" <map>\n"); for (Map.Entry<String/**/, Set<String/**/>> e : this.actualTopology.entrySet()) { sb.append(" <entry key=\"").append(e.getKey()).append("\" value=\""); for (String table : e.getValue()) { sb.append(table).append(tableNameSepInSpring); } if (sb.charAt(sb.length() - 1) == tableNameSepInSpring.charAt(0)) { sb.deleteCharAt(sb.length() - 1); } sb.append("\" />\n"); } sb.append(" </map>\n"); sb.append(" </property>\n"); logger.warn(sb); }
From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMAppBlock.java
@Override protected void generateApplicationTable(Block html, UserGroupInformation callerUGI, Collection<ApplicationAttemptReport> attempts) { // Application Attempt Table Hamlet.TBODY<Hamlet.TABLE<Hamlet>> tbody = html.table("#attempts").thead().tr().th(".id", "Attempt ID") .th(".started", "Started").th(".node", "Node").th(".logs", "Logs") .th(".appBlacklistednodes", "Nodes blacklisted by the application", "Nodes blacklisted by the app") .th(".rmBlacklistednodes", "Nodes blacklisted by the RM for the" + " app", "Nodes blacklisted by the system") ._()._().tbody();// w w w. j a va 2 s.c om RMApp rmApp = this.rm.getRMContext().getRMApps().get(this.appID); if (rmApp == null) { return; } StringBuilder attemptsTableData = new StringBuilder("[\n"); for (final ApplicationAttemptReport appAttemptReport : attempts) { RMAppAttempt rmAppAttempt = rmApp.getRMAppAttempt(appAttemptReport.getApplicationAttemptId()); if (rmAppAttempt == null) { continue; } AppAttemptInfo attemptInfo = new AppAttemptInfo(this.rm, rmAppAttempt, rmApp.getUser(), WebAppUtils.getHttpSchemePrefix(conf)); Set<String> nodes = rmAppAttempt.getBlacklistedNodes(); // nodes which are blacklisted by the application String appBlacklistedNodesCount = String.valueOf(nodes.size()); // nodes which are blacklisted by the RM for AM launches String rmBlacklistedNodesCount = String.valueOf( rmAppAttempt.getAMBlacklistManager().getBlacklistUpdates().getBlacklistAdditions().size()); String nodeLink = attemptInfo.getNodeHttpAddress(); if (nodeLink != null) { nodeLink = WebAppUtils.getHttpSchemePrefix(conf) + nodeLink; } String logsLink = attemptInfo.getLogsLink(); attemptsTableData.append("[\"<a href='") .append(url("appattempt", rmAppAttempt.getAppAttemptId().toString())).append("'>") .append(String.valueOf(rmAppAttempt.getAppAttemptId())).append("</a>\",\"") .append(attemptInfo.getStartTime()).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>\",").append("\"") .append(appBlacklistedNodesCount).append("\",").append("\"").append(rmBlacklistedNodesCount) .append("\"],\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.AppsBlock.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(".starttime", "StartTime").th(".finishtime", "FinishTime").th(".state", "State") .th(".finalstatus", "FinalStatus").th(".progress", "Progress").th(".ui", "Tracking UI")._()._() .tbody();/*from w ww .j a va 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(app, true, WebAppUtils.getHttpSchemePrefix(conf)); String percent = String.format("%.1f", appInfo.getProgress()); //AppID numerical value parsed by parseHadoopID in yarn.dt.plugins.js 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(appInfo.getStartTime()).append("\",\"").append(appInfo.getFinishTime()) .append("\",\"").append(appInfo.getState()).append("\",\"").append(appInfo.getFinalStatus()) .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._()._(); }