List of usage examples for java.util.regex Matcher appendReplacement
public Matcher appendReplacement(StringBuilder sb, String replacement)
From source file:org.opennms.netmgt.dao.support.DefaultResourceDao.java
/** * Fetch a specific resource by string ID. * * @return Resource or null if resource cannot be found. * @throws IllegalArgumentException When the resource ID string does not match the expected regex pattern * @throws ObjectRetrievalFailureException If any exceptions are thrown while searching for the resource *///ww w . j a v a2 s . c o m @Override @Transactional(readOnly = true) public OnmsResource getResourceById(String id) { OnmsResource resource = null; Matcher m = RESOURCE_ID_PATTERN.matcher(id); StringBuffer sb = new StringBuffer(); while (m.find()) { String resourceTypeName = DefaultResourceDao.decode(m.group(1)); String resourceName = DefaultResourceDao.decode(m.group(2)); try { resource = getChildResource(resource, resourceTypeName, resourceName); } catch (Throwable e) { LOG.warn("Could not get resource for resource ID \"{}\"", id, e); return null; } m.appendReplacement(sb, ""); } m.appendTail(sb); if (sb.length() > 0) { LOG.warn("Resource ID '{}' does not match pattern '{}' at '{}'", id, RESOURCE_ID_PATTERN, sb); return null; } else { return resource; } }
From source file:org.glowroot.central.SyntheticMonitorService.java
@Instrumentation.Transaction(transactionType = "Background", transactionName = "Synthetic monitor", traceHeadline = "Synthetic monitor: {{0.id}}", timer = "synthetic monitor") private void runJava(AgentRollup agentRollup, SyntheticMonitorConfig syntheticMonitorConfig, List<AlertConfig> alertConfigs) throws Exception { Matcher matcher = encryptedPattern.matcher(syntheticMonitorConfig.getJavaSource()); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String encryptedPassword = checkNotNull(matcher.group(1)); matcher.appendReplacement(sb, "\"" + Encryption.decrypt(encryptedPassword, configRepository.getLazySecretKey()) + "\""); }// ww w . j av a2s . co m matcher.appendTail(sb); runSyntheticMonitor(agentRollup, syntheticMonitorConfig, alertConfigs, () -> runJava(sb.toString())); }
From source file:com.ibm.jaggr.core.impl.modulebuilder.css.CSSModuleBuilder.java
/** * Returns a regular expression for a filepath that can include standard * file system wildcard characters (e.g. * and ?) * * @param filespec A filespec that can contain wildcards * @return A regular expression to match paths specified by <code>filespec</code> *//* w w w. j a v a 2s .c o m*/ protected Pattern toRegexp(String filespec) { Matcher m = escaper.matcher(filespec); StringBuffer sb = new StringBuffer(); while (m.find()) { String matched = m.group(0); if (matched.equals("*")) { //$NON-NLS-1$ m.appendReplacement(sb, "\\[^/]*?"); //$NON-NLS-1$ } else if (matched.equals("?")) { //$NON-NLS-1$ m.appendReplacement(sb, "[^/]"); //$NON-NLS-1$ } else if (matched.equals("$")) { //$NON-NLS-1$ m.appendReplacement(sb, "\\\\\\$"); //$NON-NLS-1$ } else if (matched.equals("\\")) { //$NON-NLS-1$ m.appendReplacement(sb, "\\\\\\\\"); //$NON-NLS-1$ } else { m.appendReplacement(sb, "\\\\" + matched); //$NON-NLS-1$ } } m.appendTail(sb); String patStr = sb.toString(); return Pattern.compile((patStr.startsWith("/") ? "" : "(^|/)") + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ patStr + "$", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$ }
From source file:org.omnaest.utils.beans.adapter.source.SourcePropertyAccessorDecoratorPropertyNameTemplate.java
private static String[] processPropertyNameWithTemplate(String propertyName, PropertyMetaInformation propertyMetaInformation) { ///*from w ww .j av a2 s. com*/ String[] retval = new String[] { propertyName }; if (propertyMetaInformation != null) { // PropertyNameTemplate propertyNameTemplate = propertyMetaInformation .getPropertyAnnotationAutowiredContainer().getValue(PropertyNameTemplate.class); if (propertyNameTemplate == null) { propertyNameTemplate = propertyMetaInformation.getClassAnnotationAutowiredContainer() .getValue(PropertyNameTemplate.class); } // if (propertyNameTemplate != null) { // final Class<? extends ElementConverter<?, String>>[] additionalArgumentConverterTypes = propertyNameTemplate .additionalArgumentConverterTypes(); final String primaryTemplate = propertyNameTemplate.value(); final String[] alternativeTemplateValues = propertyNameTemplate.alternativeValues(); final String[] templates = ArrayUtils.add(alternativeTemplateValues, 0, primaryTemplate); if (primaryTemplate != null) { retval = new String[0]; } for (String template : templates) { if (template != null) { // final String TAG_PROPERTYNAME = "\\{(?iu)propertyname(?-iu)\\}"; final String TAG_PARAMETER = "\\{(\\d)\\}"; Assert.isTrue( Pattern.matches("(" + TAG_PROPERTYNAME + "|" + TAG_PARAMETER + "|[^\\{\\}])+", template), "PropertyNameTemplate of property " + propertyName + " has an invalid format."); // String templateWithValues = template.replaceAll(TAG_PROPERTYNAME, propertyName); // StringBuffer stringBuffer = new StringBuffer(); Matcher matcher = Pattern.compile(TAG_PARAMETER).matcher(templateWithValues); while (matcher.find()) { // String group = matcher.group(1); // Assert.isTrue(StringUtils.isNumeric(group), "Parameter index position within PropertyNameTemplate of property " + propertyName + " has to be a valid number. Found: " + group); int additionalArgumentIndexPosition = Integer.valueOf(group); // Object[] additionalArguments = propertyMetaInformation.getAdditionalArguments(); int parameterIndexPositionMax = additionalArguments.length - 1; Assert.isTrue( additionalArgumentIndexPosition >= 0 && additionalArgumentIndexPosition <= parameterIndexPositionMax, "Parameter index position within PropertyNameTemplate of property " + propertyName + " has to be between 0 and " + parameterIndexPositionMax); // final Object additionalArgument = determineAdditionalArgument( additionalArgumentConverterTypes, additionalArgumentIndexPosition, additionalArguments); final String additionalArgumentString = String.valueOf(additionalArgument); matcher.appendReplacement(stringBuffer, additionalArgumentString); } matcher.appendTail(stringBuffer); // retval = ArrayUtils.add(retval, stringBuffer.toString()); } } } } return retval; }
From source file:org.gephi.ui.components.ReportSelection.java
private boolean saveReport(String html, File destinationFolder) throws IOException { if (!destinationFolder.exists()) { destinationFolder.mkdir();//from w ww . ja va 2 s . com } else { if (!destinationFolder.isDirectory()) { return false; } } //Find images location String imgRegex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>"; Pattern pattern = Pattern.compile(imgRegex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(html); StringBuffer replaceBuffer = new StringBuffer(); while (matcher.find()) { String fileAbsolutePath = matcher.group(1); if (fileAbsolutePath.startsWith("file:")) { fileAbsolutePath = fileAbsolutePath.replaceFirst("file:", ""); } File file = new File(fileAbsolutePath); if (file.exists()) { copy(file, destinationFolder); } //Replace temp path matcher.appendReplacement(replaceBuffer, "<IMG SRC=\"" + file.getName() + "\">"); } matcher.appendTail(replaceBuffer); //Write HTML file File htmlFile = new File(destinationFolder, "report.html"); FileOutputStream outputStream = new FileOutputStream(htmlFile); OutputStreamWriter out = new OutputStreamWriter(outputStream, "UTF-8"); out.append(replaceBuffer.toString()); out.flush(); out.close(); outputStream.close(); return true; }
From source file:org.kuali.rice.krad.theme.postprocessor.ThemeCssFilesProcessor.java
/** * Performs URL rewriting within the given CSS contents * * <p>// w w w .j a v a 2 s .c om * The given merge file (where the merge contents come from) and the merged file (where they are going to) * is used to determine the path difference. Once that path difference is found, the contents are then matched * to find any URLs. For each relative URL (absolute URLs are not modified), the path is adjusted and * replaced into the contents. * * ex. suppose the merged file is /plugins/foo/plugin.css, and the merged file is * /themes/mytheme/stylesheets/merged.css, the path difference will then be '../../../plugins/foo/'. So a URL * in the CSS contents of 'images/image.png' will get rewritten to '../../../plugins/foo/images/image.png' * </p> * * @param css contents to adjust URLs for * @param mergeFile file that provided the merge contents * @param mergedFile file the contents will be going to * @return css contents, with possible adjusted URLs * @throws IOException */ protected String rewriteCssUrls(String css, File mergeFile, File mergedFile) throws IOException { String urlAdjustment = ThemeBuilderUtils.calculatePathToFile(mergedFile, mergeFile); if (StringUtils.isBlank(urlAdjustment)) { // no adjustment needed return css; } // match all URLs in css string and then adjust each one Pattern urlPattern = Pattern.compile(ThemeBuilderConstants.Patterns.CSS_URL_PATTERN); Matcher matcher = urlPattern.matcher(css); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String cssStatement = matcher.group(); String cssUrl = null; if (matcher.group(1) != null) { cssUrl = matcher.group(1); } else { cssUrl = matcher.group(2); } if (cssUrl != null) { // only adjust URL if it is relative String modifiedUrl = cssUrl; if (!cssUrl.startsWith("/")) { modifiedUrl = urlAdjustment + cssUrl; } String modifiedStatement = Matcher.quoteReplacement(cssStatement.replace(cssUrl, modifiedUrl)); matcher.appendReplacement(sb, modifiedStatement); } } matcher.appendTail(sb); return sb.toString(); }
From source file:org.pentaho.osgi.platform.webjars.utils.RequireJsGenerator.java
private void requirejsFromJs(String moduleName, String moduleVersion, String jsScript) throws IOException, ScriptException, NoSuchMethodException, ParseException { moduleInfo = new ModuleInfo(moduleName, moduleVersion); Pattern pat = Pattern.compile("webjars!(.*).js"); Matcher m = pat.matcher(jsScript); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group(1)); }/*w ww . j a va 2 s.c o m*/ m.appendTail(sb); jsScript = sb.toString(); sb = new StringBuffer(); pat = Pattern.compile("webjars\\.path\\(['\"]{1}(.*)['\"]{1}, (['\"]{0,1}[^\\)]+['\"]{0,1})\\)"); m = pat.matcher(jsScript); while (m.find()) { m.appendReplacement(sb, m.group(2)); } m.appendTail(sb); jsScript = sb.toString(); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); String script = IOUtils.toString( getClass().getResourceAsStream("/org/pentaho/osgi/platform/webjars/require-js-aggregator.js")); script = script.replace("{{EXTERNAL_CONFIG}}", jsScript); engine.eval(script); requireConfig = (Map<String, Object>) parser .parse(((Invocable) engine).invokeFunction("processConfig", "").toString()); }
From source file:org.apache.roller.weblogger.business.plugins.entry.BookmarkPlugin.java
private String matchBookmarks(String text, WeblogBookmarkFolder folder) { Iterator bookmarks = folder.getBookmarks().iterator(); String workingText = text;/* www . java2 s . c o m*/ while (bookmarks.hasNext()) { WeblogBookmark bookmark = (WeblogBookmark) bookmarks.next(); String bkDescription = bookmark.getDescription(); if (bkDescription == null) bkDescription = ""; String bookmarkLink = "<a href=\"" + bookmark.getUrl() + "\" title=\"" + bkDescription + "\">" + bookmark.getName() + "</a>"; try { // Replace all occurrences of bookmark name that don't occur within the bounds of an anchor tag // Notes: // - use reluctant quantifiers on the tags to avoid gobbling more than desired // - use non-capturing groups for boundaries to avoid replacing the boundary as well as the bookmark name. // - we depend on the numbering of the specific groups in this expression in the replacement code below. // TODO: should escape the bookmark name String regEx = "(<a(?:\\s.*?)??/>)|(<a(?:\\s.*?)??>)|(</a(?:\\s.*?)??>)|(?:\\b)(" + bookmark.getName() + ")(?:\\b)"; Matcher m = Pattern.compile(regEx).matcher(workingText); StringBuffer textBuf = new StringBuffer(workingText.length()); int inLink = 0; while (m.find()) { if (m.group(1) != null) { // self-closed anchor tag <a ... /> -- ignore } else if (m.group(2) != null) { // matched opening anchor tag <a ...> inLink++; } else if (m.group(3) != null) { // closing anchor tag </a>, but ignore nonmatching ones if (inLink > 0) inLink--; } else if (m.group(4) != null) { // matched the bookmark -- replace, but only if not within a link tag. if (inLink == 0) m.appendReplacement(textBuf, bookmarkLink); } // Any remaining case indicates a bug. One could add an else with assertion here. Conservatively don't substitute. } m.appendTail(textBuf); workingText = textBuf.toString(); } catch (PatternSyntaxException e) { // Can happen since we don't escape pattern the bookmark name to protect pattern characters. mLogger.warn("Failed to substitute for bookmark [" + bookmark.getName() + "] due to regular expression characters."); } } return workingText.toString(); }
From source file:com.gewara.util.XSSFilter.java
protected String validateEntities(String s) { // validate entities throughout the string Pattern p = Pattern.compile("&([^&;]*)(?=(;|&|$))"); Matcher m = p.matcher(s); if (m.find()) { String one = m.group(1); // ([^&;]*) String two = m.group(2); // (?=(;|&|$)) s = checkEntity(one, two);// w w w. j a va2 s . c o m } // validate quotes outside of tags p = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL); m = p.matcher(s); StringBuffer buf = new StringBuffer(); if (m.find()) { String one = m.group(1); // (>|^) String two = m.group(2); // ([^<]+?) String three = m.group(3); // (<|$) m.appendReplacement(buf, one + two.replaceAll("\"", """) + three); } m.appendTail(buf); return s; }
From source file:org.b3log.symphony.service.ShortLinkQueryService.java
/** * Processes tag short link (tag id)./* w w w .ja va 2s . c o m*/ * * @param content the specified content * @return processed content */ public String linkTag(final String content) { final Matcher matcher = TAG_TITLE_PATTERN.matcher(content); final StringBuffer contentBuilder = new StringBuffer(); try { while (matcher.find()) { final String linkTagTitle = StringUtils.substringBetween(matcher.group(), "[", "]"); final Query query = new Query().addProjection(Tag.TAG_TITLE, String.class) .setFilter(new PropertyFilter(Tag.TAG_TITLE, FilterOperator.EQUAL, linkTagTitle)); final JSONArray results = tagRepository.get(query).optJSONArray(Keys.RESULTS); if (0 == results.length()) { continue; } final JSONObject linkTag = results.optJSONObject(0); final String linkTitle = linkTag.optString(Tag.TAG_TITLE); final String link = " [" + linkTitle + "](" + Latkes.getServePath() + "/tags/" + linkTitle + ") "; matcher.appendReplacement(contentBuilder, link); } matcher.appendTail(contentBuilder); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Generates tag link error", e); } return contentBuilder.toString(); }