List of usage examples for java.lang StringBuilder charAt
char charAt(int index);
From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java
/** * Converts the XPath-Expressions in the list of references into XPath-Stacks. We distinguish between references which are injected as * attributes, and references which are injected as new elements (we keep two separated lists for them, to make things a bit easier * to understand)/*from w w w . j a v a 2 s.co m*/ * @param refs the list of references * @throws IOException * */ private void prepareReferences(List<Reference> refs, NamespaceContext context) throws IOException { elementReferences = new HashMap<Reference, Stack<String>>(); attributeReferences = new HashMap<Reference, Stack<String>>(); for (Reference reference : refs) { LocalElement localElement = (LocalElement) reference.getSource(); StringBuilder path = new StringBuilder(localElement.getElementID().toString()); StringBuilder target = new StringBuilder(reference.getTarget().toString()); LocalNamespaceContext local = new LocalNamespaceContext(); this.processNamespace(target, context, local); this.processNamespace(path, context, local); // we replace the element id (formerly known as XPath) with the processed (with shiny new namespaces) xpath localElement.setElementID(path); // update the reference reference.setTarget(target); reference.setSource(localElement); // we add the namespaces in the reference to the NamespaceContext (otherwise we can't compile the XPath statements) List<QName> ns = extractNamespaces(reference.getTarget().toString()); Stack<String> stack = generator.asXPathStringStack(path.toString(), ns, context); if (target.charAt(0) == '<') { elementReferences.put(reference, stack); } else { attributeReferences.put(reference, stack); } } }
From source file:istata.service.StataService.java
/** * produce a list with possible sidebar suggestions for the current context * // ww w .j av a 2s . c o m * @param filter * @param pos * @param from * @param to * @return */ public List<ContentLine> suggest(String filter, int pos, int from, int to) { LinkedHashSet<ContentLine> res = new LinkedHashSet<ContentLine>(); ArrayList<ContentLine> rescmd = new ArrayList<ContentLine>(); { int i = 0; for (ContentLine cl : cmdRepository.findAll()) { if (cl.getContent().startsWith(filter)) { ContentLine srl = new ContentLine(); Map<String, Object> model = new HashMap<String, Object>(); model.put("cmd", cl); model.put("from", from); model.put("to", to); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "items/cmd.vm", "UTF-8", model); srl.setContent(text); srl.setLine(i++); rescmd.add(srl); } } } Collections.reverse(rescmd); res.addAll(rescmd.subList(0, Math.min(10, rescmd.size()))); List<ContentLine> out = new ArrayList<ContentLine>(); try { IStata stata = stataFactory.getInstance(); /* * get files */ Collection<ContentLine> filesNames = filteredFiles(filter, pos, from, to); res.addAll(filesNames); /* * get VARS, should be a mothod call probably */ // current token StringBuilder token = new StringBuilder(""); StringBuilder rest = new StringBuilder(filter); int p = (pos == -1 || pos > filter.length()) ? filter.length() : pos; char ch = 'x'; while (p > 0 && (CharUtils.isAsciiAlphanumeric(ch = filter.charAt(p - 1)) || ch == '_')) { token.insert(0, ch); rest.deleteCharAt(p - 1); p--; } // remove rest of potential token while (rest.length() > 0 && p > 0 && p < rest.length() && (CharUtils.isAsciiAlphanumeric(rest.charAt(p)) || rest.charAt(p) == '_')) { rest.deleteCharAt(p); } String t = token.toString(); List<StataVar> list = new ArrayList<StataVar>(); List<StataVar> listfull = stata.getVars("", false); if (t.length() > 0) { for (StataVar sv : listfull) { if (sv.getName().startsWith(t)) { list.add(sv); } } } else { list = listfull; } for (int i = 0; i < list.size(); i++) { ContentLine srl = new ContentLine(); srl.setLine(i + 100); String vname = list.get(i).getName(); String cl = new StringBuilder(rest).insert(p, " ").insert(p, vname).toString(); try { String cc = URLEncoder.encode(cl, "UTF-8"); Map<String, Object> model = new HashMap<String, Object>(); model.put("var", vname); model.put("repl", cc); model.put("focuspos", p + 1 + vname.length()); model.put("from", from); model.put("to", to); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "items/var.vm", "UTF-8", model); srl.setContent(text); res.add(srl); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (StataNotRunningException e) { ContentLine srl = new ContentLine(); srl.setLine(1); srl.setContent( "<div class='list-group-item sidebaritem error' >" + "Stata not running, you can try to start " + "an instance by clicking " + "<a target='_blank' href='/start'>here</a>" + "</div>"); out.add(srl); } catch (StataBusyException e1) { ContentLine srl = new ContentLine(); srl.setLine(1); srl.setContent("<div class='list-group-item sidebaritem error' >" + "Stata appears to by busy or not running, you can try to " + "start a new instance by clicking " + "<a target='_blank' href='/start'>here</a> " + "or wait for the current job to complete</div>"); out.add(srl); } out.addAll(res); return out; }
From source file:org.ambraproject.util.TextUtils.java
private static void linkURL(StringBuilder str, String target, int maxDisplayLength) { String urlToDisplay;//w w w. j a va 2s .c om int lastEndIndex = -1; //Stores the index position, within the whole string, of the ending char of the last URL found. String targetString = ((target == null) || (target.trim().length() == 0)) ? "" : (" target=\"" + target.trim() + '\"'); while (true) { int linkStartIndex = getStartUrl(str, lastEndIndex); //if no more links found - then end the loop if (linkStartIndex == -1) { break; } else { //Get the whole URL... //We move forward and add each character to the URL string until we encounter //an invalid URL character (we assume that the URL ends there). int linkEndIndex = linkStartIndex; String urlStr = ""; while (true) { // if char at linkEndIndex is '&' then we look at the next 4 chars // to see if they make up "&" altogether. This is the html coded // '&' and will pretty much stuff up an otherwise valid link becos of the ';'. // We therefore have to remove it before proceeding... if (str.charAt(linkEndIndex) == '&') { if (((linkEndIndex + 6) <= str.length()) && """.equals(str.substring(linkEndIndex, linkEndIndex + 6))) { break; } else if (((linkEndIndex + 5) <= str.length()) && "&".equals(str.substring(linkEndIndex, linkEndIndex + 5))) { str.replace(linkEndIndex, linkEndIndex + 5, "&"); } } if (UrlUtils.isValidURLChar(str.charAt(linkEndIndex))) { urlStr += str.charAt(linkEndIndex); linkEndIndex++; if (linkEndIndex == str.length()) { //Reached end of str... break; } } else { break; } } //if the characters before the linkStart equal 'href="' then don't link the url - CORE-44 if (linkStartIndex >= 6) { //6 = "href\"".length() String prefix = str.substring(linkStartIndex - 6, linkStartIndex); if ("href=\"".equals(prefix)) { lastEndIndex = linkEndIndex; continue; } } //if the characters after the linkEnd are '</a>' then this url is probably already linked - CORE-44 if (str.length() >= (linkEndIndex + 4)) { //4 = "</a>".length() String suffix = str.substring(linkEndIndex, linkEndIndex + 4); if ("</a>".equals(suffix)) { lastEndIndex = linkEndIndex + 4; continue; } } //Decrement linkEndIndex back by 1 to reflect the real ending index position of the URL... linkEndIndex--; // If the last char of urlStr is a '.' we exclude it. It is most likely a full stop and // we don't want that to be part of an url. while (true) { char lastChar = urlStr.charAt(urlStr.length() - 1); if (lastChar == '.') { urlStr = urlStr.substring(0, urlStr.length() - 1); linkEndIndex--; } else { break; } } //if the URL had a '(' before it, and has a ')' at the end, trim the last ')' from the url //ie '(www.opensymphony.com)' => '(<a href="http://www.openymphony.com/">www.opensymphony.com</a>)' char lastChar = urlStr.charAt(urlStr.length() - 1); if (lastChar == ')') { if ((linkStartIndex > 0) && ('(' == (str.charAt(linkStartIndex - 1)))) { urlStr = urlStr.substring(0, urlStr.length() - 1); linkEndIndex--; } } else if (lastChar == '\'') { if ((linkStartIndex > 0) && ('\'' == (str.charAt(linkStartIndex - 1)))) { urlStr = urlStr.substring(0, urlStr.length() - 1); linkEndIndex--; } } //perhaps we ended with '>', '<' or '"' //We need to strip these //ie '"www.opensymphony.com"' => '"<a href="http://www.openymphony.com/">www.opensymphony.com</a>"' //ie '<www.opensymphony.com>' => '<<a href="http://www.openymphony.com/">www.opensymphony.com</a>>' else if (lastChar == ';') { // 6 = """.length() if ((urlStr.length() > 6) && """.equalsIgnoreCase(urlStr.substring(urlStr.length() - 6))) { urlStr = urlStr.substring(0, urlStr.length() - 6); linkEndIndex -= 6; } // 4 = "<".length() || ">".length() else if (urlStr.length() > 4) { final String endingStr = urlStr.substring(urlStr.length() - 4); if ("<".equalsIgnoreCase(endingStr) || ">".equalsIgnoreCase(endingStr)) { urlStr = urlStr.substring(0, urlStr.length() - 4); linkEndIndex -= 4; } } } // we got the URL string, now we validate it and convert it into a hyperlink... if (maxDisplayLength > 0 && urlStr.length() > maxDisplayLength) { urlToDisplay = htmlEncode(urlStr.substring(0, maxDisplayLength), true) + "..."; } else { urlToDisplay = htmlEncode(urlStr, true); } if (urlStr.toLowerCase().startsWith("www.")) { urlStr = "http://" + urlStr; } if (UrlUtils.verifyHierachicalURI(urlStr)) { //Construct the hyperlink for the url... String urlLink; if (maxDisplayLength > 0 && urlStr.length() > maxDisplayLength) { //urlLink = "<a href=\"" + urlStr + "\"" + targetString + ">" + urlToDisplay + "</a>"; urlLink = "<a href=\"" + urlStr + "\"" + targetString + " title=\"" + htmlEncode(urlStr, true) + "\">" + urlToDisplay + "</a>"; } else { urlLink = "<a href=\"" + urlStr + "\"" + targetString + ">" + urlToDisplay + "</a>"; } //urlLink = "<a href=\"" + urlStr + '\"' + targetString + '>' + urlToDisplay + "</a>"; //Remove the original urlStr from str and put urlLink there instead... str.replace(linkStartIndex, linkEndIndex + 1, urlLink); //Set lastEndIndex to reflect the position of the end of urlLink //within the whole string... lastEndIndex = (linkStartIndex - 1) + urlLink.length(); } else { //lastEndIndex is different from the one above cos' there's no //<a href...> tags added... lastEndIndex = (linkStartIndex - 1) + urlStr.length(); } } } }
From source file:org.getobjects.appserver.core.WOContext.java
/** * Composes a URL suitable for use with the given request handler. * <p>//from w ww .j a v a 2 s . com * Important: this does <u>not</u> add any query parameters (like wosid). * * @param _requestHandlerKey - key of the given request handler, eg 'wa' * @param _requestHandlerPath - path to be handled by the request handler * @param _queryString - properly encoded query string * @return a URL */ public String urlWithRequestHandlerKey(String _requestHandlerKey, String _requestHandlerPath, String _queryString) { // TODO: complete me StringBuilder sb = new StringBuilder(256); if (this.request != null) { String an; if ((an = this.request.adaptorPrefix()) != null) sb.append(an); if ((an = this.request.applicationName()) != null) { int len = sb.length(); if (len == 0 || sb.charAt(len - 1) != '/') sb.append("/"); sb.append(an); } } if (_requestHandlerKey != null) { sb.append("/"); sb.append(_requestHandlerKey); } if (_requestHandlerPath != null) { if (!_requestHandlerPath.startsWith("/")) sb.append("/"); sb.append(_requestHandlerPath); } if (_queryString != null && _queryString.length() > 0) { sb.append("?"); sb.append(_queryString); } return sb.toString(); }
From source file:fr.ribesg.bukkit.api.chat.Chat.java
private static void appendItemTag(final StringBuilder builder, final ItemStack is) { boolean hasTag = false; final StringBuilder tagBuilder = new StringBuilder(); // Enchantments final Map<Enchantment, Integer> enchantments = is.getEnchantments(); if (enchantments != null && !enchantments.isEmpty()) { tagBuilder.append("ench:["); final Iterator<Entry<Enchantment, Integer>> it = enchantments.entrySet().iterator(); while (it.hasNext()) { final Entry<Enchantment, Integer> entry = it.next(); tagBuilder.append("{id:").append(entry.getKey().getId()).append(",lvl:").append(entry.getValue()); if (it.hasNext()) { tagBuilder.append(','); }/*from w w w. j a va 2 s .c o m*/ } tagBuilder.append("],"); hasTag = true; } // Meta if (is.hasItemMeta()) { final ItemMeta meta = is.getItemMeta(); if (meta.hasDisplayName() || meta.hasLore() || Chat.isLeatherArmor(is)) { Chat.appendItemDisplay(tagBuilder, meta); } if (is.getType() == Material.POTION) { Chat.appendItemPotion(tagBuilder, (PotionMeta) meta); } if (is.getType() == Material.WRITTEN_BOOK) { Chat.appendItemBook(tagBuilder, (BookMeta) meta); } if (is.getType() == Material.SKULL_ITEM) { Chat.appendItemSkull(tagBuilder, (SkullMeta) meta); } if (is.getType() == Material.FIREWORK) { // Firework Rocket Chat.appendItemFirework(tagBuilder, (FireworkMeta) meta); } if (is.getType() == Material.FIREWORK_CHARGE) { // Firework Star Chat.appendItemFireworkEffect(tagBuilder, (FireworkEffectMeta) meta); } } if (hasTag && tagBuilder.charAt(builder.length() - 1) == ',') { tagBuilder.deleteCharAt(builder.length() - 1); } // Append to main builder if (hasTag) { builder.append(',').append("tag:{").append(tagBuilder).append('}'); } }
From source file:tr.edu.gsu.nerwip.retrieval.reader.wikipedia.WikipediaReader.java
/** * Retrieve the text located in //w w w . j av a 2s .c o m * a paragraph (P) HTML element. * * @param element * Element to be processed. * @param rawStr * Current raw text string. * @param linkedStr * Current text with hyperlinks. */ private void processParagraphElement(Element element, StringBuilder rawStr, StringBuilder linkedStr) { // possibly add a new line character first if (rawStr.length() > 0 && rawStr.charAt(rawStr.length() - 1) != '\n') { rawStr.append("\n"); linkedStr.append("\n"); } // recursive processing processTextElement(element, rawStr, linkedStr); // possibly add a new line character if (rawStr.charAt(rawStr.length() - 1) != '\n') { rawStr.append("\n"); linkedStr.append("\n"); } }
From source file:com.zulip.android.util.CustomHtmlToSpannedConverter.java
public void characters(char ch[], int start, int length) throws SAXException { StringBuilder sb = new StringBuilder(); /*// w w w. java2 s . co m * Ignore whitespace that immediately follows other whitespace; newlines * count as spaces. */ for (int i = 0; i < length; i++) { char c = ch[i + start]; if (c == ' ' || c == '\n') { char pred; int len = sb.length(); if (len == 0) { len = mSpannableStringBuilder.length(); if (len == 0) { pred = '\n'; } else { pred = mSpannableStringBuilder.charAt(len - 1); } } else { pred = sb.charAt(len - 1); } if (pred != ' ' && pred != '\n') { sb.append(' '); } } else { sb.append(c); } } mSpannableStringBuilder.append(sb); }
From source file:org.apache.hadoop.yarn.server.webapp.AppAttemptBlock.java
@Override protected void render(Block html) { String attemptid = $(APPLICATION_ATTEMPT_ID); if (attemptid.isEmpty()) { puts("Bad request: requires application attempt ID"); return;//w w w . jav a 2s . c o m } try { appAttemptId = ApplicationAttemptId.fromString(attemptid); } catch (IllegalArgumentException e) { puts("Invalid application attempt ID: " + attemptid); return; } UserGroupInformation callerUGI = getCallerUGI(); ApplicationAttemptReport appAttemptReport; try { final GetApplicationAttemptReportRequest request = GetApplicationAttemptReportRequest .newInstance(appAttemptId); if (callerUGI == null) { appAttemptReport = appBaseProt.getApplicationAttemptReport(request).getApplicationAttemptReport(); } else { appAttemptReport = callerUGI.doAs(new PrivilegedExceptionAction<ApplicationAttemptReport>() { @Override public ApplicationAttemptReport run() throws Exception { return appBaseProt.getApplicationAttemptReport(request).getApplicationAttemptReport(); } }); } } catch (Exception e) { String message = "Failed to read the application attempt " + appAttemptId + "."; LOG.error(message, e); html.p()._(message)._(); return; } if (appAttemptReport == null) { puts("Application Attempt not found: " + attemptid); return; } boolean exceptionWhenGetContainerReports = false; Collection<ContainerReport> containers = null; try { final GetContainersRequest request = GetContainersRequest.newInstance(appAttemptId); if (callerUGI == null) { containers = appBaseProt.getContainers(request).getContainerList(); } else { containers = callerUGI.doAs(new PrivilegedExceptionAction<Collection<ContainerReport>>() { @Override public Collection<ContainerReport> run() throws Exception { return appBaseProt.getContainers(request).getContainerList(); } }); } } catch (RuntimeException e) { // have this block to suppress the findbugs warning exceptionWhenGetContainerReports = true; } catch (Exception e) { exceptionWhenGetContainerReports = true; } AppAttemptInfo appAttempt = new AppAttemptInfo(appAttemptReport); setTitle(join("Application Attempt ", attemptid)); String node = "N/A"; if (appAttempt.getHost() != null && appAttempt.getRpcPort() >= 0 && appAttempt.getRpcPort() < 65536) { node = appAttempt.getHost() + ":" + appAttempt.getRpcPort(); } generateOverview(appAttemptReport, containers, appAttempt, node); if (exceptionWhenGetContainerReports) { html.p()._("Sorry, Failed to get containers for application attempt" + attemptid + ".")._(); return; } createAttemptHeadRoomTable(html); html._(InfoBlock.class); createTablesForAttemptMetrics(html); // Container Table TBODY<TABLE<Hamlet>> tbody = html.table("#containers").thead().tr().th(".id", "Container ID") .th(".node", "Node").th(".exitstatus", "Container Exit Status").th(".logs", "Logs")._()._().tbody(); StringBuilder containersTableData = new StringBuilder("[\n"); for (ContainerReport containerReport : containers) { ContainerInfo container = new ContainerInfo(containerReport); containersTableData.append("[\"<a href='").append(url("container", container.getContainerId())) .append("'>").append(container.getContainerId()).append("</a>\",\"<a ") .append(container.getNodeHttpAddress() == null ? "#" : "href='" + container.getNodeHttpAddress()) .append("'>") .append(container.getNodeHttpAddress() == null ? "N/A" : StringEscapeUtils .escapeJavaScript(StringEscapeUtils.escapeHtml(container.getNodeHttpAddress()))) .append("</a>\",\"").append(container.getContainerExitStatus()).append("\",\"<a href='") .append(container.getLogUrl() == null ? "#" : container.getLogUrl()).append("'>") .append(container.getLogUrl() == null ? "N/A" : "Logs").append("</a>\"],\n"); } if (containersTableData.charAt(containersTableData.length() - 2) == ',') { containersTableData.delete(containersTableData.length() - 2, containersTableData.length() - 1); } containersTableData.append("]"); html.script().$type("text/javascript")._("var containersTableData=" + containersTableData)._(); tbody._()._(); }
From source file:byps.BBufferJson.java
public double getDouble() { StringBuilder sbuf = new StringBuilder(30); for (;;) {//from w w w .ja v a2 s .co m char c = nextJsonChar(true); if ((c >= '0' && c <= '9') || (c == '.') || (c == 'e') || (c == 'E') || (c == '-') || (c == '+')) { sbuf.append(c); } else if (c == 'N') { internalSkip(2); nextJsonChar(false); // update this.lastChar return Double.NaN; } else if (c == 'I') { boolean neg = sbuf.length() != 0 && sbuf.charAt(0) == '-'; internalSkip(7); nextJsonChar(false); // update this.lastChar return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } else { oneCharBack(); break; } } return Double.parseDouble(sbuf.toString()); }
From source file:tr.edu.gsu.nerwip.retrieval.reader.wikipedia.WikipediaReader.java
/** * Retrieve the text located in //from ww w .ja v a2 s .c o m * a quote (BLOCKQUOTE) HTML element. * * @param element * Element to be processed. * @param rawStr * Current raw text string. * @param linkedStr * Current text with hyperlinks. * @return * {@code true} iff the element was processed. */ private boolean processQuoteElement(Element element, StringBuilder rawStr, StringBuilder linkedStr) { boolean result = true; // possibly modify the previous characters if (rawStr.length() > 0 && rawStr.charAt(rawStr.length() - 1) == '\n') { rawStr.deleteCharAt(rawStr.length() - 1); linkedStr.deleteCharAt(linkedStr.length() - 1); } // insert quotes rawStr.append(" \""); linkedStr.append(" \""); // recursive processing int rawIdx = rawStr.length(); int linkedIdx = linkedStr.length(); processTextElement(element, rawStr, linkedStr); // possibly remove characters added after quote marks while (rawStr.length() > rawIdx && (rawStr.charAt(rawIdx) == '\n' || rawStr.charAt(rawIdx) == ' ')) { rawStr.deleteCharAt(rawIdx); linkedStr.deleteCharAt(linkedIdx); } // possibly modify the ending characters if (rawStr.length() > 0 && rawStr.charAt(rawStr.length() - 1) == '\n') { rawStr.deleteCharAt(rawStr.length() - 1); linkedStr.deleteCharAt(linkedStr.length() - 1); } // insert quotes rawStr.append("\""); linkedStr.append("\""); return result; }