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);
  }
  protected void initManager(ScriptEngineManager sem) {
    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());

    sem.put("log", logger);
    sem.put("Label", label);
    sem.put("FileName", fileName);
    sem.put("Parameters", scriptParameters);
    String[] args = JOrphanUtils.split(scriptParameters, " "); // $NON-NLS-1$
    sem.put("args", args);
    // Add variables for access to context and variables
    JMeterContext jmctx = JMeterContextService.getContext();
    sem.put("ctx", jmctx);
    JMeterVariables vars = jmctx.getVariables();
    sem.put("vars", vars);
    Properties props = JMeterUtils.getJMeterProperties();
    sem.put("props", props);
    // For use in debugging:
    sem.put("OUT", System.out);

    // Most subclasses will need these:
    Sampler sampler = jmctx.getCurrentSampler();
    sem.put("sampler", sampler);
    SampleResult prev = jmctx.getPreviousResult();
    sem.put("prev", prev);
  }
  @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"));
  }
예제 #4
0
 /** Tests that JMeterVariables contain inputVal_<count>, if not we can stop iterating */
 private boolean endOfArguments() {
   JMeterContext context = getThreadContext();
   String inputVariable = getInputVal() + getSeparator() + (loopCount + 1);
   if (context.getVariables().getObject(inputVariable) != null) {
     log.debug("ForEach resultstring eofArgs= false");
     return false;
   }
   log.debug("ForEach resultstring eofArgs= true");
   return true;
 }
예제 #5
0
  /** {@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;
  }
  @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"));
  }
예제 #7
0
 public void testGrabSessionId4() throws Exception {
   String html = "href='index.html;%24sid%24KQNq3AAADQZoEQAxlkX8uQV5bjqVBPbT'";
   response = new SampleResult();
   response.setResponseData(html.getBytes());
   URLRewritingModifier mod = new URLRewritingModifier();
   mod.setArgumentName("%24sid%24");
   mod.setPathExtension(true);
   mod.setPathExtensionNoEquals(true);
   HTTPSampler sampler = createSampler();
   context.setCurrentSampler(sampler);
   context.setPreviousResult(response);
   mod.process();
   Arguments args = sampler.getArguments();
   assertEquals("index.html;%24sid%24KQNq3AAADQZoEQAxlkX8uQV5bjqVBPbT", sampler.getPath());
 }
예제 #8
0
 public void testGrabSessionId3() throws Exception {
   String html = "href='index.html?session_id=jfdkjdkfjddkfdfjkdjfdf'";
   response = new SampleResult();
   response.setResponseData(html.getBytes());
   URLRewritingModifier mod = new URLRewritingModifier();
   mod.setArgumentName("session_id");
   HTTPSampler sampler = createSampler();
   context.setCurrentSampler(sampler);
   context.setPreviousResult(response);
   mod.process();
   Arguments args = sampler.getArguments();
   assertEquals(
       "jfdkjdkfjddkfdfjkdjfdf",
       ((Argument) args.getArguments().get(0).getObjectValue()).getValue());
 }
  @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"));
  }
  @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"));
  }
  @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"));
  }
  @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"));
  }
예제 #13
0
  /**
   * Check if there are any matching entries
   *
   * @return whether any entries in the list
   */
  private boolean emptyList() {
    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();
    if (context.getVariables().getObject(inputVariable) != null) {
      return false;
    }
    if (log.isDebugEnabled()) {
      log.debug("No entries found - null first entry: " + inputVariable);
    }
    return true;
  }
예제 #14
0
 public void testGrabSessionId() throws Exception {
   String html =
       "location: http://server.com/index.html?session_id=jfdkjdkf%20jddkfdfjkdjfdf%22;";
   response = new SampleResult();
   response.setResponseData(html.getBytes());
   URLRewritingModifier mod = new URLRewritingModifier();
   mod.setArgumentName("session_id");
   HTTPSampler sampler = createSampler();
   sampler.addArgument("session_id", "adfasdfdsafasdfasd");
   context.setCurrentSampler(sampler);
   context.setPreviousResult(response);
   mod.process();
   Arguments args = sampler.getArguments();
   assertEquals(
       "jfdkjdkf jddkfdfjkdjfdf\"",
       ((Argument) args.getArguments().get(0).getObjectValue()).getValue());
   assertEquals(
       "http://server.com/index.html?session_id=jfdkjdkf+jddkfdfjkdjfdf%22", sampler.toString());
 }
예제 #15
0
 /** {@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();
 }
예제 #16
0
  /**
   * 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);
    }
  }
예제 #17
0
 public String execute() throws InvalidVariableException {
   JMeterContext context = JMeterContextService.getContext();
   SampleResult previousResult = context.getPreviousResult();
   Sampler currentSampler = context.getCurrentSampler();
   return execute(previousResult, currentSampler);
 }