public Value matchPositions(Value str) { PatternMatcher matcher = getMatcher(); // Do the matching PatternMatcherInput jStr = new PatternMatcherInput(string(str)); Pair result = null; Pair prev = null; boolean found = false; while (matcher.contains(jStr, pattern)) { found = true; MatchResult matchResult = matcher.getMatch(); for (int i = 0, length = matchResult.groups(); i < length; i++) { Pair m = new Pair( Quantity.valueOf(matchResult.beginOffset(i)), Quantity.valueOf(matchResult.endOffset(i))); Pair elem = new Pair(m, EMPTYLIST); if (result == null) result = prev = elem; else { prev.setCdr(elem); prev = elem; } } } if (!found) return FALSE; else return result; }
private String getDomain(String url) { PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); PatternMatcherInput input = new PatternMatcherInput(url); Pattern pattern = null; String patternString = HTTP_PATTERN; try { pattern = compiler.compile(patternString); } catch (MalformedPatternException e) { logger.error("Incorrect pattern: " + patternString, e); } while (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); String sResult = result.group(1); logger.info("Match: " + sResult); return sResult; } patternString = WWW_PATTERN; try { pattern = compiler.compile(patternString); } catch (MalformedPatternException e) { logger.error("Incorrect pattern: " + patternString, e); } while (matcher.contains(input, pattern)) { MatchResult result = matcher.getMatch(); String sResult = result.group(1); logger.info("Match: " + sResult); return sResult; } return null; }
public Value match(Value str) { PatternMatcher matcher = getMatcher(); // Do the matching PatternMatcherInput jStr = new PatternMatcherInput(string(str)); Pair result = null; Pair prev = null; boolean found = false; while (matcher.contains(jStr, pattern)) { found = true; MatchResult matchResult = matcher.getMatch(); for (int i = 0, length = matchResult.groups(); i < length; i++) { Pair m = new Pair(new SchemeString(matchResult.group(i)), EMPTYLIST); if (result == null) result = prev = m; else { prev.setCdr(m); prev = m; } } } if (!found) return FALSE; else return result; }
public boolean check(String action, String method) { if (!StringUtil.isBlank(action)) { PatternMatcher matcher = new Perl5Matcher(); Iterator<ActionPatternHolder> iter = actionPatternList.iterator(); while (iter.hasNext()) { ActionPatternHolder holder = (ActionPatternHolder) iter.next(); if (StringUtils.isNotEmpty(action) && matcher.matches(action, holder.getActionPattern()) && StringUtils.isNotEmpty(method) && matcher.matches(method, holder.getMethodPattern())) { if (logger.isDebugEnabled()) { logger.debug( "Candidate is: '" + action + "|" + method + "'; pattern is " + holder.getActionName() + "|" + holder.getMethodName() + "; matched=true"); } return true; } } } return false; }
/** * insert正则表达式解析insert语句 如果insert语句与正则表达式匹配,本方法根据表达式对语句的分组 * 将insert语句拆分为6部分,并且将这几部分存放到字符串数组返回 分别为: 1.insert关键字 2.into关键字 3.表名称 4.表字段组 * 5.values关键字 6.插入字段值组 * * 比如insert语句: Insert into oa_meetingpromptsound ( soundCode , soundName , * soundFileName ) values ( '。.尹标平','bb','d()d' ) 将被分解为以下部分: 1.Insert 2.into * 3.oa_meetingpromptsound 4.( soundCode , soundName , soundFileName ) * 5.values 6.( '。.尹标平','bb','d()d' ) */ public static String[] parserInsert(String insert) { /** * 定义insert语句的正则表达式 该表达式将insert语句拆分为6部分,分别为: 1.insert关键字 2.into关键字 3.表名称 * 4.表字段组 5.values关键字 6.插入字段值组 比如insert语句: Insert into * oa_meetingpromptsound ( soundCode , soundName , soundFileName ) * values ( '。.尹标平','bb','d()d' ) 将被分解为以下部分: 1.Insert 2.into * 3.oa_meetingpromptsound 4.( soundCode , soundName , soundFileName ) * 5.values 6.( '。.尹标平','bb','d()d' ) */ String patternStr = "\\s*(insert)\\s+" + // 解析insert关键词 "(into)\\s+" + // 解析into关键词 "([^\\(^\\s]+)\\s*" + // 解析表名称 "(\\([^\\)]+\\))\\s*" + // 解析表字段 "(values)\\s*" + // 解析value关键词 "(\\(.*(.*\n*)*.*)"; // 解析字段值 /** * 编译正则表达式patternStr,并用该表达式与传入的sql语句进行模式匹配, * 如果匹配正确,则从匹配对象中提取出以上定义好的6部分,存放到数组中并返回 该数组 */ PatternCompiler compiler = new Perl5Compiler(); Pattern pattern = null; try { pattern = compiler.compile(patternStr, Perl5Compiler.CASE_INSENSITIVE_MASK); } catch (MalformedPatternException e) { e.printStackTrace(); return null; } PatternMatcher matcher = new Perl5Matcher(); MatchResult result = null; String[] tokens = null; boolean match = matcher.matches(insert, pattern); if (match) { result = matcher.getMatch(); tokens = new String[6]; for (int i = 0; i < 6; i++) { tokens[i] = result.group(i + 1).trim(); } } return tokens; }
public boolean matches(@NotNull final String name, @NotNull final String pattern) { final AnAction anAction = myActionManager.getAction(name); if (!(anAction instanceof ActionGroup)) { final Presentation presentation = anAction.getTemplatePresentation(); final String text = presentation.getText(); final String description = presentation.getDescription(); final Pattern compiledPattern = getPattern(pattern); if ((text != null && myMatcher.matches(text, compiledPattern)) || (description != null && myMatcher.matches(description, compiledPattern))) { return true; } } return false; }
@Override public boolean eval(Map<String, Object> context) { Object fieldVal = this.fieldAcsr.get(context); String expr = this.exprExdr.expandString(context); Pattern pattern; try { pattern = compiler.compile(expr); } catch (MalformedPatternException e) { String errMsg = "Error in evaluation in if-regexp in screen: " + e.toString(); Debug.logError(e, errMsg, module); throw new IllegalArgumentException(errMsg); } String fieldString = null; try { fieldString = (String) ObjectType.simpleTypeConvert( fieldVal, "String", null, (TimeZone) context.get("timeZone"), (Locale) context.get("locale"), true); } catch (GeneralException e) { Debug.logError(e, "Could not convert object to String, using empty String", module); } // always use an empty string by default if (fieldString == null) fieldString = ""; return matcher.matches(fieldString, pattern); }
private boolean matchExpression(String regex, String expression) { PatternCompiler compiler = new Perl5Compiler(); try { Pattern pattern = compiler.compile( "\\b(" + UpdateContextVariablesHelper.replaceSpecialChar(regex) + ")(\\b|\\_)"); //$NON-NLS-1$ //$NON-NLS-2$ PatternMatcher matcher = new Perl5Matcher(); ((Perl5Matcher) matcher).setMultiline(true); if (matcher.contains(expression, pattern)) { return true; } } catch (MalformedPatternException e) { // } return false; }
public static String[] parserValues(String values) { String patternStr = "([^\\,]*)[\\,]?"; // 解析字段值 String patternStr1 = "('?[^\\,]*'?)[\\,]?"; // 解析字段值 /** * 编译正则表达式patternStr,并用该表达式与传入的sql语句进行模式匹配, * 如果匹配正确,则从匹配对象中提取出以上定义好的6部分,存放到数组中并返回 该数组 */ String[] ret = RegexUtil.containWithPatternMatcherInput(values,patternStr1); PatternCompiler compiler = new Perl5Compiler(); Pattern pattern = null; try { pattern = compiler.compile(patternStr, Perl5Compiler.CASE_INSENSITIVE_MASK); } catch (MalformedPatternException e) { e.printStackTrace(); return null; } PatternMatcher matcher = new Perl5Matcher(); MatchResult result = null; String[] tokens = null; boolean match = matcher.matches(values.trim(), pattern); System.out.println(match); if (match) { result = matcher.getMatch(); tokens = new String[6]; for (int i = 0; i < 6; i++) { tokens[i] = result.group(i + 1).trim(); System.out.println(tokens[i]); } } return tokens; }
private void initTemplate() { if (template != null) { return; } // Contains Strings and Integers List<Object> combined = new ArrayList<Object>(); String rawTemplate = getTemplate(); PatternMatcher matcher = JMeterUtils.getMatcher(); Pattern templatePattern = JMeterUtils.getPatternCache() .getPattern( "\\$(\\d+)\\$" // $NON-NLS-1$ , Perl5Compiler.READ_ONLY_MASK & Perl5Compiler.SINGLELINE_MASK); if (log.isDebugEnabled()) { log.debug("Pattern = " + templatePattern.getPattern()); log.debug("template = " + rawTemplate); } int beginOffset = 0; MatchResult currentResult; PatternMatcherInput pinput = new PatternMatcherInput(rawTemplate); while (matcher.contains(pinput, templatePattern)) { currentResult = matcher.getMatch(); final int beginMatch = currentResult.beginOffset(0); if (beginMatch > beginOffset) { // string is not empty combined.add(rawTemplate.substring(beginOffset, beginMatch)); } combined.add(Integer.valueOf(currentResult.group(1))); // add match as Integer beginOffset = currentResult.endOffset(0); } if (beginOffset < rawTemplate.length()) { // trailing string is not empty combined.add(rawTemplate.substring(beginOffset, rawTemplate.length())); } if (log.isDebugEnabled()) { log.debug("Template item count: " + combined.size()); for (Object o : combined) { log.debug(o.getClass().getSimpleName() + " '" + o.toString() + "'"); } } template = combined; }
private void generateTemplate(String rawTemplate) { List pieces = new ArrayList(); List combined = new LinkedList(); PatternMatcher matcher = new Perl5Matcher(); Util.split(pieces, new Perl5Matcher(), templatePattern, rawTemplate); PatternMatcherInput input = new PatternMatcherInput(rawTemplate); int count = 0; Iterator iter = pieces.iterator(); boolean startsWith = isFirstElementGroup(rawTemplate); while (iter.hasNext()) { boolean matchExists = matcher.contains(input, templatePattern); if (startsWith) { if (matchExists) { combined.add(new Integer(matcher.getMatch().group(1))); } combined.add(iter.next()); } else { combined.add(iter.next()); if (matchExists) { combined.add(new Integer(matcher.getMatch().group(1))); } } } if (matcher.contains(input, templatePattern)) { combined.add(new Integer(matcher.getMatch().group(1))); } template = combined.toArray(); }
/** * Filters a collection according to the include and exclude parameters. * * @param c The collection to filter. * @return A filtered collection. */ protected Collection filterCollection(Collection c) { ArrayList<Object> result = new ArrayList<Object>(); PatternMatcher pm = new Perl5Matcher(); for (Iterator i = c.iterator(); i.hasNext(); ) { String pageName = null; Object objectje = i.next(); if (objectje instanceof WikiPage) { pageName = ((WikiPage) objectje).getName(); } else { pageName = (String) objectje; } // // If include parameter exists, then by default we include only // those // pages in it (excluding the ones in the exclude pattern list). // // include='*' means the same as no include. // boolean includeThis = m_include == null; if (m_include != null) { for (int j = 0; j < m_include.length; j++) { if (pm.matches(pageName, m_include[j])) { includeThis = true; break; } } } if (m_exclude != null) { for (int j = 0; j < m_exclude.length; j++) { if (pm.matches(pageName, m_exclude[j])) { includeThis = false; break; // The inner loop, continue on the next item } } } if (includeThis) { if (objectje instanceof WikiPage) { result.add(objectje); } else { result.add(pageName); } // // if we want to show the last modified date of the most // recently change page, we keep a "high watermark" here: WikiPage page = null; if (m_lastModified) { page = m_engine.getPage(pageName); if (page != null) { Date lastModPage = page.getLastModified(); if (log.isDebugEnabled()) { log.debug("lastModified Date of page " + pageName + " : " + m_dateLastModified); } if (lastModPage.after(m_dateLastModified)) { m_dateLastModified = lastModPage; } } } } } return result; }
private void processComponentStart( String tagName, String jwcId, boolean emptyTag, int startLine, int cursorStart, ILocation startLocation) throws TemplateParseException { if (jwcId.equalsIgnoreCase(CONTENT_ID)) { processContentTag(tagName, startLine, cursorStart, emptyTag); return; } boolean isRemoveId = jwcId.equalsIgnoreCase(REMOVE_ID); if (_ignoring && !isRemoveId) templateParseProblem( Tapestry.format( "TemplateParser.component-may-not-be-ignored", tagName, Integer.toString(startLine)), startLocation, startLine, cursorStart); String type = null; boolean allowBody = false; if (_patternMatcher.matches(jwcId, _implicitIdPattern)) { MatchResult match = _patternMatcher.getMatch(); jwcId = match.group(IMPLICIT_ID_PATTERN_ID_GROUP); type = match.group(IMPLICIT_ID_PATTERN_TYPE_GROUP); String libraryId = match.group(IMPLICIT_ID_PATTERN_LIBRARY_ID_GROUP); String simpleType = match.group(IMPLICIT_ID_PATTERN_SIMPLE_TYPE_GROUP); // If (and this is typical) no actual component id was specified, // then generate one on the fly. // The allocated id for anonymous components is // based on the simple (unprefixed) type, but starts // with a leading dollar sign to ensure no conflicts // with user defined component ids (which don't allow dollar signs // in the id). if (jwcId == null) jwcId = _idAllocator.allocateId("$" + simpleType); try { allowBody = _delegate.getAllowBody(libraryId, simpleType, startLocation); } catch (ApplicationRuntimeException e) { // give subclasses a chance to handle and rethrow templateParseProblem(e, startLine, cursorStart); } } else { if (!isRemoveId) { if (!_patternMatcher.matches(jwcId, _simpleIdPattern)) templateParseProblem( Tapestry.format( "TemplateParser.component-id-invalid", tagName, Integer.toString(startLine), jwcId), startLocation, startLine, cursorStart); if (!_delegate.getKnownComponent(jwcId)) templateParseProblem( Tapestry.format( "TemplateParser.unknown-component-id", tagName, Integer.toString(startLine), jwcId), startLocation, startLine, cursorStart); try { allowBody = _delegate.getAllowBody(jwcId, startLocation); } catch (ApplicationRuntimeException e) { // give subclasses a chance to handle and rethrow templateParseProblem(e, startLine, cursorStart); } } } // Ignore the body if we're removing the entire tag, // of if the corresponding component doesn't allow // a body. boolean ignoreBody = !emptyTag && (isRemoveId || !allowBody); if (_ignoring && ignoreBody) templateParseProblem( Tapestry.format("TemplateParser.nested-ignore", tagName, Integer.toString(startLine)), new Location(_resourceLocation, startLine), startLine, cursorStart); if (!emptyTag) pushNewTag(tagName, startLine, isRemoveId, ignoreBody); // End any open block. addTextToken(cursorStart - 1); if (!isRemoveId) { addOpenToken(tagName, jwcId, type, startLocation); if (emptyTag) _tokens.add(_factory.createCloseToken(tagName, getCurrentLocation())); } advance(); }
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { try { searchPattern = compiler.compile(((CompoundVariable) values[0]).execute()); generateTemplate(((CompoundVariable) values[1]).execute()); if (values.length > 2) { valueIndex = ((CompoundVariable) values[2]).execute(); } if (valueIndex.equals("")) { valueIndex = "1"; } if (values.length > 3) { between = ((CompoundVariable) values[3]).execute(); } if (values.length > 4) { String dv = ((CompoundVariable) values[4]).execute(); if (!dv.equals("")) { defaultValue = dv; } } if (values.length > 5) { name = ((CompoundVariable) values[values.length - 1]).execute(); } } catch (MalformedPatternException e) { log.error("", e); throw new InvalidVariableException("Bad regex pattern"); } catch (Exception e) { throw new InvalidVariableException(e.getMessage()); } getVariables().put(name, defaultValue); if (previousResult == null || previousResult.getResponseData() == null) { return defaultValue; } List collectAllMatches = new ArrayList(); try { PatternMatcher matcher = (PatternMatcher) localMatcher.get(); String responseText = new String(previousResult.getResponseData()); PatternMatcherInput input = new PatternMatcherInput(responseText); while (matcher.contains(input, searchPattern)) { MatchResult match = matcher.getMatch(); collectAllMatches.add(match); } } catch (NumberFormatException e) { log.error("", e); return defaultValue; } catch (Exception e) { return defaultValue; } if (collectAllMatches.size() == 0) { return defaultValue; } if (valueIndex.equals(ALL)) { StringBuffer value = new StringBuffer(); Iterator it = collectAllMatches.iterator(); boolean first = true; while (it.hasNext()) { if (!first) { value.append(between); } else { first = false; } value.append(generateResult((MatchResult) it.next())); } return value.toString(); } else if (valueIndex.equals(RAND)) { MatchResult result = (MatchResult) collectAllMatches.get(rand.nextInt(collectAllMatches.size())); return generateResult(result); } else { try { int index = Integer.parseInt(valueIndex) - 1; MatchResult result = (MatchResult) collectAllMatches.get(index); return generateResult(result); } catch (NumberFormatException e) { float ratio = Float.parseFloat(valueIndex); MatchResult result = (MatchResult) collectAllMatches.get((int) (collectAllMatches.size() * ratio + .5) - 1); return generateResult(result); } catch (IndexOutOfBoundsException e) { return defaultValue; } } }
/** * Count a page hit, present a pages' counter or output a list of pagecounts. * * @param context * @param params * @throws com.ecyrd.jspwiki.plugin.PluginException * @return String Wiki page snippet * @throws PluginException Malformed pattern parameter. * @concurrency concurrent */ public String execute(WikiContext context, Map params) throws PluginException { WikiEngine engine = context.getEngine(); WikiPage page = context.getPage(); String result = STR_EMPTY; if (null != page) { // get parameters String pagename = page.getName(); String count = (String) params.get(PARAM_COUNT); String show = (String) params.get(PARAM_SHOW); int entries = TextUtil.parseIntParameter((String) params.get(PARAM_MAX_ENTRIES), Integer.MAX_VALUE); final int max = TextUtil.parseIntParameter((String) params.get(PARAM_MAX_COUNT), Integer.MAX_VALUE); final int min = TextUtil.parseIntParameter((String) params.get(PARAM_MIN_COUNT), Integer.MIN_VALUE); String sort = (String) params.get(PARAM_SORT); String body = (String) params.get(PluginManager.PARAM_BODY); Pattern[] exclude = compileGlobs(PARAM_EXCLUDE, (String) params.get(PARAM_EXCLUDE)); Pattern[] include = compileGlobs(PARAM_INCLUDE, (String) params.get(PARAM_INCLUDE)); Pattern[] refer = compileGlobs(PARAM_REFER, (String) params.get(PARAM_REFER)); PatternMatcher matcher = (null != exclude || null != include || null != refer) ? new Perl5Matcher() : null; boolean increment = false; // increment counter? if (STR_YES.equals(count)) { increment = true; } else { count = null; } // default increment counter? if ((null == show || STR_NONE.equals(show)) && null == count) { increment = true; } // filter on referring pages? Collection referrers = null; if (null != refer) { ReferenceManager refManager = engine.getReferenceManager(); Iterator iter = refManager.findCreated().iterator(); while (null != iter && iter.hasNext()) { String name = (String) iter.next(); boolean use = false; for (int n = 0; !use && n < refer.length; n++) { use = matcher.matches(name, refer[n]); } if (use) { Collection refs = engine.getReferenceManager().findReferrers(name); if (null != refs && !refs.isEmpty()) { if (null == referrers) { referrers = new HashSet(); } referrers.addAll(refs); } } } } synchronized (this) { Counter counter = (Counter) counters.get(pagename); // only count in view mode, keep storage values in sync if (increment && WikiContext.VIEW.equalsIgnoreCase(context.getRequestContext())) { if (null == counter) { counter = new Counter(); counters.put(pagename, counter); } counter.increment(); storage.setProperty(pagename, counter.toString()); dirty = true; } if (null == show || STR_NONE.equals(show)) { // nothing to show } else if (PARAM_COUNT.equals(show)) { // show page count result = counter.toString(); } else if (null != body && 0 < body.length() && STR_LIST.equals(show)) { // show list of counts String header = STR_EMPTY; String line = body; String footer = STR_EMPTY; int start = body.indexOf(STR_SEPARATOR); // split body into header, line, footer on ---- // separator if (0 < start) { header = body.substring(0, start); start = skipWhitespace(start + STR_SEPARATOR.length(), body); int end = body.indexOf(STR_SEPARATOR, start); if (start >= end) { line = body.substring(start); } else { line = body.substring(start, end); end = skipWhitespace(end + STR_SEPARATOR.length(), body); footer = body.substring(end); } } // sort on name or count? Map sorted = counters; if (null != sort && PARAM_COUNT.equals(sort)) { sorted = new TreeMap(compareCountDescending); sorted.putAll(counters); } // build a messagebuffer with the list in wiki markup StringBuffer buf = new StringBuffer(header); MessageFormat fmt = new MessageFormat(line); Object[] args = new Object[] {pagename, STR_EMPTY, STR_EMPTY}; Iterator iter = sorted.entrySet().iterator(); while (null != iter && 0 < entries && iter.hasNext()) { Entry entry = (Entry) iter.next(); String name = (String) entry.getKey(); // check minimum count final int value = ((Counter) entry.getValue()).getValue(); boolean use = min <= value && value <= max; // did we specify a refer-to page? if (use && null != referrers) { use = referrers.contains(name); } // did we specify what pages to include? if (use && null != include) { use = false; for (int n = 0; !use && n < include.length; n++) { use = matcher.matches(name, include[n]); } } // did we specify what pages to exclude? if (use && null != exclude) { for (int n = 0; use && n < exclude.length; n++) { use &= !matcher.matches(name, exclude[n]); } } if (use) { args[1] = engine.beautifyTitle(name); args[2] = entry.getValue(); fmt.format(args, buf, null); entries--; } } buf.append(footer); // let the engine render the list result = engine.textToHTML(context, buf.toString()); } } } return result; }
public boolean accept(String path) { synchronized (MATCHER) { return MATCHER.matches(path, pattern); } }