List of usage examples for java.lang StringBuilder replace
@Override public StringBuilder replace(int start, int end, String str)
From source file:org.rhq.enterprise.server.discovery.DiscoveryBossBean.java
/** * @param resource//from w ww.j av a2 s. c om * @param upgradeRequest * @param allowGenericPropertiesUpgrade name and description are only upgraded if this is true * @return response to the upgrade request detailing what has been accepted on the server side */ private ResourceUpgradeResponse upgradeResource(@NotNull Resource resource, ResourceUpgradeRequest upgradeRequest, boolean allowGenericPropertiesUpgrade) { if (upgradeRequest.getUpgradeErrorMessage() != null) { ResourceError error = new ResourceError(resource, ResourceErrorType.UPGRADE, upgradeRequest.getUpgradeErrorMessage(), upgradeRequest.getUpgradeErrorStackTrace(), upgradeRequest.getTimestamp()); resourceManager.addResourceError(error); return null; } ResourceUpgradeResponse ret = new ResourceUpgradeResponse(); ret.setResourceId(resource.getId()); String resourceKey = upgradeRequest.getNewResourceKey(); String name = upgradeRequest.getNewName(); String description = upgradeRequest.getNewDescription(); if (resourceKey != null || name != null || description != null) { StringBuilder logMessage = new StringBuilder("Resource [").append(resource.toString()) .append("] upgraded its "); if (needsUpgrade(resource.getResourceKey(), resourceKey)) { resource.setResourceKey(resourceKey); logMessage.append("resourceKey, "); } ret.setUpgradedResourceKey(resource.getResourceKey()); if (allowGenericPropertiesUpgrade && needsUpgrade(resource.getName(), name)) { resource.setName(name); logMessage.append("name, "); } ret.setUpgradedResourceName(resource.getName()); if (allowGenericPropertiesUpgrade && needsUpgrade(resource.getDescription(), description)) { resource.setDescription(description); logMessage.append("description, "); } ret.setUpgradedResourceDescription(resource.getDescription()); //finally let's remove the potential previous upgrade error. we've now successfully //upgraded the resource. List<ResourceError> upgradeErrors = resourceManager.findResourceErrors(subjectManager.getOverlord(), resource.getId(), ResourceErrorType.UPGRADE); for (ResourceError error : upgradeErrors) { entityManager.remove(error); } logMessage.replace(logMessage.length() - 1, logMessage.length(), "to become [") .append(resource.toString()).append("]"); log.info(logMessage.toString()); } return ret; }
From source file:com.edgenius.wiki.render.filter.MacroFilter.java
/** * Some macro has group concept. For example, table and cell, tabs and tab. To process these * relative macro, this method parses text and insert a "group key" into these macro as a part of parameters. * During macro process, it is able to MacroParameter.getParam(Macro.GROUP_KEY) to get back the group key. * The group key contains this group unique number, the children macro unique number etc. For example, * a 2x2 table will insert following group keys(edgnius_group_key as name). * <pre>//from ww w. j a v a2 s . c o m {table:edgnius_group_key=0} {cell:edgnius_group_key=0-0-0-2} 123 {cell} {cell:edgnius_group_key=0-0-1-2} abc {cell} {rowdiv:edgnius_group_key=0-1} {cell:edgnius_group_key=0-1-0-2} 456 {cell} {cell:edgnius_group_key=0-1-1-2} def {cell} {table} * </pre> * * For 2 tabs deck: * <pre> {tabs:edgnius_group_key=0} {tab:edgnius_group_key=0-1|name=work} working for money {tab} {tab:edgnius_group_key=0-2|name=life} life for fun {tab} {tabs} * </pre> * @param text * @return */ public String initialGroup(String text) { CharSequence buffer = MarkupUtil.hideEscapeMarkup(text); LinkedList<GroupProcessor> stack = new LinkedList<GroupProcessor>(); List<GroupProcessor> processors = new ArrayList(); checkGroup(0, buffer, stack, processors); //insert group id into text if (processors.size() > 0) { //sort processor first, so that it becomes easier when insert - just insert one by one //without worries of position change impact Map<Integer, GroupProcessor> borders = new TreeMap<Integer, GroupProcessor>(new CompareToComparator( CompareToComparator.TYPE_OVERWRITE_SAME_VALUE | CompareToComparator.DESCEND)); for (GroupProcessor gp : processors) { Set<Integer> posList = gp.getPositions(); for (Integer pos : posList) { borders.put(pos, gp); } } //recreate new stringBuilder as buffer(from first line of this method) is escaped StringBuilder sb = new StringBuilder(text); //on behalf of above sort result, insert is simple, just looping borderPoint one by one as new insert won't impact //the others un-inserted point location. for (Entry<Integer, GroupProcessor> entry : borders.entrySet()) { GroupProcessor gp = entry.getValue(); int start = entry.getKey(); if (gp.suppressNewlineBetweenElements()) { //Here want to remove newline between table and cells. There are 2 tricks here, as example, //(A){table} //(B1){cell}abc{cell} (B) //(C1){cell}123{cell} (C) //{table} (D) //surroundMacro is table, it start from the 2nd cell, its end is (C) then. as GroupProcessor construct method //getPreviousMacroStart() return (D) first. Here is assume {table} macro doesn't have newline! //so it is safe remove all newline between (C) and (D). // Then next process is (B) and (BC), next is (A) and (B1), Here is also assume {table} macro doesn't have newline. // The (A) is before {table} is because GroupProcessor construct method uses surrounding macro start as "end" int end = gp.getMacroEnd(start); if (end != -1) { int prevStart = gp.getPreviousMacroStart(); //remove all newline between end(current macro) and previous processed macro start if (end <= prevStart) { //if equals, means 2 group is conjunction without any character. such as {cell}{cell} - no space or any character between cell markup. if (end < prevStart) { sb.replace(end, prevStart, sb.subSequence(end, prevStart).toString().replaceAll("\n", "")); } } else { AuditLogger.warn("GroupProcessor current macro end is less than last macro start:" + end + ">" + start + ". Overlapped!"); } } else { AuditLogger.warn("GroupProcessor doesn't find the macro end value by start " + start); } } //after process done, set new current macro start - where any unexpected happens, always setPreviousMacroStart to latest! //as insertGroupKey() will change text content. gp.setPreviousMacroStart(start); gp.insertGroupKey(start, sb); } return sb.toString(); } else { return text; } }
From source file:org.webcurator.ui.tools.controller.BrowseHelper.java
/** * Iterates through all the patterns for the given content type and * replaces the URLs with a rewritten URL that points back to the * BrowseController.//from w w w . j a v a 2 s . c o m * * @param content The resource content as a StringBuilder. * @param contentType The content-type of the resource. * @param hrOid The OID of the harvest result, used for constructing the * rewritten URL. * @param currentResource The URL of the current resource. */ public void fix(StringBuilder content, String contentType, long hrOid, String currentResource) { String resourcePrefix = prefix + "/" + hrOid + "/"; String jsPrefix = prefix.replaceFirst("curator/tools/browse", "replay/client-rewrite.js"); // The Wayback 1.2 tool adds a <base href="..."> tag after the <head> tag // provided there is not one already there. So we'll do the same. if ("text/html".equals(contentType)) { String existingBaseHref = TagMagix.getBaseHref(content); if (existingBaseHref == null) { insertAtStartOfHead(content, "<base href=\"" + currentResource + "\" />"); } else { currentResource = existingBaseHref; } } // Perform TagMagix replacements for html content. ArchivalUrlResultURIConverter resURIConverter = new ArchivalUrlResultURIConverter(); resURIConverter.setReplayURIPrefix(resourcePrefix); if ("text/html".equals(contentType)) { for (TagMagixHelper helper : htmlTagPatterns) { TagMagix.markupTagREURIC(content, resURIConverter, "", currentResource, helper.tag, helper.attribute); } } // Perform regular expression pattern matching replacements for HTML content. if (contentTypePatterns.containsKey(contentType)) { for (Pattern pattern : contentTypePatterns.get(contentType)) { Matcher matcher = pattern.matcher(content); int idx = 0; while (matcher.find(idx)) { String currentVal = matcher.group(1); if (!"".equals(currentVal.trim())) { String newVal = convertUrl(hrOid, currentResource, currentVal); log.debug("Replacing " + matcher.group(1) + " with " + newVal); int origAttrLength = currentVal.length(); int attrStart = matcher.start(1); int attrEnd = matcher.end(1); int delta = newVal.length() - origAttrLength; content.replace(attrStart, attrEnd, newVal); idx = matcher.end(0) + delta; } else { idx = matcher.end(0); } } } } // The Wayback 1.2 tool also inserts some custom JavaScript to be // executed on the client side, which performs further URI replacements. // So we'll do the same. if ("text/html".equals(contentType)) { StringBuilder toInsert = new StringBuilder(300); toInsert.append("<script type=\"text/javascript\">\n"); toInsert.append(" var sWayBackCGI = \"" + resourcePrefix + "\";\n"); toInsert.append("</script>\n"); toInsert.append("<script type=\"text/javascript\" src=\"" + jsPrefix + "\" ></script>\n"); insertAtEndOfBody(content, toInsert.toString()); } // sites sometimes use the javascript:'top.location = self.location;' or 'window.location = ..' to issue a client side redirect // but this will cause the target instance list to be redirected when using the browser tool in the // webpage preview (iframe). We add a comment to this javascript to prevent the redirect. if ("text/html".equals(contentType) || "application/javascript".equals(contentType)) { Map<String, String> tokens = BrowseController.getFixTokens(); Iterator<String> keys = tokens.keySet().iterator(); while (keys.hasNext()) { String token = keys.next(); int startIdx = content.toString().toLowerCase().indexOf(token); if (startIdx != -1) { int endIdx = startIdx + token.length(); content.replace(startIdx, endIdx, tokens.get(token)); } ; } } }
From source file:com.vmware.bdd.cli.commands.ClusterCommands.java
private String getValidateWarningMsg(Map<String, List<String>> noExistingFilesMap) { StringBuilder warningMsgBuff = new StringBuilder(); if (noExistingFilesMap != null && !noExistingFilesMap.isEmpty()) { warningMsgBuff.append("Warning: "); for (Entry<String, List<String>> noExistingFilesEntry : noExistingFilesMap.entrySet()) { List<String> noExistingFileNames = noExistingFilesEntry.getValue(); for (String noExistingFileName : noExistingFileNames) { warningMsgBuff.append(noExistingFileName).append(", "); }/* ww w. j av a2s. c o m*/ warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length()); if (noExistingFileNames.size() > 1) { warningMsgBuff.append(" are "); } else { warningMsgBuff.append(" is "); } warningMsgBuff.append("not existing in "); warningMsgBuff.append(noExistingFilesEntry.getKey() + " scope , "); } warningMsgBuff.replace(warningMsgBuff.length() - 2, warningMsgBuff.length(), ". "); warningMsgBuff.append(Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT); } return warningMsgBuff.toString(); }
From source file:org.rhq.core.pc.upgrade.ResourceUpgradeDelegate.java
private String checkUpgradeValid(Resource resource, ResourceUpgradeReport upgradeReport) { StringBuilder s = new StringBuilder(); Set<Resource> duplicitSiblings = findDuplicitSiblingResources(resource, upgradeReport); if (!duplicitSiblings.isEmpty()) { s.append(//from w w w.ja va 2 s .co m "After the upgrade, the following resources would have the same resource key which is illegal. This is an issue of either the old or the new version of the plugin '" + resource.getResourceType().getPlugin() + "'. Please consult the documentation of the plugin to see what are the recommended steps to resolve this situation:\n"); //ok, this is a little tricky //this method is called when the inventory is in the state as it would look after a //successful upgrade. //but just now, we found out that the upgrade won't succeed because we found some //conflicting resources. These resources won't be upgraded but right now, we see //them as if they were. //For each resource, we therefore need to find the corresponding "original" and report //that instead of how the resource looks like right now. for (Resource r : duplicitSiblings) { ResourceUpgradeRequest fakeRequest = new ResourceUpgradeRequest(r.getId()); fakeRequest.fillInFromResource(r); ResourceUpgradeRequest orig = findOriginal(fakeRequest); //we might not find the original, because this resource might not need an upgrade. //in that case, the reporting will be accurate because upgrade didn't touch the resource. if (orig != null) { orig.updateResource(r); } //now we have the resource as it looked before the upgrade kicked in (which is in this //case also what it will look like after the upgrade finishes, because we're failing it). s.append(r).append(",\n"); //and revert the resource back to what it looked like (i.e. back to the upgraded state so //that we don't introduce side-effects in this method). if (orig != null) { fakeRequest.updateResource(r); } } //remove the trailing ",\n" s.replace(s.length() - 2, s.length(), ""); } return s.length() > 0 ? s.toString() : null; }
From source file:org.kuali.ole.select.document.OleOrderQueueDocument.java
/** * This method returns total price of the selected requisition items. * * @return Total Price of selected items *///from w ww .j a v a2 s . c o m public KualiDecimal getTotalSelectedItemsPrice() { LOG.debug("Inside totalSelectedItems of OleOrderQueueDocument"); KualiDecimal totalPrice = KualiDecimal.ZERO; ; StringBuilder orderQueueRequisitionHasNoPrice = new StringBuilder(); boolean isInfoMsg = false; List<OleRequisitionItem> refreshItems = new ArrayList<OleRequisitionItem>(); for (OleRequisitionItem item : requisitionItems) { if (item.isItemAdded()) { if (item.getSourceAccountingLines().size() > 0) { if (item.getTotalAmount().equals(KualiDecimal.ZERO)) { orderQueueRequisitionHasNoPrice.append(item.getRequisition().getDocumentNumber()) .append(","); isInfoMsg = true; } for (int i = 0; i < item.getSourceAccountingLines().size(); i++) { KualiDecimal amount = item.getSourceAccountingLines().get(i).getAmount(); totalPrice = totalPrice.add(amount); } } else { if (item.getItemListPrice().equals(KualiDecimal.ZERO)) { orderQueueRequisitionHasNoPrice.append(item.getRequisition().getDocumentNumber()) .append(","); isInfoMsg = true; } totalPrice = totalPrice.add(item.getItemListPrice()); } } refreshItems.add(item); } requisitionItems = refreshItems; int len = orderQueueRequisitionHasNoPrice.lastIndexOf(","); if (isInfoMsg) { orderQueueRequisitionHasNoPrice.replace(len, len + 1, " "); GlobalVariables.getMessageMap().putInfo(OLEConstants.OrderQueue.REQUISITIONS, OLEKeyConstants.MESSAGE_ORDERQUEUE_REQUISITIONS_HAS_NO_PRICE, new String[] { orderQueueRequisitionHasNoPrice.toString() }); } LOG.debug("Leaving totalSelectedItems of OleOrderQueueDocument"); return totalPrice; }
From source file:org.greencheek.utils.environment.propertyplaceholder.resolver.value.VariablePlaceholderValueResolver.java
private String parseStringValue(String strVal, Map<String, String> placeholderResolver, Set<String> visitedPlaceholders, boolean trimValues) { StringBuilder buf = new StringBuilder(strVal); int startIndex = strVal.indexOf(this.placeholderPrefix); while (startIndex != -1) { int endIndex = findPlaceholderEndIndex(buf, startIndex); if (endIndex != -1) { String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex); if (!visitedPlaceholders.add(placeholder)) { throw new IllegalArgumentException( "Circular placeholder reference '" + placeholder + "' in property definitions"); }/*from ww w. j av a2s . c o m*/ // Recursive invocation, parsing placeholders contained in the placeholder key. placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders, trimValues); // Now obtain the value for the fully resolved key... String propVal = placeholderResolver.get(placeholder); if (propVal == null && (this.resolvingEnvironmentVariables || this.resolvingSystemProperties)) { if (this.resolvingEnvironmentVariables) { propVal = environmentProperties == null ? null : environmentProperties.getProperty(placeholder); } if (this.resolvingSystemProperties) { String temp = systemProperties == null ? null : systemProperties.getProperty(placeholder); if (temp != null) { propVal = temp; } } } if (propVal == null && this.valueSeparator != null) { int separatorIndex = placeholder.indexOf(this.valueSeparator); if (separatorIndex != -1) { String actualPlaceholder = placeholder.substring(0, separatorIndex); String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length()); propVal = placeholderResolver.get(actualPlaceholder); if (propVal == null) { propVal = defaultValue; } } } if (propVal != null) { // Recursive invocation, parsing placeholders contained in the // previously resolved placeholder value. propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders, trimValues); buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal); if (logger.isTraceEnabled()) { logger.trace("Resolved placeholder '" + placeholder + "'"); } startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length()); } else if (this.ignoreUnresolvablePlaceholders) { // Proceed with unprocessed value. startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length()); } else { throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "'"); } visitedPlaceholders.remove(placeholder); } else { startIndex = -1; } } if (trimValues) { return buf.toString().trim(); } else { return buf.toString(); } }
From source file:es.ehu.si.ixa.pipe.convert.Convert.java
public void absaSemEvalToNER(String fileName) { SAXBuilder sax = new SAXBuilder(); XPathFactory xFactory = XPathFactory.instance(); try {//w ww . ja v a 2s . com Document doc = sax.build(fileName); XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element()); List<Element> sentences = expr.evaluate(doc); for (Element sent : sentences) { StringBuilder sb = new StringBuilder(); String sentString = sent.getChildText("text"); sb = sb.append(sentString); Element aspectTerms = sent.getChild("aspectTerms"); if (aspectTerms != null) { List<List<Integer>> offsetList = new ArrayList<List<Integer>>(); List<Integer> offsets = new ArrayList<Integer>(); List<Element> aspectTermList = aspectTerms.getChildren(); if (!aspectTermList.isEmpty()) { for (Element aspectElem : aspectTermList) { Integer offsetFrom = Integer.parseInt(aspectElem.getAttributeValue("from")); Integer offsetTo = Integer.parseInt(aspectElem.getAttributeValue("to")); offsets.add(offsetFrom); offsets.add(offsetTo); } } Collections.sort(offsets); for (int i = 0; i < offsets.size(); i++) { List<Integer> offsetArray = new ArrayList<Integer>(); offsetArray.add(offsets.get(i++)); if (offsets.size() > i) { offsetArray.add(offsets.get(i)); } offsetList.add(offsetArray); } int counter = 0; for (List<Integer> offsetSent : offsetList) { Integer offsetFrom = offsetSent.get(0); Integer offsetTo = offsetSent.get(1); String aspectString = sentString.substring(offsetFrom, offsetTo); sb.replace(offsetFrom + counter, offsetTo + counter, "<START:term> " + aspectString + " <END>"); counter += 19; } } System.out.println(sb.toString()); } } catch (JDOMException | IOException e) { e.printStackTrace(); } }
From source file:au.org.ala.delta.util.Utils.java
/** * Removes DELTA style <> comments from the supplied string. * //from ww w . j a v a 2 s . c o m * @param text * the string to remove comments from. * @param level * 0 = don't remove, 1 = remove all, 2 = remove only if other * text, 3 = same as 2, but outer brackets are removed if * commented text is used. * @return the string with comments removed */ public static String removeComments(String text, int level, boolean convertCommentsToBrackets, boolean removeInnerComments, boolean stripSpaces, boolean removeBrackets) { int mode = level; int commentLevel = 0; boolean hasText = mode == 1; boolean hadInner = false; char ch; int i, curStart = -1, start = -1, end = -1; int innerStart = -1; boolean wasSpace = true; boolean wasBrace = false; // TODO despaceRTF(text); if (stripSpaces) { text = stripExtraSpaces(text); } StringBuilder result = new StringBuilder(text); for (i = 0; i < result.length(); ++i) { // Work through string // Is character an opening bracket? if (result.charAt(i) == '<' && (wasSpace || wasBrace || (ch = result.charAt(i - 1)) == ' ' || ch == '<' || ch == '>')) { wasBrace = true; if (convertCommentsToBrackets) { result.setCharAt(i, ')'); } if (removeBrackets || (mode == 3 && commentLevel == 0)) { result.deleteCharAt(i--); } if (commentLevel == 0) { curStart = i; if (start == -1) start = i; } else if (commentLevel == 1) { innerStart = i; hadInner = true; } // Keep track of nesting level commentLevel++; } // Was it a closing bracket? else if (result.charAt(i) == '>' && commentLevel > 0 && result.charAt(i - 1) != '|' && (i + 1 == result.length() || (ch = result.charAt(i + 1)) == ' ' || ch == '<' || ch == '>')) { // Keep track of nesting level commentLevel--; wasBrace = true; if (convertCommentsToBrackets) result.setCharAt(i, ')'); if (removeBrackets || (mode == 3 && commentLevel == 0)) result.deleteCharAt(i--); if (commentLevel == 0) { if (start != -1) { end = i; if (removeInnerComments && hadInner) // In this case, // check for // and remove an empty // comment... { int leng = end - curStart - 1; String contents = result.substring(curStart + 1, end - 1); contents = stripExtraSpaces(contents); if (contents.isEmpty() || contents == " ") { result.delete(curStart, end - 1); i = curStart; } else if (stripSpaces && contents.length() != leng) { result.replace(curStart + 1, curStart + leng, contents); i -= leng - contents.length(); } } } hadInner = false; } else if (commentLevel == 1 && removeInnerComments) { // If we're removing inner comments, get rid of this // part of the string, and any space before it. int leng = i - innerStart + 1; result.delete(innerStart, innerStart + leng); i = innerStart - 1; while (result.length() > i && result.charAt(i) == ' ') result.deleteCharAt(i--); } } else if (commentLevel == 0 && (hasText || result.charAt(i) != ' ')) { hasText = true; wasBrace = false; wasSpace = (end == i - 1 && i > 0); if (end != -1 && mode > 0) { result.delete(start, end + 1); i -= end - start + 2; // Hmm. How SHOULD spaces around the removed comments // be treated? This erases the spaces BEFORE the comment while (i >= 0 && result.length() > i && result.charAt(i) == ' ') result.deleteCharAt(i--); start = -1; end = -1; } } else wasBrace = false; } if (end != -1 && hasText && mode > 0) { result.delete(start, end + 1); for (i = result.length() - 1; i >= 0 && result.charAt(i) == ' '; --i) result.deleteCharAt(i); } return result.toString(); }
From source file:de.ub0r.android.websms.WebSMS.java
/** * Update balance.// www . ja v a 2s .co m */ private void updateBalance() { Log.d(TAG, "updateBalance()"); final StringBuilder buf = new StringBuilder(); final ConnectorSpec[] css = getConnectors(ConnectorSpec.CAPABILITIES_UPDATE, ConnectorSpec.STATUS_ENABLED, false /*isIncludePseudoConnectors*/); String singleb = null; for (ConnectorSpec cs : css) { final String b = cs.getBalance(); if (b == null || b.length() == 0) { continue; } if (buf.length() > 0) { buf.append(", "); singleb = null; } else { singleb = b; } buf.append(cs.getName()); buf.append(": "); buf.append(b); } if (singleb != null) { buf.replace(0, buf.length(), singleb); } this.getSupportActionBar().setSubtitle(buf.toString()); }