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) {
String fileName = getFilename().trim();
String mode = getShareMode();
int modeInt = CSVDataSetBeanInfo.getShareModeAsInt(mode);
switch(modeInt) {
case CSVDataSetBeanInfo.SHARE_ALL:
alias = fileName;
break;
case CSVDataSetBeanInfo.SHARE_GROUP:
alias = fileName + "@" + System.identityHashCode(context.getThreadGroup());
break;
case CSVDataSetBeanInfo.SHARE_THREAD:
alias = fileName + "@" + System.identityHashCode(context.getThread());
break;
default:
// user-specified key
alias = fileName + "@" + mode;
break;
}
final String names = getVariableNames();
if (StringUtils.isEmpty(names)) {
String header = server.reserveFile(fileName, getFileEncoding(), alias, true);
try {
vars = CSVSaveService.csvSplitString(header, delim.charAt(0));
firstLineIsNames = true;
} catch (IOException e) {
throw new IllegalArgumentException("Could not split CSV header line from file:" + fileName, e);
}
} else {
server.reserveFile(fileName, getFileEncoding(), alias, ignoreFirstLine);
// $NON-NLS-1$
vars = JOrphanUtils.split(names, ",");
}
trimVarNames(vars);
}
// 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);
}
}
}
use of org.apache.jmeter.threads.JMeterContext 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);
}
}
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(new StringBuilder("IOException: ").append(e.getLocalizedMessage()).toString());
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);
}
}
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());
}
}
}
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, false);
}
return false;
}
return super.isDone();
}
Aggregations