-
Notifications
You must be signed in to change notification settings - Fork 0
/
jabsorb.js
executable file
·1337 lines (1209 loc) · 38.9 KB
/
jabsorb.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* jabsorb - a Java to JavaScript Advanced Object Request Broker
* http://www.jabsorb.org
*
* Copyright 2010 Arthur Blake
* Copyright 2007-2009 The jabsorb team
* Copyright (c) 2005 Michael Clark, Metaparadigm Pte Ltd
* Copyright (c) 2003-2004 Jan-Klaas Kollhof
*
* This code is based on original code from the json-rpc-java library
* which was originally based on Jan-Klaas' JavaScript o lait library
* (jsolait).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Local modifications originally made for dbframe
* (but should be useful everywhere else too!)
*
* 1. Wrap entire library in one big closure to reduce global namespace
* pollution.
* 2. Customize jabsorb/jsonrpc settings:
* JSONRpcClient.max_req_active = 4; (stock value is 1)
* JSONRpcClient.transformDates = true; (stock value is false)
* 3. Check for and use native JSON decoder if available
* 4. Include "cause" exception when throwing an exception
* due to client communication error (CODE_ERR_CLIENT)
* 5. Fixed some (but not all) jslint issues.
*/
/**
* Modifications for nodeJava (a port of jabsorb front end to nodeJs)
* 1. Use exports so that it fits in commonJS framework used by node
* 2. Use driverdan's / node-XMLHttpRequest to emulate browser
* XMLHttpRequest (forked to fix a couple of bugs.)
* (see http://github.com/driverdan/node-XMLHttpRequest)
* 3. Use JSON.parse directly, rather than first testing for it in browser/window object.
* 4. Dispense with cross browser junk and just return new XMLHttpRequest.
* 5. Change alert call to console.log.
*/
// pull in XMLHttpRequest implementation for nodeJS
var XMLHttpRequest = require("./XMLHttpRequest").XMLHttpRequest;
// wrap everything in one big closure to avoid polluting the global namespace...
var JSONRpcClient=(function()
{
var JSONRpcClient;
/* encode a string into JSON format
(created inside a closure to hide "private" vars)
*/
var escapeJSONString = (function()
{
// based on Douglas Crockford's Public Domain JavaScript JSON implementation at
// http://www.json.org/json2.js as of 2008-11-28
var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
return function (string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ?
'"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
};
})();
/**
* Function to convert a JSON String into a true JS object.
* Use browser/native JSON (or json2.js) if it's available--
* otherwise, use eval.
*
* (as of 2009-07-17, IE8 and FF3.5 have native JSON codecs)
*
* @param data a JSON string.
* @return an JS object, parsed from the JSON string.
*/
// browser version:
// var fromJSON = ('JSON' in window)?
// function(data){return JSON.parse(data);} :
// function(data){var x; eval('x='+ data);return x;};
// for node :
var fromJSON = function(data){return JSON.parse(data);};
/**
* Marshall an object to JSON format.
* Circular references can be handled if the client parameter
* JSONRpcClient.fixupCircRefs is true. If this parameter is false,
* an exception will be thrown if a circular reference is detected.
*
* if the client parameter, JSONRpcClient.fixupDuplicates is true then
* duplicate objects in the object graph are also combined except for Strings
*
* (todo: it wouldn't be too hard to optimize strings as well, but probably a threshold
* should be provided, so that only strings over a certain length would be optimized)
* this would be worth doing on the upload (on the download it's not so important, because
* gzip handles this)
* if it's false, then duplicate objects are "re-serialized"
*
* @param o the object being converted to json
*
* @return an object, { 'json': jsonString, 'fixups': fixupString } or
* just { 'json' : jsonString } if there were no fixups found.
*/
function toJSON(o)
{
// to detect circular references and duplicate objects, each object has a special marker
// added to it as we go along.
// therefore we know if the object is either a duplicate or circular ref if the object
// already has this marker in it before we process it.
// the marker object itself contains two pointers-- one to the last object processed
// and another to the parent object
// therefore we can rapidly detect if an object is a circular reference
// by following the chain of parent pointer objects to see if we find the same object again.
// if we don't find the same object again in the parent recursively, then we know that it's a
// duplicate instead of a circular reference
// the pointer to the last object processed is used to link all processed objects together
// so that the marker objects can be removed when the operation is complete
// once all objects are processed, we can traverse the linked list, removing all the markers
// the special name for the marker object
// try to pick a name that would never be used for any other purpose, so
// it won't conflict with anything else
var marker="$_$jabsorbed$813492";
// the head of the marker object chain
var markerHead;
// fixups detected as we go along, both for circular references and duplicates
var fixups = [];
// unlink the whole chain of marker objects that were added to objects when processing
function removeMarkers()
{
var next;
while (markerHead)
{
next = markerHead[marker].prev;
delete markerHead[marker];
markerHead = next;
}
}
// special object used to indicate that an object should be omitted
// because it was found to be a circular reference or duplicate
var omitCircRefOrDuplicate = {};
// temp variable to hold json while processing
var json;
/**
* Do the work of converting an individual "sub" object to JSON.
* Each object that is processed has a special marker object attached to it,
* to quickly detect if it has already been processed and thus handle
* circular references and duplicates.
*
* @param o object being converted into JSON.
*
* @param p the parent of the object being processed, it should be null or
* undefined if it's the root object.
*
* @param ref the "reference" of the object in the parent that is being
* converted such that p[ref] === o.
*
* @return A string containing the JSON representation of the object o, but
* with duplicates and circular references removed (according to the
* option settings JSONRpcClient.fixupCircRefs and
* JSONRpcClient.fixupDuplicates.
*/
function subObjToJSON(o,p,ref)
{
var v = [],
// list of references to get to the fixup entry
fixup,
// list of reference to get to the original location
original,
parent,
circRef,
i;
if (o === null || o === undefined)
{
return "null"; // it's null or undefined, so serialize it as null
}
else if (typeof o === 'string')
{
//todo: handle duplicate strings! but only if they are over a certain threshold size...
return escapeJSONString(o);
}
else if (typeof o === 'number')
{
return o.toString();
}
else if (typeof o === 'boolean')
{
return o.toString();
}
else
{
// must be an object type
// look for an already existing marker which would mean this object has already been processed
// at least once and therefore either a circular ref or dup has been found!!
if (o[marker])
{
// determine if it's a circular reference
fixup = [ref];
parent = p;
// walk up the parent chain till we find null
while (parent)
{
// if a circular reference was found somewhere along the way,
// calculate the path to it as we are going
if (original)
{
original.unshift (parent[marker].ref);
}
// if we find ourself, then we found a circular reference!
if (parent===o)
{
circRef=parent;
original = [circRef[marker].ref];
}
fixup.unshift(parent[marker].ref);
parent = parent[marker].parent;
}
// if we found ourselves in the parent chain then this is a circular reference
if (circRef)
{
//either save off the circular reference or throw an exception, depending on the client setting
if (JSONRpcClient.fixupCircRefs)
{
// remove last redundant unshifted reference
fixup.shift();
original.shift();
//todo: (LATER) if multiple fixups go to the same original, this could be optimized somewhat
fixups.push([fixup, original]);
return omitCircRefOrDuplicate;
}
else
{
removeMarkers();
throw new Error("circular reference detected!");
}
}
else
{
// otherwise it's a dup!
if (JSONRpcClient.fixupDuplicates)
{
// find the original path of the dup
original = [o[marker].ref];
parent = o[marker].parent;
while (parent)
{
original.unshift(parent[marker].ref);
parent = parent[marker].parent;
}
//todo: (LATER) if multiple fixups go to the same original, this could be optimized somewhat
// remove last redundant unshifted reference
fixup.shift();
original.shift();
fixups.push([fixup, original]);
return omitCircRefOrDuplicate;
}
}
}
else
{
// mark this object as visited/processed and set up the parent link and prev link
o[marker] = {parent:p, prev:markerHead, ref:ref};
// adjust the "marker" head pointer so the prev pointer on the next object processed can be set
markerHead = o;
}
if (o.constructor === Date)
{
if (o.javaClass) // if Date already has a javaClass defined, use that
{
return '{javaClass: "' + o.javaClass + '", time: ' + o.valueOf() + '}';
}
else // otherwise use java.util.Date
{
return '{javaClass: "java.util.Date", time: ' + o.valueOf() + '}';
}
}
else if (o.constructor === Array)
{
for (i = 0; i < o.length; i++)
{
json = subObjToJSON(o[i], o, i);
// if it's a dup/circ ref, put a slot where the object would have been
// otherwise, put the json data here
v.push(json===omitCircRefOrDuplicate?null:json);
}
return "[" + v.join(", ") + "]";
}
else
{
for (var attr in o)
{
if (attr === marker)
{
/* skip */
}
else if (o[attr] === null || o[attr] === undefined)
{
v.push("\"" + attr + "\": null");
}
else if (typeof o[attr] == "function")
{
/* skip */
}
else
{
json = subObjToJSON(o[attr], o, attr);
if (json !== omitCircRefOrDuplicate)
{
v.push(escapeJSONString(attr) + ": " + json);
}
}
}
return "{" + v.join(", ") + "}";
}
}
}
json = subObjToJSON(o, null, "root");
removeMarkers();
// only return the fixups if one or more were found
if (fixups.length)
{
return {json: json, fixups: fixups};
}
else
{
return {json: json};
}
}
/**
* JSONRpcClient constructor
*
* @param callback|methods - the function to call once the rpc list methods has completed.
* if this argument is omitted completely, then the JSONRpcClient
* is constructed synchronously.
* if this argument is an array then it is the list of methods
* that can be invoked on the server (and the server will not
* be queried for that information)
*
* @param serverURL - path to JSONRpcServlet on server.
* @param user
* @param pass
* @param objectID
* @param javaClass
* @param JSONRPCType
*
*/
JSONRpcClient = function()
{
var arg_shift = 0,
req,
methods,
self,
arg0type= (typeof arguments[0]),
doListMethods=true;
//If a call back is being used grab it
if (arg0type === "function")
{
this.readyCB = arguments[0];
arg_shift++;
}
// if it's an array then just do add methods directly
else if (arguments[0] && arg0type === "object" && arguments[0].length)
{
this._addMethods(arguments[0]); // go ahead and add the methods directly
arg_shift++;
doListMethods=false;
}
//The next 3 args are passed to the http request
this.serverURL = arguments[arg_shift];
this.user = arguments[arg_shift + 1];
this.pass = arguments[arg_shift + 2];
this.objectID=0;
if (doListMethods)
{
//Add the listMethods system methods
this._addMethods(["system.listMethods"]);
//Make the call to list the methods
req = JSONRpcClient._makeRequest(this,"system.listMethods", []);
//If a callback was added to the constructor, call it
if(this.readyCB)
{
self = this;
req.cb = function(result, e)
{
if(!e)
{
self._addMethods(result);
}
self.readyCB(result, e);
};
}
if(!this.readyCB)
{
methods = JSONRpcClient._sendRequest(this,req);
this._addMethods(methods);
}
else
{
JSONRpcClient.async_requests.push(req);
JSONRpcClient.kick_async();
}
}
};
/**
* Creates a new callable proxy (reference).
*
* @param objectID The id of the object as determined by the server
* @param javaClass The package+classname of the object
* @return a new callable proxy object
*/
JSONRpcClient.prototype.createCallableProxy=function(objectID,javaClass)
{
var name, cp = {
objectID: objectID,
javaClass:javaClass,
JSONRPCType: 'CallableReference'};
//Then add all the cached methods to it.
for (name in JSONRpcClient.knownClasses[javaClass])
{
//Change the this to the object that will be calling it
cp[name]=JSONRpcClient.bind(
JSONRpcClient.knownClasses[javaClass][name], cp);
}
return cp;
};
//This is a static variable that maps className to a map of functions names to
//calls, ie Map knownClasses<ClassName,Map<FunctionName,Function>>
JSONRpcClient.knownClasses = {};
/* JSONRpcCLient.Exception */
JSONRpcClient.Exception = function (errorObject)
{
var m;
for( var prop in errorObject)
{
if (errorObject.hasOwnProperty(prop))
{
this[prop] = errorObject[prop];
}
}
if (this.trace)
{
m = this.trace.match(/^([^:]*)/);
if (m)
{
this.name = m[0];
}
}
if (!this.name)
{
this.name = "JSONRpcClientException";
}
};
//Error codes that are the same as on the bridge
JSONRpcClient.Exception.CODE_REMOTE_EXCEPTION = 490;
JSONRpcClient.Exception.CODE_ERR_CLIENT = 550;
JSONRpcClient.Exception.CODE_ERR_PARSE = 590;
JSONRpcClient.Exception.CODE_ERR_NOMETHOD = 591;
JSONRpcClient.Exception.CODE_ERR_UNMARSHALL = 592;
JSONRpcClient.Exception.CODE_ERR_MARSHALL = 593;
JSONRpcClient.Exception.prototype = new Error();
JSONRpcClient.Exception.prototype.toString = function (code, msg)
{
var str="";
if(this.name)
{
str+=this.name;
}
if(this.message)
{
str+=": "+this.message;
}
if(str.length===0)
{
str="no exception information given";
}
return str;
};
/* Default top level exception handler */
JSONRpcClient.default_ex_handler = function (e)
{
// unhandled exception thrown in jsonrpc handler
var a,str="";
for(a in e)
{
str += a + "\t" + e[a] + "\n";
}
//alert(str);
console.log(str);
};
/* Client settable variables */
JSONRpcClient.toplevel_ex_handler = JSONRpcClient.default_ex_handler;
JSONRpcClient.profile_async = false;
JSONRpcClient.max_req_active = 4;
JSONRpcClient.requestId = 1;
// if this is true, circular references in the object graph are fixed up
// if this is false, circular references cause an exception to be thrown
JSONRpcClient.fixupCircRefs = true;
// if this is true, duplicate objects in the object graph are optimized
// if it's false, then duplicate objects are "re-serialized"
JSONRpcClient.fixupDuplicates = true;
/**
* If true, java Date objects are automatically unmarshalled to JS Date objects.
*/
JSONRpcClient.transformDates = true;
/**
* If true, and JSONRpcClient.transformDates is also true, then objects that
* have the single property "time" (even if no javaClass hint is defined)
* will also be transformed into JS date objects.
*/
JSONRpcClient.transformDateWithoutHint = false;
/**
* The types of java Date classes to transform into JS Dates if JSONRpcClient.transformDates is true
*/
JSONRpcClient.javaDateClasses = {
'java.util.Date' :true,
'java.sql.Date' :true,
'java.sql.Time' :true,
'java.sql.Timestamp':true};
/**
* Used to bind the this of the serverMethodCaller() (see below) which is to be
* bound to the right object. This is needed as the serverMethodCaller is
* called only once in createMethod and is then assigned to multiple
* CallableReferences are created.
*/
JSONRpcClient.bind=function(fn, context)
{
return function() {
return fn.apply(context, arguments);
};
};
/*
* This creates a method that points to the serverMethodCaller and binds it
* with the correct methodName.
*/
JSONRpcClient._createMethod = function (client,methodName)
{
//This function is what the user calls.
//This function uses a closure on methodName to ensure that the function
//always has the same name, but can take different arguments each call.
//Each time it is added to an object this should be set with bind()
var serverMethodCaller= function()
{
var args = [],
callback;
for (var i = 0; i < arguments.length; i++)
{
args.push(arguments[i]);
}
if (typeof args[0] == "function")
{
callback = args.shift();
}
var req = JSONRpcClient._makeRequest(this, methodName, args, this.objectID,callback);
if (!callback)
{
return JSONRpcClient._sendRequest(client, req);
}
else
{
//when there is a callback, add the req to the list
JSONRpcClient.async_requests.push(req);
JSONRpcClient.kick_async();
return req.requestId;
}
};
return serverMethodCaller;
};
/**
* Creates a new object from the bridge. A callback may optionally be given as
* the first argument to make this an async call.
*
* @param callback (optional)
* @param constructorName The name of the class to create, which should be
* registered with JSONRPCBridge.registerClass()
* @param _args The arguments the constructor takes
* @return the new object if sync, the request id if async.
*/
JSONRpcClient.prototype.createObject = function ()
{
var args = [],
callback = null,
constructorName,
_args,
req;
for(var i=0;i<arguments.length;i++)
{
args.push(arguments[i]);
}
if(typeof args[0] == "function")
{
callback = args.shift();
}
constructorName=args[0]+".$constructor";
_args=args[1];
req = JSONRpcClient._makeRequest(this, constructorName, _args, 0,callback);
if(callback === null)
{
return JSONRpcClient._sendRequest(this, req);
}
else
{
JSONRpcClient.async_requests.push(req);
JSONRpcClient.kick_async();
return req.requestId;
}
};
JSONRpcClient.CALLABLE_REFERENCE_METHOD_PREFIX = ".ref";
/**
* This is used to add a list of methods to this.
* @param methodNames a list containing the names of the methods to add
* @param dontAdd If this is set, methods wont actually added
* @return the methods that were created
*/
JSONRpcClient.prototype._addMethods = function (methodNames,dontAdd)
{
var name,
obj,
names,
n,
method,
methods=[],
javaClass,
startIndex,
endIndex;
//Aha! It is a class, so create a entry for it.
//This shouldn't get called twice on the same class so we can happily
//overwrite it
//if(javaClass){
// JSONRpcClient.knownClasses[javaClass]={};
//}
for (var i = 0; i < methodNames.length; i++)
{
obj = this;
names = methodNames[i].split(".");
startIndex=methodNames[i].indexOf("[");
endIndex=methodNames[i].indexOf("]");
if((methodNames[i].substring(0,
JSONRpcClient.CALLABLE_REFERENCE_METHOD_PREFIX.length)===
JSONRpcClient.CALLABLE_REFERENCE_METHOD_PREFIX) &&
(startIndex!=-1)&&(endIndex!=-1)&&(startIndex<endIndex))
{
javaClass=methodNames[i].substring(startIndex+1,endIndex);
}
else
{
//Create intervening objects in the path to the method name.
//For example with the method name "system.listMethods", we first
//create a new object called "system" and then add the "listMethod"
//function to that object.
for (n = 0; n < names.length - 1; n++)
{
name = names[n];
if (obj[name])
{
obj = obj[name];
}
else
{
obj[name] = {};
obj = obj[name];
}
}
}
//The last part of the name is the actual functionName
name = names[names.length - 1];
//Create the method
if(javaClass)
{
method = JSONRpcClient._createMethod(this,name);
if(!JSONRpcClient.knownClasses[javaClass])
{
JSONRpcClient.knownClasses[javaClass]={};
}
JSONRpcClient.knownClasses[javaClass][name]=method;
}
else
{
method = JSONRpcClient._createMethod(this,methodNames[i]);
//If it doesn't yet exist and it is to be added to this
if ((!obj[name])&&(!dontAdd))
{
obj[name]=JSONRpcClient.bind(method,this);
}
//maintain a list of all methods created so that methods[i]==methodNames[i]
methods.push(method);
}
javaClass=null;
}
return methods;
};
JSONRpcClient._getCharsetFromHeaders = function (http)
{
var contentType,
parts,
i;
try
{
contentType = http.getResponseHeader("Content-type");
parts = contentType.split(/\s*;\s*/);
for (i = 0; i < parts.length; i++)
{
if (parts[i].substring(0, 8) == "charset=")
{
return parts[i].substring(8, parts[i].length);
}
}
}
catch (e)
{
}
return "UTF-8"; // default
};
/* Async queue globals */
JSONRpcClient.async_requests = [];
JSONRpcClient.async_inflight = {};
JSONRpcClient.async_responses = [];
JSONRpcClient.async_timeout = null;
JSONRpcClient.num_req_active = 0;
JSONRpcClient._async_handler = function ()
{
var res,
req;
JSONRpcClient.async_timeout = null;
while (JSONRpcClient.async_responses.length > 0)
{
res = JSONRpcClient.async_responses.shift();
if (res.canceled)
{
continue;
}
if (res.profile)
{
res.profile.dispatch = new Date();
}
try
{
res.cb(res.result, res.ex, res.profile);
}
catch(e)
{
JSONRpcClient.toplevel_ex_handler(e);
}
}
while (JSONRpcClient.async_requests.length > 0 &&
JSONRpcClient.num_req_active < JSONRpcClient.max_req_active)
{
req = JSONRpcClient.async_requests.shift();
if (req.canceled)
{
continue;
}
JSONRpcClient._sendRequest(req.client, req);
}
};
JSONRpcClient.kick_async = function ()
{
if (!JSONRpcClient.async_timeout)
{
JSONRpcClient.async_timeout = setTimeout(JSONRpcClient._async_handler, 0);
}
};
JSONRpcClient.cancelRequest = function (requestId)
{
/* If it is in flight then mark it as canceled in the inflight map
and the XMLHttpRequest callback will discard the reply. */
if (JSONRpcClient.async_inflight[requestId])
{
JSONRpcClient.async_inflight[requestId].canceled = true;
return true;
}
var i;
/* If its not in flight yet then we can just mark it as canceled in
the the request queue and it will get discarded before being sent. */
for (i in JSONRpcClient.async_requests)
{
if (JSONRpcClient.async_requests[i].requestId == requestId)
{
JSONRpcClient.async_requests[i].canceled = true;
return true;
}
}
/* It may have returned from the network and be waiting for its callback
to be dispatched, so mark it as canceled in the response queue
and the response will get discarded before calling the callback. */
for (i in JSONRpcClient.async_responses)
{
if (JSONRpcClient.async_responses[i].requestId == requestId)
{
JSONRpcClient.async_responses[i].canceled = true;
return true;
}
}
return false;
};
JSONRpcClient._makeRequest = function (client,methodName, args,objectID,cb)
{
var req = {};
req.client = client;
req.requestId = JSONRpcClient.requestId++;
var obj = "{id:"+req.requestId+",method:";
if ((objectID)&&(objectID>0))
{
obj += "\".obj[" + objectID + "]." + methodName +"\"";
}
else
{
obj += "\"" + methodName + "\"";
}
//TODO: i dont think this if works
if (cb)
{
req.cb = cb;
}
if (JSONRpcClient.profile_async)
{
req.profile = {submit: new Date() };
}
// use p as an alias for params to save space in the fixups
var j= toJSON(args);
obj += ",params:" + j.json;
// only attach duplicates/fixups if they are found
// this is to provide graceful backwards compatibility to the json-rpc spec.
if (j.fixups)
{
// todo: the call to toJSON here to turn the fixups into json is a bit
// inefficient, since there will never be fixups in the fixups... but
// it saves us from writing some additional code at this point...
obj += ",fixups:" + toJSON(j.fixups).json;
}
req.data = obj + "}";
return req;
};
JSONRpcClient._sendRequest = function (client,req)
{
var http;
if (req.profile)
{
req.profile.start = new Date();
}
/* Get free http object from the pool */
http = JSONRpcClient.poolGetHTTPRequest();
JSONRpcClient.num_req_active++;
/* Send the request */
http.open("POST", client.serverURL, !!req.cb, client.user, client.pass);
/* setRequestHeader is missing in Opera 8 Beta */
try
{
http.setRequestHeader("Content-type", "text/plain");
}
catch(e)
{
}
/* Construct call back if we have one */
if (req.cb)
{
http.onreadystatechange = function()
{
var res;
if (http.readyState == 4)
{
http.onreadystatechange = function ()
{
};
res = {cb: req.cb, result: null, ex: null};
if (req.profile)
{
res.profile = req.profile;
res.profile.end = new Date();
}
else
{
res.profile = false;
}
try
{
res.result = client._handleResponse(http);
}
catch(e)
{
res.ex = e;
}