parameter passing from CDE to PDI pentaho - parameter-passing

I have a scenario to pass parameters from pentaho cde using kettle to pentaho data integration and then update the table using the passed parameter in PDI. How can i pass the parameter and get the passed parameter in PDI?
Thanks in advance!!!

You will need to use the Pentaho plugin builder, SPARKL.
With it you can upload a transformation as a callable endpoint and use a CDE dashboard to call it.
First of all, you need a transformation that expects parameters. You can try it with a test one before going to a more advanced transformation:
Example:
defining a parameter and fetching with a Get Variables step
Second you will create a new plugin on SPARKL.
Sparkl welcome screen
Give your plugin a name and add a kettle endpoint to it. If you now look at your pentaho-solutions/system folder, you will have a new folder with the plugin name. Open it and find the ktr file inside the subfolders to replace it with your transformation.
The last step is to add a new dashboard to your plugin and edit it. If you go to the datasources tab now, notice the datasources with 'endpoint' in the name. We will access them by code, but is good to know they are here so you can read data from it too, not just input data.
add a new resource of javascript to your CDE layout with the following code:
var myPluginName = {};
(function(myself) {
myself.runEndpoint = function (pluginId, endpoint, opts) {
if (!pluginId && !endpoint) {
Dashboards.log('PluginId or endpointName not defined.');
return false
}
var _opts = {
success: function () {
Dashboards.log(pluginId + ': ' + endpoint + ' ran successfully.')
},
error: function (){
Dashboards.log(pluginId + ': error running ' + endpoint + '.')
},
params: {},
systemParams: {},
type: 'POST',
dataType: 'json'
}
var opts = $.extend( {}, _opts, opts);
var url = Dashboards.getWebAppPath() + '/plugin/' + pluginId + '/api/' + endpoint;
function successHandler (json) {
if (json && json.result == false) {
opts.error.apply(this, arguments);
} else {
opts.success.apply( this, arguments );
}
}
function errorHandler () {
opts.error.apply(this, arguments);
}
if (endpoint != 'renderer/refresh' ) {
var ajaxOpts = {
url: url,
async: true,
type: opts.type,
dataType: opts.dataType,
success: successHandler,
error: errorHandler,
data: {}
}
} else {
var ajaxOpts = {
url: url,
async: true,
type: 'GET',
dataType: opts.dataType,
success: successHandler,
error: errorHandler,
data: {}
}
}
_.each( opts.params , function ( value , key) {
ajaxOpts.data['param' + key] = value;
});
_.each(opts.systemParams , function (value , key) {
ajaxOpts.data[key] = value;
});
$.ajax(ajaxOpts)
}
})(myPluginName);
You can change myPluginName with whatever you want but that enables you to call that endpoint sending parameters with any button. To do so you can use that code:
myPluginName.runEndpoint(
'myPluginName', // Plugin identifier.
'endpointName', // Put your endpoint name here!
{
params: {
'EXAMPLE_PARAMETER' : foo_bar
},
success: function() { Dashboards.fireChange('refresh', 1); alert('data sent'); },
error: function() { alert('Ops, something went wrong. Check the logs.'); }
})
You can keep track of the execution by monitoring the bi-server logs.
More information on the sources:
Diethard Steiner - Blog
Francesco Corti - Blog
Follow these guys, they are amazing.

You could do that, or you could just create a CDA data source, which takes a parameter as defined in your transformation.
Params are passed to CDA via the usual &paramYOURPARAMNAME=x syntax on the URL.
In the transformation you get the parameter using the get variables step.
Did I miss something?

Related

Partial View loading using javascript : Possible XSS by HP FORTIFY

I have a js function , which Fortify identified as XSS vulnerable as below. Can you suggest any solution for this since the method is intensively used in my app.
I am here trying to call a partialview in ajax and the result html am appending to a specified dom div
My function look like the below
function loadPartialViewToDiv(div, obj, api) {
try {
const myUrl = new URL(window.location.origin + api); // always local URL only
$.ajax({
url: myUrl ,
data: obj,
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
if (data != undefined && data != null) {
$('#' + div).html(data);
}
}
});
} catch (e) {
('#' + div).html('Error');
}
}
The dynamic DOM element id was the issue ($('#' + div).html(data); ), we fixed it using two methods
giving a static id. $('#abcd').html(data);
OR
change as $('#' + div).text($(data));

Post JSON in DynamoDB via Lambda

I have trouble storing a JSON file in my DynamoDB table with the help of my Lambda function and my API Gateway on AWS. I have the following piece of code which gets executed once I press a button on my HTML site:
$('#submit').on('click', function(){
var example = {"number":"121212"};
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringify(example),
contentType: "application/json",
success: function(data){
location.reload();
}
});
return false;
});
When pressed the website reloads, hence I assume function has successfully executed. However my problem is that the data does not arrive in the correct format in the lambda function and hence does not execute properly. When checking in CloudWatch it is shown as { number: '121212' } instead of {"number":"121212"}. Any idea how I can make sure that the value 'arrives' has a valid JSON format in my Lambda function?
Here's my Lambda function:
exports.handler = function index(e, ctx, callback) {
var params = {
Item: { number: e.number },
TableName: 'collectionOfNumbers'
};
docCLient.put(params, function(err, data) {
if (err) {
callback(err, null);
} else {
callback(null, data);
}
});
}
If I'm reading this right, e.number is the value of the JSON parameter 'number' that you are passing in, e.g. '121212'. I'm making the assumption from the usage that docClient is putItem under the hood.
I think your Item param should look like:
Item: {"number": {N: e.number}}
See AWS Docs for info regarding PutItem https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html

Kendo Grid Inline MultiSelect - Posted Values

I'm replicating the functionality very close to what's seen here. https://onabai.wordpress.com/2013/07/17/kendoui-multiselect-in-a-grid-yes-we-can/
I have Kendo grid with an inline multiselect editor field. I have a datasource.sync() event kicked off on change of that multiselect. The issue I'm having is how the data is arranged in the post variables.
I'm using FireBug in FireFox. I can set a function to view the values in my multiselect field like this at the sync() event.
console.log(this.value());
This would be for a string array field I have called "RoleCode". Anyway, the console log displays the values as they should, for example
A, OU
However, when I look in the Post call to my controller and at the parameters, I see the RoleCode field is duplicated, which is why my controller doesn't recognize the method signature. For example, this is what I see in FireBug...
ID 123
Field1 TextFromField1
RoleCode[1][RoleCode] OU
RoleCode[] A
Any idea how I should set this up so the post parameters are usable?
UPDATE
For now I just altered the update function to send the multiselect values as a comma separated string. I can deal with them in the controller. I don't really like this setup, but until I find how to get the posted values to send correctly, this is what I'm going with.
update: {
url: "Home/GridUpdate",
type: "POST",
dataType: "json",
data: function () {
//Grid does not post multiselect array correctly, need to convert to a string
var rolesString = $("#gridRoleList").data("kendoMultiSelect").value().toString();
return { rolesString: rolesString };
},
complete: function (e) {
setTimeout(function () {
refreshGrid();
}, 300);
},
success: function (result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function (result) {
// notify the data source that the request failed
options.error(result);
}
},
UPDATE 2
Actually that's not a good idea because if I edit another field in the grid, I get a js error because the multiselect is not found.
Looks like your issue can be resolved by sending the data after serializing it
Read action - using MVC Wrapper
.Create(create => create.Action("Create", "Home").Data("serialize"))
JS Code
<script type="text/javascript">
function serialize(data) {
debugger;
for (var property in data) {
if ($.isArray(data[property])) {
serializeArray(property, data[property], data);
}
}
}
function serializeArray(prefix, array, result) {
for (var i = 0; i < array.length; i++) {
if ($.isPlainObject(array[i])) {
for (var property in array[i]) {
result[prefix + "[" + i + "]." + property] = array[i][property];
}
}
else {
result[prefix + "[" + i + "]"] = array[i];
}
}
}
</script>
Please refer here for complete source code
Here's how I solved it. On the change event of the editor function, I updated the value of the model with the value of the multiselect. Then the data posts correctly as a string array like this.
ID 123
Field1 TextFromField1
RoleCode[] A
RoleCode[] OU
My grid editor function
function roleMultiSelectEditor(container, options) {
$('<input id = "gridRoleList" name="' + options.field + '"/>')
.appendTo(container)
.kendoMultiSelect({
dataTextField: "RoleCode",
dataValueField: "RoleCode",
autoBind: true,
change: function (e) {
//Applies the value of the multiselect to the model.RoleCode field
//Necessary to correctly post values to controller
options.model.RoleCode = this.value();
processGridMultiSelectChange();
},
dataSource: {
type: "json",
transport: {
read: {
dataType: "json",
url: baseUrl + "api/DropDownData/RoleList",
},
}
},
dataBound: function (e) {
}
});
}

CGI API to POST using $.ajax() instead of $.getJSON() RPGLE IBM i PASE environment

What CGI API can you use to replace $.getJSON() with $(ajax)...POST. GET is used for everything (ie: GET, PUT, POST, DELETE) when using CGIDEV2 in an IBM i environment? I dont want to pass my parameters the traditiontal way eg: $('[name="EMAIL"]').val() rather I want to pass JSON object string eg: {"form" : [{ "email": "yardpenalty#yahoo.com"}]}.
We are able to perform PostToGet callbacks using the $.getJSON() using CGIDEV2 but I can't use $.ajax in its fullest. Here is what we do now which is all GET requests
PHP/JS:
// load all parameters
data = 'INSTANCE=<?echo trim($PATH_INSTANCE)?>' +
'&FUNCTION=<?echo urlencode(trim($FUNCTIONCODE))?>' +
'&USER=' + $('[name="USER"]').val() +
'&CONTACT=' + w$('[name="CONTACT"]').val() +
'&EMAIL=' + $("input[name='EMAIL']").val() +
'&MSG=' + $('[name="MSG"]').val() +
'&TYPE=' + $('[name="TYPE"]').val();
// Call the RPG REST JSONP program
$.getJSON( "http://www.domain.com:8082/rest/RPGLEPGM?callback=?",data )
.done(function( json ) { ... }
//Domain is actually
http://www.domain.com:8081
RPGLE PGM:
Begsr $Incoming;
cgiPostToGet(); // Convert POST to GET
callback = cgiParseGet('callback'); // callback
p#Function = cgiParseGet('FUNCTION');
Endsr;
But I want to be able to use the other AJAX methods doing various actions such as simply updating records .post()/.ajax() on the fly or simple .get() ajax calls without creating a callback. I don't want to have to use getJSON every time I use ajax not to mention its bad practice to POST on a GET, but from what I understand the .getJSON() provides JSONP functionality while the others do not by default.
EDIT: We do have our ajax RPGLE PGMS on a different port than the actual website so JSONP is necessary and the client knows its JSONP because we pass the callback function back.
Since our ajax RPGLE PGM CALLS are on a different port than the PHP requests (think different domains on a host server) this qualifies as cross-domain requests; therefore, we must pass the &callback=? function/wrapper back to the client using JSONP (or Cors if security is an issue). I found a really good piece on JSONP here on SO and this is exactly what this ajax call is using.
RPGLE the jQuery ajax requests are made possible by using some sort of CGI API accessible on your OS/400 - IBM i Web environment. When calling (CALLB or CALLP) an RPGLE PGM using ajax we are actually making a procedural call, but when using global temps we are actually making a SQL Procedural CALL which is way more expensive in terms of resources which is why Web Services are becoming more popular.
It is more practical to not only pass javascript objects from the form data on request but to return JSON objects with Ajax requests than storing global temp data in the db2 environment and processing it into a PHP array on the response.
By processing the JSON string on the client instead of using both server memory and drive space and disk read/writes necessary for PHP arrays and global temp files we are really able to take advantage of more modern web design practices.
Here is a working example of using $.ajax/PHP/RPGLE correctly without using $.getJSON():
<script>
$(document).ready(function(){
GetEmail("#email", '<?php echo trim($USER)?>', '<?php echo $PATH_INSTANCE?>');
FormValidation();
});
function FormValidation(){
//Variables created without the keyword var, are always global, even if they are created inside a function.
var form = $('#<?echo $PAGEID?>');
var FormError = $('.alert-danger',form);
var success = $('.alert-success',form);
form.validate({
focusInvalid: false, // do not focus the last invalid input
onkeyup: false,
ignore: ".ignore", //required for hidden input validation ie: hiddenRecaptcha
rules:{
"TYPE": {
required: true,
},
"MSG": {
required: true,
rangelength:[40,1000]
},
"CONTACT": {
required: {
depends: "#newuser:checked"
}
},
"EMAIL": {
required: true,
email: {
depends: function() {
if(!$("#newuser:checked"))
return true;
else
return false;
}
},
HTH_TelephoneEmail: {
depends: function() {
if($("#newuser:checked"))
return true;
else
return false;
}
}
},
hiddenRecaptcha: {
required: function () {
if (grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
}
},
messages: { // custom messages for form validation input
"TYPE": {
required: 'Please select an option as it pertains to your inquiry'
},
"MSG": {
required: 'Please provide some content as it pertains to your inquiry'
},
"CONTACT": {
required: "Please enter a contact person or company"
},
hiddenRecaptcha: {
required: function() {
$(".g-recaptcha:first").tooltip("enable").tooltip("show");
}
}
},
showErrors: function(errorMap, errorList) {
// Clean up any tooltips for valid elements
$.each(this.validElements(), function (index, element) {
element = $(element);
NoError_ToolTip(element);
});
// Create new tooltips for invalid elements
$.each(errorList, function (index, error) {
element = $(error.element);
message = error.message;
Error_ToolTip(element,message);
});
},
invalidHandler: function (event, validator) { //display error alert on form submit
success.hide();
$(document).scrollTop( $(".form-body").offset().top );
},
submitHandler: function () {
Submit_Complete();
}
});
function Submit_Complete(){
var obj = form.serializeObject();
console.log(obj);
$(".g-recaptcha:first").tooltip("disable").tooltip("hide");
$('.shell').html('<div class="loading"><span class="caption">Sending...</span><img src="/images/loading.gif" alt="loading"></div>');
$.ajax({
type: "POST",
url: "http://www.domain.com:8082/rest/RPGPGM2?callback=?",
data: obj,
//contentType: "application/json; charset=utf-8",
dataType: "jsonp"}).
done(function(data){
$(".shell").html('<label class="msg xs-small">' + data["MESSAGE"] + '</label><br><br><br><br><br><br><br><br><br>'+
'<div class="caption right">'+
'Home <i class="fa fa-home"></i>'+
'</div>');
}).
fail(function(){
$(".shell").html("<label class='msg xs-small'>We're Sorry!<br><br><br><br><span class='text-danger'>Unfortunately this inquiry cannot be processed at this time." +
"<br>Please try again at a later time or give us a call at:</span><br><br>+1.800.406.1291</label><br><br><br><br><br><br><br><br><br>"+
'<div class="caption right">'+
'Home <i class="fa fa-home"></i>'+
'</div>');
});
}
}
/**
* Serializes form data/objects. This actually creates a javascript object which our CGIAPI is capable of handling!
*
*/
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
var $value = '';
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
</script>
We can make RESTful calls by using some type of CGI API such as QtmhRdStin or by creating Web Services. This solution is of the former.
Here is a list of the basic CGI APIs:
RPGLE PGM:
// $Incoming: Test and load the incoming parameters
Begsr $Incoming;
cgiPostToGet(); // Convert POST to GET
callback = cgiParseGet('callback'); // never delete - unique key for the request
p#UserID = cgiParseGet('USER');
if (%scan(#lf:p#UserID) <> 0);
p#UserID = *blanks;
endif;
p#Instance = cgiParseGet('INSTANCE');
if (%scan(#lf:p#Instance) <> 0);
p#Instance = *blanks;
endif;
p#Function = cgiParseGet('FUNCTION');
p#Contact = cgiParseGet('CONTACT');
if (%scan(#lf:p#Contact) <> 0);
p#Contact = *blanks;
endif;
p#Email = cgiParseGet('EMAIL');
p#Msg = cgiParseGet('MSG');
p#Related = cgiParseGet('TYPE');
exsr $InzSr;
Endsr;
Begsr $Outgoing;
// Tell Consumer that a JSON string will be sent
ajx_data = 'Content-type: text/javascript' + CRLF + CRLF; // DO NOT CHANGE THIS LINE!!!
QtmhWrStout(ajx_data: %len(%trimr(ajx_data)): ajx_err);// DO NOT CHANGE THIS LINE!!!
ajx_data = %trim(callback) + '(' + %char(LBrace); // DO NOT CHANGE THIS LINE!!!
QtmhWrStout(ajx_data: %len(%trimr(ajx_data)): ajx_err);// DO NOT CHANGE THIS LINE!!!
ajx_data = '"MESSAGE":"' + %trim(p#message) + '"';
QtmhWrStout(ajx_data: %len(%trimr(ajx_data)): ajx_err);
// load the final right brace to complete the JSON string
ajx_data = %char(RBrace) + ');'; // DO NOT CHANGE THIS LINE!!!
QtmhWrStout(ajx_data: %len(%trimr(ajx_data)): ajx_err); // DO NOT CHANGE THIS LINE!!!
Endsr;
****NOTE****
If we can't serialize our form directly we must build a javascript object like this:
var obj = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
$.ajax({
type: "POST",
url: "http://webservices.hthackney.com/web054S?callback=?",
data: data,
dataType:'jsonp'
}).done({ //do something on success });
Unfortunately you can POST using JSONP but you cannot read the header response.
I FINALLY found the solution to executing both db2 and ajax requests on a single DOMAIN.
SOLUTION HERE
If you need to perform AJAX requests on the SAME DOMAIN in an IBMi environment w/apache/PASE you need the following ScriptAlias and two directives in your http.conf file:
ScriptAliasMatch /rest/([0-9a-zA-Z]+$) /qsys.lib/rest.lib/$1.pgm
<Directory /qsys.lib/obj.lib/>
order allow,deny
allow from all
Header Always Set Access-Control-Allow-Origin *
Options +ExecCGI +Includes -Indexes +MultiViews
CGIConvMode %%MIXED/MIXED%%
</Directory>
<Directory /qsys.lib/rest.lib>
CGIConvMode %%EBCDIC/EBCDIC%%
Order Allow,Deny
Allow From all
Header Always Set Access-Control-Allow-Origin *
Options +ExecCGI -FollowSymLinks -SymLinksIfOwnerMatch +Includes -IncludesNoExec -Indexes -MultiViews
</Directory>
rest.lib member is where all of the ajax rpgle pgms reside.
obj.lib is where all CALL WEBXXX for db2 calls in PHP are located.
Now you are able to call AJAX requests under the /rest/$1PGM pattern.
For instance:
$.ajax({
type: "POST",
url: "http://www.domain.com/rest/WEB055S",
data: obj,
contentType: "application/json; charset=utf-8"
).
done(function(data){
$("#signupForm .loading").addClass("hidden");
//Successful Submit!
if(typeof data.MESSAGE != "undefined"){
clicked = 0;
$("#ok_msg").html(data.MESSAGE).show();
}
else{//ERROR
//console.log(data.ERROR);
$("#attendee #hth_err_msg").html(data.ERROR).show();
$('.add-attendee').addClass('hidden');
$('.edit-attendee').addClass('hidden');
}
}).
fail(function(){
$("#hth_err_msg").html("We're sorry, you're request cannot be processed at this time. It is likely the corporate system is under maintenance.").show();
});

IBM Worklight JSONStore - Add and get data

I am using worlight JSONstore. I am new to it. I tried searching that read all docs but didn't get much idea.
I have one login page from that I get some json data I want to store that data using jsonstore. and get that afterwards.
I made jsonstore adapter.
Json-Store-Impl.js
function getJsonStores(custData) {
var data = custData;
return data;
//custdata is json
}
function addJsonStore(param1) {
var input = {
method : 'put',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function updateJsonStore(param1) {
var input = {
method : 'post',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function deleteJsonStore(param1) {
var input = {
method : 'delete',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
after that I Create a local JSON store.
famlCollection.js
;(function () {
WL.JSONStore.init({
faml : {
searchFields: {"response.mci.txnid":"string","response.mci.scrnseqnbr":"string","response.loginUser":"string","request.fldWebServerId":"string","response.fldRsaImageHeight":"string","request.fldRequestId":"string","request.fldTxnId":"string","response.fldDeviceTokenFSO":"string","response.fldRsaCollectionRequired":"string","response.datlastsuccesslogin":"string","response.fldRsaUserPhrase":"string","response.fldRsaAuthTxnId":"string","response.rc.returncode":"string","response.datcurrentlogin":"string","response.mci.deviceid":"string","response.customername":"string","request.fldDeviceId":"string","response.fldRsaUserStatus":"string","request.fldScrnSeqNbr":"string","response.fldRsaImageWidth":"string","request.fldLangId":"string","response.fldTptCustomer":"string","response.encflag":"string","response.rc.errorcode":"string","response.fldRsaImagePath":"string","response.mci.appid":"string","response.mci.requestid":"string","response.rc.errormessage":"string","response.mci.appserverid":"string","response.fldRsaCollectionType":"string","request.fldAppId":"string","response.fldRsaImageId":"string","request.fldLoginUserId":"string","response.mci.sessionid":"string","response.mci.langid":"string","response.mci.remoteaddress":"string","request.fldAppServerId":"string","response.mci.webserverid":"string","response.fldRsaImageText":"string","response.fldRsaEnrollRequired":"string","response.fldRsaActivityFlag":"string"},
adapter : {
name: 'JsonStore',
replace: 'updateJsonStore',
remove: 'deleteJsonStore',
add: 'addJsonStore',
load: {
procedure: 'getJsonStores',
params: [],
key: 'faml'
},
accept: function (data) {
return (data.status === 200);
}
}
}
}, {
password : 'PleaseChangeThisPassword'
})
.then(function () {
WL.Logger.debug(['Take a look at the JSONStore documentation and getting started module for more details and code samples.',
'At this point there is no data inside your collection ("faml"), but JSONStore is ready to be used.',
'You can use WL.JSONStore.get("faml").load() to load data from the adapter.',
'These are some common JSONStore methods: load, add, replace, remove, count, push, find, findById, findAll.',
'Most operations are asynchronous, wait until the last operation finished before calling the next one.',
'JSONStore is currently supported for production only in Android and iOS environments.',
'Search Fields are not dynamic, call WL.JSONStore.destroy() and then initialize the collection with the new fields.'].join('\n'));
})
.fail(function (errObj) {
WL.Logger.ctx({pretty: true}).debug(errObj);
});
}());
When I clicked on login button I call getJsonStores like this -
getJsonStores = function(){
custData = responseData();
var invocationData = {
adapter : "JsonStore",
procedure : "getJsonStores",
parameters : [custData],
compressResponse : true
};
//WL.Logger.debug('invoke msg '+invocationData, '');
WL.Client.invokeProcedure(invocationData, {
onSuccess : sucess,
onFailure : AdapterFail,
timeout: timeout
});
};
I followed these steps
Is this right way? and how can I check jsonstore working locally or not? and how can I store my jsondata in JSONStore? Where should I initialize the wlCommonInit function in project?
plz Help me out.
Open main.js and find the wlCommonInit function, add the JSONStore init code.
WL.JSONStore.init(...)
You already have an adapter that returns the data you want to add to JSONStore, call it any time after init has finished.
WL.Client.invokeProcedure(...)
Inside the onSuccess callback, a function that gets executed when you successfully get data from the adapter, start using the JSONStore API. One high level way to write the code would be, if the collection is empty (the count API returns 0), then add all documents to the collection.
WL.JSONStore.get(collectionName).count()
.then(function (countResult) {
if(countResult === 0) {
//collection is empty, add data
WL.JSONStore.get(collectionName).add([{name: 'carlos'}, {name: 'mike'}])
.then(function () {
//data stored succesfully
});
}
});
Instead of adding [{name: 'carlos'}, {name: 'mike'}] you probably want to add the data returned from the adapter.
Later in your application, you can use the find API to get data back:
WL.JSONStore.get(collectionName).findAll()
.then(function (findResults) {
//...
});
There is also a find API that takes queries (e.g. {name: 'carlos'}), look at the getting started module here and the documentation here.
It's worth mentioning that the JSONStore API is asynchronous, you must wait for the callbacks in order to perform the next operation.