How to use abortAll method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

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

search-ui-routerSpec.js

Source: search-ui-routerSpec.js Github

copy
1/* globals window */
2
3xdescribe('search router', function () {
4    'use strict';
5
6    var $q,
7        $state,
8        $stateParams,
9        searchService,
10        uiRouterTester,
11        $httpBackend;
12
13    beforeEach(module('ovpApp.search.router'));
14    beforeEach(module('ovpApp.search.searchService'));
15
16    beforeEach(inject(function ($rootScope, $injector, _$q_, _$state_,
17        _$stateParams_, _searchService_, _$httpBackend_) {
18        $q = _$q_;
19        $state = _$state_;
20        $stateParams = _$stateParams_;
21        $httpBackend = _$httpBackend_;
22
23        uiRouterTester = new UiRouterTester($injector);
24        searchService = _searchService_;
25    }));
26
27    describe('basic routes', function () {
28        describe('parent', function () {
29            it('should not go to abstract parent search state', function () {
30                uiRouterTester.goTo('/search');
31                expect($state.current.name).toEqual('');
32            });
33
34            it('should be abstract', function () {
35                var route = $state.get('search');
36
37                expect(route.abstract).toEqual(true);
38            });
39
40            it('should be able to browse backwards to the ' +
41               'app running before search started', function () {
42                $httpBackend.whenGET('/js/ovpApp/search/quick-search-results.html')
43                    .respond(200, {});
44                uiRouterTester.goTo('/search/term/something');
45
46                window.history.back();
47
48                expect($state.current.name).toEqual('');
49            });
50        });
51
52        describe('quick results', function () {
53            it('should go to quick results state', function () {
54                $httpBackend.whenGET('/js/ovpApp/search/quick-search-results.html')
55                    .respond(200, {});
56                uiRouterTester.goTo('/search/term/somesearchterm');
57
58                expect($state.current.name).toEqual('state.quickresults');
59            });
60
61            it('should be child of parent state', function () {
62                var parent = $state.get('search.quickresults');
63
64                expect(parent.name).toEqual('search');
65            });
66
67            it('should have term param', function () {
68                uiRouterTester.goTo('/search/term/somesearchterm');
69
70                // I'm not positive this is going to work. Not sure if $stateParams
71                // will have updated
72                expect($stateParams.term).toEqual('somesearchterm');
73            });
74
75            it('should clear and cancel search quick results', function () {
76                jasmine.spyOn(searchService, 'abortAll');
77
78                uiRouterTester.goTo('/search/term/somesearchterm');
79                uiRouterTester.goTo('/livetv');
80
81                expect(searchService.abortAll).toHaveBeenCalled();
82            });
83
84            it('should cancel fetch when another search is executed', function () {
85                jasmine.spyOn(searchService, 'abortAll');
86
87                uiRouterTester.goTo('/search/term/somesearchterm');
88                uiRouterTester.goTo('/search/term/othersearchterm');
89
90                expect(searchService.abortAll).toHaveBeenCalled();
91
92                uiRouterTester.goTo('/search/result/someresulturi');
93
94                expect(searchService.abortAll).toHaveBeenCalled();
95
96                uiRouterTester.goTo('/search/term/othersearchterm');
97
98                expect(searchService.abortAll).toHaveBeenCalled();
99            });
100        });
101
102        describe('results', function () {
103            it('should go to results state', function () {
104                uiRouterTester.goTo('/search/result/someresulturi');
105                expect($state.current.name).toEqual('state.results');
106            });
107
108            it('should be child of parent state', function () {
109                var parent = $state.get('search.results');
110
111                expect(parent.name).toEqual('search');
112            });
113
114            it('should have result uri param', function () {
115                uiRouterTester.goTo('/search/result/http://some.nns.uri.com');
116
117                // I'm not positive this is going to work. Not sure if $stateParams
118                // will have updated
119                expect($stateParams.uri).toEqual('http://some.nns.uri.com');
120            });
121
122            it('should clear and cancel search results', function () {
123                jasmine.spyOn(searchService, 'abortAll');
124
125                uiRouterTester.goTo('/search/result/http://some.nns.uri.com');
126                uiRouterTester.goTo('/livetv');
127
128                expect(searchService.abortAll).toHaveBeenCalled();
129            });
130
131            it('should have grid and list view', function () {
132                var state = $state.get('search.results');
133
134                expect(state.views.list).toBeDefined();
135                expect(state.views.grid).toBeDefined();
136            });
137        });
138    });
139
140    describe('resolves', inject(function ($rootScope) {
141        describe('states with w/o views', function () {
142            it('quick results', function () {
143                jasmine.spyOn(searchService, 'getQuickResults').and.callFake(function () {
144                    return $q.when('something');
145                });
146                var onResolved = jasmine.createSpy();
147
148                uiRouterTester.resolve('quickResults').forStateAndView('search.quickResults').then(onResolved);
149
150                $rootScope.$apply();
151                expect(onResolved).toHaveBeenCalledWith('something');
152            });
153        });
154
155        describe('states w/views', function () {
156            it('results list', function () {
157                jasmine.spyOn(searchService, 'getResults').and.callFake(function () {
158                    return $q.when('something');
159                });
160                var onResolved = jasmine.createSpy();
161
162                uiRouterTester.resolve('results')
163                    .forStateAndView('search.results', '[email protected]').then(onResolved);
164
165                $rootScope.$apply();
166                expect(onResolved).toHaveBeenCalledWith('something');
167            });
168
169            it('results grid', function () {
170                jasmine.spyOn(searchService, 'getResults').and.callFake(function () {
171                    return $q.when('something');
172                });
173                var onResolved = jasmine.createSpy();
174
175                uiRouterTester.resolve('results')
176                    .forStateAndView('search.results', '[email protected]').then(onResolved);
177
178                $rootScope.$apply();
179                expect(onResolved).toHaveBeenCalledWith('something');
180            });
181        });
182    }));
183});
184
Full Screen

scoped.js

Source: scoped.js Github

copy
1// scoped Store
2// ============
3
4// same as store, but with type preset to an initially
5// passed value.
6//
7var utils = require('../../utils');
8
9var exports = module.exports = function (hoodie, taskApi, options) {
10  var api = {};
11  var id = options.id;
12  var type = options.type;
13
14  // add events
15  utils.events(
16    hoodie,
17    api,
18    ['task', type, id].join(':').replace(/:$/,'')
19  );
20
21  // scoped by both: type & id
22  if (id) {
23    ['abort', 'restart'].forEach(function(method) {
24      api[method] = exports[method].bind(null, taskApi, type, id);
25    });
26
27    return api;
28  }
29
30  // scoped by type only
31  ['start', 'abort', 'restart', 'abortAll', 'restartAll'].forEach(function(method) {
32    api[method] = exports[method].bind(null, taskApi, type);
33  });
34
35  return api;
36};
37
38exports.start = function start(taskApi, type, properties) {
39  return taskApi.start(type, properties);
40};
41
42exports.abort = function abort(taskApi, type, id) {
43  return taskApi.abort(type, id);
44};
45
46exports.restart = function restart(taskApi, type, id, update) {
47  return taskApi.restart(type, id, update);
48};
49
50exports.abortAll = function abortAll(taskApi, type) {
51  return taskApi.abortAll(type);
52};
53
54exports.restartAll = function restartAll(taskApi, type, update) {
55  return taskApi.restartAll(type, update);
56};
57
Full Screen

sync.js

Source: sync.js Github

copy
1/* ***** BEGIN LICENSE BLOCK *****
2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3 *
4 * The contents of this file are subject to the Mozilla Public License Version
5 * 1.1 (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 * http://www.mozilla.org/MPL/
8 *
9 * Software distributed under the License is distributed on an "AS IS" basis,
10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11 * for the specific language governing rights and limitations under the
12 * License.
13 *
14 * The Original Code is LdapRW.
15 *
16 * The Initial Developer of the Original Code is
17 * Ilnur Kiyamov <[email protected]>.
18 * Portions created by the Initial Developer are Copyright (C) 2010
19 * the Initial Developer. All Rights Reserved.
20 *
21 * Contributor(s):
22 *  
23 * Alternatively, the contents of this file may be used under the terms of
24 * either the GNU General Public License Version 2 or later (the "GPL"), or
25 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
26 * in which case the provisions of the GPL or the LGPL are applicable instead
27 * of those above. If you wish to allow use of your version of this file only
28 * under the terms of either the GPL or the LGPL, and not to allow others to
29 * use your version of this file under the terms of the MPL, indicate your
30 * decision by deleting the provisions above and replace them with the notice
31 * and other provisions required by the GPL or the LGPL. If you do not delete
32 * the provisions above, a recipient may use your version of this file under
33 * the terms of any one of the MPL, the GPL or the LGPL.
34 *
35 * ***** END LICENSE BLOCK ***** */
36
37function debugsync(str){
38//  dump("sync.js: " + str);
39}
40
41function dumperrors(str){
42  ldapsyncabort();
43  dump(str+ "\n");
44  alert(str);
45}
46
47// error collector
48var errorstorage = {
49  data:[],
50  length: 0,
51  add: function(err) {
52    dump("");
53    data[length++] = err;
54  }
55};
56function queryerror(msg, dn, card) {
57  if (msg) this.msg = msg;
58  if (dn) this.dn = dn;
59  if (card) this.card = card;
60}
61queryerror.prototype = {
62  msg:  null,
63  dn:   null,
64  card: null
65}
66
67var QUEUESEARCHADD = 1;
68var QUEUESEARCHGET = 2;
69var QUEUEUPDATEADD = 3;
70var QUEUEUPDATEGET = 4;
71var QUEUEADDADD = 5;
72var QUEUEADDGET = 6;
73var QUEUERENADD = 7;
74var QUEUERENGET = 8;
75var QUEUEDELADD = 9;
76var QUEUEDELGET = 10;
77var ERRGET = 11;
78var ERRSOL = 12;
79
80
81var ldaprw_sync_abort = false;
82function ldapsyncabort() {
83  debugsync("ldapsyncabort\n");
84  ldaprw_sync_abort = true;
85}
86
87// debug info
88var alldn = [];
89var allmsg = [];
90var maillists = {};
91/////////////////
92
93/*
94load("chrome://ldaprw/content/abtoldap.js"); 
95load("chrome://ldaprw/content/ldaptoab.js"); 
96load("chrome://ldaprw/content/ldapsource.js");
97load("chrome://ldaprw/content/sync.js");
98load("chrome://ldaprw/content/prefs.js");
99*/
100
101/*
102  var abManager = Components.classes["@mozilla.org/abmanager;1"].getService(Components.interfaces.nsIAbManager);
103
104var mybook = pref.book;
105 var cards = mybook.childCards;
106 var card = cards.getNext()
107card instanceof Components.interfaces.nsIAbCard
108var propers = card.properties; while ( propers.hasMoreElements() ) { var p = propers.getNext(); if ( p instanceof Components.interfaces.nsIProperty ){ print(p.name + "\t" + p.value + "\n"); } }
109
110 */
111
112/*
113 * Sync all book
114 * @backstatus callback function (type, msg)
115 *
116 * example:
117 * ldapsync( function() { 
118 *              switch(type){ 
119 *               case QUEUESEARCHADD: somecounter++; break; 
120 *               case QUEUESEARCHGET: anothercounter++; break
121 *              }} )
122 *
123 * */
124
125function ldapsync(backstatus) {
126  ldaprw_sync_abort = false;
127  debugsync("ldapsync\n");
128  var prefs = getprefs();
129  for ( var i in prefs) {
130    if (ldaprw_sync_abort) {break;}
131    syncpolitic2(prefs[i],backstatus);
132  }
133}
134
135/*
136 * Generator for password manager interface
137 * @uri 
138 * */
139function gengetpassword() {
140  var counter=0;
141//  var queryURL = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(uri, null, null).QueryInterface(Components.interfaces.nsILDAPURL);
142
143  /*
144   * function getpassword returns string password or null
145   * First call ask or get existing password and return it
146   * Second call and other clear existing password and ask it again
147   * When counter > 3 break with null
148   * @queryURL 
149   * @aMsg It's defined then password incorrect, clear it and ask again
150   * */
151  return function getpassword(queryURL, aMsg) {
152      debugsync("getpassword "+ counter + "\n");
153      if (queryURL == undefined) return null;
154      
155      if (counter > 0){  
156//        debugsync("getpassword " + counter + "\t" + aMsg.errorCode + "\t" + LdapErrorsToStr(aMsg.errorCode) +"\n");
157        try{
158          var passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
159          var logins = passwordManager.findLogins( {}, queryURL.prePath, null, queryURL.spec); 
160          if (logins.length>0) {
161            passwordManager.removeLogin(logins[0])
162              debugsync("old login removed");
163          }
164        }catch(e){
165          dumperrors("getpassword:" + e + "\n"  + e.stack + "\n");
166        }
167        debugsync("getpassword counter changed"+ counter + "\n");
168      }
169      if (counter++ > 2) return null;
170
171      try {
172        var pw = { value: ""};
173        var authprompter = Components.classes["@mozilla.org/login-manager/prompter;1"] 
174                            .getService(Components.interfaces.nsIAuthPrompt);
175        var res = authprompter.promptPassword("Ldap Server Password Need", "Ldap Server Password Request\n" + queryURL.host , queryURL.spec, Components.interfaces.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY, pw);
176        if (!res) {
177          return null;
178        }
179      }catch(e){
180        dumperrors("getpassword: "+e + "\n"  + e.stack + "\n");
181      } 
182
183      return pw.value;
184   }
185}
186
187
188
189/*
190 * Second design of the sync function. The first function did send a request 
191 * to fetch all records from server and then compared cards.
192 *
193 * Primary concept of second design is to move to functional style
194 * @pref preferences
195 * @backstatus callback function (type, aMsg)
196 * */
197function syncpolitic2(pref,backstatus, mybook){
198
199  var abManager = Components.classes["@mozilla.org/abmanager;1"].getService(Components.interfaces.nsIAbManager);
200  if (mybook == undefined ) mybook = pref.book;
201
202  var queryURL = pref.queryURL;
203
204  var mapper = new LdaptoAB();
205  var mappertoldap = new ABtoLdap();
206
207  var newcards = new Array();  
208
209//  var maillists = CollectNodesMailLists(mybook);
210
211  /*
212   * Generator for callback function from ldap modify operations
213   * @querymods Array of query objects
214   *   for example [ { dn: aMsg.dn, mods: mods} ] 
215   * */
216  function genmodquery(querymods) {
217    var modquerycount = 0;
218    /*
219     * Callback function for modify operations
220     * @aMsg ldap messages
221     * */
222    return function modquery(aMsg, mdn) {
223      debugsync("modquery " + modquerycount + "\n");
224      if (ldaprw_sync_abort ) {
225        debugsync("modequery abortall\n");
226        ldap.abortall();
227        return null;
228      }
229     if (aMsg != undefined ){
230          debugsync("modquery aMsg= " + aMsg.errorCode + "\n");
231          if(aMsg.errorCode != Components.interfaces.nsILDAPErrors.SUCCESS ){
232            if (backstatus != undefined) backstatus(ERRGET, 0);
233            
234            dumperrors("Error: modquery " + aMsg.errorCode + "\n" 
235                  + LdapErrorsToStr(aMsg.errorCode) + "\n"
236                  + aMsg.errorMessage );
237          }
238          if (backstatus != undefined) backstatus(QUEUEUPDATEGET, aMsg.type);
239      }
240       if ( modquerycount < querymods.length ) {
241          debugsync( querymods[modquerycount].dn + " "
242              + querymods[modquerycount].mods+ "\n");
243       
244        return querymods[modquerycount++];
245      }
246      return null;
247    }
248  }
249
250
251  /*
252   * Callback function for ldap search results operation
253   * @aMsg ldap messages
254   * */
255  function callbacksearchresult(aMsg) {
256//    ldapcards[aMsg.dn] = aMsg;
257//    ldapcards[ldapcards.length] = aMsg;
258   debugsync("callbacksearchresult " + aMsg.type +"\n");
259      if (ldaprw_sync_abort ) {
260        debugsync("callbacksearchresult abortall\n");
261        ldap.abortall();
262        return;
263      }
264    var d = aMsg.getValues ("modifytimestamp", {}).toString();
265    var ldapdate = new Date ( Date.UTC (d.substring(0,4), d.substring(4,6) - 1, d.substring(6,8), d.substring(8,10), d.substring(10,12), d.substring(12,14) ) );
266
267    /// Search card for dn if it not exists may be we get an "alien" card 
268    var card = mybook.getCardFromProperty("dn", aMsg.dn, false);
269    if ( card == undefined ) {
270      debugsync("callbacksearchresult: can't find\n");
271      return;
272    }
273    
274    /*
275     * Compare a card date with a ldap message
276     * need to move it to function
277     * */
278
279    var carddate = new Date();
280    var carddatestr = card.getProperty("LastModifiedDate", 0);   
281    carddate.setTime( carddatestr + "000");
282
283    var oldldapdate = new Date();
284    var oldldapdatestr = card.getProperty("LdapModifiedDate", 0);
285    oldldapdate.setTime(oldldapdatestr + "000");
286
287    debugsync("callbacksearchresult ldapdate=" 
288        + ldapdate.getTime() + " carddate =" 
289        + carddate.getTime() + " oldldapdate = "
290        + oldldapdate.getTime() + "\n" );
291    
292    if ( ldapdate.getTime() != carddate.getTime() ){
293      if (ldapdate.getTime() > carddate.getTime()) {
294        mapper.map(aMsg, card);
295        debugsync("modify card in Book "+ aMsg.dn + "\n");
296        var newcard= mybook.modifyCard(card);
297        if (backstatus != undefined) backstatus(QUEUESEARCHGET, aMsg.type);
298      } else {
299        debugsync("modify card in LDAP "+ aMsg.dn + "\n");
300        var oldcard = Components.classes["@mozilla.org/addressbook/cardproperty;1"].createInstance(Components.interfaces.nsIAbCard); 
301        mapper.map(aMsg, oldcard);
302        var mods = CreateNSMutArray();
303        
304        mappertoldap.map(card, mods, oldcard);
305
306        if (mods.length >0){             
307          try { 
308            ldap.modify (queryURL, pref.binddn, gengetpassword(), 
309                         genmodquery( [ { dn: aMsg.dn, mods: mods} ] ) ); 
310            if (backstatus != undefined) backstatus(QUEUEUPDATEADD, 0);
311          } catch (e) {
312            dumperrors("Error: " + e+ "\n"  + e.stack + "\n"); 
313          }    
314        }else{
315          debugsync("modify card in LDAP nothing to modify\n");
316          if (backstatus != undefined) backstatus(QUEUESEARCHGET, aMsg.type);
317        }
318
319      }
320    } else {
321        if (backstatus != undefined) backstatus(QUEUESEARCHGET, aMsg.type);
322    }
323
324  };
325
326  /*
327   * Generator for callback search queries
328   * @queryURL
329   * */
330  function gengetsearchquery(queryURL){
331    var allcards = mybook.childCards;
332    var currentcard;
333
334    /*
335     * old "sync" card by card
336     * */
337    function iteration(){
338      debugsync("iter \n");
339        while ( allcards.hasMoreElements()  ) {
340          if (ldaprw_sync_abort ) {
341            debugsync("modequery abortall\n");
342            ldap.abortall();
343            return null;
344          }
345          currentcard = allcards.getNext();
346          if ( currentcard instanceof Components.interfaces.nsIAbCard) {
347            var dn = currentcard.getProperty("dn", null);
348            debugsync("iter while dn=" + dn + "\n");
349            if ( dn ){
350              if (backstatus != undefined) backstatus(QUEUESEARCHADD, 0);
351              
352              if ( currentcard.isMailList ) {
353                // !!! never true
354                // because card component of mailing list can't containing "dn"
355                debugsync( "iter mailng list contains dn! dn=" + dn + "\n")
356                maillists[currentcard.displayName].card = currentcard;
357              // "(objectclass=groupOfNames)"
358                return {dn: gendnML(pref, currentcard), filter: "(objectclass=" + pref.maillistClassesAR[0]  + ")"};
359//                continue;
360              } else {
361                // "(objectclass=inetorgperson)"
362                return {dn: dn, filter: "(objectclass=" + pref.objClassesAR[0] + ")"};
363              }
364            } else {
365              if ( currentcard.isMailList ) {
366                debugsync("iteration maillist\n");
367                maillists[currentcard.displayName] = {card: currentcard};
368//                search mailing list on ldap server
369//                may be need to remove 'dn' from cards and create gendn function for all type card
370                return {dn: gendnML(pref, currentcard), filter: "(objectclass=" + pref.maillistClassesAR[0]  + ")"};
371//                newmaillisttoldap(currentcard);
372              } else {
373                debugsync("iteration new card new dn\n");
374                newcardtoldap(currentcard);
375              }
376            }
377          }
378        }
379        debugsync("iteration nothing to do\n")
380        return null;
381    }
382
383    /*
384     * Callback function for search operations
385     * */
386    return function(aMsg, mydn){
387      debugsync("getsearchquery\n");
388      if (ldaprw_sync_abort ) {
389        debugsync("getsearchquery abortall\n");
390        ldap.abortall();
391        return null;
392      }
393      if ( aMsg == undefined ) return iteration();
394      else
395        if ( aMsg instanceof Components.interfaces.nsILDAPMessage) {
396
397          //// debuging infos
398//          allmsg[allmsg.length] = aMsg;
399//          if ( mydn != undefined ) {
400//            alldn[alldn.length] = { msg: aMsg, mydn: mydn };
401//            debugsync("getsearchquery mydn=" + mydn.dn + "\n");
402//          }
403          ////////////////////////
404
405          if ( aMsg.errorCode == Components.interfaces.nsILDAPErrors.SUCCESS ){
406            return iteration();
407          }else 
408            if ( aMsg.errorCode == Components.interfaces.nsILDAPErrors.NO_SUCH_OBJECT){
409
410              //// debug
411              var dumpstr = "getsearchquery new card ";
412              try {
413                if (aMsg.errorCode != undefined) {
414                  dumpstr+="errcode=" + aMsg.errorCode;
415                }
416                if (aMsg.matchedDn != undefined ) {
417                  dumpstr+= " matchedDn=" + aMsg.matchedDn;
418                }
419                if (mydn != undefined ) {
420                  dumpstr+= " dn=" + mydn.dn;
421                }
422              } catch(e) {
423                debugsync(e);
424              } finally {
425                debugsync(dumpstr + "\n");
426              }
427              /////////////////////////////////////
428
429               if (mydn != undefined ) {
430                  var card = mybook.getCardFromProperty("dn", mydn.dn, false);
431                  if ( card != undefined ) {
432                    newcardtoldap(card);
433                  } else {
434                    var rdnval = mydn.dn.split(',')[0].split('=')[1].replace(/^\s+|\s+$/g,'');
435                    var ml = maillists[rdnval];
436                    debugsync(ml.card.displayName + "\n");
437                    newmltoldap(ml.card);                    
438                  }
439                }
440
441              return iteration();
442            } else {
443              if (backstatus != undefined) backstatus(ERRGET, 0);
444              ldapsyncabort();              
445              ldap.abortall();
446              dumperrors (aMsg.type + "\n" + aMsg.errorCode + "\t" + LdapErrorsToStr(aMsg.errorCode) + "\n" + aMsg.errorMessage);
447            }
448        }
449      debugsync("getsearchquery nothing to do\n");
450      return null;  
451   }
452  }
453
454
455  
456
457  var ldap = new LdapDataSource();
458  var newcardtoldap = genaddtoldap(pref, ldap, backstatus);
459  var newmltoldap = genaddtoldapML(pref, ldap, backstatus);
460
461  
462  // Prepare Array of  requested attributes for ldap search request
463  // need to refactor to use generator iterator from mapper or move to use
464  // callback function
465  var attrs = new Array(); 
466  attrs[attrs.length]="objectClass";
467  for (var i in mapper.__proto__) { 
468    attrs[attrs.length] = i; 
469  };
470  
471  ldap.init(attrs);
472
473  try {
474  //  queryURL.filter = "(objectclass=inetorgperson)"
475    ldap.query(queryURL, pref.binddn, gengetpassword(), gengetsearchquery(pref.queryURL), callbacksearchresult );
476  } catch (e) {
477    dumperrors ("Error: " + e + "\n"  + e.stack + "\n");
478  }
479
480}
481
482function genrdnML(pref, card) {
483  //return pref.attrRdn + "=" + card.displayName;
484  var basisRdn = card.getProperty(pref.basisRdn, "");
485  if ( basisRdn.length > 0 ) {
486    return pref.attrRdn + "=" + card.getProperty(pref.basisRdn);  
487  } else {
488    throw "genrdn: basisRdn.length = 0";
489  }
490}
491
492function gendnML(pref,card) {
493  return genrdnML(pref, card) + ',' + pref.queryURL.dn;
494}
495
496function genrdn(pref, card) {
497//  return pref.attrRdn + "=" + card.displayName; 
498//  var basisRdn = card.getProperty(pref.basisRdn, "");
499  var basisRdn = pref.genRdn(card);
500  if ( basisRdn.length > 0 ) {
501    return pref.attrRdn + "=" + basisRdn;
502  } else {
503    debugsync("genrdn: basisRdn.length=" + basisRdn.length + "\n");
504    throw "genrdn: basisRdn.length = 0";
505    return null;
506  }
507}
508
509function gendn(pref,card) {
510  var rdn = genrdn(pref, card);
511  debugsync("gendn: rdn="+rdn+"\n");
512  return rdn + ',' + pref.queryURL.dn;
513}
514
515/*
516 * Generator of callback function for add operation
517 * */
518
519function genaddtoldap(pref, ldapser, backstatus) {
520
521
522  var mybook = pref.book;
523  var queryURL = pref.queryURL;
524
525  var mapper = new LdaptoAB();
526  var mappertoldap = new ABtoLdap();
527
528  var ldap = ldapser;
529  if (ldap == undefined) {    
530    var ldap = new LdapDataSource();
531    var attrs = new Array(); 
532    attrs[attrs.length]="objectClass";
533    for (var i in mapper.__proto__) { 
534      attrs[attrs.length] = i; 
535    };
536    ldap.init(attrs);
537  }
538
539  function genaddquery(card, addqueries) {
540    var addquerycount = 0;
541    return function addquery(aMsg, mdn) {
542      debugsync("addquery " + addquerycount + "\n");
543      if (ldaprw_sync_abort ) {
544        try{
545          if (backstatus != undefined) backstatus(ERRGET, 0);
546          debugsync("addquery abortall\n");
547          ldap.abortall();
548        }catch(e){
549          dumperrors("addquery aborting failed: " + e + "\n"  + e.stack + "\n");
550        }
551        return null;
552      }
553      if (aMsg != undefined ){
554          debugsync("addquery aMsg= " + aMsg.errorCode + "\n");
555        if (aMsg.errorCode != Components.interfaces.nsILDAPErrors.SUCCESS) {
556          try{
557            ldapsyncabort();
558            if (backstatus != undefined) backstatus(ERRGET, 0);
559            dump("addtoldap: aborting\n");
560            ldap.abortall();
561          }catch(e){
562            dumperrors("addquery aborting failed: " + e + "\n"  + e.stack + "\n");
563          }
564
565          dumperrors("Error: addquery " + aMsg.errorCode + "\n" 
566                  + LdapErrorsToStr(aMsg.errorCode) + "\n"
567                  + aMsg.errorMessage + "\n"
568                  + card.getProperty("dn", "") + "\n");
569          return null;
570        }else{
571          card.setProperty("dn", mdn.dn);
572          var newcard= mybook.modifyCard(card);
573          if (backstatus != undefined) backstatus(QUEUEADDGET, aMsg.type);          
574        }
575      }
576      if ( addquerycount < addqueries.length ) {
577        return addqueries[addquerycount++];
578      }
579      return null;
580    }
581  }
582
583
584    return function(card){
585      debugsync("New card\n");
586      try {
587        var oldcard = Components.classes["@mozilla.org/addressbook/cardproperty;1"] .createInstance(Components.interfaces.nsIAbCard);
588        var mods = CreateNSMutArray();
589   
590        var dn = card.getProperty("dn", null);
591        if ( !dn ){
592          //dn = pref.attrRdn + "=" + card.displayName + "," + queryURL.dn;
593          dn = gendn(pref, card);
594        }
595        debugsync("newcardtoldap dn=" + dn + "\n");
596        mods.appendElement( CreateLDAPMod( "objectClass", pref.objClassesAR, Components.interfaces.nsILDAPModification.MOD_ADD | Components.interfaces.nsILDAPModification.MOD_BVALUES ), false );
597      
598        mappertoldap.map(card, mods, oldcard);
599      
600        ldap.add(queryURL, pref.binddn, gengetpassword(), genaddquery(card, [{dn: dn, mods: mods /* maybe need: , card:card */}]) );
601        if (backstatus != undefined) backstatus(QUEUEADDADD, 0);        
602      } catch(e) {
603        dumperrors("Error: " + e+"\n"  + e.stack + "\n");
604      }      
605    }
606}
607
608
609/*
610 * Generator of callback function for add operation, mailing list
611 * */
612
613function genaddtoldapML(pref, ldapser, backstatus) {
614
615  var abManager = Components.classes["@mozilla.org/abmanager;1"].getService(Components.interfaces.nsIAbManager);
616
617  var mybook = pref.book;
618  var queryURL = pref.queryURL;
619
620  var mapper = new LdaptoML();
621  var mappertoldap = new MLtoLdap();
622
623  var ldap = ldapser;
624  if (ldap == undefined) {    
625    var ldap = new LdapDataSource();
626  }
627
628  function genaddquery(card, addqueries) {
629    var addquerycount = 0;
630    return function addquery(aMsg, mdn) {
631      debugsync("addquery " + addquerycount + "\n");
632      if (ldaprw_sync_abort ) {
633        debugsync("addquery abortall\n");
634        ldap.abortall();
635        return null;
636      }
637      if (aMsg != undefined ){
638          debugsync("addquery aMsg= " + aMsg.errorCode + "\n");
639        if (aMsg.errorCode != Components.interfaces.nsILDAPErrors.SUCCESS) {
640          dumperrors("Error: addquery " + aMsg.errorCode + "\n" 
641                  + LdapErrorsToStr(aMsg.errorCode) + "\n"
642                  + aMsg.errorMessage + "\n"
643                  + card.getProperty("dn", "") + "\n");
644          return null;
645        }else{
646//          var newcard= mybook.modifyCard(card);
647          if (backstatus != undefined) backstatus(QUEUEADDGET, aMsg.type);          
648        }
649      }
650      if ( addquerycount < addqueries.length ) {
651        return addqueries[addquerycount++];
652      }
653      return null;
654    }
655  }
656
657
658    return function(card){
659      debugsync("New mailing list to ldap\n");
660      try {
661        var node = abManager.getDirectory(card.mailListURI);
662        var ml = { card: card, node: node}; 
663
664        var mods = CreateNSMutArray();
665      
666        var dn = gendnML(pref, card);
667        debugsync("new ml to ldap dn=" + dn + "\n");
668        mods.appendElement( CreateLDAPMod( "objectClass", pref.maillistClassesAR, Components.interfaces.nsILDAPModification.MOD_ADD | Components.interfaces.nsILDAPModification.MOD_BVALUES ), false );
669        debugsync("new ml to ldap mods.length=" + mods.length + "\n");
670      
671        mappertoldap.map(ml, mods);
672
673        //// Thunderbird can't store 'dn' in mailing list nsAbCard
674        //card.setProperty("dn", dn);
675        debugsync("new ml to ldap mods.length=" + mods.length + "\n");
676      
677        ldap.add(queryURL, pref.binddn, gengetpassword(), genaddquery(card, [{dn: dn, mods: mods}]) );
678        if (backstatus != undefined) backstatus(QUEUEADDADD, 0);        
679      } catch(e) {
680        dumperrors("Error: " + e+"\n"  + e.stack + "\n");
681      }      
682    }
683}
684
685
686/*
687 * Add new card to address book from ldap or modify existing card
688 * */
689function addcardfromldap(book, aMsg, replace){
690 
691  var mapper = new LdaptoAB();
692  var card = book.getCardFromProperty("dn", aMsg.dn, false);
693  if ( card == undefined ) {
694    var card = Components.classes["@mozilla.org/addressbook/cardproperty;1"].createInstance(Components.interfaces.nsIAbCard); 
695
696    mapper.map(aMsg, card);
697
698    // NEED to change code to use onnsIAbCardPropsDo(card, func)
699    var propers = card.properties; 
700    while ( propers.hasMoreElements() ) { 
701      var p = propers.getNext(); 
702      if ( p instanceof Components.interfaces.nsIProperty ){ 
703        debugsync(p.name + "\t" + p.value + "\n"); 
704      } 
705    } 
706
707    var newcard= book.addCard(card);
708
709    return 0;
710  } else {
711    if (replace){
712      mapper.map(aMsg, card);
713      var newcard= book.modifyCard(card);      
714      return 0;
715    }
716  }
717  return 1;
718}
719
720
721
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)