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());
 }
Exemplo n.º 2
0
  public void process() {
    Sampler sampler = JMeterContextService.getContext().getCurrentSampler();
    SampleResult responseText = JMeterContextService.getContext().getPreviousResult();
    if (responseText == null) {
      return;
    }
    initRegex(getArgumentName());
    String text = new String(responseText.getResponseData());
    Perl5Matcher matcher = JMeterUtils.getMatcher();
    String value = "";
    if (matcher.contains(text, case1)) {
      MatchResult result = matcher.getMatch();
      value = result.group(1);
    } else if (matcher.contains(text, case2)) {
      MatchResult result = matcher.getMatch();
      value = result.group(1);
    } else if (matcher.contains(text, case3)) {
      MatchResult result = matcher.getMatch();
      value = result.group(1);
    } else if (matcher.contains(text, case4)) {
      MatchResult result = matcher.getMatch();
      value = result.group(1);
    }

    modify((HTTPSampler) sampler, value);
  }
Exemplo n.º 3
0
 /** @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));
   }
 }
  @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"));
  }
  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);
  }
Exemplo n.º 6
0
  // @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;
  }
 @Before
 public void createConfig() {
   config = new RemoteDriverConfig();
   variables = new JMeterVariables();
   config.setCapability(RemoteCapability.CHROME);
   JMeterContextService.getContext().setVariables(variables);
 }
  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 void setUp() throws Exception {
   super.setUp();
   jmctx = JMeterContextService.getContext();
   man = new CookieManager();
   man.setThreadContext(jmctx);
   man.testStarted(); // This is needed in order to set up the cookie policy
 }
  @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);
    }
  }
Exemplo n.º 11
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;
  }
Exemplo n.º 12
0
  @Override
  public void testIterationStart(LoopIterationEvent event) {

    final long lCurrentTime = new Date().getTime();

    if (checkEndInLock(lCurrentTime)) {
      final JMeterThread lThread = JMeterContextService.getContext().getThread();
      LOGGER.info(String.format("Cooldown stoping Thread: [%s]", lThread.getThreadName()));
      // change to jmeter 2.8
      if (!StandardJMeterEngine.stopThreadNow(lThread.getThreadName())) {
        LOGGER.warn(String.format("could not stop Thread: [%s]", lThread.getThreadName()));
      }
    }
  }
  @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"));
  }
Exemplo n.º 14
0
  public static MongoDB getMongoDB(String source) {

    Object mongoSource = JMeterContextService.getContext().getVariables().getObject(source);

    if (mongoSource == null) {
      throw new IllegalStateException("mongoSource is null");
    } else {
      if (mongoSource instanceof MongoDB) {
        return (MongoDB) mongoSource;
      } else {
        throw new IllegalStateException(
            "Variable:" + source + " is not a MongoDB instance, class:" + mongoSource.getClass());
      }
    }
  }
  @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"));
  }
 public AbstractThreadStarter(
     int groupIndex,
     AbstractDynamicThreadGroup owner,
     ListedHashTree listedHashTree,
     ListenerNotifier listenerNotifier,
     StandardJMeterEngine standardJMeterEngine) {
   super();
   this.owner = owner;
   this.treeClone = cloneTree(listedHashTree); // it needs owner inside
   this.engine = standardJMeterEngine;
   this.groupIndex = groupIndex;
   this.threadGroupTree = listedHashTree;
   this.notifier = listenerNotifier;
   this.context = JMeterContextService.getContext();
   setDaemon(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"));
  }
 /**
  * コンフィグデータに問題ないか確認
  *
  * @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;
 }
Exemplo n.º 19
0
 /**
  * Get the next or only alias.
  *
  * @return the next or only alias.
  * @throws IllegalArgumentException if {@link JmeterKeyStore#clientCertAliasVarName
  *     clientCertAliasVarName} is not empty and no key for this alias could be found
  */
 public String getAlias() {
   if (!StringUtils.isEmpty(clientCertAliasVarName)) {
     // We return even if result is null
     String aliasName =
         JMeterContextService.getContext().getVariables().get(clientCertAliasVarName);
     if (StringUtils.isEmpty(aliasName)) {
       LOG.error("No var called '" + clientCertAliasVarName + "' found");
       throw new IllegalArgumentException("No var called '" + clientCertAliasVarName + "' found");
     }
     return aliasName;
   }
   int length = this.names.length;
   if (length == 0) { // i.e. is == null
     return null;
   }
   return this.names[getIndexAndIncrement(length)];
 }
  @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"));
  }
Exemplo n.º 22
0
 public void setUp() {
   context = JMeterContextService.getContext();
 }
 @After
 public void resetConfig() {
   config.clearThreadBrowsers();
   config.getServices().clear();
   JMeterContextService.getContext().setVariables(null);
 }
Exemplo n.º 24
0
 protected JMeterVariables getVariables() {
   return JMeterContextService.getContext().getVariables();
 }
 @Before
 public void createConfig() {
   config = new ChromeDriverConfig();
   variables = new JMeterVariables();
   JMeterContextService.getContext().setVariables(variables);
 }
Exemplo n.º 26
0
 public String execute() throws InvalidVariableException {
   JMeterContext context = JMeterContextService.getContext();
   SampleResult previousResult = context.getPreviousResult();
   Sampler currentSampler = context.getCurrentSampler();
   return execute(previousResult, currentSampler);
 }