/** @see LoopIterationListener#iterationStart(LoopIterationEvent) */ @Override public void iterationStart(LoopIterationEvent event) { // Cannot use getThreadContext() as not cloned per thread JMeterVariables variables = JMeterContextService.getContext().getVariables(); long start = getStart(); long end = getEnd(); long increment = getIncrement(); if (!isPerUser()) { synchronized (this) { if (globalCounter == Long.MIN_VALUE || globalCounter > end) { globalCounter = start; } variables.put(getVarName(), formatNumber(globalCounter)); globalCounter += increment; } } else { long current = perTheadNumber.get().longValue(); if (isResetOnThreadGroupIteration()) { int iteration = variables.getIteration(); Long lastIterationNumber = perTheadLastIterationNumber.get(); if (iteration != lastIterationNumber.longValue()) { // reset current = getStart(); } perTheadLastIterationNumber.set(Long.valueOf(iteration)); } variables.put(getVarName(), formatNumber(current)); current += increment; if (current > end) { current = start; } perTheadNumber.set(Long.valueOf(current)); } }
/** * Creates the variables:<br> * basename_gn, where n=0...# of groups<br> * basename_g = number of groups (apart from g0) */ private void saveGroups(JMeterVariables vars, String basename, MatchResult match) { StringBuilder buf = new StringBuilder(); buf.append(basename); buf.append("_g"); // $NON-NLS-1$ int pfxlen = buf.length(); String prevString = vars.get(buf.toString()); int previous = 0; if (prevString != null) { try { previous = Integer.parseInt(prevString); } catch (NumberFormatException e) { log.warn("Could not parse " + prevString + " " + e); } } // Note: match.groups() includes group 0 final int groups = match.groups(); for (int x = 0; x < groups; x++) { buf.append(x); vars.put(buf.toString(), match.group(x)); buf.setLength(pfxlen); } vars.put(buf.toString(), Integer.toString(groups - 1)); for (int i = groups; i <= previous; i++) { buf.append(i); vars.remove(buf.toString()); // remove the remaining _gn vars buf.setLength(pfxlen); } }
// @Override public SampleResult runTest(JavaSamplerContext arg0) { JMeterVariables vars = JMeterContextService.getContext().getVariables(); vars.put("demo", "demoVariableContent"); setupValues(arg0); SampleResult sampleResult = new SampleResult(); sampleResult.sampleStart(); System.out.println("/level/du/parents: " + level + ", " + du + ", " + parents); // JUnitCore junit = new JUnitCore(); // Result result = junit.run(AuthenticationTest.class); // if (result.getFailureCount() > 0) { // sampleResult.setSuccessful(false); // sampleResult.setResponseCode("301"); // sampleResult.setResponseMessage("FailureCount: " // + result.getFailureCount()); // } else { sampleResult.setSuccessful(true); sampleResult.setResponseCodeOK(); sampleResult.setResponseMessageOK(); // } sampleResult.sampleEnd(); return sampleResult; }
private void saveGroups(MatchResult result) { if (result != null) { JMeterVariables vars = getVariables(); for (int x = 0; x < result.groups(); x++) { vars.put(name + "_g" + x, result.group(x)); } } }
/** {@inheritDoc} */ @Override public synchronized String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { if (bshInterpreter == null) // did we find BeanShell? { throw new InvalidVariableException("BeanShell not found"); } JMeterContext jmctx = JMeterContextService.getContext(); JMeterVariables vars = jmctx.getVariables(); String script = ((CompoundVariable) values[0]).execute(); String varName = ""; // $NON-NLS-1$ if (values.length > 1) { varName = ((CompoundVariable) values[1]).execute().trim(); } String resultStr = ""; // $NON-NLS-1$ log.debug("Script=" + script); try { // Pass in some variables if (currentSampler != null) { bshInterpreter.set("Sampler", currentSampler); // $NON-NLS-1$ } if (previousResult != null) { bshInterpreter.set("SampleResult", previousResult); // $NON-NLS-1$ } // Allow access to context and variables directly bshInterpreter.set("ctx", jmctx); // $NON-NLS-1$ bshInterpreter.set("vars", vars); // $NON-NLS-1$ bshInterpreter.set("props", JMeterUtils.getJMeterProperties()); // $NON-NLS-1$ bshInterpreter.set("threadName", Thread.currentThread().getName()); // $NON-NLS-1$ // Execute the script Object bshOut = bshInterpreter.eval(script); if (bshOut != null) { resultStr = bshOut.toString(); } if (vars != null && varName.length() > 0) { // vars will be null on TestPlan vars.put(varName, resultStr); } } catch (Exception ex) // Mainly for bsh.EvalError { log.warn("Error running BSH script", ex); } log.debug("Output=" + resultStr); return resultStr; }
/** {@inheritDoc} */ @Override public synchronized String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { JMeterVariables vars = getVariables(); String res = ((CompoundVariable) values[0]).execute().toUpperCase(); if (vars != null && values.length > 1) { String varName = ((CompoundVariable) values[1]).execute().trim(); vars.put(varName, res); } return res; }
private String generateResult(MatchResult match) { saveGroups(match); StringBuffer result = new StringBuffer(); for (int a = 0; a < template.length; a++) { if (template[a] instanceof String) { result.append(template[a]); } else { result.append(match.group(((Integer) template[a]).intValue())); } } JMeterVariables vars = getVariables(); vars.put(name, result.toString()); return result.toString(); }
/** {@inheritDoc} */ @Override public synchronized String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { String fileName = ((CompoundVariable) values[0]).execute(); String encoding = null; // means platform default if (values.length >= ENCODING) { encoding = ((CompoundVariable) values[ENCODING - 1]).execute().trim(); if (encoding.length() <= 0) { // empty encoding, return to platorm default encoding = null; } } String myName = ""; // $NON-NLS-1$ if (values.length >= PARAM_NAME) { myName = ((CompoundVariable) values[PARAM_NAME - 1]).execute().trim(); } String myValue = ERR_IND; try { myValue = FileUtils.readFileToString(new File(fileName), encoding); } catch (IOException e) { log.warn("Could not read file: " + fileName + " " + e.getMessage(), e); throw new JMeterStopThreadException("End of sequence", e); } if (myName.length() > 0) { JMeterVariables vars = getVariables(); if (vars != null) { // Can be null if called from Config item testEnded() method vars.put(myName, myValue); } } if (log.isDebugEnabled()) { String tn = Thread.currentThread().getName(); log.debug( tn + " name:" //$NON-NLS-1$ + myName + " value:" + myValue); //$NON-NLS-1$ } return myValue; }
@Override public synchronized void process() { if (file == null) { log.info("Creating file object: " + getFileName()); try { file = new FileInputStream(getFileName()).getChannel(); } catch (FileNotFoundException ex) { log.error(getFileName(), ex); return; } } String rawData; try { rawData = readNextChunk(getNextChunkSize()); } catch (EndOfFileException ex) { if (getRewindOnEOF()) { if (log.isDebugEnabled()) { log.debug("Rewind file"); } try { file.position(0); } catch (IOException ex1) { log.error("Cannot rewind", ex1); } process(); return; } else { log.info("End of file reached: " + getFileName()); if (JMeterContextService.getContext().getThread() != null) { JMeterContextService.getContext().getThread().stop(); } throw new RuntimeEOFException("End of file reached", ex); } } catch (IOException ex) { log.error("Error reading next chunk", ex); throw new RuntimeException("Error reading next chunk", ex); } final JMeterVariables vars = JMeterContextService.getContext().getVariables(); if (vars != null) { vars.put(getVarName(), rawData); } }
/** {@inheritDoc} */ @Override public synchronized String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { /* * boolean fullHostName = false; if (((CompoundFunction) values[0]) * .execute() .toLowerCase() .equals("true")) { fullHostName = true; } */ String machineName = JMeterUtils.getLocalHostName(); if (values.length >= 1) { // we have a variable name JMeterVariables vars = getVariables(); if (vars != null) { // May be null if function is used on TestPlan String varName = ((CompoundVariable) values[0]).execute().trim(); if (varName.length() > 0) { vars.put(varName, machineName); } } } return machineName; }
@Test public void testProcess_from_var() { System.out.println("process fromvar"); JMeterContext context = JMeterContextService.getContext(); JMeterVariables vars = context.getVariables(); SampleResult res = new SampleResult(); res.setResponseData("".getBytes()); context.setPreviousResult(res); vars.put("SVAR", json); JSONPathExtractor instance = new JSONPathExtractor(); instance.setDefaultValue("DEFAULT"); instance.setVar("test"); instance.setJsonPath("$.store.book[*].author"); instance.setSubject(JSONPathExtractor.SUBJECT_VARIABLE); instance.setSrcVariableName("SVAR"); instance.process(); assertEquals( "[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]", vars.get("test")); }
private void setValues() { synchronized (lock) { if (log.isDebugEnabled()) { log.debug( Thread.currentThread().getName() + " Running up named: " + getName()); // $NON-NLS-1$ } PropertyIterator namesIter = getNames().iterator(); PropertyIterator valueIter = getValues().iterator(); JMeterVariables jmvars = getThreadContext().getVariables(); while (namesIter.hasNext() && valueIter.hasNext()) { String name = namesIter.next().getStringValue(); String value = valueIter.next().getStringValue(); if (log.isDebugEnabled()) { log.debug( Thread.currentThread().getName() + " saving variable: " + name + "=" + value); //$NON-NLS-1$ } jmvars.put(name, value); } } }
/** * 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) { // Only replace default if it is provided 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) { vars.remove(refName + REF_MATCH_NR); // ensure old value is not left defined try { prevCount = Integer.parseInt(prevString); } catch (NumberFormatException e1) { log.warn("Could not parse " + prevString + " " + e1); } } int matchCount = 0; // Number of refName_n variable sets to keep 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 { removeGroups(vars, refName); // remove any single matches matchCount = matches.size(); vars.put(refName + REF_MATCH_NR, Integer.toString(matchCount)); // Save the count 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); } }