Setting setRequestBody for Rest web services using Post method - javascript

Hi I'm trying to create a rest response using post method, I want to dynamically pass the variables instead of hard coding,But where i fail is,when I'm trying to to send an array as a parameter to the Rest web service using post method(example array ["CN=XXX_XX,OU=XXXXX,OU=1_XXXX XXXXity Groups,DC=XXXX,DC=local"]) and I know that there is a better way to do that Please find my code sample.This is the method that gives me a appropriate result.
First Method:(Works)
`
try {
var r = new sn_ws.RESTMessageV2('SailPoint_IdM', 'post');
var txt = "{\r\n\t\"workflowArgs\":\r\n\t{\r\n\t\"identityName\":\"SiamR\",\r\n\t\"appName\":\"Active Directory\",\r\n\t\"listEntitlements\":[\"CN=ER_CxxxK,OU=xxxxx,OU=1_xxxxxx Security xxx,DC=xxxx,DC=local\"],\r\n\t\"operation\":\"Add\",\r\n\t\"ticketNumber\":\"RITM1234567\"\r\n\t}\r\n}";
r.setRequestBody(txt);
var response = r.execute();
var ResponseBody = response.getBody();
var HTTPCode = response.getStatusCode();
gs.log(ResponseBody);
gs.log(HTTPCode);
} catch (ex) {
var message = ex.getMessage();
}
output:
Script: {"attributes":{"requestResult":{"status":"Success"}},"complete":false,"errors":null,"failure":false,"metaData":null,"requestID":"2c988d8c5bd47cf7015bebfb64cf01e6","retry":false,"retryWait":0,"status":null,"success":false,"warnings":null}
Script: 200
2n Method (Does not Work):
try {
var r = new sn_ws.RESTMessageV2('SailPoint_IdM', 'post');
r.setStringParameter('"listEntitlements"', '["CN=Exxx_xxxK,OU=xxxxion,OU=1_xxxxx Security xxxx,DC=xxx,DC=xxxx"]');
r.setStringParameter('"identityName"', '"SiarmR"');
r.setStringParameter('"appName"', '"Active Directory"');
r.setStringParameter('"ticketNumber"', '"RITM1234567"');
r.setStringParameter('operation', '"Add"');
//override authentication profile
//authentication type ='basic'/ 'oauth2'
//r.setAuthentication(authentication type, profile name);
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
gs.log(responseBody );
}
catch(ex) {
var message = ex.getMessage();
}
output:
Script: {"attributes":{"requestResult":{"errors":["An unexpected error occurred: sailpoint.tools.GeneralException: The application script threw an exception: java.lang.NullPointerException: Null Pointer in Method Invocation BSF info: script at line: 0 column: columnNo"],"status":"FAIL","GroupStatus":null,"AppStatus":null}},"complete":false,"errors":["Status : failed\nAn unexpected error occurred: sailpoint.tools.GeneralException: The application script threw an exception: java.lang.NullPointerException: Null Pointer in Method Invocation BSF info: script at line: 0 column: columnNo\n"],"failure":false,"metaData":null,"requestID":null,"retry":false,"retryWait":0,"status":null,"success":false,"warnings":null}
Script: 200
Im facing issue with this parameter as im trying to pass this as aray paramenter '["CN=Exxx_xxxK,OU=xxxxion,OU=1_xxxxx Security xxxx,DC=xxx,DC=xxxx"]'
Please suggest a way to implement this and to pass all the variables dynamically if suggesting first method

Below is one of my function, to handle dynamic parameters in either appear in request endpoint (url), headers or body;
For eg: parameter p
var p = {abc: 'def'};
and outbuond rest settings:
rest url = https://xxxx.sss.com/api/showme?name=${abc}
rest headers name = custom-header; value = ${abc}
rest body = {name: "${abc}"}
so it will replace all ${abc} to 'def'
_.isNullOrEmpty - check is obj, string or array is null or empty;
_.loop - loop an obj or array, pass in function(nm/i, val) {}
_.isArray - to check if is array
_.str - convert anything to string
_.rpl - replace all string A to B
restParameters: function (restRequest, obj, endpoint) {
var _ = this;
if ((_.isNullOrEmpty(restRequest)) || (_.isNullOrEmpty(obj))) return;
if (_.isNullOrEmpty(endpoint)) endpoint = restRequest.getEndpoint();
var body = restRequest.getRequestBody();
var headers = restRequest.getRequestHeaders();
_.loop(obj, function(nm, val) {
if (_.isArray(val)) {
val = (_.isNullOrEmpty(val)) ? '[]' : JSON.stringify(val);
} else val = _.str(val);
//for my case my array pass in as string become: "[\"1\", \"2\"]"
//comment below if pass in as object
if (val.contains('"')) val = _.rpl(val, '"', '\\"');
restRequest.setStringParameterNoEscape(nm, val);
var sch = '${' + nm + '}';
endpoint = _.rpl(endpoint, sch, val);
body = _.rpl(body, sch, val);
_.loop(headers, function (hn, hv) {
headers[hn] = _.rpl(hv, sch, val);
});
}, true);
restRequest.setEndpoint(endpoint);
restRequest.setRequestBody(body);
_.loop(headers, function (hn, hv) { restRequest.setRequestHeader(hn, hv); });
}

Related

Unable to parse jsonp response from geocode site

I am totally new to JavaScript, trying to get JSONP geocoding data from geocoding.geo.census.gov into a website. The response looks something like that (from chrome), only the first few keys are shown:
JSONPCallback({"result":{"input":{"address":{"address":"333 e 33th st austin tx"},"vintage":{"isDefault":true,"vintageName":"Current_Current","id":"4","vintageDescription":"Current Vintage - Current Benchmark"},"benchmark":{"isDefault":false,"id":"4","benchmarkName":"Public_AR_Current","benchmarkDescription":"Public Address Ranges - Current Benchmark"}}...............
This is the code I'm using:
var jsonp = {
callbackCounter: 0,
fetch: function(url, callback) {
var fn = 'JSONPCallback_' + this.callbackCounter++;
window[fn] = this.evalJSONP(callback);
url = url.replace('=JSONPCallback', '=' + fn);
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = url;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
},
evalJSONP: function(callback) {
return function(data) {
var validJSON = false;
if (typeof data == "string") {
try {validJSON = JSON.parse(data);} catch (e) {
/*invalid JSON*/}
} else {
validJSON = JSON.parse(JSON.stringify(data));
window.console && console.warn('response data was not a JSON string');
}
if (validJSON) {
callback(validJSON);
} else {
throw("JSONP call returned invalid or empty JSON");
}
}
}
}
then:
{console.log(Object.keys(data));} //(or data[0])
and all I'm getting in the console is:
response data was not a JSON string
Array[1]0: "result"
length: 1
proto: Array[0]
I don't understand why all I'm getting is just "result"?
evalJSONP: function(callback) {
return callback;
}
That should work. If your sample is accurate. Then you don't need to parse the data.
I believe the old code wasn't working because it was trying to parse an object. Plase correct me if I'm wrong.

Unable to access JSON Element in Javascript via Object.property

I am unable to access a simple JSON Element from a JSON Structure that looks like:
{
"ACTION": "AA",
"MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01"
}
I get the data in JSON Format but when i do data.ACTION or data.MESSAGE i get Undefined as the output.
By doing case sensitive also, its not working( Image attached )
var url = base + query;
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.withCredentials = true;
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON(url).then(function (data) {
console.log(data); //Getting JSON Data
var output = JSON.stringify(data);
var obj = JSON.parse(output.replace(/ 0+(?![\. }])/g, ' '));
console.log(output);
console.log(obj.message); //Here getting UNDEFINED
}, function (status) { //error detection....
alert('Something went wrong.');
});
Console:
{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}
stringify returns the following
{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}"
EDITED. I first thought the error was due to parsing, given the print. -.-
Solution:
When you print the output, obj it's still a string, not an object. So it is OK at that point.
Your "undefined" property message should be replaced by MESSAGE.
Instead of console.log(obj.message); just use console.log(obj.MESSAGE);
Also. An example of parsing JSON:
var myJson = '{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}';
console.log(myJson); // This prints the literal string
console.log(JSON.parse(myJson)); // this prints an "object"
obj.message property is not defined and when you try to get the property which is not defined on an object, you get undefined.
Javascript is case sensitive. You should try obj.MESSAGE instead to get the property value. Also, to check if a property exists on an object you can make use of object.hasOwnProperty([propName]) method to check if a property exists on a object or not.
EDIT 1: Try running the following code snippet. JSON data string is parsed before accessing the property.
var jsonString = "{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}";
var obj = JSON.parse(jsonString);
console.log(obj.MESSAGE);
data already is a JSON string, there's no need to JSON.stringify it (which returns a string with a JSON-encoded string literal). Parsing it into output only leads to a string again, which has no properties. You should use
console.log(data);
var obj = JSON.parse(data);
console.log(obj);
obj.MESSAGE = obj.MESSAGE.replace(/ 0+(?![\. }])/g, ' ');
(notice the proper casing of the property name)
You can try:
var jsonObject = data.data;
console.log(jsonObject.ACTION)

Data not coming in JSON format from Splunk Javascript sdk

I am querying Splunk using javascript SDK. In the searchParams, i have given the output mode as "json_rows".
var searchParams = {
exec_mode: "normal",
output_mode: "json_rows"
};
But still when i get the output, i don't get it in a JSON format. The output is coming as an array.
Any idea what is going wrong? I tried "json_cols" and only "json" also. Same result.
Thanks in advance.
Edit:2
Some more of the code
var service = new splunkjs.Service({
username:"xxx",
password:"xxxx",
scheme:"https",
host:"xxxxxx.com",
port:"5500",
version:"5.0"
});
var searchQuery = 'search index=sn impact=1 OR impact=2 | eval time = round( strptime(impact_start,"%Y-%m-%d %H:%M:%S"), 0 )| where time >= ' + 14334627 + ' AND time<=' + 14568862 + '| bucket time span=1d | stats values(number) as incident_name by time';
var searchParams = {
exec_mode: "normal",
output_mode: "JSON"
};
service.oneshotSearch(
searchQuery,
searchParams,
function(err, results) {
if ( results ) {
var incidentResp = {};
incidentResp["data"] = results.rows;
incidentResp["error"] = null;
callback(null, incidentResp);
return;
}
else {
var errResp = {};
errResp["data"] = null;
errResp["error"] =err;
callback(null, errResp);
return;
}
}
);
I'm not 100% sure what you're asking, but let me try to help.
output_mode just tells the REST API how to serialize and return the results, usually either JSON, XML, or CSV
Given you're using the JavaScript SDK to pull data into your application and not actually having the results written to file, I would leave this as is (JSON default)
You'll find the actual data in the 'results' of the response.
eg.
service.oneshotSearch( query, params,
function(err, response) {
if (err) throw new Error ( err );
console.log( response.results );
});
Try changing this line:
incidentResp["data"] = results.rows;:
To this:
incidentResp["data"] = results.results;
... but yes, this will be an array of results.
Hope this helps

Mailchimp Google sheet issue with the api key

All the variables are returning correct values but the the urlfetch response returns 403 or 401 (access denied).
First log output:
var payload = {
"apikey": API_KEY,
"filters": {
"sendtime_start": REPORT_START_DATE,
"sendtime_end": REPORT_END_DATE
}
};
Logger.log(payload );
Second log output:
var params = {
"method": "POST", //what MC specifies
"muteHttpExceptions": true,
"payload": payload,
"limit": 100
};
Logger.log(params);
Third log output:
var apiCall = function(endpoint) {
//issue with syntax here?
var apiResponse = UrlFetchApp.fetch(automationsList, params);
var json = JSON.parse(apiResponse);
Logger.log(apiResponse);
return json;
};
Automation API Call that is not working:
var automations = apiCall(automationsList);
var automationsData = automations.data;
for (var i = 0; i < automationsData.length; i++) {
// are these response parameters? are these specific values getting pulled from MC - these are the type of values i want?
var a = automationsData[i];
var aid = a.id; // identifies unique campaign *** does this have anything to do with the call function above - it used to be as cid b/c this was for campaigns before??
var emails_sent = a.emails_sent;
var recipients = a.recipients;
var report_summary = a.report_summary;
var settings = a.settings;
if (send_time) {
var r = apiCall(reports, cid); // why does this have cid? but the other one didn't??
var emails_sent = r.emails_sent;
var opens = r.opens;
var unique_opens = r.unique_opens;
var clicks = r.clicks;
var unique_clicks = r.unique_clicks;
var open_rate = (unique_opens / emails_sent).toFixed(4);
var click_rate = (unique_clicks / emails_sent).toFixed(4);
}
The for loop is not even gets executed because I get following error for automationsData:
TypeError: Cannot read property "data" from undefined. (line 82, file "Code")
The apiResponse there is somehow not working, any help is appreciated.
The problem is in how you set up your project in the Developers Console. Try to follow again the process here for you to verify if you already do it in the correct way.
You can also check the solution here in this SO question, he/she explained it here, why he/she get the same 401 and 403 error that you get.
As it turns out, I was using v3.0 for the Mailchimp api whereas I needed to use 2.0.

Why Parse.Cloud.run decodes returning object into object reference on success?

Take Parse Javascript SDK 1.6.4 for example,
from line 179:
_CoreManager2['default'].setCloudController({
run: function run(name, data, options) {
var RESTController = _CoreManager2['default'].getRESTController();
var payload = (0, _encode2['default'])(data, true);
var requestOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
requestOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
requestOptions.sessionToken = options.sessionToken;
}
var request = RESTController.request('POST', 'functions/' + name, payload, requestOptions);
return request.then(function (res) {
var decoded = (0, _decode2['default'])(res);
if (decoded && decoded.hasOwnProperty('result')) {
return _ParsePromise2['default'].as(decoded.result);
}
return _ParsePromise2['default'].error(new _ParseError2['default'](_ParseError2['default'].INVALID_JSON, 'The server returned an invalid response.'));
})._thenRunCallbacks(options);
}
});
The _decode2['default'] uses fromJSON for Parse Object from line 4144:
key: 'fromJSON',
value: function fromJSON(json) {
if (!json.className) {
throw new Error('Cannot create an object without a className');
}
var constructor = classMap[json.className];
var o = constructor ? new constructor() : new ParseObject(json.className);
var otherAttributes = {};
for (var attr in json) {
if (attr !== 'className' && attr !== '__type') {
otherAttributes[attr] = json[attr];
}
}
o._finishFetch(otherAttributes);
if (json.objectId) {
o._setExisted(true);
}
return o;
}
I passed a full Parse object in my cloud code run success callback, but this decoding behavior purges my returning Parse object into a object reference.
Why do we want to have this?
Is there a option to get full object instead of a reference?
What I want is to get an updated object to update my view on success.

Categories

Resources