List of usage examples for java.lang StringBuilder replace
@Override public StringBuilder replace(int start, int end, String str)
From source file:org.sakaiproject.portlets.PortletIFrame.java
/** * Expand one macro reference//from ww w .ja v a 2 s . com * @param text Expand macros found in this text * @param macroName Macro name */ private void expand(StringBuilder sb, String macroName) { int index; /* * Replace every occurance of the macro in the parameter list */ index = sb.indexOf(macroName); while (index != -1) { String macroValue = URLEncoder.encode(getMacroValue(macroName)); sb.replace(index, (index + macroName.length()), macroValue); index = sb.indexOf(macroName, (index + macroValue.length())); } }
From source file:net.duckling.ddl.web.controller.DashboardController.java
private boolean generateApplicantMessage(List<TeamApplicantNoticeRender> tanr, StringBuilder waiting, StringBuilder reject) {/*from w ww .jav a 2 s . c o m*/ boolean isEmpty = true; if (null != tanr && !tanr.isEmpty()) { for (TeamApplicantNoticeRender tanrItem : tanr) { String status = tanrItem.getTeamApplicant().getStatus(); if (TeamApplicant.STATUS_WAITING.equals(status)) { waiting.append(tanrItem.getTeamName() + ","); isEmpty = false; } else if (TeamApplicant.STATUS_REJECT.equals(status)) { reject.append(tanrItem.getTeamName() + ","); isEmpty = false; } else { LOG.info("????"); } } if (waiting.length() > 0) { waiting.replace(waiting.lastIndexOf(","), waiting.length(), ""); } if (reject.length() > 0) { reject.replace(reject.lastIndexOf(","), reject.length(), ""); } } return isEmpty; }
From source file:org.jivesoftware.community.util.StringUtils.java
public static StringBuilder replaceAllKeys(StringBuilder stb, Map store) { List uuids = new ArrayList(store.keySet()); int loopCount = 0; label0: for (int maxLoops = uuids.size(); uuids.size() > 0 && loopCount < maxLoops; loopCount++) { Iterator i$ = store.keySet().iterator(); do {/*from www .j av a2 s .co m*/ if (!i$.hasNext()) continue label0; String uuid = (String) i$.next(); String value = (String) store.get(uuid); int idx = stb.indexOf(uuid); if (idx != -1) { stb.replace(idx, idx + uuid.length(), value); uuids.remove(uuid); } } while (true); } return stb; }
From source file:pcgui.SetupParametersPanel.java
private String generateIndependentArray(Symbol sym, IntegerDistribution intDist) { ArrayList<Integer> paramValList = new ArrayList<Integer>(); for (Object param : sym.arrayParams) { //extract the dimension param = (String) param;//w w w .jav a2s. c o m try { Integer val = Integer.parseInt((String) param); paramValList.add(val); } catch (IllegalArgumentException e) { e.printStackTrace(); // JOptionPane.showMessageDialog(this,"Check dimension of variable "+sym.name, "Error", JOptionPane.ERROR_MESSAGE); return null; } } long arraySize = 1; StringBuilder sb = new StringBuilder(); for (Integer val : paramValList) { // System.out.println("UpdatedParam : "+val); arraySize *= val; } sb.append("["); for (long r = 1; r <= arraySize; r++) { String val = Integer.toString(intDist.sample()); sb.append(val); sb.append(", "); } //remove the last "," sb.replace(sb.length() - 2, sb.length(), ""); sb.append("]"); // System.out.println("Generated Array: "+ sym.name); // System.out.println(sb.toString()); return sb.toString(); }
From source file:de.blizzy.documentr.search.PageIndex.java
private SearchTextSuggestion getSearchTextSuggestion(String searchText, Authentication authentication, IndexSearcher searcher) throws IOException, ParseException, TimeoutException { List<WordPosition> words = Lists.newArrayList(); TokenStream tokenStream = null;//from w w w .jav a 2 s .c o m try { tokenStream = analyzer.tokenStream(ALL_TEXT_SUGGESTIONS, new StringReader(searchText)); tokenStream.addAttribute(CharTermAttribute.class); tokenStream.addAttribute(OffsetAttribute.class); tokenStream.reset(); while (tokenStream.incrementToken()) { CharTermAttribute charTerm = tokenStream.getAttribute(CharTermAttribute.class); String text = charTerm.toString(); if (StringUtils.isNotBlank(text)) { OffsetAttribute offset = tokenStream.getAttribute(OffsetAttribute.class); WordPosition word = new WordPosition(text, offset.startOffset(), offset.endOffset()); words.add(word); } } tokenStream.end(); } finally { Closeables.closeQuietly(tokenStream); } Collections.reverse(words); StringBuilder suggestedSearchText = new StringBuilder(searchText); StringBuilder suggestedSearchTextHtml = new StringBuilder(searchText); boolean foundSuggestions = false; String now = String.valueOf(System.currentTimeMillis()); String startMarker = "__SUGGESTION-" + now + "__"; //$NON-NLS-1$ //$NON-NLS-2$ String endMarker = "__/SUGGESTION-" + now + "__"; //$NON-NLS-1$ //$NON-NLS-2$ DirectSpellChecker spellChecker = new DirectSpellChecker(); IndexReader reader = searcher.getIndexReader(); for (WordPosition word : words) { Term term = new Term(ALL_TEXT_SUGGESTIONS, word.getWord()); SuggestWord[] suggestions = spellChecker.suggestSimilar(term, 1, reader, SuggestMode.SUGGEST_MORE_POPULAR); if (suggestions.length > 0) { String suggestedWord = suggestions[0].string; int start = word.getStart(); int end = word.getEnd(); suggestedSearchText.replace(start, end, suggestedWord); suggestedSearchTextHtml.replace(start, end, startMarker + StringEscapeUtils.escapeHtml4(suggestedWord) + endMarker); foundSuggestions = true; } } if (foundSuggestions) { String suggestion = suggestedSearchText.toString(); SearchResult suggestionResult = findPages(suggestion, 1, authentication, searcher); int suggestionTotalHits = suggestionResult.getTotalHits(); if (suggestionTotalHits > 0) { String html = StringEscapeUtils.escapeHtml4(suggestedSearchTextHtml.toString()) .replaceAll(startMarker + "(.*?)" + endMarker, "<strong><em>$1</em></strong>"); //$NON-NLS-1$ //$NON-NLS-2$ return new SearchTextSuggestion(suggestedSearchText.toString(), html, suggestionTotalHits); } } return null; }
From source file:org.ambraproject.wombat.service.CommentFormatting.java
private static void linkURL(StringBuilder str, String target, int maxDisplayLength) { String urlToDisplay;//from w ww . j ava 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 (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 (verifyHierarchicalURI(urlStr, null)) { //Construct the hyperlink for the url... String urlLink = "<a rel=\"nofollow\" href=\"" + urlStr + "\"" + targetString; if (maxDisplayLength > 0 && urlStr.length() > maxDisplayLength) { urlLink += " title=\"" + htmlEncode(urlStr, true) + "\">" + urlToDisplay + "</a>"; } else { urlLink += ">" + 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.idempiere.webservices.AbstractService.java
/** * Parse variables inside SQL// w w w . j a v a2s.co m * @param sql * @param sqlParas * @param po * @param requestCtx * @return * @throws AdempiereException */ protected String parseSQL(String sql, ArrayList<Object> sqlParas, PO po, POInfo poInfo, Map<String, Object> requestCtx) throws AdempiereException { if (sql.startsWith("@SQL=")) sql = sql.substring(5); if (sql.toLowerCase().indexOf(" where ") == -1) throw new AdempiereException("Invalid SQL: Query do not have any filetering criteria"); StringBuilder sqlBuilder = new StringBuilder(); if (sql.indexOf('@') == -1) { sqlBuilder.append(sql); } else { int firstInd = sql.indexOf('@'); while (firstInd >= 0) { sqlBuilder.append(sql.substring(0, firstInd)); sql = sql.substring(firstInd + 1); firstInd = sql.indexOf('@'); if (firstInd == -1) { throw new AdempiereException("Missing closing '@' in SQL"); } String token = sql.substring(0, firstInd); boolean isNullable = false; if (token.charAt(0) == '!') { isNullable = true; token = token.substring(1); } sql = sql.substring(firstInd + 1); Object val = parseVariable(token, po, poInfo, requestCtx); if (val == null && isNullable) { int ind = sqlBuilder.lastIndexOf("="); sqlBuilder.replace(ind, sqlBuilder.length(), " Is Null "); } else if (val == null) throw new AdempiereException("Can not resolve varialbe '" + token + "' in sql"); else { sqlBuilder.append(" ? "); sqlParas.add(val); } firstInd = sql.indexOf('@'); } sqlBuilder.append(sql); } return sqlBuilder.toString(); }
From source file:edu.umn.msi.tropix.persistence.dao.hibernate.TropixObjectDaoImpl.java
public List<TropixObject> searchObjects(final String userId, final Class<? extends TropixObject> objectType, final String name, final String description, final String ownerId) { final StringBuilder queryBuilder = new StringBuilder( getSession().getNamedQuery("baseSearch").getQueryString()); if (StringUtils.hasText(description)) { queryBuilder.append(" and o.description like :description "); }//from w ww . j a va 2 s. com if (StringUtils.hasText(name)) { queryBuilder.append(" and o.name like :name "); } if (StringUtils.hasText(ownerId)) { queryBuilder.append( " and (select count(*) from DirectPermission ownerRole join ownerRole.users owner join ownerRole.objects ownerObject where ownerObject.id=o.id and owner.cagridId = :ownerId and ownerRole.role='owner' ) > 0"); } final String objectTypeStr = objectType == null ? "TropixObject" : objectType.getSimpleName(); final String typeStr = "TropixObject"; final int typePos = queryBuilder.indexOf(typeStr); queryBuilder.replace(typePos, typePos + typeStr.length(), objectTypeStr); final Query query = getSession().createQuery(queryBuilder.toString()); query.setParameter("userId", userId); if (StringUtils.hasText(name)) { query.setParameter("name", name); } if (StringUtils.hasText(description)) { query.setParameter("description", description); } if (StringUtils.hasText(ownerId)) { query.setParameter("ownerId", ownerId); } query.setMaxResults(maxSearchResults); @SuppressWarnings("unchecked") final List<TropixObject> results = query.list(); return results; }
From source file:pcgui.SetupParametersPanel.java
private String generateDependentArray(Symbol sym, IntegerDistribution intDist) { ArrayList<Integer> paramValList = new ArrayList<Integer>(); for (Object param : sym.arrayParams) { //extract the dimension param = (String) param;/*from www. j ava 2 s . co m*/ try { if (hashTable.containsKey(param)) { Symbol depSym = (Symbol) hashTable.get(param); String typeString = depSym.typeString; if ("Integer".equalsIgnoreCase(typeString.trim())) { //can only allow allow one more level of dependency //varA Integer varB //ourSym array(varA,varC) Object strVal = depSym.get(); if (hashTable.containsKey(strVal)) { Symbol s = (Symbol) hashTable.get(strVal); Integer val = (Integer) s.get(); paramValList.add(val); } else { Integer val = (Integer) strVal; paramValList.add(val); } } else if ("Set".equalsIgnoreCase(typeString.trim())) { String strVal = (String) depSym.get(); if (strVal.contains("..")) { //1..varA //take the upper limit String sizeVar = strVal.split("\\.\\.")[1]; if (hashTable.containsKey(sizeVar)) { Symbol s = (Symbol) hashTable.get(sizeVar); //only take the value of this var //not more than 2 level of dependency Integer val = (Integer) s.get(); paramValList.add(val); } else { //1..12 Integer val = Integer.parseInt((String) sizeVar); paramValList.add(val); } } else { //can only parse simple set size //{A,B,C,D} //{A //B //C //D} //we can get size by splitting using comma "," String strVal2 = (String) depSym.get(); Integer val = strVal2.split(",").length; paramValList.add(val); } } } //for constant integers //ourSym array(varA,5) Integer val = Integer.parseInt((String) param); paramValList.add(val); } catch (IllegalArgumentException e) { e.printStackTrace(); //JOptionPane.showMessageDialog(this,"Check dimensions of variable "+sym.name, "Error", JOptionPane.ERROR_MESSAGE); return null; } } long arraySize = 1; StringBuilder sb = new StringBuilder(); for (Integer val : paramValList) { // System.out.println("UpdatedParam : "+val); arraySize *= val; } sb.append("["); for (long r = 1; r <= arraySize; r++) { String val = Integer.toString(intDist.sample()); sb.append(val); sb.append(", "); } //remove the last "," sb.replace(sb.length() - 2, sb.length(), ""); sb.append("]"); // System.out.println("Generated Array: "+ sym.name); // System.out.println(sb.toString()); return sb.toString(); }