summaryrefslogtreecommitdiffstats
path: root/sca-cpp/trunk/modules/js/htdocs/component.js
blob: 3712ee59cb679d97137880acb3e08aeeace0427f (plain)
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.    
 *
 * The JSON-RPC client code is based on Jan-Klaas' JavaScript
 * o lait library (jsolait).
 *
 * $Id: jsonrpc.js,v 1.36.2.3 2006/03/08 15:09:37 mclark Exp $
 *
 * Copyright (c) 2003-2004 Jan-Klaas Kollhof
 * Copyright (c) 2005 Michael Clark, Metaparadigm Pte Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 */

/**
 * Client component wiring API, supporting JSON and ATOM bindings.
 */

var JSONClient = {};

/**
 * Escape a character.
 */
JSONClient.escapeJSONChar = function(c) {
    if(c == "\"" || c == "\\") return "\\" + c;
    if (c == "\b") return "\\b";
    if (c == "\f") return "\\f";
    if (c == "\n") return "\\n";
    if (c == "\r") return "\\r";
    if (c == "\t") return "\\t";
    var hex = c.charCodeAt(0).toString(16);
    if(hex.length == 1) return "\\u000" + hex;
    if(hex.length == 2) return "\\u00" + hex;
    if(hex.length == 3) return "\\u0" + hex;
    return "\\u" + hex;
};

/**
 * Encode a string into JSON format.
 */
JSONClient.escapeJSONString = function(s) {
    // The following should suffice but Safari's regex is broken (doesn't support callback substitutions)
    // return "\"" + s.replace(/([^\u0020-\u007f]|[\\\"])/g, JSONClient.escapeJSONChar) + "\"";

    // Rather inefficient way to do it
    var parts = s.split("");
    for(var i = 0; i < parts.length; i++) {
        var c = parts[i];
        if(c == '"' || c == '\\' || c.charCodeAt(0) < 32 || c.charCodeAt(0) >= 128)
            parts[i] = JSONClient.escapeJSONChar(parts[i]);
    }
    return "\"" + parts.join("") + "\"";
};

/**
 * Marshall objects to JSON format.
 */
JSONClient.toJSON = function(o) {
    if(o == null)
        return "null";
    if(o.constructor == String)
        return JSONClient.escapeJSONString(o);
    if(o.constructor == Number)
        return o.toString();
    if(o.constructor == Boolean)
        return o.toString();
    if(o.constructor == Date)
        return '{javaClass: "java.util.Date", time: ' + o.valueOf() +'}';
    if(o.constructor == Array) {
        var v = [];
        for(var i = 0; i < o.length; i++)
            v.push(JSONClient.toJSON(o[i]));
        return "[" + v.join(", ") + "]";
    }
    var v = [];
    for(attr in o) {
        if(o[attr] == null)
            v.push("\"" + attr + "\": null");
        else if(typeof o[attr] == "function")
            ; // Skip
        else
            v.push(JSONClient.escapeJSONString(attr) + ": " + JSONClient.toJSON(o[attr]));
    }
    return "{" + v.join(", ") + "}";
};

/**
 * Construct an HTTPBindingClient.
 */
function HTTPBindingClient(name, uri) {
    this.name = name;
    this.uri = uri;
    this.apply = this.createApplyMethod();
}

/**
 * JSON-RPC request counter.
 */
HTTPBindingClient.jsonrpcID = 1;

/**
 * HTTPBindingClient implementation
 */

/**
 * Generate client proxy apply method.
 */
HTTPBindingClient.prototype.createApplyMethod = function() {
    var fn = function() {
        var methodName = arguments[0];
        var args = [];
        for(var i = 1; i < arguments.length; i++)
            args.push(arguments[i]);

        var cb = null;
        if (typeof args[args.length - 1] == "function")
            cb = args.pop();

        var req = HTTPBindingClient.makeJSONRequest(methodName, args, cb);
        return fn.client.jsonApply(req);
    };
    fn.client = this;
    return fn;
};

/**
 * Make a JSON-RPC request.
 */
HTTPBindingClient.makeJSONRequest = function(methodName, args, cb) {
    var req = {};
    req.id = HTTPBindingClient.jsonrpcID++;
    if (cb)
        req.cb = cb;
    var obj = {};
    obj.id = req.id;
    obj.method = methodName;
    obj.params = args;
    req.data = JSONClient.toJSON(obj);
    return req;
};

/**
 * Return the JSON result from an XMLHttpRequest.
 */
HTTPBindingClient.jsonResult = function(http) {
    // Get the charset
    function httpCharset(http) {
        try {
            var contentType = http.getResponseHeader("Content-type");
            var parts = contentType.split(/\s*;\s*/);
            for (var 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";
    }
    if(!HTTPBindingClient.charset)
        HTTPBindingClient.charset = httpCharset(http);

    // Unmarshall the JSON response
    var obj;
    eval("obj = " + http.responseText);
    if(obj.error)
        throw new HTTPBindingClient.Exception(obj.error.code, obj.error.msg);
    var res = obj.result;
    return res;
};

/**
 * Apply a function remotely using JSON-RPC.
 */
HTTPBindingClient.prototype.jsonApply = function(req) {
    // Connect to the service
    var http = HTTPBindingClient.getHTTPRequest();
    var hascb = req.cb? true : false;
    http.open("POST", this.uri, hascb);
    http.setRequestHeader("Content-type", "application/json-rpc");

    // Construct call back if we have one
    if(hascb) {
        http.onreadystatechange = function() {
            if(http.readyState == 4) {
                // Pass the result or exception
                if(http.status == 200) {
                    var res = null;
                    try {
                        res = HTTPBindingClient.jsonResult(http);
                    } catch(e) {
                        req.cb(null, e);
                    }
                    req.cb(res);
                } else
                    req.cb(null, HTTPBindingClient.Exception(http.status, http.statusText));
            }
        };

        // Send the request
        http.send(req.data);
        return req.id;
    }

    // Send the request and return the result or exception
    http.send(req.data);
    if (http.status == 200)
        return HTTPBindingClient.jsonResult(http);
    throw new HTTPBindingClient.Exception(http.status, http.statusText);
};

/**
 * REST ATOMPub GET method.
 */
HTTPBindingClient.prototype.get = function(id, cb) {
    // Connect to the service
    var http = HTTPBindingClient.getHTTPRequest();
    var hascb = cb? true : false;
    http.open("GET", this.uri + '/' + id, hascb);

    // Construct call back if we have one
    if (hascb) {
        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                // Pass the result or exception
                if (http.status == 200)
                    cb(http.responseText);
                else
                    cb(null, new HTTPBindingClient.Exception(http.status, http.statusText));
            }
        };

        // Send the request
        http.send(null);
        return true;
    }

    // Send the request and return the result or exception
    http.send(null);
    if (http.status == 200)
        return http.responseText;
    throw new HTTPBindingClient.Exception(http.status, http.statusText);
};

/**
 * REST ATOMPub POST method.
 */
HTTPBindingClient.prototype.post = function (entry, cb) {
    // Connect to the service
    var http = HTTPBindingClient.getHTTPRequest();
    var hascb = cb? true : false;
    http.open("POST", this.uri, hascb);
    http.setRequestHeader("Content-Type", "application/atom+xml");

    // Construct call back if we have one
    if (hascb) {
        http.onreadystatechange = function() {
            // Pass the result or exception
            if (http.readyState == 4) {
                if (http.status == 201)
                    cb(http.responseText);
                else
                    cb(null, new HTTPBindingClient.Exception(http.status, http.statusText));
            }
        };
        // Send the request
        http.send(entry);
        return true;
    }

    // Send the request and return the result or exception
    http.send(entry);
    if (http.status == 201)
        return http.responseText;
    throw new HTTPBindingClient.Exception(http.status, http.statusText);
};

/**
 * REST ATOMPub PUT method.
 */
HTTPBindingClient.prototype.put = function (id, entry, cb) {
    // Connect to the service
    var http = HTTPBindingClient.getHTTPRequest();
    var hascb = cb? true : false;
    http.open("PUT", this.uri + '/' + id, hascb);
    http.setRequestHeader("Content-Type", "application/atom+xml");

    // Construct call back if we have one
    if (hascb) {
        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                // Pass any exception
                if (http.status == 200)
                    cb();
                else
                    cb(new HTTPBindingClient.Exception(http.status, http.statusText));
            }
        };
        // Send the request
        http.send(entry);
        return true;
    }

    // Send the request and return any exception
    http.send(entry);
    if (http.status == 200)
        return true;
    throw new HTTPBindingClient.Exception(http.status, http.statusText);
};

/**
 * REST ATOMPub DELETE method.
 */
HTTPBindingClient.prototype.del = function (id, cb) {       
    // Connect to the service
    var http = HTTPBindingClient.getHTTPRequest();
    var hascb = cb? true : false;
    http.open("DELETE", this.uri + '/' + id, hascb);        

    // Construct call back if we have one
    if (cb) {
        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                // Pass any exception
                if (http.status == 200)
                    cb();
                else
                    cb(new HTTPBindingClient.Exception(http.status, http.statusText));
            }
        };
        // Send the request
        http.send(null);
        return true;
    }

    // Send the request and return any exception
    http.send(null);
    if (http.status == 200)
        return true;
    throw new HTTPBindingClient.Exception(http.status, http.statusText);
};

/**
 * HTTPBindingClient exceptions.
 */
HTTPBindingClient.Exception = function(code, message) {
    this.name = "HTTPBindingClientException";
    this.code = code;
    this.message = message;
};

HTTPBindingClient.Exception.prototype = new Error();

HTTPBindingClient.Exception.prototype.toString = function() {
    return this.name + ": " + this.message;
};

/**
 * XMLHttpRequest wrapper.
 */
HTTPBindingClient.msxmlNames = [ "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];

HTTPBindingClient.getHTTPRequest = function() {
    if (HTTPBindingClient.httpFactory)
        return HTTPBindingClient.httpFactory();

    // Mozilla XMLHttpRequest
    try {
        HTTPBindingClient.httpFactory = function() {
            return new XMLHttpRequest();
        };
        return HTTPBindingClient.httpFactory();
    } catch(e) {}

    // Microsoft MSXML ActiveX
    for (var i = 0; i < HTTPBindingClient.msxmlNames.length; i++) {
        try {
            HTTPBindingClient.httpFactory = function() {
                return new ActiveXObject(HTTPBindingClient.msxmlNames[i]);
            };
            return HTTPBindingClient.httpFactory();
        } catch (e) {}
    }

    // Can't create XMLHttpRequest
    HTTPBindingClient.httpFactory = null;
    throw new HTTPBindingClient.Exception(0, "Can't create XMLHttpRequest object");
};

/**
 * Public API.
 */

var sca = {};

/**
 * Return an HTTP client proxy.
 */
sca.httpclient = function(name, uri) {
    return new HTTPBindingClient(name, uri);
};

/**
 * Return a component proxy.
 */
sca.component = function(name) {
    return new HTTPBindingClient(name, '/components/' + name);
};

/**
 * Return a reference proxy.
 */
sca.reference = function(comp, rname) {
    return new HTTPBindingClient(comp.name + '/' + rname, "/references/" + comp.name + "/" + rname);
};

/**
 * Add proxy functions to a reference proxy.
 */
sca.defun = function(ref) {
    function defapply(name) {
        return function() {
            var args = new Array();
            args[0] = name;
            for (i = 0, n = arguments.length; i < n; i++)
                args[i + 1] = arguments[i];
            return this.apply.apply(this, args);
        };
    }

    for (f = 1; f < arguments.length; f++) {
        var fn = arguments[f];
        ref[fn]= defapply(fn);
    }
    return ref;
};