cba2824a8ff4f5680499fb0cfbc3e98de05bb9d3
[contrib/cloudeebus.git] / cloudeebus / cloudeebus.js
1 /******************************************************************************
2  * Copyright 2012 Intel Corporation.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  * http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *****************************************************************************/
16
17
18
19 /*****************************************************************************/
20
21 var dbus = { // hook object for dbus types not translated by python-json
22                 Double: function(value, level) {
23                         return value;
24                 }
25 };
26
27
28
29 /*****************************************************************************/
30
31 var cloudeebus = window.cloudeebus = {
32                 version: "0.5.1",
33                 minVersion: "0.3.2"
34 };
35
36 cloudeebus.reset = function() {
37         cloudeebus.sessionBus = null;
38         cloudeebus.systemBus = null;
39         cloudeebus.wampSession = null;
40         cloudeebus.uri = null;
41 };
42
43
44 cloudeebus.log = function(msg) { 
45 };
46
47 cloudeebus.getError = function(error) {
48         if (error.desc && error.uri)
49                 return error.desc + " : " + error.uri;
50         if (error.desc)
51                 return error.desc;
52         if (error.uri)
53                 return error.uri;
54         if (error.message)
55                 return error.message;
56         return error;
57 };
58
59 cloudeebus.versionCheck = function(version) {
60         var ver = version.split(".");
61         var min = cloudeebus.minVersion.split(".");
62         for (var i=0; i<ver.length; i++) {
63                 if (Number(ver[i]) > Number(min[i]))
64                         return true;
65                 if (Number(ver[i]) < Number(min[i]))
66                         return false;
67         }
68         return true;
69 };
70
71
72 cloudeebus.connect = function(uri, manifest, successCB, errorCB) {
73         cloudeebus.reset();
74         cloudeebus.uri = uri;
75         
76         function onCloudeebusVersionCheckCB(version) {
77                 if (cloudeebus.versionCheck(version)) {
78                         cloudeebus.log("Connected to " + cloudeebus.uri);
79                         if (successCB)
80                                 successCB();
81                 } else {
82                         var errorMsg = "Cloudeebus server version " + version + " unsupported, need version " + cloudeebus.minVersion + " or superior";
83                         cloudeebus.log(errorMsg);
84                         if (errorCB)
85                                 errorCB(errorMsg);
86                 }
87         }
88         
89         function onWAMPSessionAuthErrorCB(error) {
90                 cloudeebus.log("Authentication error: " + cloudeebus.getError(error));
91                 if (errorCB)
92                         errorCB(cloudeebus.getError(error));
93         }
94         
95         function onWAMPSessionAuthenticatedCB(permissions) {
96                 cloudeebus.sessionBus = new cloudeebus.BusConnection("session", cloudeebus.wampSession);
97                 cloudeebus.systemBus = new cloudeebus.BusConnection("system", cloudeebus.wampSession);
98                 cloudeebus.wampSession.call("getVersion").then(onCloudeebusVersionCheckCB, errorCB);
99         }
100         
101         function onWAMPSessionChallengedCB(challenge) {
102                 var signature = cloudeebus.wampSession.authsign(challenge, manifest.key);
103                 cloudeebus.wampSession.auth(signature).then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
104         }
105         
106         function onWAMPSessionConnectedCB(session) {
107                 cloudeebus.wampSession = session;
108                 if (manifest)
109                         cloudeebus.wampSession.authreq(
110                                         manifest.name, 
111                                         {permissions: manifest.permissions}
112                                 ).then(onWAMPSessionChallengedCB, onWAMPSessionAuthErrorCB);
113                 else
114                         cloudeebus.wampSession.authreq().then(function() {
115                                 cloudeebus.wampSession.auth().then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
116                                 }, onWAMPSessionAuthErrorCB);
117         }
118
119         function onWAMPSessionErrorCB(code, reason) {
120                 if (code == ab.CONNECTION_UNSUPPORTED) {
121                         cloudeebus.log("Browser is not supported");
122                 }
123                 else {
124                         cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
125                 }
126                 if (errorCB)
127                         errorCB(reason);
128         }
129
130         return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
131 };
132
133
134 cloudeebus.SessionBus = function() {
135         return cloudeebus.sessionBus;
136 };
137
138
139 cloudeebus.SystemBus = function() {
140         return cloudeebus.systemBus;
141 };
142
143
144
145 /*****************************************************************************/
146
147 cloudeebus.BusConnection = function(name, session) {
148         this.name = name;
149         this.wampSession = session;
150         return this;
151 };
152
153
154 cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
155         var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
156         if (introspectCB)
157                 proxy._introspect(introspectCB, errorCB);
158         return proxy;
159 };
160
161
162 cloudeebus.BusConnection.prototype.addService = function(serviceName) {
163         var self = this;
164         
165         var promise = new cloudeebus.Promise(function (resolver) {
166           cloudeebusService = new cloudeebus.Service(self.wampSession, self, serviceName);
167         
168           function busServiceAddedSuccessCB(service) {
169                   try {
170                           service.isCreated = true;
171                           var result = [cloudeebusService];
172                           resolver.fulfill(result[0], true);
173                   }
174                   catch (e) {
175                           cloudeebus.log("Method callback exception: " + e);
176                           resolver.reject(e, true);
177                   }             
178           }
179         
180           function busServiceErrorSuccessCB(error) {
181                   resolver.reject(error, true);
182           }
183         
184           cloudeebusService.add(this).then(busServiceAddedSuccessCB, busServiceErrorSuccessCB);
185         });
186         
187         return promise;
188 };
189
190 cloudeebus.BusConnection.prototype.removeService = function(serviceName, successCB, errorCB) {
191         var self = this;
192         
193         function busServiceRemovedSuccessCB(serviceName) {
194                 // Be sure we are removing the service requested...
195                 if (serviceName == self.service.name) {
196                         self.service = null;
197                         if (successCB)
198                                 successCB(serviceName);
199                 }
200         }
201         
202         cloudeebusService.remove(busServiceRemovedSuccessCB, errorCB);
203 };
204
205
206 /*****************************************************************************/
207 //Generic definition for an agent. An agent need :
208 //srvDbusName : the DBus parent service
209 //objPath : a DBus path to access it
210 //jsHdl : a Javascript handler to process methods, 
211 //xml : the xml which describe interface/methods/signals...
212 Agent = function(srvDbusName, objPath, jsHdl, xml) {
213         this.srvName = srvDbusName;
214         this.registered = false;
215         this.xml = xml;
216         this.objectPath = objPath;
217         this.jsHdl = jsHdl;
218         return this;
219 };
220
221
222 cloudeebus.Service = function(session, busConnection, name) {
223         this.wampSession = session;
224         this.busConnection = busConnection; 
225         this.name = name;
226         this.isCreated = false;
227         return this;
228 };
229
230 cloudeebus.Service.prototype.add = function(promise) {
231         var self = this;
232         self.promise = promise;
233         var resolver = self.promise.resolver;
234         
235         function ServiceAddedSuccessCB(serviceName) {
236                 try { // calling dbus hook object function for un-translated types
237                         var result = [self];
238                         resolver.fulfill(result[0], true);
239                 }
240                 catch (e) {
241                         cloudeebus.log("Method callback exception: " + e);
242                         resolver.reject(e, true);
243                 }               
244         }
245         
246         function ServiceAddedErrorCB(error) {
247                 cloudeebus.log("Error adding service method: " + self.name + ", error: " + cloudeebus.getError(error));
248                 self.promise.resolver.reject(cloudeebus.getError(error), true);
249         }
250
251         var arglist = [
252             this.busConnection,
253             this.name
254             ];
255
256         // call dbusSend with bus type, destination, object, message and arguments
257         this.wampSession.call("serviceAdd", arglist).then(ServiceAddedSuccessCB, ServiceAddedErrorCB);
258         return promise;
259 };
260
261 cloudeebus.Service.prototype.remove = function(successCB, errorCB) {
262         function ServiceRemovedSuccessCB(serviceName) {
263                 if (successCB) {
264                         try {
265                                 successCB(serviceName);
266                         }
267                         catch (e) {
268                                 alert("Exception removing service " + serviceName + " : " + e);
269                         }
270                 }
271         }
272         
273         var arglist = [
274             this.name
275             ];
276
277         // call dbusSend with bus type, destination, object, message and arguments
278         this.wampSession.call("serviceRelease", arglist).then(ServiceRemovedSuccessCB, errorCB);
279 };
280
281 cloudeebus.Service.prototype._searchMethod = function(ifName, method, objectJS) {
282
283         var funcToCall = null;
284         
285         // Check if 'objectJS' has a member 'interfaceProxies' with an interface named 'ifName' 
286         // and a method named 'method'
287         if (objectJS.interfaceProxies && objectJS.interfaceProxies[ifName] &&
288                 objectJS.interfaceProxies[ifName][method]) {
289                 funcToCall = objectJS.interfaceProxies[ifName][method];
290         } else {
291                 // retrieve the method directly from 'root' of objectJs
292                 funcToCall = objectJS[method];
293         }
294
295         return funcToCall;
296 };
297
298 cloudeebus.Service.prototype._addMethod = function(ifName, method, agent) {
299
300         var service = this;
301         var methodId = this.name + "#" + agent.objectPath + "#" + ifName + "#" + method;
302         var funcToCall = this._searchMethod(ifName, method, agent.jsHdl);
303
304         if (funcToCall == null)
305                 cloudeebus.log("Method " + method + " doesn't exist in Javascript object");
306         else {
307                 agent.jsHdl.wrapperFunc[method] = function() {
308                         var result;
309                         var methodId = arguments[0];
310                         var callDict = {};
311                         // affectation of callDict in eval, otherwise dictionary(='{}') interpreted as block of code by eval
312                         eval("callDict = " + arguments[1]);
313                         try {
314                                 result = funcToCall.apply(agent.jsHdl, callDict.args);
315                                 service._returnMethod(methodId, callDict.callIndex, true, result);
316                         }
317                         catch (e) {
318                                 cloudeebus.log("Method " + ifName + "." + method + " call on " + agent.objectPath + " exception: " + e);
319                                 service._returnMethod(methodId, callDict.callIndex, false, e.message);
320                         }
321                 };
322                 agent.jsHdl.methodId[agent.objectPath].push(methodId);
323                 cloudeebus.log("subscribe " + methodId);
324                 this.wampSession.subscribe(methodId, agent.jsHdl.wrapperFunc[method]);
325         }
326 };
327
328 cloudeebus.Service.prototype._addSignal = function(ifName, signal, agent) {
329         var service = this;
330         var methodExist = false;
331
332         if (agent.jsHdl.interfaceProxies && agent.jsHdl.interfaceProxies[ifName])
333                 if (agent.jsHdl.interfaceProxies[ifName][signal]) {
334                         methodExist = true;
335                 } else {
336                         agent.jsHdl.interfaceProxies[ifName][signal] = function() {
337                                 service._emitSignal(agent.objectPath, signal, arguments[0]);
338                         };
339                 return;
340         }
341                 
342         if ((agent.jsHdl[signal] == undefined || agent.jsHdl[signal] == null) && !methodExist) 
343                 agent.jsHdl[signal] = function() {
344                         service.emitSignal(agent.objectPath, signal, arguments[0]);
345                 };
346         else
347                 cloudeebus.log("Can not create new method to emit signal '" + signal + "' in object JS this method already exist!");
348 };
349
350 cloudeebus.Service.prototype._createWrapper = function(agent) {
351         var self = this;
352         var parser = new DOMParser();
353         var xmlDoc = parser.parseFromString(agent.xml, "text/xml");
354         var ifXml = xmlDoc.getElementsByTagName("interface");
355         agent.jsHdl.wrapperFunc = [];
356         agent.jsHdl.methodId = [];
357         agent.jsHdl.methodId[agent.objectPath] = [];
358         for (var i=0; i < ifXml.length; i++) {
359                 var ifName = ifXml[i].attributes.getNamedItem("name").value;
360                 var ifChild = ifXml[i].firstChild;
361                 while (ifChild) {
362                         if (ifChild.nodeName == "method") {
363                                 var metName = ifChild.attributes.getNamedItem("name").value;
364                                 self._addMethod(ifName, metName, agent);
365                         }
366                         if (ifChild.nodeName == "signal") {
367                                 var metName = ifChild.attributes.getNamedItem("name").value;
368                                 self._addSignal(objectPath, ifName, metName, objectJS);
369                         }
370                         ifChild = ifChild.nextSibling;
371                 }
372         }
373 };
374
375 cloudeebus.Service.prototype.addAgent = function(agent, successCB, errorCB) {
376         function ServiceAddAgentSuccessCB(objPath) {
377                 if (successCB) {
378                         try {
379                                 successCB(objPath);
380                         }
381                         catch (e) {
382                                 alert("Exception adding agent " + agent.objectPath + " : " + e);
383                         }
384                 }
385         }
386         
387         try {
388                 this._createWrapper(agent);
389         }
390         catch (e) {
391                 alert("Exception creating agent wrapper " + agent.objectPath + " : " + e);
392                 errorCB(e);
393                 return;
394         }
395         
396         var arglist = [
397             agent.objectPath,
398             agent.xml
399             ];
400
401         // call dbusSend with bus type, destination, object, message and arguments
402         this.wampSession.call("serviceAddAgent", arglist).then(ServiceAddAgentSuccessCB, errorCB);
403 };
404
405 cloudeebus.Service.prototype._deleteWrapper = function(agent) {
406         var self = this;
407         var objJs = agent.jsHdl;
408         if (objJs.methodId[agent.objectPath]) {
409                 for (var idx in objJs.methodId[agent.objectPath]) {
410                         try {
411                                 cloudeebus.log("unsubscribe " + objJs.methodId[agent.objectPath][idx]);
412                                 this.wampSession.unsubscribe(objJs.methodId[agent.objectPath][idx]);
413                                 objJs.methodId[agent.objectPath][idx] = null;
414                         }
415                         catch (e) {
416                                 cloudeebus.log("Unsubscribe error: " + e);
417                         }
418                 }
419                 delete objJs.methodId[agent.objectPath];
420         }
421 };
422
423 cloudeebus.Service.prototype.delAgent = function(rmAgent, successCB, errorCB) {
424         function ServiceDelAgentSuccessCB(agent) {
425                 if (successCB) {
426                         try {
427                                 successCB(agent);
428                         }
429                         catch (e) {
430                                 alert("Exception deleting agent " + rmAgent.objectPath + " : " + e);
431                                 errorCB(e);
432                         }
433                 }
434         }
435
436         try {
437                 this._deleteWrapper(rmAgent);
438         }
439         catch (e) {
440                 alert("Exception deleting agent wrapper " + rmAgent.objectPath + " : " + e);
441                 errorCB(e);
442         }
443         
444         var arglist = [
445             rmAgent.objectPath
446             ];
447
448         // call dbusSend with bus type, destination, object, message and arguments
449         this.wampSession.call("serviceDelAgent", arglist).then(ServiceDelAgentSuccessCB, errorCB);
450 };
451
452 cloudeebus.Service.prototype._returnMethod = function(methodId, callIndex, success, result, successCB, errorCB) {
453         var arglist = [
454             methodId,
455             callIndex,
456             success,
457             result
458             ];
459
460         this.wampSession.call("returnMethod", arglist).then(successCB, errorCB);
461 };
462
463 cloudeebus.Service.prototype._emitSignal = function(objectPath, signalName, result, successCB, errorCB) {
464         var arglist = [
465             objectPath,
466             signalName,
467             result
468             ];
469
470         this.wampSession.call("emitSignal", arglist).then(successCB, errorCB);
471 };
472
473
474
475 /*****************************************************************************/
476
477 function _processWrappers(wrappers, value) {
478         for (var i=0; i<wrappers.length; i++)
479                 wrappers[i](value);
480 }
481
482
483 function _processWrappersAsync(wrappers, value) {
484         var taskid = -1;
485         function processAsyncOnce() {
486                 _processWrappers(wrappers, value);
487                 clearInterval(taskid);
488         }
489         taskid = setInterval(processAsyncOnce, 200);
490 }
491
492
493
494 /*****************************************************************************/
495
496 cloudeebus.PromiseResolver = function(promise) {
497         this.promise = promise;
498         this.resolved = null;
499     return this;
500 };
501
502
503 cloudeebus.PromiseResolver.prototype.resolve = function(value, sync) {
504         if (this.resolved)
505                 return;
506         
507         var then = (value && value.then && value.then.apply) ? value.then : null;
508         if (then) {
509                 var self = this;                
510                 var fulfillCallback = function(arg) {
511                         self.resolve(arg, true);
512                 };      
513                 var rejectCallback = function(arg) {
514                         self.reject(arg, true);
515                 };
516                 try {
517                         then.apply(value, [fulfillCallback, rejectCallback]);
518                 }
519                 catch (e) {
520                         this.reject(e, true);
521                 }
522         }
523         
524         this.fulfill(value, sync);
525 };
526
527
528 cloudeebus.PromiseResolver.prototype.fulfill = function(value, sync) {
529         if (this.resolved)
530                 return;
531         
532         var promise = this.promise;
533         promise.state = "fulfilled";
534         promise.result = value;
535         
536         this.resolved = true;
537         if (sync)
538                 _processWrappers(promise._fulfillWrappers, value);
539         else
540                 _processWrappersAsync(promise._fulfillWrappers, value);
541 };
542
543
544 cloudeebus.PromiseResolver.prototype.reject = function(value, sync) {
545         if (this.resolved)
546                 return;
547         
548         var promise = this.promise;
549         promise.state = "rejected";
550         promise.result = value;
551         
552         this.resolved = true;
553         if (sync)
554                 _processWrappers(promise._rejectWrappers, value);
555         else
556                 _processWrappersAsync(promise._rejectWrappers, value);
557 };
558
559
560
561 /*****************************************************************************/
562
563 cloudeebus.Promise = function(init) {
564         this.state = "pending";
565         this.result = null;
566         this._fulfillWrappers = [];
567         this._rejectWrappers = [];
568         this.resolver = new cloudeebus.PromiseResolver(this);
569         if (init) {
570                 try {
571                         init.apply(this, [this.resolver]);
572                 }
573                 catch (e) {
574                         this.resolver.reject(e, true);
575                 }
576         }
577     return this;
578 };
579
580
581 cloudeebus.Promise.prototype.appendWrappers = function(fulfillWrapper, rejectWrapper) {
582         if (fulfillWrapper)
583                 this._fulfillWrappers.push(fulfillWrapper);
584         if (rejectWrapper)
585                 this._rejectWrappers.push(rejectWrapper);
586         if (this.state == "fulfilled")
587                 _processWrappersAsync(this._fulfillWrappers, this.result);
588         if (this.state == "rejected")
589                 _processWrappersAsync(this._rejectWrappers, this.result);
590 };
591
592
593 cloudeebus.Promise.prototype.then = function(fulfillCB, rejectCB) {
594         var promise = new cloudeebus.Promise();
595         var resolver = promise.resolver;
596         var fulfillWrapper, rejectWrapper;
597         
598         if (fulfillCB)
599                 fulfillWrapper = function(arg) {
600                         try {
601                                 var value = fulfillCB.apply(promise, [arg]);
602                                 resolver.resolve(value, true);
603                         }
604                         catch (e) {
605                                 resolver.reject(e, true);
606                         }
607                 };
608         else
609                 fulfillWrapper = function(arg) {
610                         resolver.fulfill(arg, true);
611                 };
612         
613         if (rejectCB)
614                 rejectWrapper = function(arg) {
615                         try {
616                                 var value = rejectCB.apply(promise, [arg]);
617                                 resolver.resolve(value, true);
618                         }
619                         catch (e) {
620                                 resolver.reject(e, true);
621                         }
622                 };
623         else
624                 rejectWrapper = function(arg) {
625                         resolver.reject(arg, true);
626                 };
627         
628         this.appendWrappers(fulfillWrapper,rejectWrapper);
629         return promise;
630 };
631
632
633 cloudeebus.Promise.prototype["catch"] = function(rejectCB) {
634         return this.then(undefined,rejectCB);
635 };
636
637
638 cloudeebus.Promise.prototype.done = function(fulfillCB, rejectCB) {
639         this.appendWrappers(fulfillCB,rejectCB);
640 };
641
642
643 cloudeebus.Promise.resolve = function(value) {
644         var promise = new cloudeebus.Promise();
645         promise.resolver.resolve(value);
646         return promise;
647 };
648
649
650 cloudeebus.Promise.fulfill = function(value) {
651         var promise = new cloudeebus.Promise();
652         promise.resolver.fulfill(value);
653         return promise;
654 };
655
656
657 cloudeebus.Promise.reject = function(value) {
658         var promise = new cloudeebus.Promise();
659         promise.resolver.reject(value);
660         return promise;
661 };
662
663
664 cloudeebus.Promise.any = function() {
665         var promise = new cloudeebus.Promise();
666         var resolver = promise.resolver;
667         var fulfillCallback = function(arg) {
668                 resolver.resolve(arg, true);
669         };
670         var rejectCallback = function(arg) {
671                 resolver.reject(arg, true);
672         };
673         if (arguments.length == 0)
674                 resolver.resolve(undefined, true);
675         else
676                 for (i in arguments) 
677                         Promise.resolve(arguments[i]).appendWrappers(fulfillCallback,rejectCallback);
678         return promise;
679 };
680
681
682 cloudeebus.Promise.every = function() {
683         var promise = new cloudeebus.Promise();
684         var resolver = promise.resolver;
685         var index = 0;
686         var countdown = arguments.length;
687         var args = new Array(countdown);
688         var rejectCallback = function(arg) {
689                 resolver.reject(arg, true);
690         };
691         if (arguments.length == 0)
692                 resolver.resolve(undefined, true);
693         else
694                 for (i in arguments) {
695                         var fulfillCallback = function(arg) {
696                                 args[index] = arg;
697                                 countdown--;
698                                 if (countdown == 0)
699                                         resolver.resolve(args, true);
700                         };
701                         index++;
702                         Promise.resolve(arguments[i]).appendWrappers(fulfillCallback,rejectCallback);
703                 }
704         
705         return promise;
706 };
707
708
709 cloudeebus.Promise.some = function() {
710         var promise = new cloudeebus.Promise();
711         var resolver = promise.resolver;
712         var index = 0;
713         var countdown = arguments.length;
714         var args = new Array(countdown);
715         var fulfillCallback = function(arg) {
716                 resolver.resolve(arg, true);
717         };
718         if (arguments.length == 0)
719                 resolver.resolve(undefined, true);
720         else
721                 for (i in arguments) {
722                         var rejectCallback = function(arg) {
723                                 args[index] = arg;
724                                 countdown--;
725                                 if (countdown == 0)
726                                         resolver.reject(args, true);
727                         };
728                         index++;
729                         Promise.resolve(arguments[i]).appendWrappers(fulfillCallback,rejectCallback);
730                 }
731         
732         return promise;
733 };
734
735
736
737 /*****************************************************************************/
738
739 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
740         this.wampSession = session; 
741         this.busConnection = busConnection; 
742         this.busName = busName; 
743         this.objectPath = objectPath; 
744         this.interfaceProxies = {};
745         return this;
746 };
747
748
749 cloudeebus.ProxyObject.prototype.getInterface = function(ifName) {
750         return this.interfaceProxies[ifName];
751 };
752
753
754 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
755         
756         var self = this; 
757
758         function getAllPropertiesSuccessCB(props) {
759                 var ifProxy = self.interfaceProxies[self.propInterfaces[self.propInterfaces.length-1]];
760                 for (var prop in props)
761                         ifProxy[prop] = self[prop] = props[prop];
762                 getAllPropertiesNextInterfaceCB();
763         }
764         
765         function getAllPropertiesNextInterfaceCB() {
766                 self.propInterfaces.pop();
767                 if (self.propInterfaces.length > 0) 
768                         self.callMethod("org.freedesktop.DBus.Properties", 
769                                 "GetAll", 
770                                 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB, 
771                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
772                 else {
773                         self.propInterfaces = null;
774                         if (successCB)
775                                 successCB(self);
776                 }
777         }
778         
779         function introspectSuccessCB(str) {
780                 var parser = new DOMParser();
781                 var xmlDoc = parser.parseFromString(str, "text/xml");
782                 var interfaces = xmlDoc.getElementsByTagName("interface");
783                 self.propInterfaces = [];
784                 var supportDBusProperties = false;
785                 for (var i=0; i < interfaces.length; i++) {
786                         var ifName = interfaces[i].attributes.getNamedItem("name").value;
787                         self.interfaceProxies[ifName] = new cloudeebus.ProxyObject(self.wampSession, self.busConnection, self.busName, self.objectPath);
788                         if (ifName == "org.freedesktop.DBus.Properties")
789                                 supportDBusProperties = true;
790                         var hasProperties = false;
791                         var ifChild = interfaces[i].firstChild;
792                         while (ifChild) {
793                                 if (ifChild.nodeName == "method") {
794                                         var nArgs = 0;
795                                         var signature = "";
796                                         var metChild = ifChild.firstChild;
797                                         while (metChild) {
798                                                 if (metChild.nodeName == "arg" &&
799                                                         metChild.attributes.getNamedItem("direction").value == "in") {
800                                                                 signature += metChild.attributes.getNamedItem("type").value;
801                                                                 nArgs++;
802                                                 }
803                                                 metChild = metChild.nextSibling;
804                                         }
805                                         var metName = ifChild.attributes.getNamedItem("name").value;
806                                         if (!self[metName])
807                                                 self._addMethod(ifName, metName, nArgs, signature);
808                                         self.interfaceProxies[ifName]._addMethod(ifName, metName, nArgs, signature);
809                                 }
810                                 else if (ifChild.nodeName == "property") {
811                                         if (!hasProperties)
812                                                 self.propInterfaces.push(ifName);
813                                         hasProperties = true;
814                                 }
815                                 ifChild = ifChild.nextSibling;
816                         }
817                 }
818                 if (supportDBusProperties && self.propInterfaces.length > 0) {
819                         self.callMethod("org.freedesktop.DBus.Properties", 
820                                 "GetAll", 
821                                 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB, 
822                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
823                 }
824                 else {
825                         self.propInterfaces = null;
826                         if (successCB)
827                                 successCB(self);
828                 }
829         }
830
831         // call Introspect on self
832         self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", []).then(introspectSuccessCB, errorCB);
833 };
834
835
836 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs, signature) {
837
838         var self = this;
839         
840         self[method] = function() {
841                 var args = [];
842                 for (var i=0; i < nArgs; i++ )
843                         args.push(arguments[i]);
844                 return self.callMethod(ifName, method, args, signature);
845         };      
846 };
847
848
849 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, signature) {
850         
851         var self = this;
852         
853         var promise = new cloudeebus.Promise(function (resolver) {
854                 function callMethodSuccessCB(str) {
855                         try { // calling dbus hook object function for un-translated types
856                                 var result = eval(str);
857                                 resolver.fulfill(result[0], true);
858                         }
859                         catch (e) {
860                                 cloudeebus.log("Method callback exception: " + e);
861                                 resolver.reject(e, true);
862                         }
863                 }
864
865                 function callMethodErrorCB(error) {
866                         cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + cloudeebus.getError(error));
867                         resolver.reject(cloudeebus.getError(error), true);
868                 }
869
870                 var arglist = [
871                         self.busConnection.name,
872                         self.busName,
873                         self.objectPath,
874                         ifName,
875                         method,
876                         JSON.stringify(args)
877                 ];
878
879                 // call dbusSend with bus type, destination, object, message and arguments
880                 self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
881         });
882         
883         return promise;
884 };
885
886
887 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, handlerCB, errorCB) {
888         
889         var self = this; 
890
891         function signalHandler(id, data) {
892                 if (handlerCB) {
893                         try { // calling dbus hook object function for un-translated types
894                                 handlerCB.apply(self, eval(data));
895                         }
896                         catch (e) {
897                                 cloudeebus.log("Signal handler exception: " + e);
898                                 if (errorCB)
899                                         errorCB(e);
900                         }
901                 }
902         }
903         
904         function connectToSignalSuccessCB(str) {
905                 try {
906                         self.wampSession.subscribe(str, signalHandler);
907                 }
908                 catch (e) {
909                         cloudeebus.log("Subscribe error: " + e);
910                 }
911         }
912
913         function connectToSignalErrorCB(error) {
914                 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + cloudeebus.getError(error));
915                 if (errorCB)
916                         errorCB(cloudeebus.getError(error));
917         }
918
919         var arglist = [
920                 self.busConnection.name,
921                 self.busName,
922                 self.objectPath,
923                 ifName,
924                 signal
925         ];
926
927         // call dbusSend with bus type, destination, object, message and arguments
928         self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
929 };
930
931
932 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
933         try {
934                 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
935         }
936         catch (e) {
937                 cloudeebus.log("Unsubscribe error: " + e);
938         }
939 };