Search in sources :

Example 46 with Perl5Matcher

use of org.apache.oro.text.regex.Perl5Matcher in project jmeter by apache.

the class ResponseAssertion method evaluateResponse.

/**
     * Make sure the response satisfies the specified assertion requirements.
     *
     * @param response
     *            an instance of SampleResult
     * @return an instance of AssertionResult
     */
private AssertionResult evaluateResponse(SampleResult response) {
    AssertionResult result = new AssertionResult(getName());
    if (getAssumeSuccess()) {
        // Allow testing of failure codes
        response.setSuccessful(true);
    }
    // The string to check (Url or data)
    String toCheck;
    // What are we testing against?
    if (isScopeVariable()) {
        toCheck = getThreadContext().getVariables().get(getVariableName());
    } else if (isTestFieldResponseData()) {
        // (bug25052)
        toCheck = response.getResponseDataAsString();
    } else if (isTestFieldResponseDataAsDocument()) {
        toCheck = Document.getTextFromDocument(response.getResponseData());
    } else if (isTestFieldResponseCode()) {
        toCheck = response.getResponseCode();
    } else if (isTestFieldResponseMessage()) {
        toCheck = response.getResponseMessage();
    } else if (isTestFieldRequestHeaders()) {
        toCheck = response.getRequestHeaders();
    } else if (isTestFieldResponseHeaders()) {
        toCheck = response.getResponseHeaders();
    } else {
        // Assume it is the URL
        toCheck = "";
        final URL url = response.getURL();
        if (url != null) {
            toCheck = url.toString();
        }
    }
    result.setFailure(false);
    result.setError(false);
    boolean notTest = (NOT & getTestType()) > 0;
    boolean orTest = (OR & getTestType()) > 0;
    // do it once outside loop
    boolean contains = isContainsType();
    boolean equals = isEqualsType();
    boolean substring = isSubstringType();
    boolean matches = isMatchType();
    log.debug("Test Type Info: contains={}, notTest={}, orTest={}", contains, notTest, orTest);
    if (StringUtils.isEmpty(toCheck)) {
        if (notTest) {
            // Not should always succeed against an empty result
            return result;
        }
        if (log.isDebugEnabled()) {
            log.debug("Not checking empty response field in: {}", response.getSampleLabel());
        }
        return result.setResultForNull();
    }
    boolean pass = true;
    boolean hasTrue = false;
    ArrayList<String> allCheckMessage = new ArrayList<>();
    try {
        // Get the Matcher for this thread
        Perl5Matcher localMatcher = JMeterUtils.getMatcher();
        for (JMeterProperty jMeterProperty : getTestStrings()) {
            String stringPattern = jMeterProperty.getStringValue();
            Pattern pattern = null;
            if (contains || matches) {
                pattern = JMeterUtils.getPatternCache().getPattern(stringPattern, Perl5Compiler.READ_ONLY_MASK);
            }
            boolean found;
            if (contains) {
                found = localMatcher.contains(toCheck, pattern);
            } else if (equals) {
                found = toCheck.equals(stringPattern);
            } else if (substring) {
                found = toCheck.contains(stringPattern);
            } else {
                found = localMatcher.matches(toCheck, pattern);
            }
            pass = notTest ? !found : found;
            if (orTest) {
                if (!pass) {
                    log.debug("Failed: {}", stringPattern);
                    allCheckMessage.add(getFailText(stringPattern, toCheck));
                } else {
                    hasTrue = true;
                    break;
                }
            } else {
                if (!pass) {
                    log.debug("Failed: {}", stringPattern);
                    result.setFailure(true);
                    result.setFailureMessage(getFailText(stringPattern, toCheck));
                    break;
                }
                log.debug("Passed: {}", stringPattern);
            }
        }
        if (orTest && !hasTrue) {
            StringBuilder errorMsg = new StringBuilder();
            for (String tmp : allCheckMessage) {
                errorMsg.append(tmp).append('\t');
            }
            result.setFailure(true);
            result.setFailureMessage(errorMsg.toString());
        }
    } catch (MalformedCachePatternException e) {
        result.setError(true);
        result.setFailure(false);
        result.setFailureMessage("Bad test configuration " + e);
    }
    return result;
}
Also used : Pattern(org.apache.oro.text.regex.Pattern) JMeterProperty(org.apache.jmeter.testelement.property.JMeterProperty) MalformedCachePatternException(org.apache.oro.text.MalformedCachePatternException) ArrayList(java.util.ArrayList) Perl5Matcher(org.apache.oro.text.regex.Perl5Matcher) URL(java.net.URL)

Example 47 with Perl5Matcher

use of org.apache.oro.text.regex.Perl5Matcher in project jmeter by apache.

the class RegexExtractor method process.

/**
     * Parses the response data using regular expressions and saving the results
     * into variables for use later in the test.
     *
     * @see org.apache.jmeter.processor.PostProcessor#process()
     */
@Override
public void process() {
    initTemplate();
    JMeterContext context = getThreadContext();
    SampleResult previousResult = context.getPreviousResult();
    if (previousResult == null) {
        return;
    }
    log.debug("RegexExtractor processing result");
    // Fetch some variables
    JMeterVariables vars = context.getVariables();
    String refName = getRefName();
    int matchNumber = getMatchNumber();
    final String defaultValue = getDefaultValue();
    if (defaultValue.length() > 0 || isEmptyDefaultValue()) {
        // Only replace default if it is provided or empty default value is explicitly requested
        vars.put(refName, defaultValue);
    }
    Perl5Matcher matcher = JMeterUtils.getMatcher();
    String regex = getRegex();
    Pattern pattern = null;
    try {
        pattern = JMeterUtils.getPatternCache().getPattern(regex, Perl5Compiler.READ_ONLY_MASK);
        List<MatchResult> matches = processMatches(pattern, regex, previousResult, matchNumber, vars);
        int prevCount = 0;
        String prevString = vars.get(refName + REF_MATCH_NR);
        if (prevString != null) {
            // ensure old value is not left defined
            vars.remove(refName + REF_MATCH_NR);
            try {
                prevCount = Integer.parseInt(prevString);
            } catch (NumberFormatException nfe) {
                log.warn("Could not parse number: '{}'", prevString);
            }
        }
        // Number of refName_n variable sets to keep
        int matchCount = 0;
        try {
            MatchResult match;
            if (matchNumber >= 0) {
                // Original match behaviour
                match = getCorrectMatch(matches, matchNumber);
                if (match != null) {
                    vars.put(refName, generateResult(match));
                    saveGroups(vars, refName, match);
                } else {
                    // refname has already been set to the default (if present)
                    removeGroups(vars, refName);
                }
            } else // < 0 means we save all the matches
            {
                // remove any single matches
                removeGroups(vars, refName);
                matchCount = matches.size();
                // Save the count
                vars.put(refName + REF_MATCH_NR, Integer.toString(matchCount));
                for (int i = 1; i <= matchCount; i++) {
                    match = getCorrectMatch(matches, i);
                    if (match != null) {
                        final String refName_n = new StringBuilder(refName).append(UNDERSCORE).append(i).toString();
                        vars.put(refName_n, generateResult(match));
                        saveGroups(vars, refName_n, match);
                    }
                }
            }
            // Remove any left-over variables
            for (int i = matchCount + 1; i <= prevCount; i++) {
                final String refName_n = new StringBuilder(refName).append(UNDERSCORE).append(i).toString();
                vars.remove(refName_n);
                removeGroups(vars, refName_n);
            }
        } catch (RuntimeException e) {
            log.warn("Error while generating result");
        }
    } catch (MalformedCachePatternException e) {
        log.error("Error in pattern: '{}'", regex);
    } finally {
        JMeterUtils.clearMatcherMemory(matcher, pattern);
    }
}
Also used : Pattern(org.apache.oro.text.regex.Pattern) MalformedCachePatternException(org.apache.oro.text.MalformedCachePatternException) Perl5Matcher(org.apache.oro.text.regex.Perl5Matcher) MatchResult(org.apache.oro.text.regex.MatchResult) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterContext(org.apache.jmeter.threads.JMeterContext) SampleResult(org.apache.jmeter.samplers.SampleResult)

Example 48 with Perl5Matcher

use of org.apache.oro.text.regex.Perl5Matcher in project jmeter by apache.

the class RenderAsRegexp method process.

private String process(String textToParse) {
    Perl5Matcher matcher = new Perl5Matcher();
    PatternMatcherInput input = new PatternMatcherInput(textToParse);
    PatternCacheLRU pcLRU = new PatternCacheLRU();
    Pattern pattern;
    try {
        pattern = pcLRU.getPattern(regexpField.getText(), Perl5Compiler.READ_ONLY_MASK);
    } catch (MalformedCachePatternException e) {
        return e.toString();
    }
    List<MatchResult> matches = new LinkedList<>();
    while (matcher.contains(input, pattern)) {
        matches.add(matcher.getMatch());
    }
    // Construct a multi-line string with all matches
    StringBuilder sb = new StringBuilder();
    final int size = matches.size();
    sb.append("Match count: ").append(size).append("\n");
    for (int j = 0; j < size; j++) {
        MatchResult mr = matches.get(j);
        final int groups = mr.groups();
        for (int i = 0; i < groups; i++) {
            sb.append("Match[").append(j + 1).append("][").append(i).append("]=").append(mr.group(i)).append("\n");
        }
    }
    return sb.toString();
}
Also used : Pattern(org.apache.oro.text.regex.Pattern) PatternMatcherInput(org.apache.oro.text.regex.PatternMatcherInput) MalformedCachePatternException(org.apache.oro.text.MalformedCachePatternException) Perl5Matcher(org.apache.oro.text.regex.Perl5Matcher) MatchResult(org.apache.oro.text.regex.MatchResult) LinkedList(java.util.LinkedList) PatternCacheLRU(org.apache.oro.text.PatternCacheLRU)

Example 49 with Perl5Matcher

use of org.apache.oro.text.regex.Perl5Matcher in project jmeter by apache.

the class HttpMirrorThread method getRequestHeaderValue.

private static String getRequestHeaderValue(String requestHeaders, String headerName) {
    Perl5Matcher localMatcher = JMeterUtils.getMatcher();
    // We use multi-line mask so can prefix the line with ^
    // $NON-NLS-1$ $NON-NLS-2$
    String expression = "^" + headerName + ":\\s+([^\\r\\n]+)";
    Pattern pattern = JMeterUtils.getPattern(expression, Perl5Compiler.READ_ONLY_MASK | Perl5Compiler.CASE_INSENSITIVE_MASK | Perl5Compiler.MULTILINE_MASK);
    if (localMatcher.contains(requestHeaders, pattern)) {
        //            System.out.println("in: '"+localMatcher.getMatch().group(0)+"'");
        return localMatcher.getMatch().group(1);
    } else {
        return null;
    }
}
Also used : Pattern(org.apache.oro.text.regex.Pattern) Perl5Matcher(org.apache.oro.text.regex.Perl5Matcher)

Aggregations

Perl5Matcher (org.apache.oro.text.regex.Perl5Matcher)49 Pattern (org.apache.oro.text.regex.Pattern)36 MalformedPatternException (org.apache.oro.text.regex.MalformedPatternException)19 Perl5Compiler (org.apache.oro.text.regex.Perl5Compiler)19 MatchResult (org.apache.oro.text.regex.MatchResult)15 PatternMatcher (org.apache.oro.text.regex.PatternMatcher)9 ArrayList (java.util.ArrayList)8 PatternMatcherInput (org.apache.oro.text.regex.PatternMatcherInput)8 PatternCompiler (org.apache.oro.text.regex.PatternCompiler)6 MalformedCachePatternException (org.apache.oro.text.MalformedCachePatternException)5 Perl5Substitution (org.apache.oro.text.regex.Perl5Substitution)5 IOException (java.io.IOException)4 MalformedURLException (java.net.MalformedURLException)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 SampleResult (org.apache.jmeter.samplers.SampleResult)3 JMeterProperty (org.apache.jmeter.testelement.property.JMeterProperty)3 PatternCacheLRU (org.apache.oro.text.PatternCacheLRU)3 BufferedReader (java.io.BufferedReader)2 EOFException (java.io.EOFException)2 File (java.io.File)2