/** * 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); } }
public void process() { JMeterVariables vars = JMeterContextService.getContext().getVariables(); String threadId = vars.getObject(THREAD_ID).toString(); SampleResult previousResult = JMeterContextService.getContext().getPreviousResult(); Map<String, String> map = (Map<String, String>) vars.getObject(mapName); map.put(threadId, previousResult.getResponseDataAsString()); }
/** @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)); } }
protected void initManager(BSFManager mgr) throws BSFException { final String label = getName(); final String fileName = getFilename(); final String scriptParameters = getParameters(); // Use actual class name for log final Logger logger = LoggingManager.getLoggerForShortName(getClass().getName()); mgr.declareBean("log", logger, Logger.class); // $NON-NLS-1$ mgr.declareBean("Label", label, String.class); // $NON-NLS-1$ mgr.declareBean("FileName", fileName, String.class); // $NON-NLS-1$ mgr.declareBean("Parameters", scriptParameters, String.class); // $NON-NLS-1$ String[] args = JOrphanUtils.split(scriptParameters, " "); // $NON-NLS-1$ mgr.declareBean("args", args, args.getClass()); // $NON-NLS-1$ // Add variables for access to context and variables JMeterContext jmctx = JMeterContextService.getContext(); JMeterVariables vars = jmctx.getVariables(); Properties props = JMeterUtils.getJMeterProperties(); mgr.declareBean("ctx", jmctx, jmctx.getClass()); // $NON-NLS-1$ mgr.declareBean("vars", vars, vars.getClass()); // $NON-NLS-1$ mgr.declareBean("props", props, props.getClass()); // $NON-NLS-1$ // For use in debugging: mgr.declareBean("OUT", System.out, PrintStream.class); // $NON-NLS-1$ // Most subclasses will need these: Sampler sampler = jmctx.getCurrentSampler(); mgr.declareBean("sampler", sampler, Sampler.class); SampleResult prev = jmctx.getPreviousResult(); mgr.declareBean("prev", prev, SampleResult.class); }
// @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(); }
@Test public void testProcess_default() { System.out.println("process def"); JMeterContext context = JMeterContextService.getContext(); SampleResult res = new SampleResult(); context.setPreviousResult(res); JSONPathExtractor instance = new JSONPathExtractor(); instance.setDefaultValue("DEFAULT"); instance.setVar("test"); instance.process(); JMeterVariables vars = context.getVariables(); assertEquals("DEFAULT", vars.get("test")); }
private List<MatchResult> processMatches( Pattern pattern, String regex, SampleResult result, int matchNumber, JMeterVariables vars) { if (log.isDebugEnabled()) { log.debug("Regex = " + regex); } Perl5Matcher matcher = JMeterUtils.getMatcher(); List<MatchResult> matches = new ArrayList<MatchResult>(); int found = 0; if (isScopeVariable()) { String inputString = vars.get(getVariableName()); if (inputString == null) { log.warn( "No variable '" + getVariableName() + "' found to process by RegexExtractor '" + getName() + "', skipping processing"); return Collections.emptyList(); } matchStrings(matchNumber, matcher, pattern, matches, found, inputString); } else { List<SampleResult> sampleList = getSampleList(result); for (SampleResult sr : sampleList) { String inputString = getInputString(sr); found = matchStrings(matchNumber, matcher, pattern, matches, found, inputString); if (matchNumber > 0 && found == matchNumber) { // no need to process further break; } } } return matches; }
@Test public void testReported1_3() { System.out.println("process reported"); JMeterContext context = JMeterContextService.getContext(); SampleResult res = new SampleResult(); res.setResponseData(json2.getBytes()); context.setPreviousResult(res); JSONPathExtractor instance = new JSONPathExtractor(); instance.setVar("GroupID"); instance.setJsonPath("$.data.groups[?(@.name==Avtovaz)].id"); instance.setDefaultValue("NOTFOUND"); instance.process(); JMeterVariables vars = context.getVariables(); assertEquals("NOTFOUND", vars.get("GroupID")); }
/** {@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; }
/** * コンフィグデータに問題ないか確認 * * @param result * @return */ protected boolean checkConfig(SampleResult result) { if (result == null) { return false; } JMeterVariables variables = JMeterContextService.getContext().getVariables(); Object obj = variables.getObject(getVariableName()); if (!(obj instanceof RtmpConnectConfig)) { setupResult(result, "variableName is invalid" + getVariableName(), false); return false; } rtmpConnectConfig = (RtmpConnectConfig) obj; if (!rtmpConnectConfig.isValid()) { setupResult(result, rtmpConnectConfig.getName() + "'s rtmpurl is invalid...", false); return false; } return true; }
@Test public void testReported1_1() { System.out.println("process reported"); JMeterContext context = JMeterContextService.getContext(); SampleResult res = new SampleResult(); res.setResponseData(json2.getBytes()); context.setPreviousResult(res); JSONPathExtractor instance = new JSONPathExtractor(); instance.setVar("GroupID"); instance.setJsonPath("$.data.groups[*].id"); instance.setDefaultValue("NOTFOUND"); instance.process(); JMeterVariables vars = context.getVariables(); assertNotEquals("NOTFOUND", vars.get("GroupID")); assertEquals("e02991f4-a95d-43dd-8eb0-fbc44349e238", vars.get("GroupID_1")); }
@Test public void testProcess_list() { System.out.println("process list"); JMeterContext context = JMeterContextService.getContext(); SampleResult res = new SampleResult(); res.setResponseData("{\"myval\": [{\"test\":1},{\"test\":2},{\"test\":null}]}".getBytes()); context.setPreviousResult(res); JSONPathExtractor instance = new JSONPathExtractor(); instance.setDefaultValue("DEFAULT"); instance.setVar("test"); instance.setJsonPath("$.myval[*].test"); instance.process(); JMeterVariables vars = context.getVariables(); assertEquals("[1,2,null]", vars.get("test")); assertEquals("1", vars.get("test_1")); assertEquals("2", vars.get("test_2")); assertEquals("null", vars.get("test_3")); // test for cleaning prev vars res.setResponseData("{\"myval\": [{\"test\":1},{\"test\":2}]}".getBytes()); instance.process(); assertEquals("[1,2]", vars.get("test")); assertEquals("1", vars.get("test_1")); assertEquals("2", vars.get("test_2")); assertEquals(null, vars.get("test_3")); }
@Test public void testProcess() { System.out.println("process"); JMeterContext context = JMeterContextService.getContext(); SampleResult res = new SampleResult(); res.setResponseData(json.getBytes()); context.setPreviousResult(res); JSONPathExtractor instance = new JSONPathExtractor(); instance.setDefaultValue("DEFAULT"); instance.setVar("test"); instance.setJsonPath("$.store.book[*].author"); instance.process(); JMeterVariables vars = context.getVariables(); assertEquals( "[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]", vars.get("test")); }
@Ignore @Test // FIXME: we need to solve this one day public void testReported2() { System.out.println("process reported"); JMeterContext context = JMeterContextService.getContext(); SampleResult res = new SampleResult(); res.setResponseData(json3.getBytes()); context.setPreviousResult(res); JSONPathExtractor instance = new JSONPathExtractor(); instance.setVar("var"); instance.setJsonPath("$.data[?(@.attr.value>0)][0].attr"); instance.setDefaultValue("NOTFOUND"); instance.process(); JMeterVariables vars = context.getVariables(); assertNotEquals("NOTFOUND", vars.get("var")); assertEquals("{value=1}", vars.get("var")); }
@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); } }
/** * Removes the variables:<br> * basename_gn, where n=0...# of groups<br> * basename_g = number of groups (apart from g0) */ private void removeGroups(JMeterVariables vars, String basename) { StringBuilder buf = new StringBuilder(); buf.append(basename); buf.append("_g"); // $NON-NLS-1$ int pfxlen = buf.length(); // How many groups are there? int groups; try { groups = Integer.parseInt(vars.get(buf.toString())); } catch (NumberFormatException e) { groups = 0; } vars.remove(buf.toString()); // Remove the group count for (int i = 0; i <= groups; i++) { buf.append(i); vars.remove(buf.toString()); // remove the g0,g1...gn vars buf.setLength(pfxlen); } }
/** {@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; }
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); } } }
/** {@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("ForEach resultstring isDone=" + variables.get(getReturnVal())); } return false; } return super.isDone(); }
/** * 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); } }