]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - jssource/src_files/include/jsolait/lib/jsonrpc.js
Release 6.2.1
[Github/sugarcrm.git] / jssource / src_files / include / jsolait / lib / jsonrpc.js
1 /*
2
3 Modification information for LGPL compliance
4
5 r56990 - 2010-06-16 13:05:36 -0700 (Wed, 16 Jun 2010) - kjing - snapshot "Mango" svn branch to a new one for GitHub sync
6
7 r56989 - 2010-06-16 13:01:33 -0700 (Wed, 16 Jun 2010) - kjing - defunt "Mango" svn dev branch before github cutover
8
9 r55980 - 2010-04-19 13:31:28 -0700 (Mon, 19 Apr 2010) - kjing - create Mango (6.1) based on windex
10
11 r51719 - 2009-10-22 10:18:00 -0700 (Thu, 22 Oct 2009) - mitani - Converted to Build 3  tags and updated the build system 
12
13 r51634 - 2009-10-19 13:32:22 -0700 (Mon, 19 Oct 2009) - mitani - Windex is the branch for Sugar Sales 1.0 development
14
15 r50375 - 2009-08-24 18:07:43 -0700 (Mon, 24 Aug 2009) - dwong - branch kobe2 from tokyo r50372
16
17 r42807 - 2008-12-29 11:16:59 -0800 (Mon, 29 Dec 2008) - dwong - Branch from trunk/sugarcrm r42806 to branches/tokyo/sugarcrm
18
19 r21575 - 2007-04-09 16:28:53 -0700 (Mon, 09 Apr 2007) - chris - Bug 12274 - SECURITY: CSRF (cross-site request forgery) fix.
20 Fix back-ported to:
21 Maint 451
22 SecFix 451c
23 Maint 450
24 Portal Maint 450
25 SecFix 421b
26 Touched:
27         ./index.php
28         ./json.php
29         ./json_server.php
30         ./include/jsclass_async.js
31         ./include/jsclass_base.js
32         ./include/javascript/yui/connection.js
33         ./include/jsolait/lib/jsonrpc.js
34         ./include/jsolait/lib/jsonrpclite.js
35         ./include/JSON.js
36         ./include/JSON.php
37         ./modules/Emails/Email.js
38
39 r21544 - 2007-04-09 15:12:37 -0700 (Mon, 09 Apr 2007) - chris - Bug 12274 - SECURITY: CSRF (cross-site request forgery) fix.
40 Touched:
41 include/JSON.js
42 include/javascript/
43 -jsclass_async.js
44 -jsclass_base.js
45 -yui/connection.js
46 include/jsolait/lib/jsonrpc.js
47
48 r6158 - 2005-07-12 12:06:05 -0700 (Tue, 12 Jul 2005) - andrew - Need to pass data.
49
50 r6129 - 2005-07-08 16:42:58 -0700 (Fri, 08 Jul 2005) - julian - Added in-depth error reporting for "Not well formed" error
51
52 r5313 - 2005-05-13 10:01:43 -0700 (Fri, 13 May 2005) - ajay - 1010, this script now uses json.js for decoding.
53
54 r4286 - 2005-04-18 04:04:05 -0700 (Mon, 18 Apr 2005) - robert - scheduler:
55  - finishing up
56
57 r4085 - 2005-04-13 17:30:42 -0700 (Wed, 13 Apr 2005) - robert - adding meeting scheduler and accept/decline
58
59
60 */
61
62 /*
63   Copyright (c) 2003-2004 Jan-Klaas Kollhof
64   
65   This file is part of the JavaScript o lait library(jsolait).
66   
67   jsolait is free software; you can redistribute it and/or modify
68   it under the terms of the GNU Lesser General Public License as published by
69   the Free Software Foundation; either version 2.1 of the License, or
70   (at your option) any later version.
71  
72   This software is distributed in the hope that it will be useful,
73   but WITHOUT ANY WARRANTY; without even the implied warranty of
74   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
75   GNU Lesser General Public License for more details.
76  
77   You should have received a copy of the GNU Lesser General Public License
78   along with this software; if not, write to the Free Software
79   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
80 */
81
82 /**
83     Provides an JSON-RPC imlementation.
84 */
85 Module("jsonrpc", "0.3.2", function(mod){
86     
87     var lang = importModule("lang");
88     var tokens =  lang.tokens;
89     
90     var ObjectBuffer=Class("ObjectBuffer", function(publ, supr){
91         publ.init=function(){
92             this.data="";
93         }
94         publ.getObjects=function(data){
95             this.data += data;
96             var t = new lang.Tokenizer(this.data);
97             var brCnt= 0;
98             var objects = [];
99             var readCnt = 0
100             while(! t.finished()){
101                 var n = t.next();
102                 if(n.type != tokens.ERR){
103                     if(n.value == "{"){
104                         brCnt+=1;
105                     }else if(n.value == "}"){
106                         brCnt-=1;
107                         if(brCnt==0){
108                             var s = this.data.slice(readCnt, n.pos+1);
109                             readCnt += s.length;
110                             objects.push(s);
111                         }
112                     }
113                 }else{
114                     break;
115                 }
116             }
117             this.data = this.data.slice(readCnt);
118             return objects;
119         }
120     })
121     
122     var nameAllowed=function(name){
123         return name.match(/^[a-zA-Z]\w*$/) != null;
124     }
125     
126     var getMethodByName=function(obj, name){
127         try{//to get a method by asking the service
128             obj = obj._getMethodByName(name)
129         }catch(e){
130             var names = name.split(".");
131             for(var i=0;i<names.length;i++){
132                 name = names[i];
133                 if(nameAllowed(name)){
134                     obj = obj[name];
135                 }
136             }
137         }
138         return obj;
139     }
140     
141     var Response=Class("Response", function(publ, supr){
142         publ.init=function(id, result, error){
143             this.id=id;
144             this.result = result;
145             this.error = error;
146         }
147         publ._toJSON=function(){
148             var p = [lang.objToJson(this.id), lang.objToJson(this.result),lang.objToJson(this.error)];
149             return '{"id":' + p[0] + ', "result":' + p[1] + ', "error":' + p[2] + "}";
150         }
151     })
152     
153     var Request=Class("Request", function(publ, supr){
154         publ.init=function(id, method, params){
155             this.id=id;
156             this.method = method;
157             this.params = params;
158 /*
159  var str = '';
160 for(hello in this.params)
161 {
162   str += "var:"+hello+":"+this.params[hello]+":\n";
163 }
164 alert(str);
165 */
166         }
167         publ._toJSON=function(){
168             var p = [lang.objToJson(this.id), lang.objToJson(this.method),lang.objToJson(this.params)];
169             return '{"id":' + p[0] + ', "method":' + p[1] + ', "params":' + p[2] + "}";
170         }
171     })
172     
173     var Notification=Class("Notification", function(publ, supr){
174         publ.init=function(method, params){
175             this.method = method;
176             this.params = params;
177         }
178         publ._toJSON=function(){
179             var p = [lang.objToJson(this.method),lang.objToJson(this.params)];
180             return '{"method":' + p[0] + ', "params":' + p[1] + "}";
181         }
182     })
183     
184     var ResponseHandler=Class("ResponseHandler", function(publ, supr){
185         publ.init=function(callback){
186             this.callback=callback;
187         }
188         publ.handleResponse=function(resp){
189             this.callback(resp.result, resp.error);
190         }
191     })
192     
193     var RPCLib = Class("RPCLib", function(publ, supr){
194         
195     })
196     
197     var BaseConnectionHandler = Class("BaseConnectionHandler",  function(publ, supr){
198         publ.init=function(service){
199             this.service = service;
200             this.jsonParser = new lang.JSONParser();
201             this.jsonParser.addLib(new RPCLib(), "rpc", []);
202             this.respHandlers = [];
203             this.objBuffer = new ObjectBuffer();
204         }
205                 
206         publ.addResponseHandler=function(cb){
207             var id=1;
208             while(this.respHandlers[""+id] ){
209                 id+=1;
210             }
211             id="" + id;
212             this.respHandlers[id] = new ResponseHandler(cb);
213             return id;
214         }
215         
216         publ.send = function(data){
217         }
218         
219         publ.sendNotify = function(name, args){
220             var n = new Notification(name, args);
221             n = this.jsonParser.objToJson(n);
222             this.send(n)
223         }
224         
225         publ.sendRequest = function(name, args, callback){
226             var id = this.addResponseHandler(callback);
227             var r = new Request(id, name, args);
228             r = this.jsonParser.objToJson(r);
229             this.send(r);
230         }
231         
232         publ.sendResponse = function(id, result, error){
233             var r = new Response(id, result, error);
234             r = this.jsonParser.objToJson(r);
235             this.send(r);
236         }
237         
238         publ.handleRequest = function(req){
239             var name = req.method;
240             var params = req.params;
241             var id=req.id;
242             if(this.service[name]){
243                 try{
244                     var rslt = this.service[name].apply(this.service,params);
245                     this.sendResponse(id, rslt, null)
246                 }catch(e){
247                     this.sendResponse(id, null, new ApplicationError("" + e))
248                 }
249             }else{
250                 this.sendResponse(id, null, new MethodNotFound());
251             }
252         }
253         
254         publ.handleNotification = function(notif){
255             if(this.service[notif.method]){
256                 try{
257                     this.service[notif.method].apply(this.service, notif.params);
258                 }catch(e){
259                 }
260             }
261         }
262         
263         publ.handleResponse = function(resp){
264             var id=resp.id;
265             var h = this.respHandlers[id];
266             h.handleResponse(resp)
267             delete this.respHandlers[id]
268         }
269         
270         publ.handleData = function(data){
271             var objs = this.objBuffer.getObjects(data);
272             for(var i=0;i<objs.length;i++){
273                 try{
274                     var obj = this.jsonParser.jsonToObj(objs[i]);
275                 }catch(e){
276                     throw "Not well formed";
277                 }
278                 if(obj.method != null){ 
279                     if(obj.id != null){
280                         this.handleRequest(new Request(obj.id, obj.method, obj.params));
281                     }else{
282                         this.handleNotification(new Notification(obj.method, obj.params));
283                     }
284                 }else if(obj.id != null){
285                      this.handleResponse(new Response(obj.id, obj.result, obj.error));
286                 }else{
287                    throw "Unknown Data";
288                 }
289             }
290         }
291     })
292     
293     var SocketConnectionHandler = Class("SocketConnectionHandler", BaseConnectionHandler, function(publ, supr){
294         publ.init=function(socket, localService){
295             this.socket = socket;
296             socket.addEventListener("connectionData", this, false);
297             supr(this).init( localService);
298         }
299         
300         publ.handleEvent=function(evt){
301             this.handleData(evt.data);
302         }
303         
304         publ.send=function(data){
305             this.socket.send(data);
306         }
307         
308         publ.close=function(data){
309             this.socket.close();
310         }
311     })
312     
313     var HTTPConnectionHandler = Class("HTTPConnectionHandler", BaseConnectionHandler, function(publ, supr){
314         var urllib;
315         publ.request_id = 1;
316         publ.init=function(url, localService){
317             urllib=importModule("urllib");
318             this.url = url;
319             supr(this).init( localService);
320         }
321                 
322         publ.handleData = function(data){
323
324             try{                
325                 var obj = JSON.parse(data);
326             }catch(e){;
327                 throw " Not well formed\n\n" + e + "\n\nResponse from server:\n\n " + data;
328             }
329             if(obj.id != null){
330                 return obj;
331             }else{
332                 throw "Unknown Data (No id property found)";
333             }  
334         }
335         
336         publ.sendRequest = function(name, args, callback){
337             var sync = false;
338             if(typeof callback != "function"){//see if it is sync
339                 args.push(callback); 
340                 sync=true;
341             }
342             var data = new Request(this.request_id++, name, args);
343             // cn: bug 12274 - defend against CSRF
344             data = JSON.stringify(data); // creates security envelope wrapped JSON object
345             
346             if(sync){
347                 var rsp = urllib.postURL(this.url, data, [["Content-Type", "text/plain"]]);
348                 rsp = this.handleData(rsp.responseText);
349                 if(rsp.error){
350                     throw rsp.error;
351                 }else{
352                     return rsp.result;
353                 }
354             }else{//async connection uses the respHandler to handle the repsonse
355                 var self = this;
356                 var request_id = this.request_id;
357                 urllib.postURL(this.url, data, [["Content-Type", "text/plain"]], function(rsp){
358                     try{
359                         rsp = self.handleData(rsp.responseText);
360                     }catch(e){
361                         //callback(null,e);
362                         callback(request_id,null,e);
363                         return;
364                     }
365                     callback(request_id,rsp.result, rsp.error);
366                     //callback(this.request_id,rsp.result, rsp.error);
367                     //callback(rsp.result, rsp.error);
368                 });
369             }
370         }
371         
372         publ.sendNotify = function(name, args){
373             var data = new Notification(name, args);
374             data = this.jsonParser.objToJson(data);
375             urllib.postURL(this.url, data, [["Content-Type", "text/plain"]], function(rsp){});
376         }
377     })
378     
379     var PeerObject=Class("PeerObject", function(publ, supr){
380         publ.init=function(name, conn){
381             var fn=function(){
382                 var args=[];
383                 for(var i=0;i<arguments.length;i++){
384                     args[i] = arguments[i];
385                 }
386                 var cb=args.pop();
387                 return conn.sendRequest(name, args, cb);
388             }
389             return fn;
390         }
391     })
392      
393     var PeerNotifyObject=Class("PeerNotifyObject", function(publ, supr){
394         publ.init=function(name, conn){
395             var fn=function(){
396                 var args=[];
397                 for(var i=0;i<arguments.length;i++){
398                     args[i] = arguments[i];
399                 }
400                 conn.sendNotify(name, args);
401             }
402             return fn;
403         }
404     })
405     
406     var BasePeer = Class("BasePeer", function(publ, supr){
407         publ.init=function(conn, methodNames){
408             this._conn = conn;
409             this.notify = new PeerObject("notify", conn);
410             this._add(methodNames);
411         }
412         
413         var setupPeerMethod=function(root, methodName, conn, MethClass){
414             var names = methodName.split(".");
415             var obj = root;
416             for(var n=0;n<names.length-1;n++){
417                 var name = names[n];
418                 if(obj[name]){
419                     obj = obj[name];
420                 }else{
421                     obj[name] = new Object();
422                     obj = obj[name];
423                 }
424             }
425             var name = names[names.length-1];
426             if(obj[name]){
427             }else{
428                 var mth = new MethClass(methodName, conn);
429                 obj[name] = mth;
430             }
431         }
432         
433         publ._add = function(methodNames){
434             for(var i=0;i<methodNames.length;i++){
435                 setupPeerMethod(this, methodNames[i], this._conn, PeerObject);
436                 setupPeerMethod(this.notify, methodNames[i], this._conn, PeerNotifyObject);
437             }
438         }
439     })
440     
441     
442     mod.ServiceProxy = Class("ServiceProxy", BasePeer, function(publ, supr){
443         publ.init = function(url, methodNames, localService){
444             var n = url.match(/^jsonrpc:\/\/(.*:\d*)$/);
445             if(n!=null){//is it  json-rpc over TCP protocoll 
446                 var hostaddr = n[1];
447                 try{
448                     var socket = createConnection();
449                 }catch(e){
450                     throw "Can't create a socket connection."
451                 }
452                 socket.connect(hostaddr);
453                 supr(this).init( new SocketConnectionHandler(socket, localService), methodNames);
454             }else{//or is it json-rpc over http
455                 this.httpConn = new HTTPConnectionHandler(url, localService);
456                 supr(this).init( this.httpConn, methodNames);
457             }
458         }
459     })
460 })
461  
462