How to create multiple payloads from a script mediator - WSO2 ESB - wso2-esb

Say I have an initial payload as below:
{
"avail": "123",
"vendorList": "vendor1,vendor2"
}
And I use Script mediator to break these vendors and add in different payloads as below:
Payload1:
{
"avail": "123",
"vendorList": "vendor1,vendor2",
"vendor": "vendor1"
}
Payload2:
{
"avail": "123",
"vendorList": "vendor1,vendor2",
"vendor": "vendor2"
}
Currently I have script as below:
payload = mc.getPayloadJSON();
var vendors = mc.getProperty('vendorList');
var log = mc.getServiceLog();
log.info(vendors);
var array_supp = String(vendors).split(',');
for (var i = 0; i < array_supp.length; i++) {
payload.vendor = array_supp[i];
log.info(array_supp[i]);
mc.setPayloadJSON(payload);
}
This always give last vendor in one payload.
Please advise how can I achieve this using Script mediator.

The Reason why last vendor is coming is because you are not appending the result of earlier iteration.
Try the below snippet and let me know if the issue is resolved or not
for (var i = 0; i < array_supp.length; i++) {
payload.vendor = array_supp[i];
log.info(array_supp[i]);
payload=payload + payload.vendor
mc.setPayloadJSON(payload);
}

Related

Transfer UTM Parameters on vehicle results page

We have successfully added the following script to all/most pages, but it will not fire on the following page and I'm stumped. Our ultimate goal is to transfer all UTM parameters to any vehicle selected on the page.
Any help would be greatly appreciated.
https://www.cardoor.ca/used-vehicles/
(function() {
var domainsToDecorate = [
'cardoor.ca' //add or remove domains (without https or trailing slash)
],
queryParams = [
'utm_medium', //add or remove query parameters you want to transfer
'utm_source',
'utm_campaign',
'gaw_campaign_id',
'gaw_ad_group_id',
'gaw_remote_client_id',
'fbclid',
'gclid'
]
// do not edit anything below this line
var links = document.querySelectorAll('a');
// check if links contain domain from the domainsToDecorate array and then decorates
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) { if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
links[linkIndex].href = decorateUrl(links[linkIndex].href);
}
}
}
// decorates the URL with query params
function decorateUrl(urlToDecorate) {
urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
var collectedQueryParams = [];
for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
if (getQueryParam(queryParams[queryIndex])) {
collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
}
}
return urlToDecorate + collectedQueryParams.join('&');
}
// borrowed from https://stackoverflow.com/questions/831030/
// a function that retrieves the value of a query parameter
function getQueryParam(name) {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(window.location.search))
return decodeURIComponent(name[1]);
}
})();`
We are on WordPress, so I am a bit limited in the containers I can add this to but I have tried in the 2 available to me. I have tried to move it as high on the page as possible but to no avail.

BigQuery Result save as google sheets through api

In Google BigQuery WebUI, it shows query result screen after executing a query, and it shows the button of "Save as Google Sheets". I like this feature but would like to automate this, is there such function through the REST API that I could do?
It doesn’t seem like there is a straightforward way to do this directly with the BigQuery API. There are few workarounds for this though:
You can use the BigQuery API to query your data and then the GoogleSheets API to upload it to Google Sheets.
You can use Google Apps Script. If you go to this link, you click on “New Script”, you can run the code below. You can adapt this to your needs. You can also add a trigger to run the script every hour/minute …
Here the code snippet from this link:
function runQuery() {
// Replace this value with the project ID listed in the Google
// Cloud Platform project.
var projectId = 'XXXXXXXX';
var request = {
query: 'SELECT TOP(word, 300) AS word, COUNT(*) AS word_count ' +
'FROM publicdata:samples.shakespeare WHERE LENGTH(word) > 10;'
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
// Check on status of the Query Job.
var sleepTimeMs = 500;
while (!queryResults.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
}
// Get all the rows of results.
var rows = queryResults.rows;
while (queryResults.pageToken) {
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
pageToken: queryResults.pageToken
});
rows = rows.concat(queryResults.rows);
}
if (rows) {
var spreadsheet = SpreadsheetApp.create('BiqQuery Results');
var sheet = spreadsheet.getActiveSheet();
// Append the headers.
var headers = queryResults.schema.fields.map(function(field) {
return field.name;
});
sheet.appendRow(headers);
// Append the results.
var data = new Array(rows.length);
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].f;
data[i] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data[i][j] = cols[j].v;
}
}
sheet.getRange(2, 1, rows.length, headers.length).setValues(data);
Logger.log('Results spreadsheet created: %s',
spreadsheet.getUrl());
} else {
Logger.log('No rows returned.');
}
}

Display dynamic data with JSON API Jquery

I've been reading about Javascript for 2 days now and I'm still confused. I'm familiar with HTML and CSS. My goal is to display a dynamic value on my website. The data will be from an API call using JSON.
The URL i'm using displays info like this
{
"error" : 0,
"error_message" : "-",
"amount" : 35.63000
}
What I want to do is take the "amount" variable and display it on my website. So far I have managed to jumble a bunch of code together that barely makes sense to me. I'm probably using all the wrong syntax so I will continue to try and figure this out myself. All this does it displays a static variable in "div1". What is the best way to convert the variable from the API call to show instead.
$.getJSON('https://www.amdoren.com/api/currency.php?api_key=jbqe5fH8AykJTFbnyR7Hf3d2n3KVQR&from=USD&to=THB&amount=1', function(data) {
//data is the JSON string
});
////
var $items = $('#amount')
var obj = {}
$items.each(function() {
obj[this.id] = $(this).val();
})
var json = JSON.stringify(obj);
///
var obj = [ {
"error": 0,
"error_message": "-",
"amount": 35.60000 ///THIS IS OBVIOUSLY STATIC...
}]
var tbl = $("<table/>").attr("id", "mytable");
$("#div1").append(tbl);
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
var td3 = "<td>" + obj[i]["amount"] + "</td></tr>";
$("#mytable").append(tr + td3);
}

Worklight JsonStore advanced find

How to use advanced find in worklight JSONStore using QueryPart?
I have tried the following code but its not working properly, I doubt if I am calling advancedFind correctly.
var query = WL.JSONStore.QueryPart().equal('age', 35);
var collectionName = "people";
WL.JSONStore.get(collectionName).find(query).then(function(arrayResults) {
// if data not present , get the data from DB
if (arrayResults.length == 0) {
} else {
}
}).fail(function(errorObject) {
alert("fail" + errorObject);
// handle failure
});
You are calling the find() method. The one you want to call is advancedFind(). Also, advancedFind receives an array of query parts, not just one query part. Your code should look like this:
var queryPart = WL.JSONStore.QueryPart().equal('age', 35);
var collectionName = "people";
WL.JSONStore.get(collectionName).advancedFind([queryPart]).then(function(arrayResults) {
// if data not present , get the data from DB
if (arrayResults.length == 0) {
} else {
}
}).fail(function(errorObject) {
alert("fail" + errorObject);
// handle failure
});
For future reference, here is the API and some examples on how to use the Javascript JSONStore API.

BlackBerry 10 Cascades: How do I load data into a DropDown?

I have managed to load data from a remote Json web service into a QML ListView, but there doesn't seem to be any such thing for the DropDown control.
Does someone have an example or an alternative method to accomplish a DropDown bound to attachedObjects data sources in Cascades?
I have an alternate method for you, Do note that I have used google's web service here for demonstration purpose, you need to replace it with your url & parse response according to that.
import bb.cascades 1.0
Page {
attachedObjects: [
ComponentDefinition {
id: optionControlDefinition
Option {
}
}
]
function getData() {
var request = new XMLHttpRequest()
request.onreadystatechange = function() {
if (request.readyState == 4) {
var response = request.responseText
response = JSON.parse(response)
var addressComponents = response.results[0].address_components
for (var i = 0; i < addressComponents.length; i ++) {
var option = optionControlDefinition.createObject();
option.text = addressComponents[i].long_name
dropDown.add(option)
}
}
}
// I have used goole's web service url, you can replace with your url
request.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=" + "Ahmedabad" + "&sensor=false", true)
request.send()
}
Container {
DropDown {
id: dropDown
}
Button {
onClicked: getData()
}
}
}
Hope this helps.