Search in sources :

Example 81 with JMeterContext

use of org.apache.jmeter.threads.JMeterContext in project jmeter by apache.

the class BeanShellPostProcessor method process.

@Override
public void process() {
    JMeterContext jmctx = JMeterContextService.getContext();
    SampleResult prev = jmctx.getPreviousResult();
    if (prev == null) {
        // TODO - should we skip processing here?
        return;
    }
    final BeanShellInterpreter bshInterpreter = getBeanShellInterpreter();
    if (bshInterpreter == null) {
        log.error("BeanShell not found");
        return;
    }
    try {
        // Add variables for access to context and variables
        // $NON-NLS-1$
        bshInterpreter.set("data", prev.getResponseData());
        processFileOrScript(bshInterpreter);
    } catch (JMeterException e) {
        if (log.isWarnEnabled()) {
            log.warn("Problem in BeanShell script: {}", e.toString());
        }
    }
}
Also used : JMeterException(org.apache.jorphan.util.JMeterException) JMeterContext(org.apache.jmeter.threads.JMeterContext) SampleResult(org.apache.jmeter.samplers.SampleResult) BeanShellInterpreter(org.apache.jmeter.util.BeanShellInterpreter)

Example 82 with JMeterContext

use of org.apache.jmeter.threads.JMeterContext in project jmeter by apache.

the class BoundaryExtractor method process.

/**
 * Parses the response data using Boundaries and saving the results
 * into variables for use later in the test.
 *
 * @see PostProcessor#process()
 */
@Override
public void process() {
    JMeterContext context = getThreadContext();
    SampleResult previousResult = context.getPreviousResult();
    if (previousResult == null) {
        return;
    }
    if (log.isDebugEnabled()) {
        log.debug("Boundary Extractor {}: processing result", getName());
    }
    if (StringUtils.isEmpty(getRefName())) {
        throw new IllegalArgumentException("One of the mandatory properties is missing in Boundary Extractor:" + getName());
    }
    JMeterVariables vars = context.getVariables();
    String refName = getRefName();
    final String defaultValue = getDefaultValue();
    if (StringUtils.isNotBlank(defaultValue) || isEmptyDefaultValue()) {
        vars.put(refName, defaultValue);
    }
    int matchNumber = getMatchNumber();
    int prevCount = 0;
    int matchCount = 0;
    try {
        prevCount = removePrevCount(vars, refName);
        List<String> matches = extractMatches(previousResult, vars, matchNumber);
        matchCount = saveMatches(vars, refName, matchNumber, matches);
    } catch (RuntimeException e) {
        // NOSONAR
        if (log.isWarnEnabled()) {
            // NOSONAR We don't want to be too verbose
            log.warn("{}: Error while generating result. {}", getName(), e.toString());
        }
    } finally {
        // Remove any left-over variables
        for (int i = matchCount + 1; i <= prevCount; i++) {
            vars.remove(refName + UNDERSCORE + i);
        }
    }
}
Also used : JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterContext(org.apache.jmeter.threads.JMeterContext) SampleResult(org.apache.jmeter.samplers.SampleResult)

Example 83 with JMeterContext

use of org.apache.jmeter.threads.JMeterContext in project jmeter by apache.

the class XPathExtractor method process.

/**
 * Do the job - extract value from (X)HTML response using XPath Query.
 * Return value as variable defined by REFNAME. Returns DEFAULT value
 * if not found.
 */
@Override
public void process() {
    JMeterContext context = getThreadContext();
    final SampleResult previousResult = context.getPreviousResult();
    if (previousResult == null) {
        return;
    }
    JMeterVariables vars = context.getVariables();
    String refName = getRefName();
    vars.put(refName, getDefaultValue());
    final String matchNR = concat(refName, REF_MATCH_NR);
    // number of previous matches
    int prevCount = 0;
    try {
        prevCount = Integer.parseInt(vars.get(matchNR));
    } catch (NumberFormatException e) {
    // ignored
    }
    // In case parse fails // $NON-NLS-1$
    vars.put(matchNR, "0");
    // In case parse fails // $NON-NLS-1$
    vars.remove(concat(refName, "1"));
    int matchNumber = getMatchNumber();
    List<String> matches = new ArrayList<>();
    try {
        if (isScopeVariable()) {
            String inputString = vars.get(getVariableName());
            if (inputString != null) {
                if (inputString.length() > 0) {
                    Document d = parseResponse(inputString);
                    getValuesForXPath(d, getXPathQuery(), matches, matchNumber);
                }
            } else {
                if (log.isWarnEnabled()) {
                    log.warn("No variable '{}' found to process by XPathExtractor '{}', skipping processing", getVariableName(), getName());
                }
            }
        } else {
            List<SampleResult> samples = getSampleList(previousResult);
            for (SampleResult res : samples) {
                Document d = parseResponse(res.getResponseDataAsString());
                getValuesForXPath(d, getXPathQuery(), matches, matchNumber);
            }
        }
        final int matchCount = matches.size();
        vars.put(matchNR, String.valueOf(matchCount));
        if (matchCount > 0) {
            String value = matches.get(0);
            if (value != null) {
                vars.put(refName, value);
            }
            for (int i = 0; i < matchCount; i++) {
                value = matches.get(i);
                if (value != null) {
                    vars.put(concat(refName, i + 1), matches.get(i));
                }
            }
        }
        // Just in case
        vars.remove(concat(refName, matchCount + 1));
        // Clear any other remaining variables
        for (int i = matchCount + 2; i <= prevCount; i++) {
            vars.remove(concat(refName, i));
        }
    } catch (IOException e) {
        // e.g. DTD not reachable
        log.error("IOException on ({})", getXPathQuery(), e);
        AssertionResult ass = new AssertionResult(getName());
        ass.setError(true);
        ass.setFailureMessage("IOException: " + e.getLocalizedMessage());
        previousResult.addAssertionResult(ass);
        previousResult.setSuccessful(false);
    } catch (ParserConfigurationException e) {
        // Should not happen
        final String errrorMessage = "ParserConfigurationException while processing (" + getXPathQuery() + ")";
        log.error(errrorMessage, e);
        throw new JMeterError(errrorMessage, e);
    } catch (SAXException e) {
        // Can happen for bad input document
        if (log.isWarnEnabled()) {
            log.warn("SAXException while processing ({}). {}", getXPathQuery(), e.getLocalizedMessage());
        }
        // Should this also fail the sample?
        addAssertionFailure(previousResult, e, false);
    } catch (TransformerException e) {
        // Can happen for incorrect XPath expression
        if (log.isWarnEnabled()) {
            log.warn("TransformerException while processing ({}). {}", getXPathQuery(), e.getLocalizedMessage());
        }
        addAssertionFailure(previousResult, e, false);
    } catch (TidyException e) {
        // Will already have been logged by XPathUtil
        // fail the sample
        addAssertionFailure(previousResult, e, true);
    }
}
Also used : AssertionResult(org.apache.jmeter.assertions.AssertionResult) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) TidyException(org.apache.jmeter.util.TidyException) SAXException(org.xml.sax.SAXException) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterError(org.apache.jorphan.util.JMeterError) JMeterContext(org.apache.jmeter.threads.JMeterContext) SampleResult(org.apache.jmeter.samplers.SampleResult) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Example 84 with JMeterContext

use of org.apache.jmeter.threads.JMeterContext in project jmeter by apache.

the class CSVDataSet method iterationStart.

@Override
public void iterationStart(LoopIterationEvent iterEvent) {
    FileServer server = FileServer.getFileServer();
    final JMeterContext context = getThreadContext();
    String delim = getDelimiter();
    if ("\\t".equals(delim)) {
        // $NON-NLS-1$
        // Make it easier to enter a Tab // $NON-NLS-1$
        delim = "\t";
    } else if (delim.isEmpty()) {
        log.debug("Empty delimiter, will use ','");
        delim = ",";
    }
    if (vars == null) {
        initVars(server, context, delim);
    }
    // TODO: fetch this once as per vars above?
    JMeterVariables threadVars = context.getVariables();
    String[] lineValues = {};
    try {
        if (getQuotedData()) {
            lineValues = server.getParsedLine(alias, recycle, firstLineIsNames || ignoreFirstLine, delim.charAt(0));
        } else {
            String line = server.readLine(alias, recycle, firstLineIsNames || ignoreFirstLine);
            lineValues = JOrphanUtils.split(line, delim, false);
        }
        for (int a = 0; a < vars.length && a < lineValues.length; a++) {
            threadVars.put(vars[a], lineValues[a]);
        }
    } catch (IOException e) {
        // treat the same as EOF
        log.error(e.toString());
    }
    if (lineValues.length == 0) {
        // i.e. EOF
        if (getStopThread()) {
            throw new JMeterStopThreadException("End of file:" + getFilename() + " detected for CSV DataSet:" + getName() + " configured with stopThread:" + getStopThread() + ", recycle:" + getRecycle());
        }
        for (String var : vars) {
            threadVars.put(var, EOFVALUE);
        }
    }
}
Also used : JMeterStopThreadException(org.apache.jorphan.util.JMeterStopThreadException) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterContext(org.apache.jmeter.threads.JMeterContext) IOException(java.io.IOException) FileServer(org.apache.jmeter.services.FileServer)

Example 85 with JMeterContext

use of org.apache.jmeter.threads.JMeterContext in project jmeter by apache.

the class ForeachController method isDone.

/**
 * {@inheritDoc}
 */
@Override
public boolean isDone() {
    if (loopCount >= getEndIndex()) {
        return true;
    }
    JMeterContext context = getThreadContext();
    StringBuilder builder = new StringBuilder(getInputVal().length() + getSeparator().length() + 3);
    String inputVariable = builder.append(getInputVal()).append(getSeparator()).append(Integer.toString(loopCount + 1)).toString();
    final JMeterVariables variables = context.getVariables();
    final Object currentVariable = variables.getObject(inputVariable);
    if (currentVariable != null) {
        variables.putObject(getReturnVal(), currentVariable);
        if (log.isDebugEnabled()) {
            log.debug("{} : Found in vars:{}, isDone:{}", getName(), inputVariable, Boolean.FALSE);
        }
        return false;
    }
    return super.isDone();
}
Also used : JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterContext(org.apache.jmeter.threads.JMeterContext)

Aggregations

JMeterContext (org.apache.jmeter.threads.JMeterContext)98 JMeterVariables (org.apache.jmeter.threads.JMeterVariables)64 SampleResult (org.apache.jmeter.samplers.SampleResult)47 Test (org.junit.Test)19 Test (org.junit.jupiter.api.Test)18 BeforeEach (org.junit.jupiter.api.BeforeEach)13 JSONPostProcessor (org.apache.jmeter.extractor.json.jsonpath.JSONPostProcessor)11 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)11 CompoundVariable (org.apache.jmeter.engine.util.CompoundVariable)10 Sampler (org.apache.jmeter.samplers.Sampler)9 TestSampler (org.apache.jmeter.junit.stubs.TestSampler)8 ArrayList (java.util.ArrayList)6 IOException (java.io.IOException)4 Properties (java.util.Properties)3 JMeterProperty (org.apache.jmeter.testelement.property.JMeterProperty)3 JMeterException (org.apache.jorphan.util.JMeterException)3 HashMap (java.util.HashMap)2 Bindings (javax.script.Bindings)2 Arguments (org.apache.jmeter.config.Arguments)2 ReplaceStringWithFunctions (org.apache.jmeter.engine.util.ReplaceStringWithFunctions)2