Java script written for UUID is not working in jmeter - javascript

Find below the code we have developed in java script to run in jmeter using JSR223 sampler(running as a java script). The same code worked on Jquery when developed but not posting the id while running in jmeter. the error thrown is "appid" is not defined. Could someone help debugging the issue looking at the code
vars.put("guid", "${__UUID}"); 
vars.put("appId", "ce547c40-acf9-11e6-80f5-76304dec7eb7");
var id=getAppInfo(appId, guid);
function getAppInfo(appId, guid)
{
var appInfo = null;
var appIdBytes = guidToBytes(appId);
var guidBytes = guidToBytes(guid);
var appInfoBytes = [];
for (var cnt = 0; cnt < appIdBytes.length; cnt++)
{
appInfoBytes[cnt] = appIdBytes[cnt] + guidBytes[cnt];
}
var appInfoGuidfromBytes = bytesToGuid(appInfoBytes);
return appInfoGuidfromBytes;
}
function bytesToGuid(guidBytes) {
var x = guidBytes;
var result = "";
var bytes = x.slice(0, 4).reverse().concat(x.slice(4, 6).reverse()).concat(x.slice(6, 8).reverse()).concat(x.slice(8));
var y = bytes.map(function (item) { return ('00' + item.toString(16)).substr(-2, 2) });
var byteArray = y;
for (var cnt = 0; cnt < byteArray.length; cnt++) {
if (cnt === 4 || cnt === 6 || cnt === 8 || cnt === 10)
result = result + "-" + byteArray[cnt];
else
result = result + byteArray[cnt];
}
return result;
}
function guidToBytes(guid) {
var bytes = [];
guid.split('-').map(function (number, index) {
var bytesInChar = index < 3 ? number.match(/.{1,2}/g).reverse() : number.match(/.{1,2}/g);
bytesInChar.map(function (byte) { bytes.push(parseInt(byte, 16)); });
});
return bytes;
}
// Create the Randon Number. It will call from NewGuid function.
function getRandomNumber() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
// Creating GUID eg. "cbe26df8-2b01-4377-9ae8-1d023ccd5171"
// getRandomNumber returns 4 digit Alphanumeric number and we are going to concatenating this with "-" symbol and third number starts with "-4" and substring the random number and concatenate the string and return.
function newGuid() {
return (getRandomNumber() + getRandomNumber() + "-" + getRandomNumber() + "-4" + getRandomNumber().substr(0, 3) + "-" + getRandomNumber() + "-" + getRandomNumber() + getRandomNumber() + getRandomNumber()).toLowerCase();
};

You shouldn't call JMeter's function inside JSR223 script.
Instead, add it to Parameters field as ${__UUID}
and then use it using args:
vars.put("guid", args[0]);
args - the parameters as a String array (split on whitespace)

Related

Copy string and increment version

For example if we have string str and I copy it it will be str_1, str_2, str_3 and so on..
If I copy str_2 then it will be str_2_1, str_2_2 and so on.
I have following logic but it does not work..
It should return 'Test2_5' (because Test2 AND Test2_4 already exists) but it returns 'Test2_4'
function createName(nameToCopy) {
var i;
var version = 1;
var nameCopiesArr = ["Test2", "Test2_2",
"Test2_3",
"Test2_4",
"Test2_2_2",
"Test2_3_1",
"Test2_2_1_2",
"Test2_2_3"
];
if (nameCopiesArr && nameCopiesArr.length > 1) {
for (i = 0; i < nameCopiesArr.length; i++) {
var indexes = nameCopiesArr[i].lastIndexOf('_') ? nameCopiesArr[i].match(/\d+$/) : 0
if (indexes) {
version = indexes[indexes.length - 1];
version = parseInt(version) + 1;
}
}
}
p = nameToCopy + '_' + version;
document.getElementById("demo").innerHTML = p;
return p;
}
<button onclick="createName('Test2')">Click me</button>
<p id="demo"></p>
You could search for all string which starts with the given name and a dash and an ending number. Then take the max number of ending and return the given string with an incremented version.
function createName(nameToCopy) {
var copies = ["Test2", "Test2_2", "Test2_3", "Test2_4", "Test2_2_2", "Test2_3_1", "Test2_2_1_2", "Test2_2_3"],
filtered = copies.filter(/./.test.bind(new RegExp(nameToCopy + '_' + '\\d+$'))),
version = filtered.reduce((v, s) => Math.max(v, +s.match(/\d+$/)[0]), 0);
return nameToCopy + '_' + ++version;
}
console.log(['Test2', 'Test', 'Test2_2'].map(createName));
More traditional
function createName(nameToCopy) {
var copies = ["Test2", "Test2_2", "Test2_3", "Test2_4", "Test2_2_2", "Test2_3_1", "Test2_2_1_2", "Test2_2_3"],
regexp = new RegExp(nameToCopy + '_' + '\\d+$'),
version = 0,
i, v;
for (i = 0; i < copies.length; i++) {
if (regexp.test(copies[i])) {
v = +copies[i].match(/\d+$/)[0];
if (v > version) {
version = v;
}
}
}
return nameToCopy + '_' + (version + 1);
}
console.log(['Test2', 'Test', 'Test2_2'].map(createName));
I update your code to test the number of the '_' char and if the current string contains the given input.
function createName(nameToCopy) {
var i;
var version = 1;
var nameToCopy_Nb = (nameToCopy.match(/_/g) || []).length; //number of the '_' char
var nameCopiesArr = ["Test2", "Test2_2",
"Test2_3",
"Test2_4",
"Test2_2_2",
"Test2_3_1",
"Test2_2_1_2",
"Test2_2_3"
];
if (nameCopiesArr && nameCopiesArr.length > 1) {
for (i = 0; i < nameCopiesArr.length; i++) {
var item_Nb = (nameCopiesArr[i].match(/_/g) || []).length;//number of the '_' char
if (nameCopiesArr[i].indexOf(nameToCopy) !== -1 && item_Nb === nameToCopy_Nb + 1) {
var indexes = nameCopiesArr[i].lastIndexOf('_') ? nameCopiesArr[i].match(/\d+$/) : 0
if (indexes) {
version = indexes[indexes.length - 1];
version = parseInt(version) + 1;
}
}
}
}
p = nameToCopy + '_' + version;
document.getElementById("demo").innerHTML = p;
return p;
}
But the answer of #Nina is good and probably the shortest !!! (I upvote her answer)
JSFiddle
I'm not sure what you're trying to do here, or why, so I can't really comment on your code. Just note that it is not too efficient, and not too understandable. And as a side note, your html doesn't call the code you wrote.
to answer your question of why it returns 'Test2_4' : your code loops through the hard coded values you put into the nameCopiesArr, and the version variable keeps the number of the current name + 1. And then you overwrite this with the result from the next entry in the array. Since the last entry in the array is 'Test2_2_3', you grab the last number there - which is 3 - and add 1 to that, so after your last iteration the version variable holds the value of 4 - and this is what you return.

Internationally pretty print string objects that contain decimals

I am using MikeMcl's big.js for precise accounting which outputs a string when calling toFixed().
I'd like to pretty print decimal results in an internationally aware way much like how the Date Object can automatically print dates and times in a local format.
Is there a way to format string objects that contain decimals internationally?
var myNumber = 123456.78;
console.log(myNumber.toLocaleString());
This should do the job.
function localize(fixed) {
/*Determine decimal symbol and digit grouping symbol.*/
var decimalSymbol = '.';
var digitGroupingSymbol = ',';
var dummy = 1234.5;
testResult = dummy.toLocaleString();
/*Browsers using digit grouping symbol.*/
if (testResult.length === 7) {
decimalSymbol = testResult[5];
digitGroupingSymbol = testResult[1];
}
/*Browsers not using digit grouping symbol.*/
if (testResult.length === 6) {
decimalSymbol = testResult[4];
digitGroupingSymbol = (decimalSymbol === '.'? ',': '.');
}
/*Format the number.*/
var result = '';
var dsIndex = fixed.indexOf('.');
if (dsIndex < 0) {
throw new Error('Expected decimal separator \'.\' in "' + fixed + '".');
}
for (var i = 0; i < dsIndex; ++i) {
if (fixed[i] < '0' || fixed[i] > '9') {
throw new Error('Expected digit, got "' + fixed[i] + '".');
}
if (i > 0 && i%3 === dsIndex%3) result += digitGroupingSymbol ;
result += fixed[i];
}
result += decimalSymbol + fixed.substr(dsIndex + 1);
return result;
}
/*Demonstration*/
var n1 = '123.4567890';
console.assert(localize(n1));
var n2 = '1234.567890';
console.log(localize(n2));
var n3 = '123456789012345678.1234567890';
console.log(localize(n3));
var n4 = '1234567890123456789.1234567890';
console.log(localize(n4));
var n5 = '12345678901234567890.1234567890';
console.log(localize(n5));
Output:
123.4567890
1.234.567890
123.456.789.012.345.678.1234567890
1.234.567.890.123.456.789.1234567890
12.345.678.901.234.567.890.1234567890

Adding a comma at every third number character

In my code I have a variable myCash, which is printed into an h1 element using javaScript's innerHTML. I found a function online that puts a comma after every third character from the end of the number so that the number is easier to read. I've tried for a couple of hours now sending my variable myCash into the function and then print it on the screen. I CANNOT get it to work.
I've tried just alerting the new variable to the screen after page load or by pressing a button, but I get nothing and the alert doesn't even work. Here's the comma insert function:
function commaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
now when I want my variable to change I've tried it a few different ways including this:
var newMyCash = commaFormatted(myCash);
alert(newMyCash);
and this:
alert(commaFormatted(myCash);
Where of course myCash equal some large number;
This does absolutely nothing! What am I doing wrong here??
Also,
Try this as a drop in replacement and try alerting the response:
http://phpjs.org/functions/number_format:481
Do you see any errors in the console of your browser (usually f12)?
This is not my function, but I hope it helps you.
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Usage:
var newMyCash = addCommas( myCash ); alert( newMyCash );
Source: http://www.mredkj.com/javascript/nfbasic.html
You are most likely not passing in a number that contains a decimal, which the function expects.
Working Demo

how to get formatted integer value in javascript

This is my integer value
12232445
and i need to get like this.
12,232,445
Using prototype how to get this?
var number = 12232445,
value = number.toString(),
parts = new Array;
while (value.length) {
parts.unshift(value.substr(-3));
value = value.substr(0, value.length - 3);
}
number = parts.join(',');
alert(number); // 12,232,445
It might not be the cleanest solution, but it'll do:
function addCommas(n)
{
var str = String(n);
var result = '';
for(var i = 0; i < str.length; i++)
{
if((i - str.length) % 3 == 0)
result += ',';
result += str[i];
}
return result;
}
Here is the function I use, to format thousands separators and takes into account decimals if any:
function thousands(s) {
var rx = /(-?\d+)(\d{3})/,
intDec = (''+s)
.replace(new RegExp('\\' + $b.localisation.thousandSeparator,'g'), '')
.split('\\' + $b.user.localisation.decimalFormat),
intPart = intDec[0],
decPart = intDec[1] || '';
while (rx.test(intPart)) {
intPart = intPart.replace(rx,'$1'+$b.localisation.thousandSeparator+'$2');
}
return intPart + (decPart && $b.localisation.decimalFormat) + decPart;
}
thousands(1234.56) //--> 1,234.56
$b.localisation is a global variable used for the session.
$b.localisation.thousands can have the values , or . or a space.
And $b.localisation.decimalFormat can have the values , or . depending on the locale of the user

Adding commas, decimal to number output javascript

I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.
function createCounter(elementId,start,end,totalTime,callback)
{
var jTarget=jQuery("#"+elementId);
var interval=totalTime/(end-start);
var intervalId;
var current=start;
var f=function(){
jTarget.text(current);
if(current==end)
{
clearInterval(intervalId);
if(callback)
{
callback();
}
}
++current;
}
intervalId=setInterval(f,interval);
f();
}
jQuery(document).ready(function(){
createCounter("counter",12714086+'',9999999999,10000000000000,function(){
alert("finished")
})
})
Executed here: http://jsfiddle.net/blackessej/TT8BH/3/
var s = 121221;
Use the function insertDecimalPoints(s.toFixed(2));
and you get 1,212.21
function insertDecimalPoints(s) {
var l = s.length;
var res = ""+s[0];
console.log(res);
for (var i=1;i<l-1;i++)
{
if ((l-i)%3==0)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res = res.replace(',.','.');
return res;
}
Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.
var num = 3874923.12 + ''; //converts to a string
numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;
commaNumber = '';
i = numArray[0].length;
do
{
//we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
sliceStart = (i-3 >= 0) ? i-3 : 0;
//we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
var setOf3 = numArray[0].slice(sliceStart, i);
commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want
i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
}
while(i >= 0)
//result at this point: 3,874,923,
//remove the trailing comma
commaNumber = commaNumber.substring(0,commaNumber.length-1);
//add the decimal to the end
commaNumber += '.' + numArray[1];
//voila!
This function can be used for if not working locale somite
number =1000.234;
number=insertDecimalPoints(number.toFixed(3));
function insertDecimalPoints(s) {
console.log(s);
var temaparray = s.split(".");
s = temaparray[0];
var l = s.length;
var res = ""//+s[0];
console.log(res);
for (var i=0;i<l-1;i++)
{
if ((l-i)%3==0 && l>3)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res =res +"."+temaparray[1];
return res;
}
function convertDollar(number) {
var num =parseFloat(number);
var n = num.toFixed(2);
var q =Math.floor(num);
var z=parseFloat((num).toFixed(2)).toLocaleString();
var p=(parseFloat(n)-parseFloat(q)).toFixed(2).toString().replace("0.", ".");
return z+p;
}

Categories