Best JavaScript code snippet using apimocker
services.js
Source:services.js  
1'use strict';2/* Services */3var ecommerceServices = angular.module('myApp.services', ['ngResource']);4ecommerceServices.value('version', '0.1');5ecommerceServices.factory('InitializerSvc', ['$rootScope', 'RootUrlSvc', 'CompanySvc', 'SalesItemSvc', 'CustomerSvc', 'ShoppingCartSvc', 'CartItemSvc', 'SystemPropertySvc', 'IntuitSvc', 'TaxCloudSvc',6    function ($rootScope, RootUrlSvc, CompanySvc, SalesItemSvc, CustomerSvc, ShoppingCartSvc, CartItemSvc, SystemPropertySvc, IntuitSvc, TaxCloudSvc) {7        var initialized = false;8        var initialize = function () {9            $rootScope.$on('api.loaded', function() {10                SystemPropertySvc.initializeModel();11                TaxCloudSvc.initialize();12                CompanySvc.initialize();13                SalesItemSvc.initialize();14                CustomerSvc.initialize();15                ShoppingCartSvc.initialize();16                CartItemSvc.initialize();17                CompanySvc.initializeModel();18                IntuitSvc.initialize();19            });20            $rootScope.$on('model.company.change', function() {21                SalesItemSvc.initializeModel();22                CustomerSvc.initializeModel();23            });24            $rootScope.$on('model.customer.change', function () {25                ShoppingCartSvc.initializeModel();26            });27            $rootScope.$on('model.shoppingcart.change', function () {28            });29            $rootScope.$on('model.shoppingcartitem.change', function () {30                ShoppingCartSvc.calculate();31            });32            RootUrlSvc.initialize();33            $rootScope.$on('$viewContentLoaded', function (scope, next, current) {34                /*35                 Every time we load a new view, we need to reinitialize the intuit anywhere library36                 so that the connect to quickbooks button is rendered properly37                 */38                if (initialized) { //only reinitialize from the 2nd time onwards39                    intuit.ipp.anywhere.init();40                }41                initialized = true;42            });43        };44        return {45            initialize: initialize46        }47    }]);48//A service which contains the current model (e.g. companies, items, etc)49ecommerceServices.factory('ModelSvc', ['$rootScope',50    function ($rootScope) {51        var model = {};52        model.company = {};53        var broadcastCompanyChange = function () {54            $rootScope.$broadcast('model.company.change');55        };56        var onCompanyChange = function ($scope, callback) {57            $scope.$on('model.company.change', function () {58                callback(model);59            });60        };61        return {62            model: model,63            onCompanyChange: onCompanyChange,64            broadcastCompanyChange: broadcastCompanyChange65        }66    }]);67//a service which reads the root of the API and stores all the resource urls68ecommerceServices.factory('RootUrlSvc', ['$resource', '$rootScope', '$location',69    function ($resource, $rootScope, $location) {70        var rootUrls = {};71        var apiRoot = function() {72            return $location.protocol() +"://" + $location.host() + ":9001";73        };74        var initialize = function () {75            $resource(apiRoot()).get(function (data) {76                var links = data._links;77                for (var link in  links) {78                    var href = links[link].href;79//                    console.log("Discovered the URL for " + link + ": " + href);80                    rootUrls[link] = href.split(/\{/)[0]; //chop off the template stuff81                }82                rootUrls['syncRequest'] = apiRoot() + "/syncrequest";  // non-discoverable83                rootUrls['orders'] = apiRoot() + "/orders";  // non-discoverable84                $rootScope.$broadcast('api.loaded');  //broadcast an event so that the CompanySvc can know to load the companies85            });86        };87        var oauthGrantUrl = function() {88            return apiRoot() + "/request_token";89        }90        var onApiLoaded = function ($scope, callback) {91            $scope.$on('api.loaded', function () {92                callback();93            });out94        };95        return {96            initialize: initialize,97            rootUrls: rootUrls,98            onApiLoaded: onApiLoaded,99            oauthGrantUrl : oauthGrantUrl100        }101    }]);102//A service which deals with CRUD operations for companies103ecommerceServices.factory('CompanySvc', ['$resource', '$rootScope', 'RootUrlSvc', 'ModelSvc',104    function ($resource, $rootScope, RootUrlSvc, ModelSvc) {105        var Company;106        var initialize = function () {107            Company = $resource(RootUrlSvc.rootUrls.companies + ':companyId', {}, { query: {method: 'GET', isArray: false} });108        };109        var initializeModel = function() {110            Company.query(function (data) {111                var companies = data._embedded.companies;112                ModelSvc.model.companies = companies;113                ModelSvc.model.company = companies[0]; //select the first company for now114                ModelSvc.broadcastCompanyChange();115                var grantUrl = RootUrlSvc.oauthGrantUrl() + '?appCompanyId=' + ModelSvc.model.company.id;116                intuit.ipp.anywhere.setup({117                    grantUrl: grantUrl,118                    datasources: {119                        quickbooks: true,120                        payments: true121                    }122                });123            });124        };125        return {126            initialize: initialize,127            initializeModel: initializeModel128        }129    }]);130ecommerceServices.factory('SalesItemSvc', ['$resource', '$rootScope', 'RootUrlSvc', 'ModelSvc',131    function ($resource, $rootScope, RootUrlSvc, ModelSvc) {132        var SalesItem;133        var initialize = function() {134            SalesItem = $resource(RootUrlSvc.rootUrls.salesItems, {}, { query: {method: 'GET', isArray: false} });135        };136        var initializeModel = function() {137            SalesItem.query(function (data) {138                var salesItems = data._embedded.salesItems;139                ModelSvc.model.company.salesItems = salesItems;140            });141        }142        return {143            initialize: initialize,144            initializeModel: initializeModel145        }146    }]);147ecommerceServices.factory('CustomerSvc', ['$http', '$resource', '$rootScope', 'RootUrlSvc', 'ModelSvc', 'ShoppingCartSvc',148    function ($http, $resource, $rootScope, RootUrlSvc, ModelSvc, ShoppingCartSvc) {149        var broadcastCustomerChange = function () {150            $rootScope.$broadcast('model.customer.change');151            ModelSvc.taxCloud.addressDestination.name = "TaxCloud/Intuit eCommerce Sample App";152            ModelSvc.taxCloud.addressDestination.address1 = "3205 South Judkins Street";153            ModelSvc.taxCloud.addressDestination.city = "Seattle";154            ModelSvc.taxCloud.addressDestination.state = "WA";155            ModelSvc.taxCloud.addressDestination.zip5 = "98144";156            ModelSvc.taxCloud.VerifyDestinationAddress(function (flag) {157                if (flag)158                    console.debug('TaxCloud destination address verified');159                else160                    console.debug('TaxCloud destination address NOT verified');161            });162        };163        //var onCustomerChange = function ($scope, callback) {164        //    $scope.$on('model.customer.change', function () {165        //        //callback(model);166        //    });167        //};168        var promise = $http.get('/customers').success(function (data) {169            var customers = data._embedded.customers;170            ModelSvc.model.company.customers = customers;171            ModelSvc.model.customer = customers[0];  // auto-set the 'logged in' customer172            ModelSvc.taxCloud.customerID = ModelSvc.model.customer.id;173            broadcastCustomerChange();174        });175        var Customer;176        var initialize = function() {177            Customer = $resource(RootUrlSvc.rootUrls.customers, {}, { query: {method: 'GET', isArray: false} });178        };179        var initializeModel = function() {180            //Customer.query(function(data) {181                //var customers = data._embedded.customers;182                //ModelSvc.model.company.customers = customers;183                //ModelSvc.model.customer = customers[0];  // auto-set the 'logged in' customer184                //ShoppingCartSvc.initializeModel();185            //});186        }187        return {188            promise: promise,189            initialize: initialize,190            initializeModel: initializeModel,191            broadcastCustomerChange: broadcastCustomerChange192        }193    }]);194ecommerceServices.factory('ShoppingCartSvc', ['$resource', '$rootScope', 'RootUrlSvc', 'ModelSvc', 'CartItemSvc',195    function ($resource, $rootScope, RootUrlSvc, ModelSvc, CartItemSvc) {196        var broadcastShoppingCartChange = function () {197            $rootScope.$broadcast('model.shoppingcart.change');198        };199        var calculate = function () {200            ModelSvc.model.shoppingCart.total -= ModelSvc.model.shoppingCart.taxAmount;201            ModelSvc.model.shoppingCart.taxAmount = 0.0;202            angular.forEach(ModelSvc.model.shoppingCartItems, function (cartItem) {203                ModelSvc.model.shoppingCart.taxAmount += cartItem.taxAmount;204                ModelSvc.model.shoppingCart.total += cartItem.taxAmount;205            });206            $rootScope.$apply();207        };208        var ShoppingCart;209        var initialize = function() {210            ShoppingCart = $resource(RootUrlSvc.rootUrls.shoppingCarts, {},211                {212                    forCustomer: {  method: 'GET',213                        url: RootUrlSvc.rootUrls.shoppingCarts + '/search/findByCustomerId',214                        params: {projection: 'order'},215                        isArray: false},216                    query: { method: 'GET', isArray: false}217                });218        };219        var initializeModel = function() {220            refreshShoppingCart();221        };222        var refreshShoppingCart = function() {223            var customerShoppingCart = ShoppingCart.forCustomer({customerId: ModelSvc.model.customer.id}, function() {224                ModelSvc.model.shoppingCart = customerShoppingCart._embedded.shoppingCarts[0];225                ModelSvc.taxCloud.CreateCart(ModelSvc.model.shoppingCart.instanceId);226                console.debug('TaxCloud cart created with id: ' + ModelSvc.taxCloud.cart.id);227                CartItemSvc.getCartItems();228            });229        };230        return {231            initialize: initialize,232            initializeModel: initializeModel,233            refreshShoppingCart: refreshShoppingCart,234            calculate: calculate,235            broadcastShoppingCartChange: broadcastShoppingCartChange236        }237    }]);238ecommerceServices.factory('CartItemSvc', ['$http', '$resource', '$rootScope', 'RootUrlSvc', 'ModelSvc',239    function ($http, $resource, $rootScope, RootUrlSvc, ModelSvc) {240        var broadcastShoppingCartItemChange = function () {241            $rootScope.$broadcast('model.shoppingcartitem.change');242        };243        var calculate = function () {244            $rootScope.$apply();245        };246        var CartItem;247        var initialize = function() {248            CartItem = $resource(RootUrlSvc.rootUrls.cartItems, {},249                        {   query: { method: 'GET', isArray: false },250                            forShoppingCart: {251                                method: 'GET',252                                url: RootUrlSvc.rootUrls.cartItems + '/search/findByShoppingCartId',253                                params: {projection: 'summary'},254                                isArray: false}255                        });256            ModelSvc.model.shoppingCartItems = [];257        };258        var angularCartItemsToTaxCloudCartItems = function (aCart, tCart) {259            ModelSvc.taxCloud.cart.ClearItems();260            angular.forEach(aCart.cartItems, function (item) {261                ModelSvc.taxCloud.cart.AddItem(new TaxCloudCartItem(item.salesItem.id, item.salesItem.name, item.salesItem.unitPrice, ModelSvc.model.shoppingCart.promotionDiscount, item.quantity, item.salesItem.tic));262                console.debug('\tTaxCloud load cart item: ' + item.salesItem.name);263            });264        };265        var taxCloudCartItemsToAngularCartItems = function (tCart, aCart) {266            for (var ii = 0; ii < tCart.items.length; ++ii) {267                var tItem = tCart.items[ii];268                var aItem = aCart.cartItems[ii];269                aItem.taxRate = tItem.TaxRate();270                aItem.taxAmount = tItem.taxAmount;271                broadcastShoppingCartItemChange();272            }273        };274        var getCartItems = function() {275            if (ModelSvc.model.shoppingCart != 'undefined') {276                var shoppingCartItems = CartItem.forShoppingCart({ shoppingCartId: ModelSvc.model.shoppingCart.id }, function (data) {277                    ModelSvc.model.shoppingCartItems =278                        shoppingCartItems._embedded ?279                            ModelSvc.model.shoppingCartItems = shoppingCartItems._embedded.cartItems : {};280                });281                shoppingCartItems.$promise.then(function (data) {282                    if (data._embedded) {283                        angularCartItemsToTaxCloudCartItems(data._embedded, ModelSvc.taxCloud.cart);284                        console.debug('TaxCloud cart loaded with persistent items');285                    }286                    else287                        console.debug('TaxCloud cart is empty');288                });289            }290        };291        var addCartItem = function(salesItem, shoppingCart) {292            var cartItem = new CartItem();293            cartItem.shoppingCart = shoppingCart._links.self.href.split(/\{/)[0];294            cartItem.salesItem = salesItem._links.self.href.split(/\{/)[0];295            cartItem.quantity = 1;296            //cartItem.taxRate = "9.50%";297            //cartItem.taxAmount = "6.50";298            //cartItem.$save();299            ModelSvc.taxCloud.cart.AddItem(new TaxCloudCartItem(salesItem.id, salesItem.name, salesItem.unitPrice, shoppingCart.promotionDiscount, cartItem.quantity, salesItem.tic));300            ModelSvc.taxCloud.Lookup(function (success) {301                if (success) {302                    cartItem.taxRate = (ModelSvc.taxCloud.cart.items[0].TaxRate() * 100.0).toFixed(2) + '%';303                    cartItem.taxAmount = ModelSvc.taxCloud.cart.items[0].taxAmount.toFixed(2);304                    cartItem.$save();305                    console.debug('TaxCloud item added to cart');306                }307            });308        };309        return {310            initialize: initialize,311            getCartItems: getCartItems,312            addCartItem: addCartItem,313            calculate: calculate,314            broadcastShoppingCartItemChange: broadcastShoppingCartItemChange315        }316    }]);317ecommerceServices.factory('OrderSvc', ['$http', '$rootScope', 'RootUrlSvc', 'ModelSvc',318    function ($http, $rootScope, RootUrlSvc, ModelSvc) {319        var sendOrder = function (creditCard, billingInfo, successCallback, errorCallback) {320            // step 1 - tokenize credit card info321            var request = {};322            request.card = {};323            var card = request.card;324            card.number = creditCard.number;325            card.expMonth = creditCard.expMonth;326            card.expYear = creditCard.expYear;327            card.cvc = creditCard.CVC;328            card.address = {};329            card.address.streetAddress = billingInfo.address;330            card.address.city = billingInfo.cityStateZip.split(",")[0];331            card.address.region = billingInfo.cityStateZip.split(",")[1].trim().split(" ")[0];332            card.address.country = "US";333            card.address.postalCode = billingInfo.cityStateZip.split(",")[1].trim().split(" ")[1];;334            tokenize(request, successCallback, errorCallback);335        };336        var tokenize = function(card, successCallback, errorCallback) {337            intuit.ipp.payments.tokenize(ModelSvc.model.systemProperties.appToken, card, function(token, response) {338                if (token) {339                    // step 2 - place order to backend340                    console.log('placing order to: ' + RootUrlSvc.rootUrls.orders + ' with args: ' + token + ", " + ModelSvc.model.shoppingCart.id);341                    $http.post(342                        RootUrlSvc.rootUrls.orders,343                        { shoppingCartId: ModelSvc.model.shoppingCart.id, paymentToken: token })344                        .success(successCallback)345                        .error(errorCallback);346                }347                else {348                    console.log("Error during tokenization " + response.code +"<br/>" + response.message + "<br/>" + response.detail + "<br/>" + response.moreinfo);349                    errorCallback(response);350                }351            });352         };353        var initialize = function () {354        };355        return {356            initialize: initialize,357            sendOrder: sendOrder358        }359    }]);360ecommerceServices.factory('SyncRequestSvc', ['$http', '$rootScope', 'RootUrlSvc', 'ModelSvc',361    function ($http, $rootScope, RootUrlSvc, ModelSvc) {362        var sendSyncRequest = function (entityType, successCallback, errorCallback) {363            $http.post(RootUrlSvc.rootUrls.syncRequest, {type: entityType, companyId: ModelSvc.model.company.id})364                    .success(successCallback);365        };366        var initialize = function () {367        };368        return {369            initialize: initialize,370            sendCustomerSyncRequest: function (callback) { sendSyncRequest('Customer', callback); },371            sendSalesItemSyncRequest: function (callback) { sendSyncRequest('SalesItem', callback) }372        }373    }]);374ecommerceServices.factory('DeepLinkSvc', ['ModelSvc',375    function (ModelSvc) {376        var getQboDeepLinkURLRoot = function () {377            return "https://" + ModelSvc.model.systemProperties.qboUiHostname + "/login?";378        };379        var getMultipleEntitiesUrl = function (entityType) {380            return getQboDeepLinkURLRoot() + "deeplinkcompanyid=" + ModelSvc.model.company.qboId + "&pagereq=" + entityType;381        };382        var getSingleEntityUrl = function (entityType, entityId) {383            return getQboDeepLinkURLRoot() + "pagereq=" + entityType + "?txnId=" + entityId + "&deeplinkcompanyid=" + ModelSvc.model.company.qboId;384        };385        var getCustomersLink = function () {386            return getMultipleEntitiesUrl("customers");387        };388        var getSalesReceiptLink = function (entityId) {389            return getSingleEntityUrl("salesreceipt", entityId);390        };391        var getItemsLink = function () {392            return getMultipleEntitiesUrl("items");393        };394        return {395            getCustomersLink: getCustomersLink,396            getItemsLink: getItemsLink,397            getSalesReceiptLink: getSalesReceiptLink398        }399    }400]);401ecommerceServices.factory('SystemPropertySvc', [ '$resource', 'RootUrlSvc', 'ModelSvc',402    function ($resource, RootUrlSvc, ModelSvc) {403        var SystemProperty;404        var initializeModel = function () {405            SystemProperty = $resource(RootUrlSvc.rootUrls.systemProperties, {},406                {407                    query: {408                        isArray: false409                    }410                });411            SystemProperty.query(function (data) {412                ModelSvc.model.systemProperties = {};413                if (data._embedded) {414                    angular.forEach(data._embedded.systemProperties, function (systemProperty) {415                        ModelSvc.model.systemProperties[systemProperty.key] = systemProperty.value;416                    });417                }418            });419        }420        return {421            initializeModel: initializeModel422        }423}]);424ecommerceServices.factory('TrackingSvc', [function () {425    return {426        trackPage: function (pageName, event, properties) {427            var props = properties || {};428            props['site_section'] = 'sampleapps';429            pageName = 'sampleapps/ecommerce/' + pageName;430            wa.trackPage(pageName, event, properties);431        },432        trackEvent: function (event, properties) {433            var props = properties || {};434            props['site_section'] = 'sampleapps';435            wa.trackEvent(event, properties);436        }437    };438}]);439//A service which works with Inuit440ecommerceServices.factory('IntuitSvc', ['$resource', '$rootScope', 'RootUrlSvc', 'ModelSvc',441    function ($resource, $rootScope, RootUrlSvc, ModelSvc) {442        var Connection;443        var initialize = function () {444        };445        return {446            initialize: initialize,447        }448    }]);449//A service which works with TaxCLoud450ecommerceServices.factory('TaxCloudSvc', ['$resource', '$rootScope', 'RootUrlSvc', 'ModelSvc',451    function ($resource, $rootScope, RootUrlSvc, ModelSvc) {452        var taxCloud = null;453        var initialize = function () {454            taxCloud = new TaxCloud('C1988C0', 'D35B1C5F-D6D8-43C0-B804-10EDFCA52796');455            taxCloud.Ping(function (flag) {456                if (flag)457                    console.debug('TaxCloud ping successful');458                else459                    console.debug('TaxCloud ping NOT successful');460            });461            taxCloud.addressOrigin.name = "TaxCloud/Intuit eCommerce Sample App";462            taxCloud.addressOrigin.address1 = "3205 South Judkins Street";463            taxCloud.addressOrigin.city = "Seattle";464            taxCloud.addressOrigin.state = "WA";465            taxCloud.addressOrigin.zip5 = "98144";466            taxCloud.VerifyOriginAddress(function (flag) {467                if (flag)468                    console.debug('TaxCloud origin address verified');469                else470                    console.debug('TaxCloud origin address NOT verified');471            });472            ModelSvc.taxCloud = taxCloud;473        };474        return {475            initialize: initialize,476        }...centreon.js
Source:centreon.js  
1/**2 * centreon.js3 *4 * Copyright (c)2015 Jorge Morgado. All rights reserved (MIT license).5 */6// Helper constants7const POLLER_STATE      = 0;8const POLLER_LATENCY    = 1;9const POLLER_ACTIVE     = 2;10const POLLER_ERRSTATE   = 3;11const POLLER_ERRLATENCY = 4;12const POLLER_ERRACTIVE  = 5;13const HOST_TOTAL = 0;14const HOST_UP    = 1;15const HOST_PEND  = 2;16const HOST_UNRC  = 3;17const HOST_DOWN  = 4;18const SVC_TOTAL = 0;19const SVC_OK    = 1;20const SVC_PEND  = 2;21const SVC_UNKN  = 3;22const SVC_WARN  = 4;23const SVC_CRIT  = 5;24const SVC_UNKNU = 6;25const SVC_WARNU = 7;26const SVC_CRITU = 8;27function Centreon() {28  this.message = '';29  this.status  = OK;30  this.count   = 0;31  this.svcList = [];32  this.pollers  = {33    POLLER_STATE:      0,34    POLLER_LATENCY:    0,35    POLLER_ACTIVE:     0,36    POLLER_ERRSTATE:   '',37    POLLER_ERRLATENCY: '',38    POLLER_ERRACTIVE:  '',39  };40  this.hosts    = {41    HOST_TOTAL: 0,42    HOST_UP:    0,43    HOST_PEND:  0,44    HOST_UNRC:  0,45    HOST_DOWN:  0,46  };47  this.services = {48    SVC_TOTAL: 0,49    SVC_OK:    0,50    SVC_PEND:  0,51    SVC_UNKN:  0,52    SVC_WARN:  0,53    SVC_CRIT:  0,54    SVC_UNKNU: 0,55    SVC_WARNU: 0,56    SVC_CRITU: 0,57  };58  this.setTimestamp = function(ts) {59    this.ts = ts;60  }61  this.pollerState = function(state, latency, active, errstate, errlatency, erractive) {62    this.pollers[POLLER_STATE]   = parseInt(state);63    this.pollers[POLLER_LATENCY] = parseInt(latency);64    this.pollers[POLLER_ACTIVE]  = parseInt(active);65    this.pollers[POLLER_ERRSTATE]   = errstate;66    this.pollers[POLLER_ERRLATENCY] = errlatency;67    this.pollers[POLLER_ERRACTIVE]  = erractive;68  }69  this.hostState = function(total, up, pend, unrc, down) {70    this.hosts[HOST_TOTAL] = parseInt(total);71    this.hosts[HOST_UP]    = parseInt(up);72    this.hosts[HOST_PEND]  = parseInt(pend);73    this.hosts[HOST_UNRC]  = parseInt(unrc);74    this.hosts[HOST_DOWN]  = parseInt(down);75  }76  this.serviceState = function(total, ok, pend, unkn, warn, crit, unknu, warnu, critu) {77    this.services[SVC_TOTAL] = parseInt(total);78    this.services[SVC_OK]    = parseInt(ok);79    this.services[SVC_PEND]  = parseInt(pend);80    this.services[SVC_UNKN]  = parseInt(unkn);81    this.services[SVC_WARN]  = parseInt(warn);82    this.services[SVC_CRIT]  = parseInt(crit);83    this.services[SVC_UNKNU] = parseInt(unknu);84    this.services[SVC_WARNU] = parseInt(warnu);85    this.services[SVC_CRITU] = parseInt(critu);86  }87  this.setStatus = function(addHandled) {88    // If should include handled services (acknowledged and in-downtime)89    if (addHandled) {90      // Then, the real value is the whole total91      svc_unkn = SVC_UNKN;92      svc_warn = SVC_WARN;93      svc_crit = SVC_CRIT;94    } else {95      // Otherwise, the real value the unhandled96      svc_unkn = SVC_UNKNU;97      svc_warn = SVC_WARNU;98      svc_crit = SVC_CRITU;99    }100    // Critical status: host(s) down, service(s) critical or pollers critical101    if (this.hosts[HOST_DOWN] > 0 || this.services[svc_crit] > 0) {102      this.message = i18n('check_hosts_services');103      this.status  = CRIT;104      // Only show the hosts count if HOST_DOWN > 0 - the assumption is that105      // if a host is down, likely some or all of its services will be down106      // too, thus it doesn't make sense to include this value as well.107      this.count   = this.hosts[HOST_DOWN] || this.services[svc_crit];108    } else if (this.pollers[POLLER_STATE] == 2 || this.pollers[POLLER_LATENCY] == 2 || this.pollers[POLLER_ACTIVE] == 2) {109      this.message = i18n('check_pollers');110      this.status  = CRIT;111      this.count   = 'P';112    // Warning status: service(s) warning or pollers warning113    } else if (this.services[svc_warn]  > 0) {114      this.message = i18n('check_services');115      this.status  = WARN;116      this.count   = this.services[svc_warn] ;117    } else if (this.pollers[POLLER_STATE] == 1 || this.pollers[POLLER_LATENCY] == 1 || this.pollers[POLLER_ACTIVE] == 1) {118      this.message = i18n('check_pollers');119      this.status  = WARN;120      this.count   = 'P';121    // Unreachable status: host(s) unreachable122    } else if (this.hosts[HOST_UNRC] > 0) {123      this.message = i18n('check_hosts');124      this.status  = UNRC;125      this.count   = this.hosts[HOST_UNRC];126    // Unknown status: host(s) pending or service(s) unknown127    } else if (this.hosts[HOST_PEND] > 0 || this.services[svc_unkn] > 0) {128      this.message = i18n('check_hosts_services');129      this.status  = UNKN;130      // Also, only show the hosts count if HOST_PEND > 0 - again, we assume131      // that if a host is pending, likely its services will also be pending.132      this.count   = this.hosts[HOST_PEND] || this.services[svc_unkn];133    // Anything else is OK134    } else {135      this.message = i18n('all_ok');136      this.status  = OK;137      this.count   = this.services[SVC_OK];138    }139  }140  this.emptyServices = function() {141    this.svcList.length = 0;142  }143  this.addService = function(row) {144    this.svcList.push(row);145  }146  this.toJSON = function() {147    return {148      ts:      this.ts || (new Date().getTime() / 1000),149      message: this.message,150      status:  this.status,151      count:   this.count,152      pollerState:      this.pollers[POLLER_STATE],153      pollerLatency:    this.pollers[POLLER_LATENCY],154      pollerActive:     this.pollers[POLLER_ACTIVE],155      pollerErrState:   this.pollers[POLLER_ERRSTATE],156      pollerErrLatency: this.pollers[POLLER_ERRLATENCY],157      pollerErrActive:  this.pollers[POLLER_ERRACTIVE],158      hostTotal: this.hosts[HOST_TOTAL],159      hostUp:    this.hosts[HOST_UP],160      hostPend:  this.hosts[HOST_PEND],161      hostUnrc:  this.hosts[HOST_UNRC],162      hostDown:  this.hosts[HOST_DOWN],163      svcTotal: this.services[SVC_TOTAL],164      svcOk:    this.services[SVC_OK],165      svcPend:  this.services[SVC_PEND],166      svcUnkn:  this.services[SVC_UNKN],167      svcWarn:  this.services[SVC_WARN],168      svcCrit:  this.services[SVC_CRIT],169      svcUnknu: this.services[SVC_UNKNU],170      svcWarnu: this.services[SVC_WARNU],171      svcCritu: this.services[SVC_CRITU],172      svcList: this.svcList,173    };174  }...JSIL.Host.js
Source:JSIL.Host.js  
1/* It is auto-generated file. Do not modify it. */2"use strict";3if (typeof (JSIL) === "undefined")4  throw new Error("JSIL.Core required");5JSIL.Host.isBrowser = (typeof (window) !== "undefined") && (typeof (navigator) !== "undefined");6JSIL.Host.initCallbacks = [];7JSIL.Host.runInitCallbacks = function () {8  for (var i = 0; i < JSIL.Host.initCallbacks.length; i++) {9    var cb = JSIL.Host.initCallbacks[i];10    cb();11  }12  JSIL.Host.initCallbacks = null;13};14JSIL.Host.services = JSIL.CreateDictionaryObject(null);15JSIL.Host.getService = function (key, noThrow) {16  var svc = JSIL.Host.services[key];17  if (!svc) {18    if (noThrow)19      return null;20    else21      JSIL.RuntimeError("Service '" + key + "' not available");22  }23  return svc;24};25JSIL.Host.registerService = function (name, service) {26  JSIL.Host.services[name] = service;27};28JSIL.Host.registerServices = function (services) {29  for (var key in services) {30    if (!services.hasOwnProperty(key))31      continue;32    JSIL.Host.registerService(key, services[key]);33  }34};35// Access services using these methods instead of getService directly.36// Returns UTC time37JSIL.Host.getTime = function () {38  var svc = JSIL.Host.getService("time");39  return svc.getUTC();40};41JSIL.Host.getTimezoneOffsetInMilliseconds = function () {42  var svc = JSIL.Host.getService("time");43  return svc.getTimezoneOffsetInMilliseconds();44};45// Returns elapsed ticks since some starting point (usually page load), high precision.46JSIL.Host.getTickCount = function () {47  var svc = JSIL.Host.getService("time");48  return svc.getTickCount();49};50// Entry point used by storage APIs to get UTC time.51JSIL.Host.getFileTime = function () {52  // FIXME53  return Date.now();54};55JSIL.Host.getCanvas = function (desiredWidth, desiredHeight) {56  var svc = JSIL.Host.getService("canvas");57  if (58    (typeof (desiredWidth) !== "undefined") &&59    (typeof (desiredHeight) !== "undefined")60  )61    return svc.get(desiredWidth, desiredHeight);62  else63    return svc.get();64};65JSIL.Host.createCanvas = function (desiredWidth, desiredHeight) {66  var svc = JSIL.Host.getService("canvas");67  return svc.create(desiredWidth, desiredHeight);68};69JSIL.Host.getHeldKeys = function () {70  var svc = JSIL.Host.getService("keyboard", true);71  if (!svc)72    return [];73  return svc.getHeldKeys();74};75JSIL.Host.getMousePosition = function () {76  var svc = JSIL.Host.getService("mouse", true);77  if (!svc)78    return [0, 0];79  return svc.getPosition();80};81JSIL.Host.getHeldMouseButtons = function () {82  var svc = JSIL.Host.getService("mouse", true);83  if (!svc)84    return [];85  return svc.getHeldButtons();86};87JSIL.Host.isPageVisible = function () {88  var svc = JSIL.Host.getService("pageVisibility", true);89  if (!svc)90    return true;91  return svc.get();92};93JSIL.Host.runLater = function (action) {94  var svc = JSIL.Host.getService("runLater", true);95  if (!svc)96    return false;97  svc.enqueue(action);98  return true;99};100JSIL.Host.runLaterFlush = function () {101  var svc = JSIL.Host.getService("runLater", true);102  if (!svc)103    return false;104  if (svc.flush) {105    svc.flush();106    return true;107  }108  return false;109};110JSIL.Host.logWrite = function (text) {111  var svc = JSIL.Host.getService("stdout");112  svc.write(text);113};114JSIL.Host.logWriteLine = function (text) {115  var svc = JSIL.Host.getService("stdout");116  svc.write(text + "\n");117};118JSIL.Host.warning = function (text) {119  var svc = JSIL.Host.getService("stderr");120  var stack = Error().stack;121  if (stack)122    svc.write(text + "\n" + stack.slice(stack.indexOf("\n", 6)+1, -1));123  else124    svc.write(text + "\n");125}126JSIL.Host.abort = function (exception, extraInfo) {127  var svc = JSIL.Host.getService("stderr");128  if (extraInfo)129    svc.write(extraInfo);130  try {131    svc.write(exception);132  } catch (exc) {133  }134  try {135    if (exception.stack)136      svc.write(exception.stack);137  } catch (exc) {138  }139  var svc = JSIL.Host.getService("error");140  svc.error(exception);141};142JSIL.Host.assertionFailed = function (message) {143  var svc = JSIL.Host.getService("error");144  svc.error(new Error(message || "Assertion Failed"));145};146JSIL.Host.scheduleTick = function (tickCallback) {147  var svc = JSIL.Host.getService("tickScheduler");148  svc.schedule(tickCallback);149};150JSIL.Host.reportPerformance = function (drawDuration, updateDuration, cacheSize, isWebGL) {151  var svc = JSIL.Host.getService("performanceReporter", true);152  if (!svc)153    return;154  svc.report(drawDuration, updateDuration, cacheSize, isWebGL);155};156// Default service implementations that are environment-agnostic157// Don't use for anything that needs to be reproducible in replays!158(function () {159  if (160    (typeof (window) !== "undefined") &&161    (typeof (window.performance) !== "undefined") &&162    (typeof (window.performance.now) === "function")163  )164    JSIL.$GetHighResTime = window.performance.now.bind(window.performance);165  else166    JSIL.$GetHighResTime = Date.now.bind(Date);167})();168JSIL.Host.ES5TimeService = function () {169  this.started = JSIL.$GetHighResTime();170};171JSIL.Host.ES5TimeService.prototype.getTickCount = function () {172  var result = JSIL.$GetHighResTime() - this.started;173  // Round it to a few digits past the decimal.174  result *= 100;175  result = Math.round(result);176  result /= 100;177  return result;178};179JSIL.Host.ES5TimeService.prototype.getUTC = function () {180  return Date.now();181};182JSIL.Host.ES5TimeService.prototype.getTimezoneOffsetInMilliseconds = function () {183  return new Date().getTimezoneOffset() * 60000;184};185JSIL.Host.ThrowErrorService = function () {186};187JSIL.Host.ThrowErrorService.prototype.error = function (exception) {188  throw exception;189};190JSIL.Host.registerServices({191  time: new JSIL.Host.ES5TimeService(),192  error: new JSIL.Host.ThrowErrorService()...Using AI Code Generation
1var svc = apimocker.svc;2    console.log(res);3});4var svc = apimocker.svc;5var options = {6    headers: {7    },8    body: {9    }10};11svc.post(options, function(err, res) {12    console.log(res);13});14var svc = apimocker.svc;15var options = {16    headers: {17    },18    body: {19    }20};21svc.put(options, function(err, res) {22    console.log(res);23});24var svc = apimocker.svc;25var options = {26    headers: {27    }28};29svc.delete(options, function(err, res) {30    console.log(res);31});32var svc = apimocker.svc;33var options = {34    headers: {35    }36};37svc.patch(options, function(err, res) {38    console.log(res);39});40var svc = apimocker.svc;41var options = {42    headers: {43    }44};45svc.head(options, function(err, res) {46    console.log(res);47});48var svc = apimocker.svc;49var options = {50    headers: {51    }52};53svc.options(options, function(err, res) {54    console.log(res);55});Using AI Code Generation
1var apimocker = require('./apimocker.js');2apimocker.svc('test');3var apimocker = require('./apimocker.js');4apimocker.svc('test');5var apimocker = require('./apimocker.js');6apimocker.svc('test');7var apimocker = require('./apimocker.js');8apimocker.svc('test');9var apimocker = require('./apimocker.js');10apimocker.svc('test');11var apimocker = require('./apimocker.js');12apimocker.svc('test');13var apimocker = require('./apimocker.js');14apimocker.svc('test');15var apimocker = require('./apimocker.js');16apimocker.svc('test');17var apimocker = require('./apimocker.js');18apimocker.svc('test');19var apimocker = require('./apimocker.js');20apimocker.svc('test');21var apimocker = require('./apimocker.js');22apimocker.svc('test');Using AI Code Generation
1var svc = require('apimocker').svc;2svc(function(err, data) {3    if (err) {4        console.log("Error: " + err);5    } else {6        console.log("Data: " + data);7    }8});9var svc = require('apimocker').svc;10svc(function(err, data) {11    if (err) {12        console.log("Error: " + err);13    } else {14        console.log("Data: " + data);15    }16});17var svc = require('apimocker').svc;18svc(function(err, data) {19    if (err) {20        console.log("Error: " + err);21    } else {22        console.log("Data: " + data);23    }24});25var svc = require('apimocker').svc;26svc(function(err, data) {27    if (err) {28        console.log("Error: " + err);29    } else {30        console.log("Data: " + data);31    }32});33var svc = require('apimocker').svc;34svc(function(err, data) {35    if (err) {36        console.log("Error: " + err);37    } else {38        console.log("Data: " + data);39    }40});41var svc = require('apimocker').svc;42svc(function(err, data) {43    if (err) {44        console.log("Error: " + err);45    } else {46        console.log("Data: " + data);47    }48});49var svc = require('apimocker').svc;50svc(function(errUsing AI Code Generation
1var apimocker = require('./apimocker.js');2apimocker.svc('test');3var svc = function (svcName) {4    console.log('svcName is: ' + svcName);5}6module.exports = {7}Using AI Code Generation
1var svc = require('apimocker').svc;2    if (err) {3        console.log('Error: ', err);4    } else {5        console.log('Response: ', res);6    }7});8var svc = require('apimocker').svc;9    if (err) {10        console.log('Error: ', err);11    } else {12        console.log('Response: ', res);13    }14});15var svc = require('apimocker').svc;16    if (err) {17        console.log('Error: ', err);18    } else {19        console.log('Response: ', res);20    }21});22var svc = require('apimocker').svc;23    if (err) {24        console.log('Error: ', err);25    } else {26        console.log('Response: ', res);27    }28});29var svc = require('apimocker').svc;30    if (err) {31        console.log('Error: ', err);32    } else {33        console.log('Response: ', res);34    }35});36var svc = require('apimocker').svc;37    if (err) {38        console.log('Error: ', err);39    } else {40        console.log('Response: ', res);41    }42});Using AI Code Generation
1var svc = require('svc');2  console.log(body);3});4var request = require('request');5module.exports = {6  get: function(url, callback) {7    request(url, callback);8  }9};Using AI Code Generation
1var apimock = require("./apimock.js");2    console.log(data);3});4var http = require('http');5var fs = require('fs');6var svc = function (host, svcName, svcMethod, svcParam, callback) {7    var options = {8    };9    var req = http.get(options, function (res) {10        var bodyChunks = [];11        res.on('data', function (chunk) {12            bodyChunks.push(chunk);13        }).on('end', function () {14            var body = Buffer.concat(bodyChunks);15            callback(null, JSON.parse(body));16        })17    });18    req.on('error', function (e) {19        callback(e, null);20    });21}22exports.svc = svc;23var http = require('http');24var fs = require('fs');25var server = http.createServer(function (req, res) {26    var url = req.url;27    if (url.indexOf("/test") > -1) {28        var data = {29        };30        res.writeHead(200, { "Content-Type": "application/json" });31        res.end(JSON.stringify(data));32    }33});34server.listen(3000, function () {35    console.log('Server listening on port 3000');36});37var http = require('http');38var fs = require('fs');39var server = http.createServer(function (req, res) {40    var url = req.url;41    if (url.indexOf("/test") > -1) {42        var data = {43        };44        res.writeHead(200, { "Content-Type": "application/json" });45        res.end(JSON.stringify(data));46    }47});48server.listen(3000, function () {49    console.log('Server listening on port 3000');50});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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
