List of usage examples for java.util.regex Matcher appendTail
public StringBuilder appendTail(StringBuilder sb)
From source file:org.kuali.rice.krad.theme.postprocessor.ThemeCssFilesProcessor.java
/** * Performs URL rewriting within the given CSS contents * * <p>// w w w.ja v a 2 s . c o m * 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.gephi.ui.components.ReportSelection.java
private boolean saveReport(String html, File destinationFolder) throws IOException { if (!destinationFolder.exists()) { destinationFolder.mkdir();/*from w ww .j ava 2s .c o m*/ } 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.cesecore.certificates.ocsp.logging.PatternLogger.java
/** * //ww w . ja v a 2 s .co m * @return output to be logged */ private String interpolate() { final StringBuffer sb = new StringBuffer(this.orderString.length()); final Matcher matcher = getMatcher(); matcher.reset(); while (matcher.find()) { // when the pattern is ${identifier}, group 0 is 'identifier' final String key = matcher.group(1); final String value = this.valuepairs.get(key); // if the pattern does exists, replace it by its value // otherwise keep the pattern ( it is group(0) ) if (value != null) { matcher.appendReplacement(sb, value); } else { // I'm doing this to avoid the backreference problem as there will be a $ // if I replace directly with the group 0 (which is also a pattern) matcher.appendReplacement(sb, ""); final String unknown = matcher.group(0); sb.append(unknown); } } matcher.appendTail(sb); return sb.toString(); }
From source file:net.canarymod.util.SysOutWriterThread.java
private String replaceColours(String toProcess) throws IOException { if (!reader.getTerminal().isAnsiSupported()) { return TextFormat.removeFormatting(toProcess); } else {/*ww w . j a v a 2s. c om*/ Matcher matcher = colourPattern.matcher(toProcess); boolean result = matcher.find(); if (result) { StringBuffer sb = new StringBuffer(); do { String match = matcher.group(); String replacement = ""; if (colourMap.containsKey(match)) { Ansi replace = Ansi.ansi().reset(); replace = colourMap.get(match).getRight() ? replace.fgBright(colourMap.get(match).getLeft()) : replace.fg(colourMap.get(match).getLeft()); replacement = replace.toString(); } else if (attributeMap.containsKey(match)) { replacement = Ansi.ansi().a(attributeMap.get(match)).toString(); } matcher.appendReplacement(sb, replacement); result = matcher.find(); } while (result); matcher.appendTail(sb); sb.append(Ansi.ansi().reset()); return sb.toString(); } return toProcess; } }
From source file:org.signserver.module.pdfsigner.PDFSigner.java
/** * Helper method for formatting a text given a set of fields and a date. * * Sample://w ww. j a v a 2 s . c o m * "${WORKERID}-${REQUESTID}_${DATE:yyyy-MM-dd}.pdf" * Could be: * "42-123123123_2010-04-28.pdf" * * @param pattern Pre-compiled pattern to use for parsing * @param text The text that contains keys to be replaced with values * @param date The date to use if date should be inserted * @param fields Keys and their values that should be used if they exist in * the text. * @return The test with keys replaced with values from fields or by * formatted date * @see java.text.SimpleDateFormat */ static String formatFromPattern(final Pattern pattern, final String text, final Date date, final Map<String, String> fields) { final String result; if (LOG.isDebugEnabled()) { LOG.debug("Input string: " + text); } final StringBuffer sb = new StringBuffer(); Matcher m = pattern.matcher(text); while (m.find()) { // when the pattern is ${identifier}, group 0 is 'identifier' final String key = m.group(1); final String value; if (key.startsWith("DATE:")) { final SimpleDateFormat sdf = new SimpleDateFormat(key.substring("DATE:".length()).trim()); value = sdf.format(date); } else { value = fields.get(key); } // if the pattern does exists, replace it by its value // otherwise keep the pattern ( it is group(0) ) if (value != null) { m.appendReplacement(sb, value); } else { // I'm doing this to avoid the backreference problem as there will be a $ // if I replace directly with the group 0 (which is also a pattern) m.appendReplacement(sb, ""); final String unknown = m.group(0); sb.append(unknown); } } m.appendTail(sb); result = sb.toString(); if (LOG.isDebugEnabled()) { LOG.debug("Result: " + result); } return result; }
From source file:org.omnaest.utils.beans.adapter.source.SourcePropertyAccessorDecoratorPropertyNameTemplate.java
private static String[] processPropertyNameWithTemplate(String propertyName, PropertyMetaInformation propertyMetaInformation) { //// w w w . jav a 2s .c o m 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:com.norconex.commons.lang.url.URLNormalizer.java
/** * Decodes percent-encoded unreserved characters.<p> * <code>http://www.example.com/%7Eusername/ → * http://www.example.com/~username/</code> * @return this instance/*from w w w . java 2 s . c om*/ */ public URLNormalizer decodeUnreservedCharacters() { if (url.contains("%")) { StringBuffer sb = new StringBuffer(); Matcher m = PATTERN_PERCENT_ENCODED_CHAR.matcher(url); try { while (m.find()) { String enc = m.group(1).toUpperCase(); if (isEncodedUnreservedCharacter(enc)) { m.appendReplacement(sb, URLDecoder.decode(enc, CharEncoding.UTF_8)); } } } catch (UnsupportedEncodingException e) { LOG.debug("UTF-8 is not supported by your system. " + "URL will remain unchanged:" + url, e); } url = m.appendTail(sb).toString(); } return this; }
From source file:mergedoc.core.JavaBuffer.java
/** * ?????????//from w w w . j av a2s.c o m * @return ?????????? null */ public Signature getSignature() { int commentEndPos = commentMatcher.end(); String commentEndToEOF = source.substring(commentEndPos, source.length()); // ?????????? Matcher matcher = PatternCache.getPattern("(?s)/\\*(.*?)\\*/").matcher(commentEndToEOF); StringBuffer sb = new StringBuffer(commentEndToEOF.length()); while (matcher.find()) { matcher.appendReplacement(sb, "/*"); char[] cs = matcher.group(1).toCharArray(); for (char c : cs) { switch (c) { case '*': case '\n': sb.append(c); break; default: sb.append(' '); break; } } sb.append("*/"); } matcher.appendTail(sb); commentEndToEOF = sb.toString(); // ??????????? commentEndToEOF = FastStringUtils.replaceFirst(commentEndToEOF, "(?s)^(\\s*@[\\w]+\\s*\\(.*?\\))*\\s*", ""); Pattern sigPattern = PatternCache.getPattern("(?s)(.+?)(throws|\\{|\\=|;|,\\s*/\\*|\\})"); Matcher sigMatcher = sigPattern.matcher(commentEndToEOF); if (sigMatcher.find()) { // ????? ClassBlock classBlock = classStack.peek(); while (commentEndPos > classBlock.end && classStack.size() > 1) { classStack.pop(); classBlock = classStack.peek(); } // ???Javadoc ????? // ????????? String sigStr = sigMatcher.group(1); sigStr = FastStringUtils.replaceFirst(sigStr, "(?s)/\\*[^\\*].*?\\*/\\s*", ""); if (classKind.equals("@interface")) { sigStr = sigStr.replace("()", ""); } Signature sig = new Signature(classBlock.name, sigStr); // ???? if (sig.isDeclareInnerClass()) { String name = sig.getClassName(); int end = searchEndOfInner(commentEndToEOF, name); classBlock = new ClassBlock(name, end); classStack.push(classBlock); } return sig; } log.warn("Javadoc ?????????????\n" + commentEndToEOF); return null; }
From source file:org.forgerock.openidm.repo.orientdb.impl.query.TokenHandler.java
/** * Replaces a query string with tokens of format ${token-name} with the * token format in OrientDB, which is of the form :token-name. * /* w ww. j av a2 s .c om*/ * OrientDB tokens has some limitations, e.g. they can currently only be used * in the where clause, and hence the returned string is not guaranteed to be * valid for use in a prepared statement. If the parsing fails the system may * have to fall back onto non-prepared statements and manual token replacement. * * @param queryString the query with OpenIDM format tokens ${token} * @return the query with all tokens replaced with the OrientDB style tokens :token * @throws PrepareNotSupported if this method knows a given statement can not be converted into a prepared statement. * That a statement was not rejected here though does not mean it could not fail during the parsing phase later. */ String replaceTokensWithOrientToken(String queryString) throws PrepareNotSupported { Matcher matcher = tokenPattern.matcher(queryString); StringBuffer buf = new StringBuffer(); while (matcher.find()) { String origToken = matcher.group(1); String tokenKey = origToken; String tokenPrefix = null; String[] tokenKeyParts = tokenKey.split(":", 2); // if prefix found if (tokenKeyParts.length == 2) { tokenPrefix = tokenKeyParts[0]; tokenKey = tokenKeyParts[1]; } matcher.appendReplacement(buf, ""); if (tokenPrefix != null && tokenPrefix.equals(PREFIX_DOTNOTATION)) { buf.append(JSON_POINTER_TO_DOT_NOTATION.apply(tokenKey)); } else if (tokenKey != null && tokenKey.length() > 0) { // OrientDB token is of format :token-name String newToken = ":" + tokenKey; buf.append(newToken); } } matcher.appendTail(buf); return buf.toString(); }
From source file:net.sf.jasperreports.engine.export.FlashPrintElement.java
/** * Resolves hyperlink placeholders to URLs in a Flash variable. * /*w w w. j a v a 2 s . com*/ * @param text the text in which hyperlink placeholders are to be replaced * @param element the print element where hyperlink parameters will be looked for * @param linkProducer the hyperlink producer which transforms hyperlink * objects to String URLs * @return the text with hyperlink placeholders replaced by URLs * @see #makeLinkPlaceholder(String) */ public static String resolveLinks(String text, JRGenericPrintElement element, JRHyperlinkProducer linkProducer, boolean prepareForSerialization) { Matcher matcher = LINK_PATTERN.matcher(text); StringBuffer xml = new StringBuffer(); List<HyperlinkData> hyperlinksData = new ArrayList<HyperlinkData>(); while (matcher.find()) { String paramName = matcher.group(LINK_PARAM_NAME_GROUP); JRPrintHyperlink hyperlink = (JRPrintHyperlink) element.getParameterValue(paramName); String replacement; if (hyperlink == null) { if (log.isWarnEnabled()) { log.warn("Hyperlink parameter " + paramName + " not found in element"); } replacement = null; } else { replacement = linkProducer.getHyperlink(hyperlink); if (prepareForSerialization) { String id = String.valueOf(hyperlink.hashCode() & 0x7FFFFFFF); HyperlinkData hyperlinkData = new HyperlinkData(); hyperlinkData.setId(id); hyperlinkData.setHref(replacement); hyperlinkData.setHyperlink(hyperlink); hyperlinkData.setSelector("._jrHyperLink." + hyperlink.getLinkType()); replacement = "jrhl-" + id + ";" + hyperlink.getLinkType(); hyperlinksData.add(hyperlinkData); } } if (replacement == null) { replacement = ""; } else { try { if (!prepareForSerialization) { replacement = URLEncoder.encode(replacement, "UTF-8"); } } catch (UnsupportedEncodingException e) { throw new JRRuntimeException(e); } } matcher.appendReplacement(xml, replacement); } matcher.appendTail(xml); if (hyperlinksData.size() > 0) { element.setParameterValue("hyperlinksData", hyperlinksData); } return xml.toString(); }