List of usage examples for java.lang StringBuilder replace
@Override public StringBuilder replace(int start, int end, String str)
From source file:org.ambraproject.service.search.SolrSearchService.java
@SuppressWarnings("unchecked") private SearchResultSinglePage readQueryResults(QueryResponse queryResponse, SolrQuery query) { SolrDocumentList documentList = queryResponse.getResults(); if (log.isInfoEnabled()) { StringBuilder filterQueriesForLog = new StringBuilder(); if (query.getFilterQueries() != null && query.getFilterQueries().length > 0) { for (String filterQuery : query.getFilterQueries()) { filterQueriesForLog.append(filterQuery).append(" , "); }/*from ww w.ja v a2 s .co m*/ if (filterQueriesForLog.length() > 3) { filterQueriesForLog.replace(filterQueriesForLog.length() - 3, filterQueriesForLog.length(), ""); } else { filterQueriesForLog.append("No Filter Queries"); } } log.info("query.getQuery():{ " + query.getQuery() + " }" + ", query.getSortFields():{ " + (query.getSortFields() == null ? null : Arrays.asList(query.getSortFields())) + " }" + ", query.getFilterQueries():{ " + filterQueriesForLog.toString() + " }" + ", found:" + documentList.getNumFound() + ", start:" + documentList.getStart() + ", max_score:" + documentList.getMaxScore() + ", QTime:" + queryResponse.getQTime() + "ms"); // TODO: implement spell-checking in a meaningful manner. This loop exists only to generate log output. // TODO: Add "spellcheckAlternatives" or something like it to the SearchHits class so it can be displayed to the user like Google's "did you mean..." // TODO: Turn off spellchecking for the "author" field. if (queryResponse.getSpellCheckResponse() != null && queryResponse.getSpellCheckResponse().getSuggestionMap() != null && queryResponse.getSpellCheckResponse().getSuggestionMap().keySet().size() > 0) { StringBuilder sb = new StringBuilder("Spellcheck alternative suggestions:"); for (String token : queryResponse.getSpellCheckResponse().getSuggestionMap().keySet()) { sb.append(" { ").append(token).append(" : "); if (queryResponse.getSpellCheckResponse().getSuggestionMap().get(token).getAlternatives() .size() < 1) { sb.append("NO ALTERNATIVES"); } else { for (String alternative : queryResponse.getSpellCheckResponse().getSuggestionMap() .get(token).getAlternatives()) { sb.append(alternative).append(", "); } sb.replace(sb.length() - 2, sb.length(), ""); // Remove last comma and space. } sb.append(" } ,"); } log.info(sb.replace(sb.length() - 2, sb.length(), "").toString()); // Remove last comma and space. } else { log.info("Solr thinks everything in the query is spelled correctly."); } } List<SearchHit> searchResults = new ArrayList<SearchHit>(); for (SolrDocument document : documentList) { String id = SolrServiceUtil.getFieldValue(document, "id", String.class, query.toString()); String message = id == null ? query.toString() : id; Float score = SolrServiceUtil.getFieldValue(document, "score", Float.class, message); String title = SolrServiceUtil.getFieldValue(document, "title_display", String.class, message); Date publicationDate = SolrServiceUtil.getFieldValue(document, "publication_date", Date.class, message); String eissn = SolrServiceUtil.getFieldValue(document, "eissn", String.class, message); String journal = SolrServiceUtil.getFieldValue(document, "journal", String.class, message); String articleType = SolrServiceUtil.getFieldValue(document, "article_type", String.class, message); String strikingImage = SolrServiceUtil.getFieldValue(document, "striking_image", String.class, message); List<String> abstractText = SolrServiceUtil.getFieldMultiValue(document, "abstract", String.class, message); List<String> abstractPrimary = SolrServiceUtil.getFieldMultiValue(document, "abstract_primary_display", String.class, message); List<String> authorList = SolrServiceUtil.getFieldMultiValue(document, "author_display", String.class, message); // TODO create a dedicated field for checking the existence of assets for a given article. List<String> figureTableCaptions = SolrServiceUtil.getFieldMultiValue(document, "figure_table_caption", String.class, message); List<String> subjects = SolrServiceUtil.getFieldMultiValue(document, "subject", String.class, message); List<String> expressionOfconcern = SolrServiceUtil.getFieldMultiValue(document, "expression_of_concern", String.class, message); String retraction = SolrServiceUtil.getFieldValue(document, "retraction", String.class, message); String abstractResult = ""; //Use the primary abstract if it exists if (abstractPrimary.size() > 0) { abstractResult = StringUtils.join(abstractPrimary, ", "); } else { if (abstractText.size() > 0) { abstractResult = StringUtils.join(abstractText, ", "); } } //Flatten the list of subjects to a unique set Set<String> flattenedSubjects = new HashSet<String>(); for (String subject : subjects) { for (String temp : subject.split("/")) { if (temp.trim().length() > 0) { flattenedSubjects.add(temp); } } } SearchHit hit = SearchHit.builder().setHitScore(score).setUri(id).setTitle(title) .setListOfCreators(authorList).setDate(publicationDate).setIssn(eissn).setJournalTitle(journal) .setArticleTypeForDisplay(articleType).setAbstractText(abstractResult) .setStrikingImage(strikingImage).setHasAssets(figureTableCaptions.size() > 0) .setSubjects(flattenedSubjects).setSubjectsPolyhierarchy(subjects) .setExpressionOfConcern(expressionOfconcern).setRetraction(retraction).build(); if (log.isDebugEnabled()) log.debug(hit.toString()); searchResults.add(hit); } //here we assume that number of hits is always going to be withing range of int SearchResultSinglePage results = new SearchResultSinglePage((int) documentList.getNumFound(), -1, searchResults, query.getQuery()); if (queryResponse.getFacetField("subject_facet") != null) { List<Map> subjects = facetCountsToHashMap(queryResponse.getFacetField("subject_facet")); if (subjects != null) { List<Map> subjectResult = new ArrayList<Map>(); SortedMap<String, Long> topSubjects = null; try { topSubjects = getTopSubjects(); } catch (ApplicationException ex) { throw new RuntimeException(ex.getMessage(), ex); } //Remove top level 1 subjects from list, FEND-805 for (Map<String, Object> m : subjects) { if (!topSubjects.containsKey(m.get("name"))) { HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("name", m.get("name")); hm.put("count", m.get("count")); subjectResult.add(hm); } } results.setSubjectFacet(subjectResult); } else { results.setSubjectFacet(null); } } if (queryResponse.getFacetField("author_facet") != null) { results.setAuthorFacet(facetCountsToHashMap(queryResponse.getFacetField("author_facet"))); } if (queryResponse.getFacetField("editor_facet") != null) { results.setEditorFacet(facetCountsToHashMap(queryResponse.getFacetField("editor_facet"))); } if (queryResponse.getFacetField("article_type_facet") != null) { results.setArticleTypeFacet(facetCountsToHashMap(queryResponse.getFacetField("article_type_facet"))); } if (queryResponse.getFacetField("affiliate_facet") != null) { results.setInstitutionFacet(facetCountsToHashMap(queryResponse.getFacetField("affiliate_facet"))); } if (queryResponse.getFacetField("cross_published_journal_key") != null) { results.setJournalFacet( facetCountsToHashMap(queryResponse.getFacetField("cross_published_journal_key"))); } return results; }
From source file:com.mycompany.searchengineaggregator.SearchEngineAggregator.java
public String compileResults(ArrayList<JSONObject> result1, ArrayList<JSONObject> result2, ArrayList<JSONObject> result3) { StringBuilder finalResult = new StringBuilder(); ArrayList<JSONObject> combinedResults = new ArrayList<>(result1.size() + result2.size() + result3.size()); combinedResults.addAll(result1);// w w w . j a v a 2s .com combinedResults.addAll(result2); combinedResults.addAll(result3); //Sorts combined list so that all results appear in order of "hit" //E.g. Google's first result, Yahoo's first result, Bing's first result, etc. Collections.sort(combinedResults, new Comparator<JSONObject>() { @Override public int compare(JSONObject obj1, JSONObject obj2) { try { if (obj1.getInt("result number") < obj2.getInt("result number")) { return -1; } else if (obj1.getInt("result number") == obj2.getInt("result number")) { return 0; } else { return 1; } } catch (JSONException ex) { Logger.getLogger(SearchEngineAggregator.class.getName()).log(Level.SEVERE, null, ex); } return -1; } }); finalResult.append("\n["); //Appends all results from each search engine to the final result string for (JSONObject s : combinedResults) { finalResult.append(s.toString()); finalResult.append(","); } //Replace last comma with ']' finalResult.replace(finalResult.length() - 1, finalResult.length(), "]"); return finalResult.toString(); }
From source file:pcgui.SetupParametersPanel.java
/** * @param sym// ww w .ja v a2 s.c om * @param realDist */ private String generateIndependentArray(Symbol sym, RealDistribution realDist) { ArrayList<Integer> paramValList = new ArrayList<Integer>(); for (Object param : sym.arrayParams) { //extract the dimension param = (String) param; 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++) { DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.CEILING); String val = df.format(realDist.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:org.sakaiproject.email.impl.BasicEmailService.java
protected String cleanUp(String str) { StringBuilder buf = new StringBuilder(str); for (int i = 0; i < buf.length(); i++) { if (buf.charAt(i) == '\n' || buf.charAt(i) == '\r') buf.replace(i, i + 1, " "); }/*from w w w .j a v a 2s . co m*/ return buf.toString(); }
From source file:de.micromata.genome.gwiki.page.gspt.ExtendedTemplate.java
/** * Replace el inline expressions.//w w w . j a v a2 s . c om * * @param elements the elements * @param elIdx the el idx * @return the int */ private int replaceElInlineExpressions(List<ParseElement> elements, int elIdx) { if (elements.get(elIdx).text.indexOf("${") == -1) return elIdx; StringBuilder sb = elements.get(elIdx).text; elements.remove(elIdx); for (int i = 0; i < sb.length(); ++i) { char c = sb.charAt(i); if (c == '$' && sb.length() > i + 1 && sb.charAt(i + 1) == '{') { int startIdx = i; int endIdx = -1; i += 2; for (; i < sb.length(); ++i) { if (sb.charAt(i) == '}') { endIdx = i; break; } } if (endIdx == -1) continue; String rt = sb.substring(0, startIdx); elements.add(elIdx++, new ParseElement(Type.ConstString, rt)); String text = sb.substring(startIdx, endIdx + 1); String r = "TagSupport.printEvalInlineElExpression(pageContext, \"\\" + escapeLiteral(text) + "\");"; elements.add(elIdx++, new ParseElement(Type.Statement, r)); sb.replace(0, endIdx + 1, ""); i = 0; } } if (sb.length() > 0) elements.add(elIdx++, new ParseElement(Type.ConstString, sb.toString())); return elIdx; }
From source file:pcgui.SetupParametersPanel.java
private String generateDependentArray(Symbol sym, RealDistribution realDist) { ArrayList<Integer> paramValList = new ArrayList<Integer>(); for (Object param : sym.arrayParams) { //extract the dimension param = (String) param;/* w ww. ja v a 2 s .c o m*/ System.out.println("Param name =" + param); try { if (hashTable.containsKey(param)) { Symbol depSym = (Symbol) hashTable.get(param); String typeString = depSym.typeString; if ("Integer".equalsIgnoreCase(typeString.trim())) { Object strVal = depSym.get(); //can only allow allow one more level of dependency //varA Integer varB //ourSym array(varA,varC) 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); } } } else { //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++) { DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.CEILING); String val = df.format(realDist.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:org.apache.stratos.cloud.controller.services.impl.CloudControllerServiceImpl.java
private void replaceInPayload(String payloadParamName, StringBuilder payload, String name, String value) { payload.replace(payload.indexOf(payloadParamName), payload.indexOf(",", payload.indexOf(payloadParamName)), "," + name + "=" + value); }
From source file:org.ambraproject.util.TextUtils.java
private static void linkURL(StringBuilder str, String target, int maxDisplayLength) { String urlToDisplay;// w ww . ja va 2 s .co m 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:com.irccloud.android.ColorFormatter.java
public static String emojify(String msg) { if (msg == null) return ""; boolean disableConvert = false; try {/*from w w w . j ava 2 s . c o m*/ if (NetworkConnection.getInstance().getUserInfo() != null && NetworkConnection.getInstance().getUserInfo().prefs != null) { disableConvert = NetworkConnection.getInstance().getUserInfo().prefs .getBoolean("emoji-disableconvert"); } else { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()); disableConvert = prefs.getBoolean("emoji-disableconvert", false); } } catch (Exception e) { } StringBuilder builder = new StringBuilder(msg); int offset; if (!disableConvert) { Matcher m = EMOJI.matcher(msg); while (m.find()) { if (emojiMap.containsKey(m.group(1))) { offset = msg.length() - builder.length(); builder.replace(m.start(1) - offset - 1, m.end(1) - offset + 1, emojiMap.get(m.group(1))); } } msg = builder.toString(); } Matcher m = CONVERSION.matcher(msg); while (m.find()) { if (conversionMap.containsKey(m.group(1))) { offset = msg.length() - builder.length(); builder.replace(m.start(1) - offset, m.end(1) - offset, conversionMap.get(m.group(1))); } } return builder.toString(); }
From source file:org.gvnix.web.theme.roo.addon.ThemeOperationsImpl.java
/** * Utility method to get a formated string that shows complete Theme info. * This method is designed to be used from {@link #getThemesInfo()}. Theme * info:/*from w w w .ja va 2 s. c o m*/ * <ul> * <li>Theme ID</li> * <li>Theme available to be installed in the project</li> * <li>Installed theme</li> * <li>Active theme</li> * </ul> * Note that the resulting String will have the same length, 72 chars. * * @return Theme info */ private String getThemeInfo(Theme theme) { // ID must be 15 chars length StringBuilder idStrBuilder = new StringBuilder(" "); String id = theme.getId(); if (id.length() > 15) { idStrBuilder.replace(0, 15, id.substring(0, 15)); } else { idStrBuilder.replace(0, id.length(), id); } // description could be null String description = theme.getDescription(); if (description == null) { description = ""; } // Message builder. StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(idStrBuilder); stringBuilder.append(" "); stringBuilder.append(theme.isAvailable() ? " Yes " : " No "); stringBuilder.append(" "); stringBuilder.append(theme.isInstalled() ? " Yes " : " No "); stringBuilder.append(" "); stringBuilder.append(theme.isActive() ? " Yes " : " No "); stringBuilder.append(" "); // tail description to 30 chars length stringBuilder.append(description.length() > 30 ? description.substring(0, 30) : description); stringBuilder.append("\n"); return stringBuilder.toString(); }