IBM Worklight 6.0 - Pass parameter to JSONStore load function - adapter

I want to load a JSONStore based on a provided param to the adapter mapped load function.
Let me explain it better.
The JSONStore initialization is like this:
collections[EMPLOYEE_COLLECTION_NAME] = {
searchFields : {ENAME: 'string', EMPNO:'integer'},
//-- Start optional adapter metadata
adapter : {
name: 'EmployeesDB',
add: 'addEmployee',
remove: 'deleteEmployee',
replace: 'updateEmployee',
load: {
procedure: 'getEmployee',
params: [region],
key: 'resultSet'
}
}
//-- End optional adapter metadata
};
//Initialize the people collection
WL.JSONStore.init(collections, options)
As you can see in the code above, even after the param region was passed to the adapter collection init, is it supposed to change during my app life cycle, so there are moments where region let's say is SOUTH, others is NORTH and so on.
I realized that even though I change this value after the store was created, the mapped load function in the adapter getEmployee (see below) always get value that region contained at the time the jsonstore was initialized regardless I change the region variable value later on. Looks like the adapter binds conf is getting at collection creation time, and never changes it
function getEmployee(data) {
WL.Logger.info('Show param:'+data);
return WL.Server.invokeSQLStatement({
preparedStatement : selectStatement,
parameters : []
});
}
Is there a way to pass parameter to the Jsonstore load function that can change after the store was initialized ?
I wanted to avoid close and init the collection again to save time and resources.
By the way, what I really need is to have flexibility on what I load from the database based on a adapter parameter that is bound to a collection.

Try something like:
WL.JSONStore.get(EMPLOYEE_COLLECTION_NAME).adapter.load.params = ['...']
Before calling WL.JSONStore.get(EMPLOYEE_COLLECTION_NAME).load().
If you want more flexibility, you can always call WL.Client.invokeProcedure and inside the onSuccess callback you can call: WL.JSONStore.get(EMPLOYEE_COLLECTION_NAME).add(['...'], {push: false}). The push: false section will make sure JSONStore understands that the data added is up-to-date with the data on the backend. This means it won't show those documents when you call: WL.JSONStore.get(EMPLOYEE_COLLECTION_NAME).getPushRequired() or WL.JSONStore.get(EMPLOYEE_COLLECTION_NAME).push().

Related

How to refresh previously bound entity every time user visits the page

I just ran into a problem where I am not sure how to solve.
Background: I've got an App with two views:
1st one to input a number,
2nd one to see the details.
After the view switched to the detail view, I would call the bindElement() to get my data from the backend.
_onRoutePatternMatched: function(oEvent) {
// ...
this.getView().bindElement({
path: "/EntitySet('" + id+ "')"
});
},
Problem is that the ID is quite often the same, hence, the method will call the backend only if the ID is different from the last call.
So I tried to solve the problem by using the following:
this.getView().getModel().read("/EntitySet('" + id+ "')",{
success: function(oData, response) {
that.getView().setModel(oData, "");
}
});
By this, the data is always up to date. But now the binding is a bit different.
Binding with bindElement():
{
"id": "1234",
"propety1": "abc",
// ...
}
Binding with setModel() and id = 1234:
{
"EntitySet('1234')": {
"id": "1234",
"propety1": "abc",
// ...
}
}
For the first way, my binding looked like this:
<ObjectHeader title="{id}">
Now, it would have to look like this:
<ObjectHeader title="{/EntitySet('1234')/id}">
And here I have a problem, because the value of id (in this case 1234) will always be different and so the binding won't work. I can't bind directly to the ObjectHeader, because I will need some properties from the model later. That is the reason I am binding to the view so that all that remain available.
My idea was to edit the binding inside the success method of the read method. I would like to delete the surrounding element. Do you have an idea, how to do this? Or even a simpler/better idea to solve my pity?
Edit:
I forgot to mention the refresh method. This would be possible, but where do I have to put it? I don't want to call the backend twice.
Simply call the API myODataModel.invalidateEntry(<key>) before binding the context in order to retrieve the latest data.
// after $metadata loaded..
const model = this.getOwnerComponent().getModel("odata");
const key = model.createKey(/*...*/) //See https://stackoverflow.com/a/47016070/5846045
model.invalidateEntry(key); // <-- before binding
this.getView().bindElement({
path: "odata>/" + key,
// ...
});
From https://embed.plnkr.co/b0bXJK?show=controller/Detail.controller.js,preview
invalidateEntrydoc
Invalidate a single entry in the model data.
Mark the selected entry in the model cache as invalid. Next time a context binding or list binding is done, the entry will be detected as invalid and will be refreshed from the server.

Is there a way in deployd to map a collection to a different endpoint?

I have a collection called customer_devices and I can't change the name. Can I expose it via deployd as /devices ? How?
There are a few ways that I can think of. If you really just want to rename the collection, you can do so from the dashboard, as #thomasb mentioned in his answer.
Alternatively, you can create a "proxy" event resource devices and forward all queries to customer_devices. For example, in devices/get.js you would say
dpd.customer_devices.get(query, function(res, err) {
if (err) cancel(err);
setResult(res);
});
Update
Finally, here is a "hack" to redirect all requests from one resource path to a different path. This is poorly tested so use at your own risk. This requires that you set up your own server as explained here. Once you have that, you can modify the routing behaviour using this snippet:
server.on('listening', function() {
var customer_devices = server.router.resources.filter(function (res) {
return res.path === '/customer_devices';
})[0];
// Make a copy of the Object's prototype
var devices = Object.create(customer_devices);
// Shallow copy the properties
devices = extend(devices, customer_devices);
// Change the routing path
devices.path = "/devices";
// Add back to routing cache
server.router.resources.push(devices);
});
This will take your customer_devices resource, copy it, change the path, and re-insert it into the cached routing table. I tested it and it works, but I won't guarantee that it's safe or a good idea...
Can't you change the name via dashboard?
Mouseover your collection customer_devices
Click the down arrow
Select 'Rename'
Enter the new name and click 'Rename'

Getting service metadata of SAPUI5 v2 ODataModel?

I try to get the service metadata of a sapui5 v2 odata model.
Code:
var oModel = new sap.ui.model.odata.v2.ODataModel(someServiceURL);
var oMetadata = oModel.getServiceMetadata();
This should work according to this page:
https://openui5beta.hana.ondemand.com/docs/guide/6c47b2b39db9404582994070ec3d57a2.html
Anyhow I got "undefined" for oMetadata.
If I change code to:
var oModel = new sap.ui.model.odata.v2.ODataModel({
loadMetadataAsync : false,
serviceUrl : someServiceURL
});
Still oMetadata === undefined
According to SDK documentation metadata should be loaded in sync:
Return the metadata object. Please note that when using the model with
bLoadMetadataAsync = true then this function might return undefined
because the metadata has not been loaded yet. In this case attach to
the metadataLoaded event to get notified when the metadata is
available and then call this function.
What is wrong with my code?
I am using (1.28.11):
<script src="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js" ...
I started debugging the UI5 code and detected following line:
this.bLoadMetadataAsync = true;
I started debugging of SAPUI5 code and detected following line (seems to be called each time):
this.bLoadMetadataAsync = true;
Is it a bug? Or is something wrong with my code?
Solution:
The following worked for me in an actual application environment. I guess it not being fired in my fiddle was due to no actual data request being made:
var oModel = new sap.ui.model.odata.v2.ODataModel(<ServiceURL>);
oModel.attachMetadataLoaded(null, function(){
var oMetadata = oModel.getServiceMetadata();
console.log(oMetadata);
},null);
Lead up to the solution:
Ok so I started playing around with this a bit and found the following:
.getServiceMetadata() worked fine with sap.ui.model.odata.ODataModel.
with the sap.ui.model.odata.v2.ODataModel the request for the metadata was sent through the network but somehow .getServiceMetadata() returned undefined.
I tried to sap.ui.model.odata.v2.ODataModel.attachMetadataLoaded() but the event was never fired. (This only applied in the jsbin I used)
I will edit this with any further findings I make. If you have anything that should be included in my findings/testing just tell me.
Edit:
The bLoadMetadataAsync is a parameter you can set on the sap.ui.model.odata.ODataModel. The parameter is not in the API for sap.ui.model.odata.v2.ODataModel anymore. I assume that the async loading has been choosen as default.
Edit:
#user3783327 Reported a bug here: https://github.com/SAP/openui5/issues/564
As sirion already mentioned, the ODataModel has now an API named metadataLoaded which returns a promise accordingly. In the resolve function, we can definitely get the service metadata via getServiceMetadata().
myODataModel.metadataLoaded()
.then(() =>/* Do something with */myODataModel.getServiceMetadata());
Alternatively, we can also make use of ODataMetaModel which can be set on any ManagedObject (including View) and provides several useful accessors related to the service metadata. In order to get the meta model, we need to use the appropriate API from the ODataModel instead of instantiating the model directly:
myODataModel.getMetaModel().loaded()
.then(() =>/* Do something with */myODataModel.getMetaModel()/*...*/);
Documentation: Meta Model for OData V2

API to modify Firefox downloads list

I am looking to write a small firefox add-on that detects when files that were downloaded are (or have been) deleted locally and removes the corresponding entry in the firefox download list.
Can anybody point me to the relevant api to manipulate the download list? I cannot seem to find it.
The relevant API is PlacesUtils which abstracts the complexity of the Places database.
If your code runs in the context of a chrome window then you get a PlacesUtils glabal variable for free. Otherwise (bootstrapped, Add-on SDK, whatever) you have to import PlacesUtils.jsm.
Cu.import("resource://gre/modules/PlacesUtils.jsm");
As far as Places is concerned, downloaded files are nothing more than a special kind of visited pages, annotated accordingly. It's a matter of just one line of code to get an array of all downloaded files.
var results = PlacesUtils.annotations.getAnnotationsWithName("downloads/destinationFileURI");
Since we asked for the destinationFileURI annotation, each element of the resultarray holds the download location in the annotationValue property as a file: URI spec string.
With that you can check if the file actually exists
function getFileFromURIspec(fileurispec){
// if Services is not available in your context Cu.import("resource://gre/modules/Services.jsm");
var filehandler = Services.io.getProtocolHandler("file").QueryInterface(Ci.nsIFileProtocolHandler);
try{
return filehandler.getFileFromURLSpec(fileurispec);
}
catch(e){
return null;
}
}
getFileFromURIspec will return an instance of nsIFile, or null if the spec is invalid which shouldn't happen in this case but a sanity check never hurts. With that you can call the exists() method and if it returns false then the associated page entry in Places is eligible for removal. We can tell which is that page by its uri, which conveniently is also a property of each element of the results.
PlacesUtils.bhistory.removePage(result.uri);
To sum it up
var results = PlacesUtils.annotations.getAnnotationsWithName("downloads/destinationFileURI");
results.forEach(function(result){
var file = getFileFromURIspec(result.annotationValue);
if(!file){
// I don't know how you should treat this edge case
// ask the user, just log, remove, some combination?
}
else if(!file.exists()){
PlacesUtils.bhistory.removePage(result.uri);
}
});

Server-side internationalization for Backbone and Handlebars

I'm working on a Grails / Backbone / Handlebars application that's a front end to a much larger legacy Java system in which (for historical & customizability reasons) internationalization messages are deep in a database hidden behind a couple of SOAP services which are in turn hidden behind various internal Java libraries. Getting at these messages from the Grails layer is easy and works fine.
What I'm wondering, though, is how to get (for instance) internationalized labels into my Handlebars templates.
Right now, I'm using GSP fragments to generate the templates, including a custom tag that gets the message I'm interested in, something like:
<li><myTags:message msgKey="title"/> {{title}}</li>
However, for performance and code layout reasons I want to get away from GSP templates and get them into straight HTML. I've looked a little into client-side internationalization options such as i18n.js, but they seem to depend on the existence of a messages file I haven't got. (I could generate it, possibly, but it would be ginormous and expensive.)
So far the best thing I can think of is to wedge the labels into the Backbone model as well, so I'd end up with something like
<li>{{titleLabel}} {{title}}</li>
However, this really gets away from the ideal of building the Backbone models on top of a nice clean RESTful JSON API -- either the JSON returned by the RESTful service is cluttered up with presentation data (i.e., localized labels), or I have to do additional work to inject the labels into the Backbone model -- and cluttering up the Backbone model with presentation data seems wrong as well.
I think what I'd like to do, in terms of clean data and clean APIs, is write another RESTful service that takes a list of message keys and similar, and returns a JSON data structure containing all the localized messages. However, questions remain:
What's the best way to indicate (probably in the template) what message keys are needed for a given view?
What's the right format for the data?
How do I get the localized messages into the Backbone views?
Are there any existing Javascript libraries that will help, or should I just start making stuff up?
Is there a better / more standard alternative approach?
I think you could create quite an elegant solution by combining Handelbars helpers and some regular expressions.
Here's what I would propose:
Create a service which takes in a JSON array of message keys and returns an JSON object, where keys are the message keys and values are the localized texts.
Define a Handlebars helper which takes in a message key (which matches the message keys on the server) and outputs an translated text. Something like {{localize "messageKey"}}. Use this helper for all template localization.
Write a template preprocessor which greps the message keys from a template and makes a request for your service. The preprocessor caches all message keys it gets, and only requests the ones it doesn't already have.
You can either call this preprocessor on-demand when you need to render your templates, or call it up-front and cache the message keys, so they're ready when you need them.
To optimize further, you can persist the cache to browser local storage.
Here's a little proof of concept. It doesn't yet have local storage persistence or support for fetching the texts of multiple templates at once for caching purposes, but it was easy enough to hack together that I think with some further work it could work nicely.
The client API could look something like this:
var localizer = new HandlebarsLocalizer();
//compile a template
var html = $("#tmpl").html();
localizer.compile(html).done(function(template) {
//..template is now localized and ready to use
});
Here's the source for the lazy reader:
var HandlebarsLocalizer = function() {
var _templateCache = {};
var _localizationCache = {};
//fetches texts, adds them to cache, resolves deferred with template
var _fetch = function(keys, template, deferred) {
$.ajax({
type:'POST',
dataType:'json',
url: '/echo/json',
data: JSON.stringify({
keys: keys
}),
success: function(response) {
//handle response here, this is just dummy
_.each(keys, function(key) { _localizationCache[key] = "(" + key + ") localized by server"; });
console.log(_localizationCache);
deferred.resolve(template);
},
error: function() {
deferred.reject();
}
});
};
//precompiles html into a Handlebars template function and fetches all required
//localization keys. Returns a promise of template.
this.compile = function(html) {
var cacheObject = _templateCache[html],
deferred = new $.Deferred();
//cached -> return
if(cacheObject && cacheObject.ready) {
deferred.resolve(cacheObject.template);
return deferred.promise();
}
//grep all localization keys from template
var regex = /{{\s*?localize\s*['"](.*)['"]\s*?}}/g, required = [], match;
while((match = regex.exec(html))) {
var key = match[1];
//if we don't have this key yet, we need to fetch it
if(!_localizationCache[key]) {
required.push(key);
}
}
//not cached -> create
if(!cacheObject) {
cacheObject = {
template:Handlebars.compile(html),
ready: (required.length === 0)
};
_templateCache[html] = cacheObject;
}
//we have all the localization texts ->
if(cacheObject.ready) {
deferred.resolve(cacheObject.template);
}
//we need some more texts ->
else {
deferred.done(function() { cacheObject.ready = true; });
_fetch(required, cacheObject.template, deferred);
}
return deferred.promise();
};
//translates given key
this.localize = function(key) {
return _localizationCache[key] || "TRANSLATION MISSING:"+key;
};
//make localize function available to templates
Handlebars.registerHelper('localize', this.localize);
}
We use http://i18next.com for internationalization in a Backbone/Handlebars app. (And Require.js which also loads and compiles the templates via plugin.)
i18next can be configured to load resources dynamically. It supports JSON in a gettext format (supporting plural and context variants).
Example from their page on how to load remote resources:
var option = {
resGetPath: 'resources.json?lng=__lng__&ns=__ns__',
dynamicLoad: true
};
i18n.init(option);
(You will of course need more configuration like setting the language, the fallback language etc.)
You can then configure a Handlebars helper that calls i18next on the provided variable (simplest version, no plural, no context):
// namespace: "translation" (default)
Handlebars.registerHelper('_', function (i18n_key) {
i18n_key = Handlebars.compile(i18n_key)(this);
var result = i18n.t(i18n_key);
if (!result) {
console.log("ERROR : Handlebars-Helpers : no translation result for " + i18n_key);
}
return new Handlebars.SafeString(result);
});
And in your template you can either provide a dynamic variable that expands to the key:
<li>{{_ titleLabeli18nKey}} {{title}}</li>
or specify the key directly:
<li>{{_ "page.fancy.title"}} {{title}}</li>
For localization of datetime we use http://momentjs.com (conversion to local time, formatting, translation etc.).

Resources