How to concatenate string and integer values in jmeter - jmeter

I'm trying to concatenate string and integer values in JMeter as below
for(int i in 1..100){
def cloudItemId="cloudItemId"+i;
def deviceItemId="deviceItemId"+i;
}
but I'm getting this below error
Response message:Exception: groovy.lang.MissingMethodException: No signature of method:
java.lang.String.positive() is applicable for argument types: () values: []
Possible solutions: notify(), size(), tokenize()
How can Iconcatenate with cloudItemId/deviceItemId

I cannot reproduce your issue using latest JMeter 5.4.1 (you're supposed to be using the latest JMeter version just in case):
so pay attention to your syntax and suspicious entries in jmeter.log file.
You can also slightly refactor your code to use GStrings and make it more Groovy:
1.upto(100, { i ->
def cloudItemId = "cloudItemId$i"
def deviceItemId = "deviceItemId$i"
log.info('cloudItemId: ' + cloudItemId)
})

The issue is + sign is used for mathematic plus in integers and concatenation in Strings
You can concatenate using <<:
for(int i in 1..100){
def cloudItemId="cloudItemId" <<i;
log.info(cloudItemId.toString());
def deviceItemId="deviceItemId"<<i;
log.info(cloudItemId.toString());
}
Or call String.valueOf to concat Strings:
for(int i in 1..100){
def cloudItemId="cloudItemId" + String.valueOf(i);
log.info(cloudItemId);
def deviceItemId="deviceItemId"+ String.valueOf(i)
log.info(cloudItemId);
}

Related

Jmeter throws error on Encryption - using Public Key

I am currently working in a application where RSA Encryption is being used for Encrypting sensitive data. I have tried incorporating the standard encryption method but it is throwing errors. I have selected the language Groovy. Can someone throw light on whether i am doing it right?
import javax.crypto.Cipher
import java.security.KeyFactory
import java.security.spec.X509EncodedKeySpec
def publicKey = '5dy47yt7ty5ad283c0c4955f53csa24wse244wfrfafa34239rsgd89gfsg8342r93r98efae89fdf9983r9gjsdgnsgjkwt23r923r2r0943tf9sdg9d8gfsgf90sgsf89grw098tg09s90ig90g90s903r5244r517823rea8f8werf9842tf24tf42e0132saf9fg6f65afa43f12r103tf4040ryrw0e9rtqtwe0r9t04ty8842t03e9asfads0fgadg675'
def x509PublicKey = new X509EncodedKeySpec(publicKey.decodeBase64())
def keyFactory = KeyFactory.getInstance('RSA')
def key = keyFactory.generatePublic(x509Publickey)
def string2Encrypt = '("testinga#gmail.com|testingb#gmail.com").'
def encryptCipher = Cipher.getInstance('RSA')
encryptCipher.init(Cipher.ENCRYPT_MODE,key)
def secretMessage = string2Encrypt.getBytes('UTF-8')
def encryptedMessage = encryptCipher.doFinal(secretMessage)
def encodedMessage = encryptedMessage.encodedBase64().toString()
vars.put('encodedMessage',encodedMessage)
The Output Error i am getting
Response Code: 500
Response Message:javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: x509Publickey for class: Script4
SampleResult fields:
ContentType:
DataEncoding: null
You have:
def x509PublicKey
^ mind the capital K
and
def key = keyFactory.generatePublic(x509Publickey)
^ mind the lower-case k
in Groovy they're absolutely different beasts and case sensitivity matters a lot, choose one option and stick to it and "your" script will start working as expected (or at least this error will go away)
More information:
Apache Groovy - Syntax
Apache Groovy - Why and How You Should Use It

jmeter: evaluate the values of JSON values

I am trying to test my API response using JSON assertion in JMeter, but couldn't find out on how to achieve it. The API returns 2 values, and I need to check if the difference between these two value are consistent
API response:
{
"start": "12759898",
"end": "12759907"
}
I've tried like the above, but it seems to be wrong, as its a JSONPath variable.
Could anyone guide on how to evaluate these values? is it possible to achieve this?
It looks like a job for JSR223 Assertion
Add JSR223 Assertion as a child of the request which returns the above JSON
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def start = response.start as long
def end = response.end as long
def delta = end - start
if (delta != 10) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Expected: 10, got: ' + delta)
}
If the difference between start and end will not be equal to 10 - the request will be marked as failed.
More information:
Groovy: Parsing and producing JSON
Scripting JMeter Assertions in Groovy - A Tutorial

How to pass symbol as parameter of post request in ruby?

This code work well
Geokit::default_units = :miles #:kms, :nms, :meters
But this code make errors
puts params[:unit] # miles
Geokit::default_units = params[:unit] #:miles, :kms, :nms, :meters
What is wrong with this?
That's because all that goes through the params is an string, if you want a symbol, then consider using .to_sym:
params = { unit: 'miles' }
p params[:unit].class # String
p params[:unit].to_sym.class # Symbol
have you confirmed that params[:unit] is actually a symbol, and not a string?
Geokit::default_units = params[:unit].to_sym
If the above solves your problem, then you didn't have a symbol in there to start with (likely, if params has been read from an HTTP request)

HMAC-SHA1 in bash

Is there a bash script available to generate a HMAC-SHA1 hash?
The equivalent of the following PHP code:
hash_hmac("sha1", "value", "key", TRUE);
Parameters
true : When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.
Thanks.
see HMAC-SHA1 in bash
In bash itself, no, it can do a lot of stuff but it also knows when to rely on external tools.
For example, the Wikipedia page provides a Python implementation which bash can call to do the grunt work for HMAC_MD5, repeated below to make this answer self-contained:
#!/usr/bin/env python
from hashlib import md5
trans_5C = "".join(chr(x ^ 0x5c) for x in xrange(256))
trans_36 = "".join(chr(x ^ 0x36) for x in xrange(256))
blocksize = md5().block_size
def hmac_md5(key, msg):
if len(key) > blocksize:
key = md5(key).digest()
key += chr(0) * (blocksize - len(key))
o_key_pad = key.translate(trans_5C)
i_key_pad = key.translate(trans_36)
return md5(o_key_pad + md5(i_key_pad + msg).digest())
if __name__ == "__main__":
h = hmac_md5("key", "The quick brown fox jumps over the lazy dog")
print h.hexdigest() # 80070713463e7749b90c2dc24911e275
(keeping in mind that Python also contains SHA1 stuff as well, see here for details on how to use HMAC with the hashlib.sha1() constructor).
Or, if you want to run the exact same code as PHP does, you could try running it with phpsh, as detailed here.

Jython: Determine the number of arguments a Java method takes at runtime

I'm trying to write an object inspector for Java objects in Jython, and I want to determine how many arguments a given Java method expects. Is there any way to do that in python, or do I have to use Java reflection for that.
To explain, I'd like to call all "get..." methods of a Java object that don't take any arguments:
from java.util import Date, ArrayList
def numberOfArguments(fct):
# Some magic happens here
return 0
def check(o):
print("")
print(type(o).name)
for fctName in dir(o):
if not str(fctName).startswith("get"): continue
print("== " + fctName)
fct = eval("o."+fctName)
if numberOfArguments(fct) == 0:
print(" " + str(fct()))
check(Date())
check(ArrayList())
Oh well, it turns out that I was doing the wrong thing by using dir(obj). It's just way easier to use o.getClass().getMethods(). This way, I also don't get bitten by overloaded methods.
from java.util import Date, ArrayList
def numberOfArguments(fct):
# Not very magic:
return len(fct.getParameterTypes())
def check(o):
print("")
print(type(o).name)
# Use Java reflection instead of Python dir() function
for fct in o.getClass().getMethods():
fctName = fct.getName()
if not str(fctName).startswith("get"): continue
print("== " + fctName)
if numberOfArguments(fct) == 0:
print(" " + str(fct.invoke(o, [])))
check(Date())
check(ArrayList())

Resources