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; }
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(); }
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; }
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; }
/** * 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 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 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; } } }