List of usage examples for java.util.regex Matcher quoteReplacement
public static String quoteReplacement(String s)
From source file:org.entando.edo.builder.TestBuilder.java
@Test public void test_TestResources() throws IOException { String commonPath = "src/test/resources".replaceAll("/", Matcher.quoteReplacement(File.separator)); String actualPath = ACTUAL_BASE_FOLDER + commonPath; File actualDir = new File(actualPath); Assert.assertTrue(actualDir.exists()); List<File> actualFiles = this.searchFiles(actualDir, null); Assert.assertEquals(2, actualFiles.size()); this.compareFiles(actualFiles); }
From source file:net.dv8tion.jda.core.entities.impl.ReceivedMessage.java
@Override public String getContentDisplay() { if (altContent != null) return altContent; synchronized (mutex) { if (altContent != null) return altContent; String tmp = content;/*w w w .ja va 2s. co m*/ for (User user : getMentionedUsers()) { String name; if (isFromType(ChannelType.TEXT) && getGuild().isMember(user)) name = getGuild().getMember(user).getEffectiveName(); else name = user.getName(); tmp = tmp.replaceAll("<@!?" + Pattern.quote(user.getId()) + '>', '@' + Matcher.quoteReplacement(name)); } for (Emote emote : getEmotes()) { tmp = tmp.replace(emote.getAsMention(), ":" + emote.getName() + ":"); } for (TextChannel mentionedChannel : getMentionedChannels()) { tmp = tmp.replace(mentionedChannel.getAsMention(), '#' + mentionedChannel.getName()); } for (Role mentionedRole : getMentionedRoles()) { tmp = tmp.replace(mentionedRole.getAsMention(), '@' + mentionedRole.getName()); } return altContent = tmp; } }
From source file:com.mediaworx.opencms.moduleutils.manifestgenerator.OpenCmsModuleManifestGenerator.java
/** * Generates the manifest.xml for OpenCms modules from meta files (manifest_stub.xml and separate meta files for all * files and folders in the VFS).//w w w . j a v a2 s .c o m * @param manifestRoot file representing the root folder of the manifest meta data (including manifest_stub.xml) * * @throws OpenCmsMetaXmlParseException if the XmlHelper can not be initialized or the manifest stub file or any * meta file can not be read or parsed * @throws OpenCmsMetaXmlFileWriteException if the resulting manifest file can not be written */ public void generateManifest(File manifestRoot) throws OpenCmsMetaXmlParseException, OpenCmsMetaXmlFileWriteException { manifestRootPath = manifestRoot.getPath(); handledSiblingResourceIds = new HashSet<String>(); String manifestStubPath = manifestRoot.getPath() + File.separator + FILENAME_MANIFEST_STUB; String manifestPath = manifestRoot.getPath() + File.separator + FILENAME_MANIFEST; LOG.info("manifestStubPath: {}", manifestStubPath); Node filesNode; Document manifest; try { xmlHelper = new XmlHelper(); Map<String, String> replacements = null; if (replaceMetaVariables) { replacements = new HashMap<String, String>(); replacements.put(META_VAR_CREATEDATE, formatDate((new Date()).getTime())); } manifest = xmlHelper.parseFile(manifestStubPath, replacements); filesNode = xmlHelper.getSingleNodeForXPath(manifest, FILES_NODE_XPATH); } catch (ParserConfigurationException e) { throw new OpenCmsMetaXmlParseException("The XmlHelper could not be initialized", e); } catch (IOException e) { throw new OpenCmsMetaXmlParseException("The manifest stub file could not be read", e); } catch (SAXException e) { throw new OpenCmsMetaXmlParseException("The manifest stub xml could not be parsed (parse error)", e); } catch (XPathExpressionException e) { throw new OpenCmsMetaXmlParseException("The manifest stub xml could not be parsed (xpath error)", e); } // Regular Expression matching anything but Strings ending with the VFS folder meta file suffix (".ocmsfolder.xml") String excludeFolderMetaRegex = "^(?:(?!" + Pattern.quote(FOLDER_META_SUFFIX) + "$).)*$"; // FileFilter filtering all VFS folder meta files (so only VFS file meta files and folders are included) IOFileFilter excludeFolderMetaFilter = new RegexFileFilter(excludeFolderMetaRegex); // read all files and folders excluding VFS folder meta files Collection<File> files = FileUtils.listFilesAndDirs(manifestRoot, excludeFolderMetaFilter, TrueFileFilter.INSTANCE); for (File file : files) { if (file.isDirectory()) { // exclude the manifest root if (file.getPath().equals(manifestRoot.getPath())) { continue; } addFolderToFilesNode(filesNode, file); } else { // exclude the manifest stub file and the manifest file if (file.getPath().equals(manifestPath) || file.getPath().equals(manifestStubPath)) { continue; } addFileToFilesNode(filesNode, file); } } // render the xml string String manifestString = xmlHelper.getXmlStringFromDocument(manifest, CDATA_NODES); // if a specific version is provided, replace the original version if (StringUtils.isNotBlank(moduleVersion)) { manifestString = manifestString.replaceFirst("<version>[^<]*</version>", "<version>" + Matcher.quoteReplacement(moduleVersion) + "</version>"); } // write the manifest to the disk try { writeManifest(manifestPath, manifestString); } catch (IOException e) { throw new OpenCmsMetaXmlFileWriteException("manifest.xml could not be written", e); } }
From source file:org.etudes.util.XrefHelper.java
/** * Replace any embedded references in the html data with the translated, new references listed in translations. * /* w w w . ja v a 2 s . c o m*/ * @param data * the html data. * @param translations * The translations. * @param siteId * The site id. * @param parentRef * Reference of the resource that has data as body. * @return The translated html data. */ @SuppressWarnings("unchecked") public static String translateEmbeddedReferences(String data, Collection<Translation> translations, String siteId, String parentRef) { if (data == null) return data; if (translations == null) return data; // get our thread-local list of translations made in this thread (if any) List<Translation> threadTranslations = (List<Translation>) ThreadLocalManager.get(THREAD_TRANSLATIONS_KEY); Pattern p = getPattern(); Matcher m = p.matcher(data); StringBuffer sb = new StringBuffer(); // process each "harvested" string (avoiding like strings that are not in src= or href= patterns) while (m.find()) { if (m.groupCount() == 3) { String ref = m.group(2); String terminator = m.group(3); if (ref != null) ref = ref.trim(); // expand to a full reference if relative ref = adjustRelativeReference(ref, parentRef); // harvest any content hosting reference int index = indexContentReference(ref); if (index != -1) { // except those we don't want to harvest if (exception(ref, siteId)) index = -1; } if (index != -1) { // save just the reference part (i.e. after the /access); String normal = ref.substring(index + 7); // deal with %20, &, and other encoded URL stuff normal = decodeUrl(normal); // translate the normal form String translated = normal; for (Translation translation : translations) { translated = translation.translate(translated); } // also translate with our global list if (threadTranslations != null) { for (Translation translation : threadTranslations) { translated = translation.translate(translated); } } // URL encode translated String escaped = escapeUrl(translated); // if changed, replace if (!normal.equals(translated)) { m.appendReplacement(sb, Matcher.quoteReplacement( m.group(1) + "=\"" + ref.substring(0, index + 7) + escaped + terminator)); } } } } m.appendTail(sb); return sb.toString(); }
From source file:org.kuali.rice.core.impl.config.property.JAXBConfigImpl.java
/** * This method parses the value string to find all nested properties (foo=${nested}) and * replaces them with the value returned from calling resolve(). It does this in a new string * and does not modify the raw or resolved properties objects. * /*from w ww . j a va 2 s.c o m*/ * @param value the string to search for nest properties * @param keySet contains all keys used so far in this recursion. used to check for circular * references. * @return */ protected String parseValue(String value, Set<String> keySet) { String result = value; Matcher matcher = pattern.matcher(value); while (matcher.find()) { // get the first, outermost ${} in the string. removes the ${} as well. String key = matcher.group(1); String resolved = resolve(key, keySet); result = matcher.replaceFirst(Matcher.quoteReplacement(resolved)); matcher = matcher.reset(result); } return result; }
From source file:fr.paris.lutece.plugins.search.solr.business.SolrSearchEngine.java
/** * @param strValues//from w w w. j a va 2 s.co m * @param strStart * @param strEnd * @return */ private String extractQuery(List<String> strValues, String strOperator) { String strFacetString = ""; String strStart = strValues.size() > 1 ? "(" : ""; String strEnd = strValues.size() > 1 ? ")" : ""; for (String strTmpSearch : strValues) { if (!StringUtils.isBlank(strTmpSearch)) { strTmpSearch = "\"" + strTmpSearch.replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\""; if (SOLR_SPELLFIELD_OR.equalsIgnoreCase(strOperator) || SOLR_SPELLFIELD_AND.equalsIgnoreCase(strOperator)) strFacetString += StringUtils.isBlank(strFacetString) ? strTmpSearch.trim() : " " + strOperator + " " + strTmpSearch.trim(); if (SOLR_SPELLFIELD_SWITCH.equalsIgnoreCase(strOperator)) strFacetString = strTmpSearch.trim(); } } strFacetString = strStart.concat(strFacetString).concat(strEnd); return strFacetString; }
From source file:com.hexidec.ekit.component.HTMLUtilities.java
private static String converteBlocosEmParagrafos(String str) { Matcher m = pBlocos.matcher(str); if (!m.find()) { return str; }/*from w w w .ja va2 s . c o m*/ StringBuffer sb = new StringBuffer(); String antes, depois; do { antes = m.group(1); depois = m.group(2); m.appendReplacement(sb, Matcher.quoteReplacement(antes + "p" + depois)); } while (m.find()); m.appendTail(sb); return sb.toString(); }
From source file:io.github.swagger2markup.markup.builder.internal.AbstractMarkupDocBuilder.java
protected void importMarkupStyle2(Pattern titlePattern, String titleFormat, boolean startFrom0, Reader markupText, MarkupLanguage markupLanguage, int levelOffset) { Validate.isTrue(levelOffset <= MAX_TITLE_LEVEL, String.format("Specified levelOffset (%d) > max levelOffset (%d)", levelOffset, MAX_TITLE_LEVEL)); Validate.isTrue(levelOffset >= -MAX_TITLE_LEVEL, String.format("Specified levelOffset (%d) < min levelOffset (%d)", levelOffset, -MAX_TITLE_LEVEL)); StringBuffer leveledText = new StringBuffer(); try (BufferedReader bufferedReader = new BufferedReader(markupText)) { String readLine;//from w w w . ja v a 2s . co m while ((readLine = bufferedReader.readLine()) != null) { Matcher titleMatcher = titlePattern.matcher(readLine); while (titleMatcher.find()) { int titleLevel = Integer.valueOf(titleMatcher.group(1)) - (startFrom0 ? 0 : 1); String title = titleMatcher.group(2); if (titleLevel + levelOffset > MAX_TITLE_LEVEL) throw new IllegalArgumentException(String.format( "Specified levelOffset (%d) set title '%s' level (%d) > max title level (%d)", levelOffset, title, titleLevel, MAX_TITLE_LEVEL)); if (titleLevel + levelOffset < 0) throw new IllegalArgumentException( String.format("Specified levelOffset (%d) set title '%s' level (%d) < 0", levelOffset, title, titleLevel)); else titleMatcher.appendReplacement(leveledText, Matcher.quoteReplacement(String .format(titleFormat, (startFrom0 ? 0 : 1) + titleLevel + levelOffset, title))); } titleMatcher.appendTail(leveledText); leveledText.append(newLine); } } catch (IOException e) { throw new RuntimeException("Failed to import Markup", e); } if (!StringUtils.isBlank(leveledText)) { documentBuilder.append(newLine); documentBuilder.append(convert(leveledText.toString(), markupLanguage)); documentBuilder.append(newLine); } }
From source file:org.grails.web.mapping.RegexUrlMapping.java
@SuppressWarnings({ "unchecked" }) private String createURLInternal(Map paramValues, String encoding, boolean includeContextPath) { if (encoding == null) encoding = "utf-8"; String contextPath = ""; if (includeContextPath) { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes(); if (webRequest != null) { contextPath = webRequest.getAttributes().getApplicationUri(webRequest.getCurrentRequest()); }/*from w ww.j a va 2s . c o m*/ } if (paramValues == null) paramValues = Collections.emptyMap(); StringBuilder uri = new StringBuilder(contextPath); Set usedParams = new HashSet(); String[] tokens = urlData.getTokens(); int paramIndex = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (i == tokens.length - 1 && urlData.hasOptionalExtension()) { token += OPTIONAL_EXTENSION_WILDCARD; } Matcher m = OPTIONAL_EXTENSION_WILDCARD_PATTERN.matcher(token); if (m.find()) { boolean tokenSet = false; if (token.startsWith(CAPTURED_WILDCARD)) { ConstrainedProperty prop = constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = paramValues.get(propName); usedParams.add(propName); if (value != null) { token = token.replaceFirst(DOUBLE_WILDCARD_PATTERN.pattern(), value.toString()); tokenSet = true; } else { token = token.replaceFirst(DOUBLE_WILDCARD_PATTERN.pattern(), ""); } } else { tokenSet = true; } if (tokenSet) { uri.append(SLASH); } ConstrainedProperty prop = constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = paramValues.get(propName); usedParams.add(propName); if (value != null) { String ext = "." + value; uri.append(token.replace(OPTIONAL_EXTENSION_WILDCARD + '?', ext) .replace(OPTIONAL_EXTENSION_WILDCARD, ext)); } else { uri.append(token.replace(OPTIONAL_EXTENSION_WILDCARD + '?', "") .replace(OPTIONAL_EXTENSION_WILDCARD, "")); } continue; } if (token.endsWith("?")) { token = token.substring(0, token.length() - 1); } m = DOUBLE_WILDCARD_PATTERN.matcher(token); if (m.find()) { StringBuffer buf = new StringBuffer(); do { ConstrainedProperty prop = constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = paramValues.get(propName); usedParams.add(propName); if (value == null && !prop.isNullable()) { throw new UrlMappingException("Unable to create URL for mapping [" + this + "] and parameters [" + paramValues + "]. Parameter [" + prop.getPropertyName() + "] is required, but was not specified!"); } else if (value == null) { m.appendReplacement(buf, ""); } else { m.appendReplacement(buf, Matcher.quoteReplacement(value.toString())); } } while (m.find()); m.appendTail(buf); try { String v = buf.toString(); if (v.indexOf(SLASH) > -1 && CAPTURED_DOUBLE_WILDCARD.equals(token)) { // individually URL encode path segments if (v.startsWith(SLASH)) { // get rid of leading slash v = v.substring(SLASH.length()); } String[] segs = v.split(SLASH); for (String segment : segs) { uri.append(SLASH).append(encode(segment, encoding)); } } else if (v.length() > 0) { // original behavior uri.append(SLASH).append(encode(v, encoding)); } else { // Stop processing tokens once we hit an empty one. break; } } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException("Error creating URL for parameters [" + paramValues + "], problem encoding URL part [" + buf + "]: " + e.getMessage(), e); } } else { uri.append(SLASH).append(token); } } populateParameterList(paramValues, encoding, uri, usedParams); if (LOG.isDebugEnabled()) { LOG.debug("Created reverse URL mapping [" + uri.toString() + "] for parameters [" + paramValues + "]"); } return uri.toString(); }
From source file:net.sf.jasperreports.functions.standard.TextFunctions.java
public static String SUBSTITUTE(String originalText, String oldText, String newText, Integer occurrenceNum) { if (originalText == null || oldText == null || newText == null) { logHavingNullArguments();//w w w . j a v a 2 s .c o m return null; } else if (occurrenceNum == null) { // Replace all occurrences return originalText.replaceAll(Pattern.quote(oldText), Matcher.quoteReplacement(newText)); } else { int startIdx = 0; int counter = 1; // Find the right occurrence while (startIdx < originalText.length() - 1) { // Locate the next index position of the occurrence of the old text int foundPosition = originalText.indexOf(oldText, startIdx); if (counter == occurrenceNum) { return REPLACE(originalText, foundPosition + 1, oldText.length(), newText); } else { startIdx = foundPosition + oldText.length(); counter++; } } // Fall-back return null; } }