Java Code Examples for org.apache.jmeter.threads.JMeterVariables#put()

The following examples show how to use org.apache.jmeter.threads.JMeterVariables#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConversationUpdateSampler.java    From BotServiceStressToolkit with MIT License 6 votes vote down vote up
private String ensureFromUser() {
	JMeterContext context = getThreadContext();
	JMeterVariables vars = context.getVariables();

	String fromUserId = "";
	if (getGenRandomUserIdPerThread()) {
		if (vars.get(Constants.USER) == null) {
			fromUserId = "user-" + RandomStringUtils.randomAlphabetic(3, 7);
			vars.put(Constants.USER, fromUserId);
		} else {
			fromUserId = vars.get(Constants.USER);
		}
	} else {
		fromUserId = getFromMemberId();
	}

	return fromUserId;
}
 
Example 2
Source File: StrReplace.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {

    String totalString = getParameter(0).replace(getParameter(1), getParameter(2));

    JMeterVariables vars = getVariables();

    if (values.length > 3) {
        String varName = getParameter(3);
        if (vars != null && varName != null && varName.length() > 0) {// vars will be null on TestPlan
            vars.put(varName, totalString);
        }
    }

    return totalString;
}
 
Example 3
Source File: JSONPathExtractorTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example 4
Source File: FifoPop.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {
    String fifoName = ((CompoundVariable) values[0]).execute();

    String value = null;
    try {
        Object valueObj = FifoMap.getInstance().pop(fifoName, timeout);
        if (valueObj != null) {
            value = valueObj.toString();
        }
    } catch (InterruptedException ex) {
        log.warn("Interrupted pop from queue " + fifoName);
        value = "INTERRUPTED";
    }

    JMeterVariables vars = getVariables();
    if (vars != null && values.length > 1) {
        String varName = ((CompoundVariable) values[1]).execute().trim();
        vars.put(varName, value);
    }

    return value;
}
 
Example 5
Source File: MD5.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {
    JMeterVariables vars = getVariables();
    String str = ((CompoundVariable) values[0]).execute();
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("md5");
    } catch (NoSuchAlgorithmException ex) {
        return "Error creating digest: " + ex;
    }

    String res = JOrphanUtils.baToHexString(digest.digest(str.getBytes()));

    if (vars != null && values.length > 1) {
        String varName = ((CompoundVariable) values[1]).execute().trim();
        vars.put(varName, res);
    }

    return res;
}
 
Example 6
Source File: If.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {

    String actual = getParameter(0);
    String expected = getParameter(1);

    String result = null;
    if (actual.equals(expected)) {
        result = getParameter(2).toString();
    } else {
        result = getParameter(3).toString();
    }

    JMeterVariables vars = getVariables();
    if (vars != null && values.length > 4) {
        String varName = getParameter(4).trim();
        vars.put(varName, result);
    }

    return result;
}
 
Example 7
Source File: Base64Decode.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {
    String sourceString = values[0].execute();

    String decodedValue = new String(Base64.decodeBase64(sourceString));
    if (values.length > 1) {
        String variableName = values[1].execute();
        if (variableName.length() > 0) {// Allow for empty name
            final JMeterVariables variables = getVariables();
            if (variables != null) {
                variables.put(variableName, decodedValue);
            }
        }
    }
    return decodedValue;
}
 
Example 8
Source File: FlexibleFileWriterTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void testSampleOccurred_var() throws IOException {
    System.out.println("sampleOccurred-var");
    SampleResult res = new SampleResult();
    res.setResponseData("test".getBytes());
    JMeterVariables vars = new JMeterVariables();
    vars.put("TEST1", "TEST");
    SampleEvent e = new SampleEvent(res, "Test", vars);
    FlexibleFileWriter instance = new FlexibleFileWriter();
    instance.setFilename(File.createTempFile("ffw_test_", ".txt").getAbsolutePath());
    System.out.println("prop: " + JMeterUtils.getProperty("sample_variables"));
    System.out.println("count: " + SampleEvent.getVarCount());
    instance.setColumns("variable#0| |variable#| |variable#4t");
    instance.testStarted();
    for (int n = 0; n < 10; n++) {
        String exp = "TEST variable# variable#4t";
        System.out.println(exp);
        instance.sampleOccurred(e);
        //ByteBuffer written = instance.fileEmul.getWrittenBytes();
        //assertEquals(exp, JMeterPluginsUtils.byteBufferToString(written));
    }
    instance.testEnded();
}
 
Example 9
Source File: ParameterizedController.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
private void processVariables() {
    final Arguments args1 = (Arguments) this.getUserDefinedVariablesAsProperty().getObjectValue();
    Arguments args = (Arguments) args1.clone();

    final JMeterVariables vars = JMeterContextService.getContext().getVariables();

    Iterator<Entry<String, String>> it = args.getArgumentsAsMap().entrySet().iterator();
    Entry<String, String> var;
    while (it.hasNext()) {
        var = it.next();
        log.debug("Setting " + var.getKey() + "=" + var.getValue());
        vars.put(var.getKey(), var.getValue());
    }
}
 
Example 10
Source File: StrLen.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {
    JMeterVariables vars = getVariables();
    Integer len = ((CompoundVariable) values[0]).execute().length();

    if (vars != null && values.length > 1) {
        String varName = ((CompoundVariable) values[1]).execute().trim();
        vars.put(varName, len.toString());
    }

    return len.toString();

}
 
Example 11
Source File: RedisDataSet.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public void iterationStart(LoopIterationEvent event) {
    Jedis connection = null;
    try {
        connection = pool.getResource();

        // Get data from list's head
        String line = getDataFromConnection(connection, redisKey);

        if(line == null) { // i.e. no more data (nil)
            throw new JMeterStopThreadException("End of redis data detected");
        }

        if (getRecycleDataOnUse()) {
            addDataToConnection(connection, redisKey, line);
        }

        final String names = variableNames;
        if (vars == null) {
            vars = JOrphanUtils.split(names, ","); 
        }
        
        final JMeterContext context = getThreadContext();
        JMeterVariables threadVars = context.getVariables();
        String[] values = JOrphanUtils.split(line, delimiter, false);
        for (int a = 0; a < vars.length && a < values.length; a++) {
            threadVars.put(vars[a], values[a]);
        }
        
    } finally {
        pool.returnResource(connection);
    }
}
 
Example 12
Source File: ChooseRandom.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {
    JMeterVariables vars = getVariables();
    String varName = ((CompoundVariable) values[values.length - 1]).execute().trim();
    int index = random.nextInt(values.length - 1);
    String choice = ((CompoundVariable) values[index]).execute();

    if (vars != null && varName != null && varName.length() > 0) {// vars will be null on TestPlan
        vars.put(varName, choice);
    }

    return choice;
}
 
Example 13
Source File: DoubleSum.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {

    JMeterVariables vars = getVariables();

    Double sum = 0D;
    String varName = ((CompoundVariable) values[values.length - 1]).execute().trim();

    for (int i = 0; i < values.length - 1; i++) {
        sum += Double.parseDouble(((CompoundVariable) values[i]).execute());
    }

    try {
        sum += Double.parseDouble(varName);
        varName = null; // there is no variable name
    } catch (NumberFormatException ignored) {
    }

    String totalString = Double.toString(sum);
    if (vars != null && varName != null && varName.length() > 0) {// vars will be null on TestPlan
        vars.put(varName, totalString);
    }

    return totalString;

}
 
Example 14
Source File: LoadGenerator.java    From kafkameter with Apache License 2.0 5 votes vote down vote up
@Override
public void iterationStart(LoopIterationEvent loopIterationEvent) {
  if (generator == null) {
    generator = createGenerator(getClassName(), readFile(getFileName()));
  }
  JMeterVariables variables = JMeterContextService.getContext().getVariables();
  variables.put(getVariableName(), generator.nextMessage());
}
 
Example 15
Source File: SetVariablesActionTest.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    JMeterVariables vars = new JMeterVariables();
    vars.put("var1", "val1");
    JMeterContextService.getContext().setVariables(vars);
    JMeterContextService.getContext().setSamplingStarted(true);

    instance = new SetVariablesAction();
    instance.setRunningVersion(true);
}
 
Example 16
Source File: UpperCase.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
/**
 * {@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;

}
 
Example 17
Source File: LowerCase.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {
    JMeterVariables vars = getVariables();
    String res = ((CompoundVariable) values[0]).execute().toLowerCase();

    if (vars != null && values.length > 1) {
        String varName = ((CompoundVariable) values[1]).execute().trim();
        vars.put(varName, res);
    }

    return res;

}
 
Example 18
Source File: AggregatedTypeUpdaterTest.java    From jmeter-prometheus-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void testSummaryResponseSize() {
	BaseCollectorConfig base = TestUtilities.simpleSummaryCfg();
	base.setLabels(labels);
	ListenerCollectorConfig cfg = new ListenerCollectorConfig(base);
	cfg.setMetricName("ct_updater_test_summary_rsize");
	cfg.setMeasuring(Measurable.ResponseSize.toString());

	Summary collector = (Summary) reg.getOrCreateAndRegister(cfg);
	AggregatedTypeUpdater u = new AggregatedTypeUpdater(cfg);
	
	SampleResult res = new SampleResult();
	res.setSampleLabel(name);
	int responseSize = 650;
	res.setResponseData(new byte[responseSize]);
	res.setResponseCode(code);
	
	JMeterVariables vars = new JMeterVariables();
	vars.put("foo_label", var_value);
	JMeterContextService.getContext().setVariables(vars);
	SampleEvent e = new SampleEvent(res,"tg1", vars);
	
	
	String[] actualLabels = u.labelValues(e);
	Assert.assertArrayEquals(expectedLabels, actualLabels);
	
	u.update(e);
	
	List<MetricFamilySamples> metrics = collector.collect();
	Assert.assertEquals(1, metrics.size());
	MetricFamilySamples family = metrics.get(0);
	Assert.assertEquals(5, family.samples.size()); 	// 3 quantiles + count + sum
	
	
	for(Sample sample : family.samples) {
		List<String> values = sample.labelValues;
		List<String> names = sample.labelNames;
		
		this.correctLabels(names, values);
		
		// _sum and _count don't have an 'le' label
		if(sample.name.endsWith("count") || sample.name.endsWith("sum")) {
			assertTrue(values.size() == 3 && names.size() == 3);
			
			if(sample.name.endsWith("count")) {
				Assert.assertEquals(1, sample.value, 0.1);
			}else {
				Assert.assertEquals(responseSize, sample.value, 0.1);
			}
			
		}else {
			assertTrue(values.size() == 4 && names.size() == 4);
			Assert.assertEquals(responseSize, sample.value, 0.1);
		}
	}
}
 
Example 19
Source File: RandomCSVDataSetConfig.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
private void putVariables(JMeterVariables variables, String[] keys, String[] values) {
    int minLen = (keys.length > values.length) ? values.length : keys.length;
    for (int i = 0; i < minLen; i++) {
        variables.put(keys[i], values[i]);
    }
}
 
Example 20
Source File: BaseBotSampler.java    From BotServiceStressToolkit with MIT License 4 votes vote down vote up
protected Activity send(Activity activity) throws UnirestException, HttpResponseException, AuthenticationException {
	log.info(String.format(
			"Sending activity of type %s with activityId=%s, conversationId=%s with callbackUrl as %s",
			activity.getType(), activity.getId(), activity.getConversation().getId(), activity.getServiceUrl()));

	Jsonb jsonb = JsonbBuilder.create();
	String jsonPayload = jsonb.toJson(activity);

	log.debug("Sending payload: " + jsonPayload);

	RequestBodyEntity request = Unirest.post(getBotUrl()).body(jsonPayload);
	Map<String, List<String>> headers = request.getHttpRequest().getHeaders();
	headers.put(CONTENT_TYPE_HEADER_KEY, Collections.singletonList(CONTENT_TYPE_APPLICATION_JSON));

	if (hasAuthProperties()) {
		JMeterVariables vars = getThreadContext().getVariables();
		log.debug("Has security data");

		if (vars.get(TOKEN) == null) {
			log.debug("Token is null, authenticating");
			TokenResponse tokenResponse = AuthHelper.getToken(getPropertyAsString(BotServiceSecurityConfig.APP_ID),
					getPropertyAsString(BotServiceSecurityConfig.CLIENT_SECRET));

			vars.put(TOKEN, tokenResponse.getAccessToken());

		} else {
			log.debug("Token is not null, will reuse it");
		}

		String token = vars.get(TOKEN);
		headers.put(AUTHORIZATION_HEADER, Collections.singletonList("Bearer " + token));

	} else {
		log.debug("No security properties available. Will proceed without authentication.");
	}

	HttpResponse<InputStream> postResponse = request.asBinary();
	ensureResponseSuccess(postResponse);

	return activity;
}