aboutsummaryrefslogtreecommitdiffstats
path: root/lib/util.js
blob: b019022c881cb8685db6e269f67c3f1df1cdfe0f (plain) (blame)
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
/*global exports: false, require: false */
/*jslint onevar: false */
// Released under the MIT/X11 license
// http://www.opensource.org/licenses/mit-license.php
"use strict";
// ==============================================================
var xhrMod = require("xhr");
var urlMod = require("url");

/**
 * Function for the management of the prototypal inheritace
 * David Flanagan, Javascript: The Definitve Guide,
 * IV. edition, O'Reilly, 2006, p. 168
 * 
 * @param superobject
 * @return new object, it needs new prototype.constructor
 *
 * <pre>
 * function Father(x) {
 *    this.family = x;
 * }
 *
 * function Son(x,w) {
 *    Father.call(this,x);
 *    this.wife = w;
 * }
 * Son.prototype = heir(Father);
 * Son.prototype.constructor = Son;
 * </pre>
 */
exports.heir = function heir(p) {
    function f() {};
    f.prototype = p.prototype;
    return new f();
};


var getBugNo = exports.getBugNo = function getBugNo(url) {
    var re = new RegExp(".*id=([0-9]+).*$");
    var bugNo = null;
    var reResult = re.exec(url);
    if (reResult[1]) {
        bugNo = reResult[1];
    }
    return bugNo;
};

/**
 * Load text from URL
 *
 * @param URL String
 * @param cb_function Function to be called when the download happens with
 * the downloaded body of the HTTP message as the only parameter
 * @param what optional Object argument representing this for this call
 * @return none
 */
var loadText = exports.loadText = function loadText(URL, cb_function, what) {
    if (what === undefined) { // missing optional argument
        what = this;
    }

    var req = new xhrMod.XMLHttpRequest();
    req.open("GET", URL, true);
    req.onreadystatechange = function (aEvt) {
        if (req.readyState === 4) {
            if (req.status === 200) {
                cb_function.call(what, req.responseText);
            } else {
                throw "Getting " + URL + "failed!";
            }
        }
    };
    req.send("");
};

/**
 * Load JSON from URL
 *
 * @param URL String
 * @param cb_function Function to be called when the download happens with
 * the downloaded JSON as the only parameter
 * @param what optional Object argument representing this for this call
 * @return none
 */
exports.loadJSON = function loadJSON(URL, cb_function, what) {
    if (what === undefined) { // missing optional argument
        what = this;
    }

    loadText(URL, function (text) {
        var data = JSON.parse(text);
        cb_function.call(what, data);
    }, what);
};