List of usage examples for java.lang StringBuilder replace
@Override public StringBuilder replace(int start, int end, String str)
From source file:org.zaproxy.zap.spider.SpiderParam.java
/** * Gets the scope's regex.//w w w . ja v a 2 s.c o m * * @return returns the scope. * @deprecated (2.3.0) Replaced by {@link #getDomainsAlwaysInScope()} and {@link #getDomainsAlwaysInScopeEnabled()}. */ @Deprecated public String getScope() { StringBuilder scopeTextStringBuilder = new StringBuilder(); for (DomainAlwaysInScopeMatcher domainInScope : domainsAlwaysInScope) { if (domainInScope.isRegex()) { scopeTextStringBuilder.append("\\Q").append(domainInScope.getValue()).append("\\E"); } else { scopeTextStringBuilder.append(domainInScope.getValue()); } scopeTextStringBuilder.append('|'); } if (scopeTextStringBuilder.length() != 0) { scopeTextStringBuilder.append("("); scopeTextStringBuilder.replace(scopeTextStringBuilder.length() - 1, scopeTextStringBuilder.length() - 1, ")$"); } return scopeTextStringBuilder.toString(); }
From source file:org.ff4j.spring.placeholder.PropertiesPlaceHolderBeanDefinitionVisitor.java
/** * Parsing value to handle//from www . j av a 2s. c om * @param strVal * @param uriMap * @param visitedPlaceholders * @return * @throws BeanDefinitionStoreException */ protected String parseStringValue(String strVal, Map<String, Property<?>> propertiesMap, Map<String, Feature> featureMap, Set<String> visitedPlaceholders) throws BeanDefinitionStoreException { StringBuilder builder = new StringBuilder(strVal); // @ff4jProperty{} int startIndex = strVal.indexOf(PLACEHOLDER_PROPERTY_PREFIX); while (startIndex != -1) { int endIndex = builder.toString().indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PROPERTY_PREFIX.length()); if (endIndex != -1) { String placeholder = builder.substring(startIndex + PLACEHOLDER_PROPERTY_PREFIX.length(), endIndex); if (!visitedPlaceholders.add(placeholder)) { throw new BeanDefinitionStoreException( "Circular placeholder reference '" + placeholder + "' in property definitions"); } if (propertiesMap == null || !propertiesMap.containsKey(placeholder)) { throw new PropertyNotFoundException( PLACEHOLDER_PROPERTY_PREFIX + ": Cannot perform placeholding on " + placeholder); } String propVal = propertiesMap.get(placeholder).asString(); if (propVal != null) { propVal = parseStringValue(propVal, propertiesMap, featureMap, visitedPlaceholders); builder.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Resolved placeholder '{}' to value '{}'", placeholder, propVal); } startIndex = builder.toString().indexOf(PLACEHOLDER_PROPERTY_PREFIX, startIndex + propVal.length()); } else { throw new BeanDefinitionStoreException("Could not resolve placeholder '" + placeholder + "'"); } visitedPlaceholders.remove(placeholder); } else { startIndex = -1; } } // @ff4jFeature{} startIndex = strVal.indexOf(PLACEHOLDER_FEATURE_PREFIX); while (startIndex != -1) { int endIndex = builder.toString().indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_FEATURE_PREFIX.length()); if (endIndex != -1) { String placeholder = builder.substring(startIndex + PLACEHOLDER_FEATURE_PREFIX.length(), endIndex); if (!visitedPlaceholders.add(placeholder)) { throw new BeanDefinitionStoreException( "Circular placeholder reference '" + placeholder + "' in property definitions"); } if (featureMap == null || !featureMap.containsKey(placeholder)) { throw new FeatureNotFoundException( PLACEHOLDER_FEATURE_PREFIX + ": Cannot perform placeholding on " + placeholder); } String propVal = String.valueOf(featureMap.get(placeholder).isEnable()); if (propVal != null) { propVal = parseStringValue(propVal, propertiesMap, featureMap, visitedPlaceholders); builder.replace(startIndex, endIndex + PLACEHOLDER_FEATURE_PREFIX.length(), propVal); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Resolved placeholder '{}' to value '{}'", placeholder, propVal); } startIndex = builder.toString().indexOf(PLACEHOLDER_FEATURE_PREFIX, startIndex + propVal.length()); } else { throw new BeanDefinitionStoreException("Could not resolve placeholder '" + placeholder + "'"); } visitedPlaceholders.remove(placeholder); } else { startIndex = -1; } } return builder.toString(); }
From source file:nl.b3p.viewer.stripes.LayarActionBean.java
/** * Replace all the [attributename] in the given string with the values in the SimpleFeature * @param string// w ww. jav a2s. c o m * @param f * @return * @throws Exception */ private String replaceValuesInString(String string, SimpleFeature f) throws Exception { if (string == null) { return null; } if (!string.contains("[") && !string.contains("]")) { return string; } StringBuilder url = new StringBuilder(string); int begin = -1; int end = -1; for (int i = 0; i < url.length(); i++) { char c = url.charAt(i); if (c == '[') { if (begin == -1) { begin = i; } else { throw new Exception("Configuration of \"" + string + "\" not correct. ']' missing ."); } } else if (c == ']') { end = i; if (begin != -1 && end != -1) { String attribName = url.substring(begin + 1, end); Object value = null; if (attribName == null || attribName.length() == 0) { value = ""; } else { value = f.getAttribute(attribName); } if (value == null) { value = ""; } url.replace(begin, end + 1, value.toString().trim()); i = begin; begin = -1; end = -1; } else { throw new Exception("Configuration of \"" + string + "\" not correct. Missing '[' ."); } } else if (i == url.length() - 1 && begin != -1) { throw new Exception("Configuration of \"" + string + "\" not correct. Missing ']' ."); } } return url.toString(); }
From source file:org.jivesoftware.community.util.StringUtils.java
public static StringBuilder removeTag(String s, StringBuilder html) { String tagBegin = (new StringBuilder()).append("<").append(s).append(" ").toString(); String tagEnd = (new StringBuilder()).append("</").append(s).append(">").toString(); int start = html.indexOf(tagBegin); do {/*from ww w . j ava 2s. c o m*/ if (start == -1) break; int end = html.indexOf(tagEnd, start + 1); if (end != -1) { html.replace(start, end, ""); start = html.indexOf(tagBegin); } } while (true); return html; }
From source file:com.intellij.lang.jsgraphql.ide.annotator.JSGraphQLAnnotator.java
private CharSequence getWhitespacePaddedGraphQL(PsiFile psiFile, CharSequence buffer) { // find the template expressions in the file Collection<JSStringTemplateExpression> stringTemplateExpressions = PsiTreeUtil .collectElementsOfType(psiFile, JSStringTemplateExpression.class); StringBuilder sb = new StringBuilder(0); Integer builderPos = null;/*from w ww .java2 s . co m*/ for (JSStringTemplateExpression stringTemplateExpression : stringTemplateExpressions) { if (JSGraphQLLanguageInjectionUtil.isJSGraphQLLanguageInjectionTarget(stringTemplateExpression)) { final TextRange graphQLTextRange = JSGraphQLLanguageInjectionUtil .getGraphQLTextRange(stringTemplateExpression); if (builderPos == null) { sb.setLength(buffer.length()); builderPos = 0; } // write the JS as whitespace so it'll be ignored by the GraphQL tooling, while preserving line numbers and columns. TextRange templateTextRange = stringTemplateExpression.getTextRange(); int graphQLStartOffset = templateTextRange.getStartOffset() + graphQLTextRange.getStartOffset(); int graphQLEndOffset = templateTextRange.getStartOffset() + graphQLTextRange.getEndOffset(); applyWhiteSpace(buffer, sb, builderPos, graphQLStartOffset); String graphQLText = buffer.subSequence(graphQLStartOffset, graphQLEndOffset /* end is exclusive*/) .toString(); sb.replace(graphQLStartOffset, graphQLEndOffset /* end is exclusive*/, graphQLText); builderPos = graphQLEndOffset /* start next whitespace padding after the graph ql */; } } // last whitespace segment if (builderPos != null && builderPos < buffer.length()) { applyWhiteSpace(buffer, sb, builderPos, buffer.length()); } return sb; }
From source file:org.alfresco.util.exec.RuntimeExec.java
/** * Get the command that will be executed post substitution. * <p>//from w w w . j a v a2s. c om * <code>null</code> properties will be treated as an empty string for substitution * purposes. * * @param properties the properties that the command might be executed with * @return Returns the command that will be executed should the additional properties * be supplied */ public String[] getCommand(Map<String, String> properties) { Map<String, String> execProperties = null; if (properties == defaultProperties) { // we are just using the default properties execProperties = defaultProperties; } else { execProperties = new HashMap<String, String>(defaultProperties); // overlay the supplied properties execProperties.putAll(properties); } // Perform the substitution for each element of the command ArrayList<String> adjustedCommandElements = new ArrayList<String>(20); for (int i = 0; i < command.length; i++) { StringBuilder sb = new StringBuilder(command[i]); for (Map.Entry<String, String> entry : execProperties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); // ignore null if (value == null) { value = ""; } // progressively replace the property in the command key = (VAR_OPEN + key + VAR_CLOSE); int index = sb.indexOf(key); while (index > -1) { // replace sb.replace(index, index + key.length(), value); // get the next one index = sb.indexOf(key, index + 1); } } String adjustedValue = sb.toString(); // Now SPLIT: it if (adjustedValue.startsWith(DIRECTIVE_SPLIT)) { String unsplitAdjustedValue = sb.substring(DIRECTIVE_SPLIT.length()); // There may be quoted arguments here (see ALF-7482) ExecParameterTokenizer quoteAwareTokenizer = new ExecParameterTokenizer(unsplitAdjustedValue); List<String> tokens = quoteAwareTokenizer.getAllTokens(); adjustedCommandElements.addAll(tokens); } else { adjustedCommandElements.add(adjustedValue); } } // done return adjustedCommandElements.toArray(new String[adjustedCommandElements.size()]); }
From source file:com.miz.functions.MizLib.java
public static String decryptName(String input, String customTags) { if (TextUtils.isEmpty(input)) return ""; String output = getNameFromFilename(input); output = fixAbbreviations(output);/*from ww w . jav a2s.c o m*/ // Used to remove [SET {title}] from the beginning of filenames if (output.startsWith("[") && output.contains("]")) { String after = ""; if (output.matches("(?i)^\\[SET .*\\].*?")) { try { after = output.substring(output.indexOf("]") + 1, output.length()); } catch (Exception e) { } } if (!TextUtils.isEmpty(after)) output = after; } output = output.replaceAll(WAREZ_PATTERN + "|\\)|\\(|\\[|\\]|\\{|\\}|\\'|\\<|\\>|\\-", ""); // Improved support for French titles that start with C' or L' if (output.matches("(?i)^(c|l)(\\_|\\.)\\w.*?")) { StringBuilder sb = new StringBuilder(output); sb.replace(1, 2, "'"); output = sb.toString(); } if (!TextUtils.isEmpty(customTags)) { String[] custom = customTags.split("<MiZ>"); int count = custom.length; for (int i = 0; i < count; i++) try { output = output.replaceAll("(?i)" + custom[i], ""); } catch (Exception e) { } } output = output.replaceAll("\\s\\-\\s|\\.|\\,|\\_", " "); // Remove separators output = output.trim().replaceAll("(?i)(part)$", ""); // Remove "part" in the end of the string output = output.trim().replaceAll("(?i)(?:s|season[ ._-]*)\\d{1,4}.*", ""); // Remove "season####" in the end of the string return output.replaceAll(" +", " ").trim(); // replaceAll() needed to remove all instances of multiple spaces }
From source file:org.wso2.carbon.governance.registry.extensions.executors.ServiceVersionExecutor.java
public boolean execute(RequestContext requestContext, String currentState, String targetState) { // To keep track of the registry transaction state boolean transactionStatus = false; OMElement historyOperation = null;/* w w w . j a v a 2 s . c o m*/ List<String> otherDependencyList = new ArrayList<String>(); // for logging purposes try { historyOperation = AXIOMUtil.stringToOM("<operation></operation>"); } catch (XMLStreamException e) { log.error(e); } // getting the necessary values from the request context Resource resource = requestContext.getResource(); Registry registry = requestContext.getRegistry(); String resourcePath = requestContext.getResourcePath().getPath(); Map<String, String> currentParameterMap = new HashMap<String, String>(); Map<String, String> newPathMappings; // Returning true since this executor is not compatible with collections if (resource instanceof Collection) { return true; } else if (resource.getMediaType() == null || "".equals(resource.getMediaType().trim())) { log.warn("The media-type of the resource '" + resourcePath + "' is undefined. Hence exiting the service version executor."); return true; } else if (!resource.getMediaType().equals(serviceMediaType)) { // We have a generic copy executor to copy any resource type. // This executor is written for services. // If a resource other than a service comes here, then we simply return true // since we can not handle it using this executor. return true; } // Getting the target environment and the current environment from the parameter map. String targetEnvironment = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), (String) parameterMap.get(TARGET_ENVIRONMENT)); String currentEnvironment = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), (String) parameterMap.get(CURRENT_ENVIRONMENT)); if ((targetEnvironment == null || currentEnvironment == null) || (currentEnvironment.isEmpty() || targetEnvironment.isEmpty())) { log.warn("Current environment and the Target environment has not been defined to the state"); // Here we are returning true because the executor has been configured incorrectly // We do NOT consider that as a execution failure // Hence returning true here return true; } // Here we are populating the parameter map that was given from the UI if (!populateParameterMap(requestContext, currentParameterMap)) { log.error("Failed to populate the parameter map"); return false; } try { // Starting a registry transaction registry.beginTransaction(); Resource newResource = registry.newResource(); // This loop is there to reformat the paths with the new versions. newPathMappings = getNewPathMappings(targetEnvironment, currentEnvironment, currentParameterMap, otherDependencyList); // Once the paths are updated with the new versions we do through the service resource and update the // content of the service resource with the new service version, wsdl path. if (!CommonUtil.isUpdateLockAvailable()) { return false; } CommonUtil.acquireUpdateLock(); try { // Iterating through the list of dependencies for (Map.Entry<String, String> currentParameterMapEntry : currentParameterMap.entrySet()) { if (registry.resourceExists(currentParameterMapEntry.getKey())) { String newTempResourcePath; Resource tempResource = registry.get(currentParameterMapEntry.getKey()); if (!(tempResource instanceof Collection) && tempResource.getMediaType() != null) { updateNewPathMappings(tempResource.getMediaType(), currentEnvironment, targetEnvironment, newPathMappings, currentParameterMapEntry.getKey(), currentParameterMapEntry.getValue()); } StringBuilder resourceContent = new StringBuilder(getResourceContent(tempResource)); // Update resource content to reflect new paths for (Map.Entry<String, String> newPathMappingsEntry : newPathMappings.entrySet()) { if (resourceContent != null && !ENDPOINT_MEDIA_TYPE.equals(tempResource.getMediaType())) { int index; if ((index = resourceContent.indexOf(newPathMappingsEntry.getKey())) > -1) { resourceContent.replace(index, index + newPathMappingsEntry.getKey().length(), newPathMappingsEntry.getValue()); } else if (SCHEMA_MEDIA_TYPE.equals(tempResource.getMediaType())) { updateSchemaRelativePaths(targetEnvironment, currentEnvironment, resourceContent, newPathMappingsEntry); } else if (WSDL_MEDIA_TYPE.equals(tempResource.getMediaType())) { updateWSDLRelativePaths(targetEnvironment, currentEnvironment, resourceContent, newPathMappingsEntry); } } } tempResource.setContent(resourceContent.toString()); newTempResourcePath = newPathMappings.get(tempResource.getPath()); // Checking whether this resource is a service resource // If so, then we handle it in a different way if ((tempResource.getMediaType() != null) && (tempResource.getMediaType().equals(serviceMediaType))) { newResource = tempResource; OMElement serviceElement = getServiceOMElement(newResource); OMFactory fac = OMAbstractFactory.getOMFactory(); // Adding required fields at the top of the xml which will help to easily read in service side Iterator it = serviceElement.getChildrenWithLocalName("newServicePath"); if (it.hasNext()) { OMElement next = (OMElement) it.next(); next.setText(newTempResourcePath); } else { OMElement operation = fac.createOMElement("newServicePath", serviceElement.getNamespace(), serviceElement); operation.setText(newTempResourcePath); } setServiceVersion(serviceElement, currentParameterMap.get(tempResource.getPath())); // This is here to override the default path serviceElement.build(); resourceContent = new StringBuilder(serviceElement.toString()); newResource.setContent(resourceContent.toString()); addNewId(registry, newResource, newTempResourcePath); continue; } addNewId(registry, tempResource, newTempResourcePath); // We add all the resources other than the original one here if (!tempResource.getPath().equals(resourcePath)) { // adding logs historyOperation.addChild(getHistoryInfoElement(newTempResourcePath + " created")); registry.put(newTempResourcePath, tempResource); // copyCommunityFeatures(requestContext, registry, resourcePath, newPathMappings, historyOperation); copyComments(registry, newTempResourcePath, currentParameterMapEntry.getKey(), historyOperation); copyRatings(requestContext.getSystemRegistry(), newTempResourcePath, currentParameterMapEntry.getKey(), historyOperation); copyAllAssociations(registry, newTempResourcePath, currentParameterMapEntry.getKey(), historyOperation); } } } // We check whether there is a resource with the same name,namespace and version in this environment // if so, we make it return false based on override flag. if (registry.resourceExists(newPathMappings.get(resourcePath)) & !override) { // This means that we should not do this operation and we should fail this String message = "A resource exists with the given version"; requestContext.setProperty(LifecycleConstants.EXECUTOR_MESSAGE_KEY, message); throw new RegistryException(message); } // This is to handle the original resource and put it to the new path registry.put(newPathMappings.get(resourcePath), newResource); historyOperation.addChild(getHistoryInfoElement(newPathMappings.get(resourcePath) + " created")); // Initializing statCollection object StatCollection statCollection = new StatCollection(); // Set action type="association" statCollection.setActionType(ASSOCIATION); statCollection.setAction(""); statCollection.setRegistry(registry.getRegistryContext().getEmbeddedRegistryService() .getSystemRegistry(CurrentSession.getTenantId())); statCollection.setTimeMillis(System.currentTimeMillis()); statCollection.setState(currentState); statCollection.setResourcePath(newPathMappings.get(resourcePath)); statCollection.setUserName(CurrentSession.getUser()); statCollection.setOriginalPath(newPathMappings.get(resourcePath)); statCollection.setTargetState(targetState); statCollection.setAspectName(resource.getProperty(LIFECYCLE_ASPECT_NAME)); // Writing the logs to the registry as history if (isAuditEnabled) { StatWriter.writeHistory(statCollection); } } finally { CommonUtil.releaseUpdateLock(); } // Associating the new resource with the LC String aspectName = resource.getProperty(REGISTRY_LC_NAME); registry.associateAspect(newPathMappings.get(resourcePath), aspectName); makeDependencies(requestContext, currentParameterMap, newPathMappings); makeOtherDependencies(requestContext, newPathMappings, otherDependencyList); // Here we are coping the comments,tags,rating and associations of the original resource copyCommunityFeatures(requestContext, registry, resourcePath, newPathMappings, historyOperation); addSubscriptionAvailableProperty(newResource); requestContext.setResource(newResource); requestContext.setOldResource(resource); requestContext.setResourcePath(new ResourcePath(newPathMappings.get(resourcePath))); // adding logs StatCollection statCollection = (StatCollection) requestContext .getProperty(LifecycleConstants.STAT_COLLECTION); // keeping the old path due to logging purposes newResource.setProperty(LifecycleConstants.REGISTRY_LIFECYCLE_HISTORY_ORIGINAL_PATH + aspectName, statCollection.getOriginalPath()); statCollection.addExecutors(this.getClass().getName(), historyOperation); transactionStatus = true; } catch (RegistryException e) { log.error("Failed to perform registry operation", e); return false; } finally { try { if (transactionStatus) { registry.commitTransaction(); } else { registry.rollbackTransaction(); } } catch (RegistryException e) { log.error("Unable to finish the transaction", e); } } return true; }
From source file:pl.nask.hsn2.normalizers.URLNormalizerUtils.java
private static StringBuilder arrayToIPv6(long[] octets, boolean lastAsIPv4) throws URLHostParseException { StringBuilder sb = new StringBuilder(); sb.append("["); int i = 0;/* w ww . j a va 2 s. c o m*/ while (octets[i] == 0l) { i++; } switch (i) { case 3: case 4: if (lastAsIPv4) { sb.append("::"); } else { i = 0; } break; case 5: if (octets[5] == 0xffffl) { octets[4] = octets[6] >> 8; octets[5] = octets[6] & 0xff; octets[6] = octets[7] >> 8; octets[7] = octets[7] & 0xff; octets[3] = 0xffffl; i = 3; lastAsIPv4 = true; sb.append("::"); } else { i = 0; } break; case 6: octets[4] = octets[6] >> 8; octets[5] = octets[6] & 0xff; octets[6] = octets[7] >> 8; octets[7] = octets[7] & 0xff; i = 4; sb.append("::"); lastAsIPv4 = true; break; default: i = 0; break; } if (lastAsIPv4) { checkIPv46correctness(octets); } for (; i < octets.length; i++) { if (!lastAsIPv4) { sb.append(Long.toHexString(octets[i])).append(":"); } else { if (i < 4) { sb.append(Long.toHexString(octets[i])).append(":"); } else { sb.append(Long.toString(octets[i])).append("."); } } } i = sb.length(); sb.replace(i - 1, i, "]"); return sb; }
From source file:org.jahia.services.render.filter.URLFilter.java
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain) throws Exception { if (handlers != null && handlers.length > 0) { final String thisuuid = StringUtils.leftPad(Integer.toHexString(resource.hashCode()), 8, "0"); Map<String, String> alreadyParsedFragmentsMap = new HashMap<>(); StringBuilder sb = null; int i;//from w w w. j a v a 2s.com if (previousOut.indexOf(TEMP_START_TAG) > -1) { sb = new StringBuilder(previousOut); // store all the already processed url traverse while ((i = sb.indexOf(TEMP_START_TAG)) > -1) { String uuid = sb.substring(i + TEMP_START_TAG.length(), i + TEMP_START_TAG.length() + 8); final String endTag = TEMP_END_TAG + uuid + TEMP_CLOSING; int j = sb.indexOf(endTag); alreadyParsedFragmentsMap.put(uuid, sb.substring(i + TEMP_FULL_START_TAG.length(), j)); sb.delete(i, j + endTag.length()); sb.insert(i, "\"/>").insert(i, uuid).insert(i, REPLACED_START_TAG); } } // traverse the fragment and wrap it with a temp tag sb = new StringBuilder(urlTraverser.traverse(sb == null ? previousOut : sb.toString(), renderContext, resource, handlers)); sb.insert(0, TEMP_CLOSING).insert(0, thisuuid).insert(0, TEMP_START_TAG); sb.append(TEMP_END_TAG).append(thisuuid).append(TEMP_CLOSING); // replace all the previous stored fragments while ((i = sb.indexOf(REPLACED_START_TAG)) > -1) { String uuid = sb.substring(i + REPLACED_START_TAG.length(), i + REPLACED_START_TAG.length() + 8); sb.replace(i, i + REPLACED_START_TAG.length() + 8 + 3, alreadyParsedFragmentsMap.get(uuid)); } return sb.toString(); } return previousOut; }