Search in sources :

Example 46 with JMeterContext

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

the class JSONPostProcessor method process.

@Override
public void process() {
    JMeterContext context = getThreadContext();
    JMeterVariables vars = context.getVariables();
    String jsonResponse;
    if (isScopeVariable()) {
        jsonResponse = vars.get(getVariableName());
        if (log.isDebugEnabled()) {
            log.debug("JSON Extractor is using variable: {}, which content is: {}", getVariableName(), jsonResponse);
        }
    } else {
        SampleResult previousResult = context.getPreviousResult();
        if (previousResult == null) {
            return;
        }
        jsonResponse = previousResult.getResponseDataAsString();
        if (log.isDebugEnabled()) {
            log.debug("JSON Extractor {} working on Response: {}", getName(), jsonResponse);
        }
    }
    String[] refNames = getRefNames().split(SEPARATOR);
    String[] jsonPathExpressions = getJsonPathExpressions().split(SEPARATOR);
    String[] defaultValues = getDefaultValues().split(SEPARATOR);
    int[] matchNumbers = getMatchNumbersAsInt(defaultValues.length);
    if (refNames.length != jsonPathExpressions.length || refNames.length != defaultValues.length) {
        // $NON-NLS-1$
        log.error("Number of JSON Path variables must match number of default values and json-path expressions, check you use separator ';' if you have many values");
        throw new IllegalArgumentException(JMeterUtils.getResString(// $NON-NLS-1$
        "jsonpp_error_number_arguments_mismatch_error"));
    }
    for (int i = 0; i < jsonPathExpressions.length; i++) {
        int matchNumber = matchNumbers[i];
        String currentRefName = refNames[i].trim();
        String currentJsonPath = jsonPathExpressions[i].trim();
        clearOldRefVars(vars, currentRefName);
        try {
            if (jsonResponse.isEmpty()) {
                vars.put(currentRefName, defaultValues[i]);
            } else {
                List<Object> extractedValues = localMatcher.get().extractWithJsonPath(jsonResponse, currentJsonPath);
                // if no values extracted, default value added
                if (extractedValues.isEmpty()) {
                    vars.put(currentRefName, defaultValues[i]);
                    //$NON-NLS-1$
                    vars.put(currentRefName + REF_MATCH_NR, "0");
                    if (matchNumber < 0 && getComputeConcatenation()) {
                        log.debug("No value extracted, storing empty in: {}{}", currentRefName, ALL_SUFFIX);
                        vars.put(currentRefName + ALL_SUFFIX, "");
                    }
                } else {
                    // if more than one value extracted, suffix with "_index"
                    if (extractedValues.size() > 1) {
                        if (matchNumber < 0) {
                            // Extract all
                            int index = 1;
                            StringBuilder concat = new StringBuilder(getComputeConcatenation() ? extractedValues.size() * 20 : 1);
                            for (Object extractedObject : extractedValues) {
                                String extractedString = stringify(extractedObject);
                                vars.put(currentRefName + "_" + index, //$NON-NLS-1$
                                extractedString);
                                if (getComputeConcatenation()) {
                                    concat.append(extractedString).append(JSONPostProcessor.JSON_CONCATENATION_SEPARATOR);
                                }
                                index++;
                            }
                            if (getComputeConcatenation()) {
                                concat.setLength(concat.length() - 1);
                                vars.put(currentRefName + ALL_SUFFIX, concat.toString());
                            }
                        } else if (matchNumber == 0) {
                            // Random extraction
                            int matchSize = extractedValues.size();
                            int matchNr = JMeterUtils.getRandomInt(matchSize);
                            placeObjectIntoVars(vars, currentRefName, extractedValues, matchNr);
                        } else {
                            // extract at position
                            if (matchNumber > extractedValues.size()) {
                                if (log.isDebugEnabled()) {
                                    log.debug("matchNumber({}) exceeds number of items found({}), default value will be used", matchNumber, extractedValues.size());
                                }
                                vars.put(currentRefName, defaultValues[i]);
                            } else {
                                placeObjectIntoVars(vars, currentRefName, extractedValues, matchNumber - 1);
                            }
                        }
                    } else {
                        // else just one value extracted
                        String suffix = (matchNumber < 0) ? "_1" : "";
                        placeObjectIntoVars(vars, currentRefName + suffix, extractedValues, 0);
                        if (matchNumber < 0 && getComputeConcatenation()) {
                            vars.put(currentRefName + ALL_SUFFIX, vars.get(currentRefName + suffix));
                        }
                    }
                    if (matchNumber != 0) {
                        vars.put(currentRefName + REF_MATCH_NR, Integer.toString(extractedValues.size()));
                    }
                }
            }
        } catch (Exception e) {
            // if something wrong, default value added
            if (log.isDebugEnabled()) {
                log.error("Error processing JSON content in {}, message: {}", getName(), e.getLocalizedMessage(), e);
            } else {
                log.error("Error processing JSON content in {}, message: {}", getName(), e.getLocalizedMessage());
            }
            vars.put(currentRefName, defaultValues[i]);
        }
    }
}
Also used : JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterContext(org.apache.jmeter.threads.JMeterContext) SampleResult(org.apache.jmeter.samplers.SampleResult)

Example 47 with JMeterContext

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

the class TestAction method sample.

/**
     * {@inheritDoc}
     */
@Override
public SampleResult sample(Entry e) {
    JMeterContext context = JMeterContextService.getContext();
    int target = getTarget();
    int action = getAction();
    if (action == PAUSE) {
        pause(getDurationAsString());
    } else if (action == STOP || action == STOP_NOW || action == RESTART_NEXT_LOOP) {
        if (target == THREAD) {
            if (action == STOP || action == STOP_NOW) {
                log.info("Stopping current thread from element {}", getName());
                context.getThread().stop();
            } else {
                log.info("Restarting next loop from element {}", getName());
                context.setRestartNextLoop(true);
            }
        } else if (target == TEST) {
            if (action == STOP_NOW) {
                log.info("Stopping all threads now from element {}", getName());
                context.getEngine().stopTest();
            } else {
                log.info("Stopping all threads from element {}", getName());
                context.getEngine().askThreadsToStop();
            }
        }
    }
    // This means no sample is saved
    return null;
}
Also used : JMeterContext(org.apache.jmeter.threads.JMeterContext)

Aggregations

JMeterContext (org.apache.jmeter.threads.JMeterContext)47 JMeterVariables (org.apache.jmeter.threads.JMeterVariables)33 SampleResult (org.apache.jmeter.samplers.SampleResult)21 Test (org.junit.Test)11 Sampler (org.apache.jmeter.samplers.Sampler)9 JSONPostProcessor (org.apache.jmeter.extractor.json.jsonpath.JSONPostProcessor)8 Before (org.junit.Before)8 CompoundVariable (org.apache.jmeter.engine.util.CompoundVariable)7 Properties (java.util.Properties)3 TestSampler (org.apache.jmeter.junit.stubs.TestSampler)3 JMeterProperty (org.apache.jmeter.testelement.property.JMeterProperty)3 JMeterException (org.apache.jorphan.util.JMeterException)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 ReplaceStringWithFunctions (org.apache.jmeter.engine.util.ReplaceStringWithFunctions)2 HTTPSamplerBase (org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase)2 StringProperty (org.apache.jmeter.testelement.property.StringProperty)2 BeanShellInterpreter (org.apache.jmeter.util.BeanShellInterpreter)2 MatchResult (org.apache.oro.text.regex.MatchResult)2