How to use _bindProvider method in wpt

Best JavaScript code snippet using wpt

AbstractBindFactory.js

Source:AbstractBindFactory.js Github

copy

Full Screen

1/*****************************************************************2 * Copyright (c) 2015 Texas Instruments and others3 * All rights reserved. This program and the accompanying materials4 * are made available under the terms of the Eclipse Public License v1.05 * which accompanies this distribution, and is available at6 * http://www.eclipse.org/legal/epl-v10.html7 *8 * Contributors:9 * Paul Gingrich - Initial API and implementation10 *****************************************************************/11var gc = gc || {};12gc.databind = gc.databind || {};13(function()14{15 var StorageProvider = function(modelBindings)16 {17 this._bindings = modelBindings;18 };19 StorageProvider.prototype.readData = function()20 {21 var data = {};22 for(var bindName in this._bindings)23 {24 if (this._bindings.hasOwnProperty(bindName))25 {26 var bind = this._bindings[bindName];27 if (!bind.isReadOnly() && bind.excludeFromStorageProviderData === undefined)28 {29 data[bindName] = this._bindings[bindName].getValue();30 }31 }32 }33 return data;34 };35 StorageProvider.prototype.writeData = function(data)36 {37 for(var bindName in data)38 {39 if (data.hasOwnProperty(bindName))40 {41 var bind = this._bindings[bindName];42 if (bind)43 {44 bind.setValue(data[bindName]);45 }46 }47 }48 };49 var TARGET_CONNECTED_BINDNAME = '$target_connected';50 /**51 * Abstract class that provides default implementation of IBindFactory. This class52 * implements the getName() method for IBindFactory.53 *54 * @constructor55 * @implements gc.databind.IBindFactory56 * @param {string} name - uniquely identifiable name for this bind factory.57 */58 gc.databind.AbstractBindFactory = function(name)59 {60 if ( name !== undefined )61 {62 this._id = name;63 }64 };65 gc.databind.AbstractBindFactory.prototype = new gc.databind.IBindFactory();66 /**67 * Method to initialize internal private data structures. This method must be called once, by68 * final concrete class to initialize all abstract base classes. This is necessary because the69 * abstract base class constructors are called multiple times, and some initialization needs to70 * be performed only once. Derived implementations should override this method, and their own71 * one time initialization steps, and call the base classes init() function too.72 *73 */74 gc.databind.AbstractBindFactory.prototype.init = function()75 {76 this._modelBindings = {};77 this._modelBindings[TARGET_CONNECTED_BINDNAME] = new gc.databind.VariableBindValue(false, true);78 this._modelQualifiers = new gc.databind.internal.QualifierFactoryMap();79 };80 /**81 * Method to create a storage provider for this Model. This method should be called from the82 * overridden init() method of the derived Model. Do this if you wish menu item File/Save Settings83 * should store the bindings in this model when the user requests it. In general, Math and prop84 * bindings do not need to be stored, because their value is not read from a target and therefore85 * represent calculated values that do not change.86 */87 gc.databind.AbstractBindFactory.prototype.createStorageProvider = function()88 {89 var modelBindings = this._modelBindings;90 var name = this.getName();91 gc.File = gc.File || {};92 gc.File.ready = gc.File.ready || Q.Promise(function(resolve) { gc.File.fireReady = resolve; });93 gc.File.ready.then(function()94 {95 // register data provider to load and store data from the factory provided when called upon.96 gc.File.addDataProvider(name, new StorageProvider(modelBindings));97 });98 };99 gc.databind.AbstractBindFactory.prototype.getName = function()100 {101 return this._id;102 };103 /**104 * Helper method for finding and/or creating bindings on this model. This method does not go through the binding registry105 * to find the binding, and does not apply qualifiers. If the binding does not already exist it will be created.106 * To parse bindings, including qualifiers, use gc.databind.registry.getBinding() api instead, but be sure to prepend the model name to the binding name.107 * to ensure this model is used to create the binding.108 *109 * @param {String} name - uniquely identifying the bindable object within the model.110 * @return {gc.databind.IBind} - the existing or newly created bindable object, or null if this name is not supported by this model.111 */112 gc.databind.AbstractBindFactory.prototype.getBinding = function(name)113 {114 // ensure aliased bindings like "uart.temp" and "target_dev.temp" return the same instance of the model's binding.115 // We do this by storing model bindings in the model factory so we can lookup aliased bindings.116 var bind = this._modelBindings[name];117 if (!bind)118 {119 bind = this.createNewBind(name);120 if (bind)121 {122 bind.setName(name);123 }124 this._modelBindings[name] = bind;125 }126 return bind;127 };128 gc.databind.AbstractBindFactory.prototype.hasBinding = function(bindingName) {129 return this._modelBindings.hasOwnProperty(bindingName);130 };131 gc.databind.AbstractBindFactory.prototype.parseModelBinding = function(name)132 {133 return this._modelQualifiers.parseQualifiers(name, this.getBinding, this);134 };135 gc.databind.AbstractBindFactory.prototype.getAllBindings = function()136 {137 return this._modelBindings;138 };139 /**140 * Method to set the connected or disconnected state of the model. This method141 * is called by the transport when a connecting is established or broken. The connected142 * state is available as a binding, "$target_connected", to app developers if they143 * need to show the connected state of a transport.144 * This method must be called once from the concrete class instance's constructor.145 *146 * @param {boolean} newState - true if to set state to connected, otherwise new state is disconnected.147 */148 gc.databind.AbstractBindFactory.prototype.setConnectedState = function(newState)149 {150 this._modelBindings[TARGET_CONNECTED_BINDNAME].updateValue(newState);151 if (newState && this._connectDeferred)152 {153 this._connectDeferred.resolve();154 this._connectDeferred = null;155 }156 };157 /**158 * Query method to determine if the model is connected or disconnected from a target.159 *160 * @return {boolean} - true if the model is connected to a target, otherwise false.161 */162 gc.databind.AbstractBindFactory.prototype.isConnected = function()163 {164 return this._modelBindings[TARGET_CONNECTED_BINDNAME].getValue();165 };166 /**167 * Method to register model specific qualifiers. Qualifiers are registered by name with a factory method168 * for creating the qualifier on demand. To use a qualifier on a binding, append '.$' plus the name of the169 * qualifier with an optional numeric agrument; for example, "mybind.$q7" would apply the "q" value qualifier with 7 fractional bits.170 * All qualifiers can have an optional single value numeric argument. This means that the qualifier name cannot end with numeric characters;171 * otherwise, they will be parsed as an argument instead of the qualifier name. All models have the default "q", "hex", "dec", etc..., number172 * formatting qualifiers already registered. Use this method to register additional, model specific qualifiers.173 *174 *175 * @param {string} name - the name of the qualifier, without the '.$' prefix.176 * @param {gc.databind.AbstractBindFactory#qualifierFactoryMethod} factory - the factory method to create the qualifier on a specific binding.177 */178 gc.databind.AbstractBindFactory.prototype.addQualifier = function(name, factory)179 {180 this._modelQualifiers.add(name, factory);181 };182 /**183 * Factory method used by addQualifier.184 *185 * @param {gc.databind.IBindValue} bind - the binding to apply the qualifier to.186 * @param {number} [param] - optional numeric argument for the qualifier. If an argument is required,187 * but it is undefined, an appropriate default (like zero) should be applied.188 * @callback gc.databind.AbstractBindFactory#qualifierFactoryMethod189 */190 /**191 * Helper method to get a promise that is resolved when the model is connected to a target.192 * Derived classes should use this to delay accessing the target until the model is connected.193 *194 * @return {promise} - a promise that is either already resolved, or will resolve the next time195 * the model is connected to a target through a transport.196 */197 gc.databind.AbstractBindFactory.prototype.whenConnected = function()198 {199 this._connectDeferred = this._connectDeferred || Q.defer();200 return this._connectDeferred.promise;201 };202 /**203 * Creates a new scripting instance.204 *205 * @param {number} [bufferLength] - The buffer length that will be used for data exchange206 * between the main UI thread and the script execution worker thread. The default is 2072 bytes.207 * @param {string} [logfile] - The log file path208 * @return {gc.databind.Scripting} - the newly created script instance.209 */210 gc.databind.AbstractBindFactory.prototype.newScriptInstance = function(bufferLength, logfile) {211 var logs = [];212 var instance = new gc.databind.Scripting(bufferLength || (24 /*header*/ + 2048 /*payload*/), this._scriptHandler.bind(this));213 var handler = {214 _saveLog: function() {215 var defer = Q.defer();216 if (logs && logs.length > 0) {217 if (typeof process === 'undefined') {218 gc.File.saveBrowserFile(logs.join('\n'), {filename: logfile || 'scripting.log'});219 logs = [];220 defer.resolve();221 } else {222 gc.File.save(logs.join('\n'), {localPath: logfile || 'scripting.log'}, null, function(){223 logs = [];224 defer.resolve();225 });226 }227 }228 return defer.promise;229 },230 onLog: function(detail) {231 if (detail.clear) {232 logs = [];233 }234 if (detail.text) {235 logs.push(detail.text);236 }237 },238 onMainCompleted: function() {239 this._saveLog();240 },241 onTerminated: function() {242 this._saveLog();243 },244 onExit: function() {245 this._saveLog().then(function() {246 window.close();247 });248 }249 };250 instance.addEventListener('Exit', handler);251 instance.addEventListener('Log', handler);252 instance.addEventListener('MainCompleted', handler);253 instance.addEventListener('Terminated', handler);254 return instance;255 };256 /**257 * Callback message handler for the scripting engine.258 *259 * @private260 */261 gc.databind.AbstractBindFactory.prototype._scriptHandler = function(event) {262 var detail = event.data;263 /* handle common messages */264 switch (detail.cmd) {265 case 'read':266 return this._scriptRead(detail.name);267 case 'write':268 return this._scriptWrite(detail.name, detail.value);269 case 'invoke':270 return this._scriptInvoke(detail.name, detail.args, detail.inf);271 }272 var msg = "Unsupported cmd or event: " + detail.cmd || detail.event;273 gc.console.error("Scripting", msg);274 return Q.reject(msg);275 };276 /**277 * Default implementation for reading value from the target.278 *279 * @protected280 * @param {string} uri - the name of the binding to read281 * @return {Promise} - a promise that resolves to the value read.282 */283 gc.databind.AbstractBindFactory.prototype._scriptRead = function(uri) {284 var binding = this.getBinding(uri);285 if (binding) {286 return Q(binding.getValue());287 } else {288 var msg = "Failed to read value, " + uri + " does not exist."289 gc.console.error("Scripting", msg);290 return Q.reject(msg);291 }292 };293 /**294 * Default implementation for writing value to the target.295 *296 * @protected297 * @param {string} uri - the name of the binding to write298 * @param {Object} value - the value to write299 * @return {Promise} - that resolves when the write operation has completed.300 */301 gc.databind.AbstractBindFactory.prototype._scriptWrite = function(uri, value) {302 var binding = this.getBinding(uri);303 if (binding.isReadOnly()) {304 var msg = "Failed writing value, " + url + " is reaonly.";305 gc.console.error("Scripting", msg)306 return Q.reject(msg);307 }308 if (binding) {309 return Q.Promise(function(resolve) {310 var progress = new gc.databind.ProgressCounter(resolve);311 binding.setValue(value, progress, true);312 progress.done();313 });314 } else {315 var msg = "Failed to write value, " + uri + " does not exist."316 gc.console.error("Scripting", msg);317 return Q.reject(msg);318 }319 };320 /**321 * Sub-class can override this method to expose method that can be invoked by the scripting engine.322 *323 * @protected324 * @param {String} method - name of the method to invoke from the script325 * @param {Object[]} args - array of arguments to pass to the method326 * @param {String} [inf] - name of the interface to invoke the method, if appropriate.327 */328 gc.databind.AbstractBindFactory.prototype._scriptInvoke = function(method, args, inf) {329 var self = this;330 if (args && !Array.isArray(args)) args = [args];331 /* invoke matching interface defined by the codec */332 if (self._codec && self._codec.getInterfaces && inf) {333 var infs = self._codec.getInterfaces();334 for (var i in infs) {335 if (inf === i && infs.hasOwnProperty(i)) {336 var _inf = infs[i];337 return _inf[method] ? Q(_inf[method].apply(_inf, args)) : Q.reject(inf + " does not have ${method} method.");338 }339 }340 return Q.reject(self._codec.name + " does not have ${inf}.");341 }342 /* invoke codec method */343 if (self._codec) {344 return self._codec[method] ? Q(self._codec[method].apply(self._codec, args)) : Q.reject(self._codec.name + " does not have " + method + " method.");345 }346 return Q.reject("Failed to invoke " + method + " method.");347 };348 var ModelBindProvider = function(model)349 {350 this._model = model;351 this._bindings = {};352 this._expressionParser = new gc.databind.internal.expressionParser.ExpressionParser(this);353 };354 ModelBindProvider.prototype = new gc.databind.IBindProvider();355 var stripSpacesMatchString = /^\s+|\s*([^A-Za-z0-9$_ ']+|'[^']*')\s*|\s+$/g;356 ModelBindProvider.prototype.getBinding = function(name, hint)357 {358 if (hint === undefined)359 {360 name = name.replace(stripSpacesMatchString, "$1");361 }362 363 var bind = this._bindings[name]; // lookup an existing binding for the same expression364 if (bind === undefined) // if not created yet, use expressionParser to create a new binding.365 {366 if (name === 'this') 367 {368 bind = new gc.databind.VariableBindValue();369 }370 else 371 {372 // pass hint to expressionParser so skip operators already tested for in sub-expressions.373 bind = this._expressionParser.parse(name, hint) || null;374 }375 376 if (bind !== null)377 {378 bind.setName(name);379 }380 this._bindings[name] = bind;381 }382 return bind;383 };384 ModelBindProvider.prototype.getModel = function(name)385 {386 if (name)387 {388 return gc.databind.registry.getModel(name);389 }390 return this._model;391 };392 ModelBindProvider.prototype.dispose = function()393 {394 for ( var name in this._bindings)395 {396 if (this._bindings.hasOwnProperty(name))397 {398 var bind = this._bindings[name];399 if (bind.dispose !== undefined)400 {401 bind.dispose();402 }403 }404 }405 this._bindings = {};406 };407 /**408 * Helper method to parse a binding expression using this model as the default for all binding URI's.409 * The resulting bind expression will not be store in the global registry, but rather in a private one.410 * Therefore, you must use this API to retrieve existing model specific bind expressions.411 *412 * @param {string} expression - the binding expression to parse.413 *414 * @return {gc.databind.IBind} - the existing or newly created bindable object, or null if this name is not supported by this model.415 */416 gc.databind.AbstractBindFactory.prototype.parseModelSpecificBindExpression = function(expression)417 {418 this._bindProvider = this._bindProvider || new ModelBindProvider(this);419 var result = this._bindProvider.getBinding("" + expression);420 return result;421 };422 /**423 * Helper method clear all private model specific bind expressions that have been created. Use this to clear bindings424 * created with the parseModelSpecificBindExpression() helper method.425 */426 gc.databind.AbstractBindFactory.prototype.clearAllModelSpecificBindExpressions = function()427 {428 if (this._bindProvider)429 {430 this._bindProvider = undefined;431 }432 };433 /**434 * Method called when a transport is disconnected from the target. The default implementation is to iterate through435 * all the bindings and call onDisconnected() on each binding if it supports such a method. The purpose is for those436 * bindings to clear any critical errors that might have incurred.437 */438 gc.databind.AbstractBindFactory.prototype.onDisconnected = function()439 {440 this.setConnectedState(false);441 var bindings = this.getAllBindings();442 for(var bindName in bindings)443 {444 if (bindings.hasOwnProperty(bindName))445 {446 var bind = bindings[bindName];447 if (bind.onDisconnected)448 {449 bind.onDisconnected();450 }451 }452 }453 };454 455 /**456 * <p>Helper method that can be used to do custom conversion of values based on getter and setter bind expressions. It is not457 * necessary to provide both a getter and setter for this conversion to work. The getter and setter expressions are model 458 * specific bind expressions that can use other model bindings and a 'this' variable. The 'this' variable is expected 459 * to be used in these expressions because it represents the value to be converted. If a 'this' variable is not used, then460 * the result of the conversion will be independent of the input value.</p> 461 * 462 * <p>If a getter expression is specified, the 'this' variable is assigned the value passed in, and the return value is 463 * calculated by calling getValue() on this getter expression.</p>464 * <p>If a setter expression is specified, the setValue() of setter bind expression is called with the value passed in, and 465 * the value of the 'this' variable is returned as the result. In this situation, the setter expression must be a bi-directional466 * expression since it will be evaluated inversely. A bi-directional expression is an expression that contains only one 467 * variable bind and uses simple scale and shift operations; for example, 'this*9/5+32'. This example could be used to 468 * convert Celcius values to Fahrenheit if passed in as the getter expression. When passed in as the setter expression it 469 * performs the inverse operation and converts Fahrenheit to Celcius.</p>470 * 471 * @param {Number} value - the value that is to be converted472 * @param {string} [getter] - the getter expression to do the conversion. If specified, the setter expression is not used.473 * @param {String} [setter] - the setter expression to do the inverse conversion if no getter is specified..474 * @return the converted value based on the getter expression, or if not provided, then the setter expression.475 */476 gc.databind.AbstractBindFactory.prototype.getConvertedValue = function(value, getterExpression, setterExpression) 477 {478 var expr;479 if (getterExpression) 480 {481 expr = this.parseModelSpecificBindExpression(getterExpression);482 this._bindProvider.getBinding('this').setValue(value);483 return expr && expr.getValue();484 } 485 else if (setterExpression)486 {487 expr = this.parseModelSpecificBindExpression(setterExpression);488 if (expr)489 {490 var thisBind = this._bindProvider.getBinding('this');491 thisBind.setValue(undefined);492 expr.setValue(value);493 return thisBind.getValue();494 }495 return undefined;496 } else {497 return value;498 }499 };500 ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptd = require('wptd');2wptd._bindProvider('test', function (done) {3 done(null, 'test');4});5var wptd = require('wptd');6wptd.get('test', function (err, data) {7 done();8});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptoolkit = require('wptoolkit');2var wp = new wptoolkit();3wp._bindProvider('test', 'test', function (provider) {4 provider.test = function (a, b, callback) {5 callback(null, a + b);6 };7});8var wptoolkit = require('wptoolkit');9var wp = new wptoolkit();10wp.test.test(1, 2, function (err, result) {11 console.log(result);12});13#### new WPTOOLKIT([options])14#### WPTOOLKIT#_bindProvider(providerNamespace, providerName, provider)15#### WPTOOLKIT#_bindProvider(providerNamespace, providerName, providerPath)16#### new WP(options)

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2var wptObj = new wpt();3var providerObj = new wptObj.provider();4wptObj._bindProvider(providerObj);5wptObj.request('test', function(response) {6 console.log(response);7});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org', 'A.2b4d4d3e4e4f4c4e4d4e4e4f4c4e4d4');3wpt.runTest('www.google.com', function(err, data) {4 if(err) return console.error(err);5 console.log(data);6});7var wpt = require('wpt');8var wpt = new WebPageTest('www.webpagetest.org', 'A.2b4d4d3e4e4f4c4e4d4e4e4f4c4e4d4');9wpt.runTest('www.google.com', function(err, data) {10 if(err) return console.error(err);11 console.log(data);12});13var wpt = require('wpt');14var wpt = new WebPageTest('www.webpagetest.org', 'A.2b4d4d3e4e4f4c4e4d4e4e4f4c4e4d4');15wpt.runTest('www.google.com', function(err, data) {16 if(err) return console.error(err);17 console.log(data);18});19var wpt = require('wpt');20var wpt = new WebPageTest('www.webpagetest.org', 'A.2b4d4d3e4e4f4c4e4d4e4e4f4c4e4d4');21wpt.runTest('www.google.com', function(err, data) {22 if(err) return console.error(err);23 console.log(data);24});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful