Converting Postman Json body request to Jmeter body request - json

var moment = require("moment");
var time = moment().valueOf();
pm.environment.set('time', time);
var eventArray = [];_
for(var i = 1; i <= 50; i++)
{
var t = time + (i * 1000);
eventArray.push({
"eid": i,
"time": t
});
}
var data = { "event": eventArray };
var JSONData = new Buffer(JSON.stringify(data)).toString();
pm.environment.set("JSONData", JSONData);
console.log("JSONDATA", JSONData);
Change your entire request body to the following variable:
{{JSONData}}
This is what would be sent:
{“event”:[{“eid”:1,“time”:1538518294839},{“eid”:2,“time”:1538518295839},{“eid”:3,“time”:1538518296839},{“eid”:4,“time”:1538518297839},{“eid”:5,“time”:1538518298839},{“eid”:6,“time”:1538518299839},{“eid”:7,“time”:1538518300839},{“eid”:8,“time”:1538518301839},{“eid”:9,“time”:1538518302839},{“eid”:10,“time”:1538518303839},{“eid”:11,“time”:1538518304839},{“eid”:12,“time”:1538518305839},{“eid”:13,“time”:1538518306839},{“eid”:14,“time”:1538518307839},{“eid”:15,“time”:1538518308839},{“eid”:16,“time”:1538518309839},{“eid”:17,“time”:1538518310839},{“eid”:18,“time”:1538518311839},{“eid”:19,“time”:1538518312839},{“eid”:20,“time”:1538518313839},{“eid”:21,“time”:1538518314839},{“eid”:22,“time”:1538518315839},{“eid”:23,“time”:1538518316839},{“eid”:24,“time”:1538518317839},{“eid”:25,“time”:1538518318839},{“eid”:26,“time”:1538518319839},{“eid”:27,“time”:1538518320839},{“eid”:28,“time”:1538518321839},{“eid”:29,“time”:1538518322839},{“eid”:30,“time”:1538518323839},{“eid”:31,“time”:1538518324839},{“eid”:32,“time”:1538518325839},{“eid”:33,“time”:1538518326839},{“eid”:34,“time”:1538518327839},{“eid”:35,“time”:1538518328839},{“eid”:36,“time”:1538518329839},{“eid”:37,“time”:1538518330839},{“eid”:38,“time”:1538518331839},{“eid”:39,“time”:1538518332839},{“eid”:40,“time”:1538518333839},{“eid”:41,“time”:1538518334839},{“eid”:42,“time”:1538518335839},{“eid”:43,“time”:1538518336839},{“eid”:44,“time”:1538518337839},{“eid”:45,“time”:1538518338839},{“eid”:46,“time”:1538518339839},{“eid”:47,“time”:1538518340839},{“eid”:48,“time”:1538518341839},{“eid”:49,“time”:1538518342839},{“eid”:50,“time”:1538518343839}]}
Now i need the above request to be converted as jmeter request and pass in a single variable.

The equivalent Groovy code for using in a suitable JSR223 Test Element would be something like:
def events = []
def time = System.currentTimeMillis()
1.upto(50, {
events.add([eid: it, time: time + it * 1000])
})
def JSONData = new groovy.json.JsonBuilder([event: events]).toPrettyString()
vars.put('JSONData', JSONData)
The generated value can be accessed as ${JSONData} JMeter Variable where required
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Related

How to access json nested objects in node.js

I have used xml2js parser to parse the xml file in node.js. It is parsing the xml successfully. But now i want to parse the json or to identify the particular data in json.
My node.js code
var fs = require('fs');
var parseString = require('xml2js').parseString;
var xml = 'C:\\temp\\Masters.xml';
var fileData = fs.readFileSync(xml,'utf8');
parseString(fileData, function (err, result) {
console.log(JSON.stringify(result));
var json = JSON.stringify(result);
var jsonObj = JSON.parse(json);
for (var key in jsonObj) {
console.dir(key + ": " + jsonObj[key].Customer_Name);
}
});
In console output:
'Masters: undefined'
Json data:
'{"Masters":
{
"Customer":
[
{"Customer_Name":["Kim"],
"Customer_Code":["c86"],
"Date":["23-11-15"],
"Address":["Narhe"],
"City":["Pune"],
"State":["Maharashtra"],
"TIN":["3365670"],
"PAN_Number":["AAAAA1111a"],
"Mobile_Number":["8999000090"],
"Email_ID":["amitshirke#gmail.com"],
"Contact_Person":["Anish"],
"Opening_Balance":["0"] },
{"Customer_Name":["Ankit"],
"Customer_Code":["c87"],
"Date":["12-04-15"],
"Address":["Narhe"],
"City":["Pune"],
"State":["Maharashtra"],
"TIN":["336567"],
"PAN_Number":["AAAAA1111p"],
"Mobile_Number":["8900000000"],
"Email_ID":["amitshirke1#gmail.com"],
"Contact_Person":["Anuj"],
"Opening_Balance":["0"] }
]
}
}'
In above data, Masters is root element(Object), Customer is another nested object and there two customers. Then how can I access the customer names or how to use the for loop to access the same?.
Thanks in advance.
You can access the Customer array as follows -
var customerArray = Masters.Customer,
length = customerArray.length;
for(var i = 0; i < length; i++)
{
// You can access the customers array from here -
console.log(customerArray[i].Customer_Name[0]); // [0] hardcoded because as you can see all the variables are in array at 0th position
// similarly you can access other data
console.log(customerArray[i].City[0]);
}

Convert a javascript array to specific json format

I have this JSON.stringify(array) result: ["id:1x,price:150","id:2x,price:200"] and I have to convert it in a json format similar to this (it would be sent to php):
[{
"id":"1x",
"price":150
},
{
"id":"2x",
"price":200
}]
Please help.
You can convert the structure of your data before using JSON.stringify, for example you can convert the data to a list of objects like so:
var strItems = ["id:1x,price:150", "id:2x,price:200"];
var objItems = [];
for (var i = 0; i < strItems.length; i++) {
var pairs = strItems[i].split(",");
objItems.push({
id: pairs[0].split(':')[1],
price: parseInt(pairs[1].split(':')[1])
});
}
Before calling JSON.stringify to get the result you're after:
var json = JSON.stringify(objItems);
console.log(json);
JSON.stringify(array) only does on layer, but you can change the stringify function to work for multiple layers with this function written by JVE999 on this post:
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Once you have declared this, then you can call JSON.stringify(array)

Passing a JSON AngularJS structure to a mongoDB database

I have just recentely used AngularJS to "convert" a data structure I had in pure SVG format into JSON format.
Now, I want to store such a structure in a MongoDB database to start finally connecting some components of the MEAN stack together and start seeing some things working! Basically, I have the following code inside a Webstorm AngularJS project:
JS:
var app = angular.module('app', []);
var RectangleDim=30;
app.controller('MainCtrl', function($scope) {
$scope.graph = {'width': 5000, 'height': 5000};
$scope.circles = [
/* JSON.parse("{\"x\": 85, \"y\": 20, \"r\":15}"),
{"x": 20, "y": 60, "r":20},
{"x": 18, "y": 10, "r":40} */
];
$scope.draw=function(val)
{
// val = document.getElementById("NumQuest").value;
return JSON.parse('{\"cx\":'+val+', "cy": 20, "r":30}');
// $scope.circles.push(JSON.parse('{\"x\":'+val+', "y": 220, "r":30}'));
};
$scope.rectangles = [
// {'x':220, 'y':220, 'width' : 300, 'height' : 100},
// {'x':520, 'y':220, 'width' : 10, 'height' : 10},
];
$scope.DrawRect=function(xpos,ypos) {
return JSON.parse('{\"x\":' + xpos + ', \"y\":' + ypos + ', \"width\":' + RectangleDim + ', \"height\":' + RectangleDim+ '}');
};
$scope.Debug=function(desiredNo){
desiredNo=document.getElementById("NumQuest").value;
for(var i = 0;i < RectangleDim*desiredNo+desiredNo;i++){
$scope.rectangles.push($scope.DrawRect(i+RectangleDim+1,40));
}
};
$scope.DrawLineOdd=function(desiredNo,lineNo,pozY){
var pozX = lineNo*RectangleDim;
var aux = 2*Math.floor(Math.sqrt(desiredNo))-1-2*lineNo;
for (var j = 0; j < aux; j++) {
$scope.rectangles.push($scope.DrawRect(pozX, pozY));//$scope.DrawRect(pozX, pozY);
pozX += RectangleDim;
}
//return aux;
};
$scope.DrawMatrixPerfectProgression=function(desiredNo) {
desiredNo=document.getElementById("NumQuest").value;
var line=0;
var pozy=0;
while(line<Math.floor(Math.sqrt(desiredNo))) {
$scope.DrawLineOdd(desiredNo, line, pozy);
//document.getElementById("val").innerHTML = teste;
line += 1;
pozy+=RectangleDim;
}
//document.getElementById('tablePrint').innerHTML = finalTable;
};
$scope.DrawLineEven=function(desiredNo, lineNo, pozY){
var pozX = lineNo*RectangleDim;
//var pozY = lineno*20;
var aux = 2*Math.floor(Math.sqrt(desiredNo))-2*lineNo;
for (var j = 0; j < aux; j++) {
$scope.rectangles.push($scope.DrawRect(pozX, pozY));
pozX += RectangleDim;
}
//return aux;
};
$scope.DrawMatrixEvenProgression=function(desiredNo) {
desiredNo=document.getElementById("NumQuest").value;
var line=0;
var pozy=0;
while(line<Math.floor((Math.sqrt(4*desiredNo+1)-1)/2)) {
$scope.DrawLineEven(desiredNo, line, pozy);
//document.getElementById("val").innerHTML = teste;
line += 1;
pozy+=RectangleDim;
}
//document.getElementById('tablePrint').innerHTML = finalTable;
};
$scope.AddExtraRectangles=function(desiredNo) {
desiredNo = document.getElementById("NumQuest").value;
var arg1 = desiredNo - ( Math.floor(Math.sqrt(desiredNo))*Math.floor(Math.sqrt(desiredNo)));
var arg2 = desiredNo-(Math.floor((Math.sqrt(4*desiredNo+1)-1)/2)*Math.floor((Math.sqrt(4*desiredNo+1)-1)/2))-Math.floor((Math.sqrt(4*desiredNo+1)-1)/2);
var OptimalLeftOver = Math.min( arg1 ,arg2 );
//We add two rectangles per row: one at the beginning one at the end
//we start with the row below the first one
var line;
var pozy;
var pozx1, pozx2;
var nRectLine_i;
if(OptimalLeftOver===arg1){
line=1;//1st line is skipped
pozy=RectangleDim;
pozx1 = 0;
while(OptimalLeftOver>0) {
nRectLine_i = 2* Math.floor(Math.sqrt(desiredNo))-1-2*line;
pozx2 = (line-1)*RectangleDim+RectangleDim*(nRectLine_i+1);//pozx1+nRectLine_i+2*RectangleDim;
$scope.rectangles.push($scope.DrawRect(pozx1,pozy));
OptimalLeftOver-=1;
if(OptimalLeftOver>0) {
$scope.rectangles.push($scope.DrawRect(pozx2, pozy));
OptimalLeftOver -= 1;
}
//document.getElementById("val").innerHTML = teste;
line += 1;
pozy+=RectangleDim;
pozx1=RectangleDim*line - RectangleDim;
}
//document.getElementById('tablePrint').innerHTML = finalTable;
}
else {
line=1;//1st line is skipped
pozy=RectangleDim;
pozx1 = 0;
while(OptimalLeftOver>0) {
nRectLine_i = 2* Math.floor(Math.sqrt(desiredNo))-2*line;
pozx2 = RectangleDim*(line-1)+RectangleDim*(nRectLine_i+1);//pozx1+nRectLine_i+2*RectangleDim;
$scope.rectangles.push($scope.DrawRect(pozx1,pozy));
OptimalLeftOver-=1;
if(OptimalLeftOver>0) {
$scope.rectangles.push($scope.DrawRect(pozx2, pozy));
OptimalLeftOver -= 1;
}
//document.getElementById("val").innerHTML = teste;
line += 1;
pozy+=RectangleDim;
pozx1=RectangleDim*line - RectangleDim;
}
//document.getElementById('tablePrint').innerHTML = finalTable;
}
};
/* $scope.DrawMatrix=function(desiredNo)
{
/* Chooses optimal leftover number based on the progression formulas.
Attempts to minimize the work of the designer of the response form without
making too much assumptions
desiredNo = document.getElementById("NumQuest").value;
var arg1 = desiredNo - ( Math.floor(Math.sqrt(desiredNo))*Math.floor(Math.sqrt(desiredNo)));
var arg2 = desiredNo - (Math.floor((Math.sqrt(4*desiredNo+1)-1)/2)*Math.floor((Math.sqrt(4*desiredNo+1)-1)/2))-Math.floor((Math.sqrt(4*desiredNo+1)-1)/2);
var OptimalLeftOver = Math.min( arg1 ,arg2 );
document.getElementById("val").innerHTML = 'There are '+OptimalLeftOver+' questions missing!'+ arg1+ '___'+arg2;
console.log(arg1);
if(OptimalLeftOver===arg1){
DrawMatrixPerfectProgression(desiredNo);
AddExtraRectangles(desiredNo);
}
else {
DrawMatrixEvenProgression(desiredNo);
AddExtraRectangles(desiredNo);
}
}; */
}
);
angular.bootstrap(document.getElementById('body'), ["app"]);
The relevant part of the code is the $scope.rectangles array which contains the JSON.parse of the strings representing my data structure on the html side and that structure in JSON (or JSON parsed or whatever) is what I want to save in the MongoDB database...How can I do that? The HTML relevant part is just like this:
HTML:
<p><button ng-click="DrawMatrixEvenProgression(NumQuest)">Draw</button></p>
<svg ng-attr-height="{{graph.height}}" ng-attr-width="{{graph.width}}">
<rect ng-repeat="rect in rectangles"
ng-attr-x="{{rect.x}}"
ng-attr-y="{{rect.y}}"
ng-attr-width="{{rect.width}}"
ng-attr-height="{{rect.height}}">
</rect>
</svg>
Any help will be appreciated... Can I start by adding more files to that project to handle the database and then things will be linked together?
Like adding stuff to handle the mongoose and the connections?
Thanks in advance!
Because Angular is a front-end framework. So to communicate with database (in this case MongoDB) you need to have application on the server-side to handle this and I suggest you to use Node.js and Mongoose as a MongoDB driver.
Node.js
Mongoose
Come back to Angular, you can create Angular service or factory and let the them talk to your server with service like $http or $resource.
Angular service documentation
Example for angular service
angular.module('app')
.factory('RectangleService', function($http){
return {
create: create
}
function create(rectangle){
// make http request to the server
return $http({
url: 'API_URL',
method: 'GET',
params: rectangle
});
}
});
After you create your service you have to inject it to your controller and
you may create some function to your $scope to talk with service like this
app.controller('MainCtrl', function($scope, RectangleService) { // <-- Inject service to controller
// your controller code
$scope.createRectangle = function(rectangle){
RectangleService.create(rectangle);
}
});
You can map createRectangle function to directive like ng-click and pass your json data as a parameter
Because I don't know what server-side language you can use, so I don't come with an example for Node.js & Mongoose
Hope this can help :)

Store User Control JSON object in DB

I have a JSON object that I want to store in a database. The JSON is generated by an User Control.
The JSON object:
var datatosend = {
isit: isitArray,
ec: ecArray,
bc: bcArray,
bb: bbArray,
io: ioArray
};
What is the best way to record a JSON object in the database using GeneXus?
Edit:
var isitArray = getObjectsRequest('isit', isitID);
var ecArray = getObjectsRequest('ec', ecID);
var bcArray = getObjectsRequest('bc', bcID);
var bbArray = getObjectsRequest('bb', bbID);
var ioArray = getObjectsRequest('io', ioID);
function getObjectsRequest(type, compId){
var array = [];
for (var i = 0; i<compId; i++) {
var comp = mainLayer.find('#'+ type + i)[0];
array.push({
xposition: comp.getX(),
yposition: comp.getY(),
titleid: comp.getId(),
description: comp.find('.textDescription')[0].getText(),
leftrelationsids: comp.leftCRelations,
rightrelationsids: comp.rightCRelations
});
};
return array;
}
var datatosend = {
isit: isitArray,
ec: ecArray,
bc: bcArray,
bb: bbArray,
io: ioArray
};
You can use a LongVarChar attribute to store the JSON, but you'll need to convert the JavaScript object to String first.

Multipart/form-data Flex HTTPService uploading a file

I am new to Flex and also new to writing a client for a web service.
My question is more about Flex (Flash Builder 4.5) APIs, what APIs to use.
I want to access a web service, and create a Flex / AIRwrapper for it,
which anyone can use.
Here is the spec of webservice.
I have to do a post on POST https://build.phonegap.com/api/v1/apps
content type has to be "multipart/form-data"
JSON bodies of requests are expected to have the name 'data' and will be something like this:
data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}
include a zip file in the multipart body of your post, with the parameter name 'file'.
I want to make a 'multipart/form-data' Post and send one string and one zip file.
My first question to self was if I send both string + binary data in the body,
how will server understand where string end and where zip file starts?
Then I read how text + binary data can be sent through "multipart/form-data" post request. There has to be some boundaries.
After this I read and example in flex and tried following it.
http://codeio.wordpress.com/2010/04/03/5-minutes-on-adobe-flex-mimic-file-upload-for-in-memory-contents/
but it doesn't seem to be working for me.
public function createNewApp(cb:Function , appFile : File):void
{
var service:HTTPService = new HTTPService();
service.url = ROOT+"apps";
service.showBusyCursor = true;
service.addEventListener(ResultEvent.RESULT, function(e:ResultEvent):void {
//translate JSON
trace(e.result);
var result:String = e.result.toString();
var data:Object = JSON.parse(result);
cb(data.link);
});
service.addEventListener(FaultEvent.FAULT, defaultFaultHandler); //todo : allow user to add his own as well
authAndUploadNewApp(service,appFile);
}
private function authAndUploadNewApp(service:HTTPService,appFile : File):void {
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(username + ":"+password);
service.headers = {Accept:"application/json", Authorization:"Basic " + encoder.toString()};
service.method ="POST";
var boundary:String = UIDUtil.createUID();
service.contentType = "multipart/form-data; boundary=—————————" + boundary;
var stream:FileStream = new FileStream();
stream.open(appFile, FileMode.READ);
var binaryData:ByteArray = new ByteArray();
var fileData : String = new String();
stream.readBytes(binaryData);
stream.close();
fileData = binaryData.readUTFBytes(binaryData.bytesAvailable); // I think this is where I have problem.... how do
//how do i converrt this bytearray/stream of data to string and send it in my post request's body - i guess if this step work rest should work..
var params: String = new String();
var content:String = "—————————" + boundary + "nr";
content += 'Content-Disposition: form-data; name="data";' + '{"title":"ELS test app 2","package":"com.elsapp.captivate","version":"12.3.09","create_method":"file"}' + "nr";
content += "—————————" + boundary + "nr";
content += 'Content-Disposition: form-data; name="file";' + fileData + "nr";
content += "—————————–" + boundary + "–nr";
service.request = content;
service.send();
}