undefined
< show > hide
> hide
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




























































































































































































































































































































































// Borrowed from helma-ng
// Hack till real logger will be available
var log = {
    debug: function(message) { print('filestore | debug | ' + message); },
    error: function(message) { print('filestore | error | ' + message); }
}
var file = require("file");
var JSON = require("json");
//var dir = require("dir");

var Functional = require("./functional");
var bindArguments = Functional.bindArguments;
var bindThisObject = Function.bindThisObject;

var TEXT = 0;
var REFERENCE = 10;
var COLLECTION = 20;
var LIST = 21;

function Text() { return {id: TEXT} };
function Reference(type) {
    if (!type) throw new Error("Missing type argument in Reference()");
    return {id: REFERENCE, type: type};
};
function Collection(type, options) {
    if (!type) throw new Error("Missing type argument in Collection()");
    return { id: COLLECTION, type: type, options: options };
};
function List(type, options) {
    if (!type) throw new Error("Missing type argument in List()");
    return { id: LIST, type: type, options: options };
};
/**
 * File Store class
 * @class
 * @param path the database directory
 */
function Store(path) {

    // the class registry
    var typeRegistry = {};

    // map of type to current id tip
    var idMap = {};

    /**
     * @param constructor a plain JavaScript constructor
     * @param fields container of fields defined for this object type
     */
    this.registerType = function(constructor, fields) {
        if (typeof constructor != "function") {
           throw new Error("registerType() called with non-function argument: " + constructor);
        }
        if (typeof constructor.name != "string") {
           throw new Error("constructor must not be an anonymous function");
        }

        var typeName = constructor.name;

        // install filter, all, and get methods on constructor
        constructor.list = bindArguments(list, typeName);
        constructor.all = bindArguments(getAll, typeName);
        constructor.get = bindArguments(get, typeName);
        constructor.store = this;
        // add class to registry
        typeRegistry[typeName] = constructor;

        function getter(name, def) {
            if (def.id == REFERENCE) {
                var key = this.properties[name];
                if (isKey(key)) {
                    return get(key._type, key._id);
                }
            } else if (def.id == LIST) {
                if (def.options) {
                    return def.type.list(def.options, this);
                } else {
                    return def.type.all();
                }
            }
            return this.properties[name];
        }

        function setter(name, definition, value) {
            if (value == null) {
                delete this.properties[name];
            } else {
                this.properties[name] = value;
            }
        }

        var proto = constructor.prototype;

        for (var [key, field] in fields) {
            proto.__defineSetter__(key, bindArguments(setter, key, field));
            proto.__defineGetter__(key, bindArguments(getter, key, field));
        }

        proto.__defineGetter__("_type", function() { return typeName });

        proto.getKey = function() {
            if (!(typeof this._id == "string")) {
                throw new Error("getKey() called on non-persistent object");
            }
            return {_id: this._id, _type: this._type};
        }

        proto.save = function(txn) {
            save(txn, this);
        };

        proto.remove = function(txn) {
            remove(txn, this);
        };

        proto.toString = function() {
            return typeName + this.properties.toSource();
        };

        proto.equals = function(obj) {
            return this === obj || obj &&
                                   this._type === obj._type &&
                                   this._id == obj._id;
        }
/*  Jack uses Rhino 1.7 release 3 PRERELEASE 2009 04 05
    Which doesn't supports iterators / generators
        proto.__iterator__ = function(namesOnly) {
            for (var i in this.properties) {
                yield namesOnly ? i : [i, this[i]];
            }
            throw StopIteration;
        }
*/
    }

    this.getRegisteredType = function(name) {
        return typeRegistry[name];
    }

    var list = function(type, options, thisObj) {
        var array = getAll(type);
        if (options) {
            // first filter out the the items we're not interested in
            var filter = options.filter;
            if (typeof filter == "function") {
                array = array.filter(filter, thisObj);
            }
            // then put them into order
            var [orderBy, ascDesc] = [options.orderBy, options.order == "desc" ? -1 : 1];
            if (options.orderBy) {
                array = array.sort(function(o1, o2) {
                    var [p1, p2] = [o1[orderBy], o2[orderBy]];
                    if (p1 < p2) return -1 * ascDesc;
                    if (p1 > p2) return  1 * ascDesc;
                    return 0;
                })
            }
            // finally apply pagination/slicing
            var [start, max] = [parseInt(options.start, 10), parseInt(options.max, 10)];
            if (isFinite(start) || isFinite(max)) {
                var start = start || 0;
                array = array.slice(start, start + max || array.length);
            }
        }
        return array;
    };

    var getAll = function(type) {
        var dir = base.join(type);
        if (!file.exists(dir) || !file.isDirectory(dir)) { return []; }
        var entries = file.list(dir);
        var list = [];

        for each (var entry in entries) {
            // dont check if the files are hidden or not
            if (!file.isFile(dir.join(entry))) continue;
            list.push(persister.retrieve(type, dir.join(entry)));
        }
        return list;
    };

    var get = this.get = function(type, id) {
        var dir = base.join(type);
        var path = dir.join(id);

        if (!file.exists(path)) return null;
        else if (!file.isFile(path)) throw new Error("Is not a regular file: " + path);
        return persister.retrieve(type, path);
    }

    var save = function(txn, obj) {
        var wrapTransaction = !txn;
        if (wrapTransaction) txn = new Transaction();
        for (var i in obj.properties) {
            var v = obj.properties[i];
            if (isStorable(v)) {
                if (isTransientStorable(v)) {
                    v.save(txn);
                }
                obj.properties[i] = v.getKey();
            }
        }
        var [type, id] = [obj._type, obj._id];
        var dir = base.join(type);
        if (!file.exists(dir)) {
            try {
                file.mkdirs(dir);
            } catch(e) {
                throw new Error("Can't create directory for type " + type + " : " + dir);
            }
        }
        if (id == undefined) obj._id = id = persister.generateId(type, dir);

        var path = dir.join(id);
        var tempPath = base.join(type + id + "..tmp");

        persister.store(obj.properties, tempPath);

        if (file.exists(path) && !file.isWritable(path))
            throw new Error("No write permission for " + path);

        txn.updateResource({ path: path, tempPath: tempPath });

        if (wrapTransaction) txn.commit();
    };

    var remove = function(txn, obj) {
        var wrapTransaction = !txn;
        if (wrapTransaction) txn = Transaction();
        for (var i in obj) {
            var v = obj[i];
            if (isPersistentStorable(v)) {
                // cascading delete (just to show it works)
                v.remove(txn);
            }
        }
        var [type, id] = [obj._type, obj._id];
        if (!type) throw new Error("type not defined in object " + obj);
        if (!id) throw new Error("id not defined in object " + obj);

        var path = base.join(type).join(id);
        txn.deleteResource({ path: path });

        if (wrapTransaction) txn.commit();
    };

    // the persister
    var persister = {
        store: function(object, path) {
            log.debug("Storing object: " + object.toSource());
            file.write(path, JSON.encode(object), {append: true});
        },
        retrieve: function(type, path) {
            var content = file.read(path);
            // File read is not a string ??
            var properties = JSON.decode(content.toString());
            var ctor = typeRegistry[type];
            if (!ctor) throw new Error("constructor not registered for type " + type);
            var obj = new ctor(properties);
            obj._id = file.basename(path);
            return obj;
        },

        generateId: function(type, dir) {
            var id = idMap[type] || 1;
            var path = dir.join(id.toString(36));
            while(file.exists(path)) {
                id += 1;
                path = dir.join(id.toString(36));
            }

            idMap[type] = id + 1;
            return file.basename(path);
        }
    };

    var base = new file.Path(path).absolute();
    log.debug("Set up new store: " + base);
};

var isKey = function(value) {
    return value
            && !value.getKey
            && typeof value._id == 'string';
}

var isStorable = function(value) {
    return value && typeof value.getKey == 'function';
}

var isPersistentStorable = function(value) {
    return isStorable(value)
            && typeof value._id == 'string';
}

var isTransientStorable = function(value) {
    return isStorable(value)
            && typeof value._id == 'undefined';
}

function Transaction() {
    var updateList = [];
    var deleteList = [];

    this.deleteResource = function(res) {
        deleteList.push(res);
    };

    this.updateResource = function(res) {
        updateList.push(res);
    };

    this.commit = function() {
        for each (var res in updateList) {
            // because of a Java/Windows quirk, we have to delete
            // the existing file before trying to overwrite it
            if (file.exists(res.path)) file.remove(res.path);
            // move temporary file to permanent name
            try {
                // Think it's stupid to convert them to strings
                // Need to report about this bug
                file.move(res.tempPath.valueOf(), res.path.valueOf());
                // success - delete tmp file
                try { file.remove(res.tempPath); } catch(e) {}
            } catch (e) {
                // error - leave tmp file and print a message
                log.error("Couldn't move file, committed version is in " + res.tempPath);
            }
        }

        for each (var res in deleteList) try { file.remove(res); } catch(e) {}

        updateList = [];
        deleteList = [];
    };

    this.abort = function() {
        for each (var res in updateList) file.remove(res.tempPath);
    };
};

exports.Reference = Reference;
exports.Text = Text;
exports.Collection = Collection;
exports.List = List;
exports.Store = Store;
exports.Transaction = Transaction;