<commit_before>(function() {
    load("classpath:internals.js");
    //this === global;
    var global = this;
    var oldP = global.P;
    global.P = {};
    Object.defineProperty(global.P, "restore", {
        value: function() {
            var ns = global.P;
            global.P = oldP;
            return ns;
        }
    });
    /*
     global.P = this; // global scope of api - for legacy applications
     global.P.restore = function() {
     throw "Legacy api can't restore the global namespace.";
     };
     */

    // core imports
    var ExecutorsClass = Java.type("java.util.concurrent.Executors");
    var Lock = Java.type("java.util.concurrent.locks.ReentrantLock");
    var EngineUtilsClass = Java.type("jdk.nashorn.api.scripting.ScriptUtils");
    var JavaArrayClass = Java.type("java.lang.Object[]");
    var JavaCollectionClass = Java.type("java.util.Collection");
    var FileClass = Java.type("java.io.File");
    var JavaDateClass = Java.type("java.util.Date");
    var LoggerClass = Java.type("java.util.logging.Logger");
    var RowClass = Java.type("com.bearsoft.rowset.Row");
    var FieldsClass = Java.type("com.bearsoft.rowset.metadata.Fields");
    var ParamsClass = Java.type("com.bearsoft.rowset.metadata.Parameters");
    var IDGeneratorClass = Java.type("com.bearsoft.rowset.utils.IDGenerator");
    var RowsetJSAdapterClass = Java.type("com.bearsoft.rowset.events.RowsetJSAdapter");
    var RowsComparatorClass = Java.type("com.bearsoft.rowset.sorting.RowsComparator");
    var ScriptTimerTaskClass = Java.type("com.eas.client.scripts.ScriptTimerTask");
    var ScriptedResourceClass = Java.type("com.eas.client.scripts.PlatypusScriptedResource");
    var DeamonThreadFactoryClass = Java.type("com.eas.concurrent.DeamonThreadFactory");
    var ScriptUtilsClass = Java.type('com.eas.script.ScriptUtils');
    var FileUtilsClass = Java.type("com.eas.util.FileUtils");
    var MD5GeneratorClass = Java.type("com.eas.client.login.MD5Generator");
    var TemplateLoaderClass = Java.type('com.eas.client.reports.store.Dom2ReportDocument');
    var ModelLoaderClass = Java.type('com.eas.client.scripts.store.Dom2ModelDocument');
    var TwoTierModelClass = Java.type('com.eas.client.model.application.ApplicationDbModel');
    var ThreeTierModelClass = Java.type('com.eas.client.model.application.ApplicationPlatypusModel');
    var CreateRequestClass = Java.type('com.eas.client.threetier.requests.CreateServerModuleRequest');
    // gui imports
    var KeyEventClass = Java.type("java.awt.event.KeyEvent");
    var SwingUtilitiesClass = Java.type("javax.swing.SwingUtilities");
    var FileChooserClass = Java.type("javax.swing.JFileChooser");
    var ColorChooserClass = Java.type("javax.swing.JColorChooser");
    var OptionPaneClass = Java.type("javax.swing.JOptionPane");
    try {
        var ColorClass = Java.type("com.eas.gui.ScriptColor");
        var FormClass = Java.type("com.eas.client.forms.Form");
        var FormLoaderClass = Java.type('com.eas.client.forms.store.Dom2FormDocument');
        var IconResourcesClass = Java.type("com.eas.client.forms.IconResources");
        var HorizontalPositionClass = Java.type("com.eas.client.forms.api.HorizontalPosition");
        var VerticalPositionClass = Java.type("com.eas.client.forms.api.VerticalPosition");
        var OrientationClass = Java.type("com.eas.client.forms.api.Orientation");
    } catch (e) {
        //GUI API could not load in server
    }

    //
    Object.defineProperty(P, "HTML5", {value: "HTML5 client"});
    Object.defineProperty(P, "J2SE", {value: "Java SE client/server environment"});
    Object.defineProperty(P, "agent", {value: P.J2SE});
    /** 
     * invokeLater - invokes given function in AWT event thread
     */
    Function.prototype.invokeLater = function() {
        var func = this;
        var args = arguments;
        SwingUtilitiesClass.invokeLater(function() {
            func.apply(func, args);
        });
    };
    /** 
     * Thread - schedules given function in the pool thread
     */
    Function.prototype.invokeDelayed = function() {
        var func = this;
        var args = arguments;
        if (!args || !args.length || args.length < 1)
            throw "invokeDelayed needs at least 1 argument - timeout value.";
        var userArgs = [];
        for (var i = 1; i < args.length; i++) {
            userArgs.push(args[i]);
        }
        ScriptTimerTaskClass.schedule(function() {
            SwingUtilitiesClass.invokeLater(function() {
                try {
                    func.apply(func, userArgs);
                } catch (e) {
                    P.Logger.severe(e);
                }
            });
        }, args[0]);
        // HTML5 client doesn't support cancel feature and so, we don't support it too.
    };
    var fixedThreadPool = null;
    /** 
     * Thread - schedules given function in the thread pool
     */
    Function.prototype.invokeBackground = function() {
        if (!fixedThreadPool) {
            fixedThreadPool = ExecutorsClass.newFixedThreadPool(10, new DeamonThreadFactoryClass());
        }
        var func = this;
        var args = arguments;
        fixedThreadPool.execute(function() {
            func.apply(func, args);
        });
    };
    /** 
     * Swing invokeAndWait - invokes given function in AWT event thread
     * and waits for it's completion
     */
    Function.prototype.invokeAndWait = function() {
        var func = this;
        var args = arguments;
        SwingUtilitiesClass.invokeAndWait(function() {
            func.apply(func, args);
        });
    };
    load("classpath:deps.js");
    load("classpath:http-context.js");

    /**
     * @static
     * @param {type} deps
     * @param {type} aOnSuccess
     * @param {type} aOnFailure
     * @returns {undefined}
     */
    function require(deps, aOnSuccess, aOnFailure) {
        try {
            if (deps) {
                if (Array.isArray(deps)) {
                    for (var i = 0; i < deps.length; i++) {
                        ScriptedResourceClass.executeScriptResource(deps[i]);
                    }
                } else {
                    ScriptedResourceClass.executeScriptResource(deps);
                }
            }
            if (aOnSuccess) {
                aOnSuccess();
            }
        } catch (e) {
            if (aOnFailure)
                aOnFailure(e);
            else
                throw e;
        }
    }
    Object.defineProperty(P, "require", {value: require});
    function extend(Child, Parent) {
        var prevChildProto = {};
        for (var m in Child.prototype) {
            var member = Child.prototype[m];
            if (typeof member === 'function') {
                prevChildProto[m] = member;
            }
        }
        var F = function() {
        };
        F.prototype = Parent.prototype;
        Child.prototype = new F();
        for (var m in prevChildProto)
            Child.prototype[m] = prevChildProto[m];
        Child.prototype.constructor = Child;
        Child.superclass = Parent.prototype;
    }
    Object.defineProperty(P, "extend", {value: extend});

    var cached = {};
    function getModule(aName) {
        if (!cached[aName]) {
            var c = global[aName];
            if (c) {
                cached[aName] = new c();
            } else {
                ScriptedResourceClass.executeScriptResource(aName);
                c = global[aName];
                if (c) {
                    cached[aName] = new c();
                } else {
                    throw 'No function: ' + aName + ' found while Modules.get(...).';
                }
            }
        }
        return cached[aName];
    }
    ;
    ScriptUtilsClass.setGetModuleFunc(getModule);
    var PModules = {};
    Object.defineProperty(P, "Modules", {
        value: PModules
    });
    Object.defineProperty(PModules, "get", {
        value: getModule
    });

    function objectToInsertIniting(aObject) {
        var jsIniting = [];
        for (var pn in aObject) {
            var pName = pn + '';
            jsIniting[jsIniting.length] = pName;
            jsIniting[jsIniting.length] = aObject[pName];
        }
        var initing = new JavaArrayClass(jsIniting.length);
        for (var v = 0; v < jsIniting.length; v++)
            initing[v] = boxAsJava(jsIniting[v]);
        return initing;
    }

    function BoundArray() {
        BoundArray.superclass.constructor.apply(this, arguments);
        var target = this;
        var rowset = this.unwrap().getRowset();
        var adapter = new RowsetJSAdapterClass();
        rowset.addRowsetListener(adapter);
        adapter.rowsetFiltered = function() {
            Array.prototype.splice.call(target, 0, target.length);
            var rows = rowset.current;
            var publishedRows = [];
            for each (var aRow in rows) {
                publishedRows.push(EngineUtilsClass.unwrap(aRow.getPublished()));
            }
            Array.prototype.push.apply(target, publishedRows);
        };
        adapter.rowsetRequeried = function(event) {
            adapter.rowsetFiltered(null);
        };
        adapter.rowsetNextPageFetched = function(event) {
            adapter.rowsetFiltered(null);
        };
        adapter.rowsetSaved = function(event) {
            // ignore
        };
        adapter.rowsetRolledback = function(event) {
            // ignore
        };
        adapter.rowsetScrolled = function(event) {
            // ignore
        };
        adapter.rowsetSorted = function(event) {
            adapter.rowsetFiltered(null);
        };
        adapter.rowInserted = function(event) {
            if (!event.ajusting)
                adapter.rowsetFiltered(null);
        };
        adapter.rowChanged = function(event) {
            if (event.oldRowCount != event.newRowCount) {
                adapter.rowsetFiltered(null);
            }
        };
        adapter.rowDeleted = function(event) {
            if (!event.ajusting)
                adapter.rowsetFiltered(null);
        };

        Object.defineProperty(target, "fill", {
            value: function() {
                throw '\'fill\' is unsupported in BoundArray because of it\'s distinct values requirement';
            }
        });
        Object.defineProperty(target, "pop", {
            value: function() {
                if (!rowset.empty) {
                    var res = rowset.getRow(rowset.size());
                    rowset.deleteAt(rowset.size(), true);
                    Array.prototype.pop.call(target);
                    return res.getPublished();
                }
            }
        });
        Object.defineProperty(target, "push", {
            value: function() {
                if (arguments.length > 1) {
                    for (var a = 0; a < arguments.length; a++) {
                        rowset.insertAt(rowset.size() + 1, a < arguments.length - 1, objectToInsertIniting(arguments[a]));
                    }
                } else if (arguments.length === 1) {
                    var justInserted = rowset.insertAt(rowset.size() + 1, true, objectToInsertIniting(arguments[0]));
                    Array.prototype.push.call(target, justInserted.getPublished());
                }
                return target.length;
            }
        });
        Object.defineProperty(target, "reverse", {
            value: function() {
                rowset.reverse();
            }
        });
        Object.defineProperty(target, "shift", {
            value: function() {
                if (!rowset.empty) {
                    var res = rowset.getRow(1);
                    rowset.deleteAt(1, true);
                    Array.prototype.shift.call(target);
                    return res.getPublished();
                }
            }
        });
        var defaultCompareFunction = function(o1, o2) {
            var s1 = (o1 + '');
            var s2 = (o2 + '');
            return s1 > s2 ? 1 : s1 < s2 ? -1 : 0;
        };
        Object.defineProperty(target, "sort", {
            value: function() {
                if (arguments.length > 0 && arguments[0] instanceof RowsComparatorClass) {
                    rowset.sort(arguments[0]);
                } else {
                    var compareFunc = defaultCompareFunction;
                    if (arguments.length > 0 && typeof arguments[0] === 'function') {
                        compareFunc = arguments[0];
                    }
                    Array.prototype.sort.call(target, compareFunc);
                }
                return target;
            }
        });
        Object.defineProperty(target, "splice", {
            value: function() {
                if (arguments.length > 0) {
                    var beginToDeleteAt = arguments[0];
                    var howManyToDelete = Number.MAX_VALUE;
                    if (arguments.length > 1) {
                        howManyToDelete = arguments[1];
                    }
                    var needToAdd = arguments.length > 2;
                    var deleted = [];
                    while (!rowset.empty && deleted.length < howManyToDelete) {
                        var rowToDelete = rowset.getRow(beginToDeleteAt + 1);
                        deleted.push(rowToDelete);
                        rowset.deleteAt(beginToDeleteAt + 1, needToAdd);
                    }
                    var insertAt = beginToDeleteAt;
                    for (var a = 2; a < arguments.length; a++) {
                        rowset.insertAt(insertAt + 1, a < arguments.length - 1, objectToInsertIniting(arguments[a]));
                        insertAt++;
                    }
                    return deleted;
                } else {
                    return [];
                }
            }
        });

        Object.defineProperty(target, "unshift", {
            value: function() {
                if (arguments.length > 1) {
                    for (var a = 0; a < arguments.length; a++) {
                        rowset.insertAt(a + 1, a < arguments.length - 1, objectToInsertIniting(arguments[a]));
                    }
                } else if (arguments.length === 1) {
                    var justInserted = rowset.insertAt(1, true, objectToInsertIniting(arguments[0]));
                    Array.prototype.unshift.call(target, justInserted.getPublished());
                }
                return target.length;
            }
        });

        Object.defineProperty(target, "insert", {
            value: function() {
                var initing = new JavaArrayClass(arguments.length);
                for (var v = 0; v < arguments.length; v++)
                    initing[v] = boxAsJava(arguments[v]);
                rowset.insert(initing);
            }
        });

        Object.defineProperty(target, "insertAt", {
            value: function() {
                if (arguments.length > 0) {
                    var index = arguments[0];
                    var initing = new JavaArrayClass(arguments.length - 1);
                    for (var v = 1; v < arguments.length; v++)
                        initing[v - 1] = boxAsJava(arguments[v]);
                    rowset.insertAt(index, false, initing);
                }
            }
        });

        Object.defineProperty(target, "createFilter", {
            value: function() {
                var nEntity = this.unwrap();
                var varargs = new JavaArrayClass(arguments.length);
                for (var v = 0; v < arguments.length; v++)
                    varargs[v] = boxAsJava(arguments[v]);
                return boxAsJs(nEntity.createFilter(varargs));
            }
        });

        Object.defineProperty(target, "createSorting", {
            value: function() {
                var nEntity = this.unwrap();
                var varargs = new JavaArrayClass(arguments.length);
                for (var v = 0; v < arguments.length; v++)
                    varargs[v] = boxAsJava(arguments[v]);
                return boxAsJs(nEntity.createSorting(varargs));
            }
        });

        Object.defineProperty(target, "find", {
            value: function() {
                var nEntity = this.unwrap();
                var varargs = new JavaArrayClass(arguments.length);
                for (var v = 0; v < arguments.length; v++)
                    varargs[v] = boxAsJava(arguments[v]);
                var found = nEntity.find(varargs);
                var res = [];
                for (var f = 0; f < found.size(); f++) {
                    res.push(EngineUtilsClass.unwrap(found[f].getPublished()));
                }
                return res;
            }
        });
    }

    RowClass.setPublisher(function(aDelegate) {
        var nnFields = aDelegate.getFields();
        var instanceCTor = nnFields.getInstanceConstructor();
        var target = !!instanceCTor ? new instanceCTor() : {};
        var nFields = nnFields.toCollection();
        // plain mutable properties
        for (var n = 0; n < nFields.size(); n++) {
            (function() {
                var colIndex = n + 1;
                var nField = nFields[n];
                var valueAccessorDesc = {
                    get: function() {
                        return boxAsJs(aDelegate.getColumnObject(colIndex));
                    },
                    set: function(aValue) {
                        aDelegate.setColumnObject(colIndex, boxAsJava(aValue));
                    }
                };
                Object.defineProperty(target, nField.name, {get: valueAccessorDesc.get, set: valueAccessorDesc.set, enumerable: true});
                Object.defineProperty(target, n, valueAccessorDesc);
            })();
        }
        if (!target.schema)
            Object.defineProperty(target, "schema", {value: nnFields.getPublished()});
        // ORM mutable scalar and readonly collection properties
        var ormDefs = nnFields.getOrmDefinitions();
        for each (var o in ormDefs.keySet()) {
            var def = EngineUtilsClass.unwrap(ormDefs.get(o));
            Object.defineProperty(target, o, def);
        }
        Object.defineProperty(target, "unwrap", {
            value: function() {
                return aDelegate;
            }});
        return target;
        // WARNING!!! Don't define target.length, because of possible conflict with subject area data properties.
    });
    FieldsClass.setPublisher(function(aDelegate) {
        var target = {};
        var nFields = aDelegate.toCollection();
        for (var n = 0; n < nFields.size(); n++) {
            (function() {
                var nField = nFields[n];
                var pField = EngineUtilsClass.unwrap(nField.getPublished());
                Object.defineProperty(target, nField.name, {
                    value: pField
                });
                Object.defineProperty(target, n, {
                    value: pField
                });
            })();
        }
        Object.defineProperty(target, "length", {
            value: nFields.size()
        });
        return target;
    });

    extend(BoundArray, Array);
    extend(P.ApplicationDbEntity, BoundArray);
    extend(P.ApplicationPlatypusEntity, BoundArray);
    extend(P.ApplicationDbParametersEntity, BoundArray);
    extend(P.ApplicationPlatypusParametersEntity, BoundArray);

    P.Filter.prototype.apply = function() {
        var varargs = new JavaArrayClass(arguments.length);
        for (var v = 0; v < arguments.length; v++)
            varargs[v] = boxAsJava(arguments[v]);
        var nFilter = this.unwrap();
        nFilter.apply(varargs);
    };

    /**
     * @static
     * @param {type} aName
     * @param {type} aTarget
     * @returns {P.loadModel.publishTo}
     */
    function loadModel(aName, aTarget) {
        var model = ModelLoaderClass.load(ScriptedResourceClass.getClient(), aName);
        var modelCTor;
        if (model instanceof TwoTierModelClass) {
            modelCTor = P.ApplicationDbModel;
        } else if (model instanceof ThreeTierModelClass) {
            modelCTor = P.ApplicationPlatypusModel;
        } else {
            throw "Can't determine model's type.";
        }
        if (aTarget) {
            modelCTor.call(aTarget, model);
        } else {
            aTarget = new modelCTor(model);
        }
        function publishEntity(nEntity, aName) {
            var published = EngineUtilsClass.unwrap(nEntity.getPublished());
            var paramsSubject = published instanceof P.ApplicationDbParametersEntity
                    || published instanceof P.ApplicationPlatypusParametersEntity;
            var pSchema = {};
            Object.defineProperty(published, "schema", {
                value: pSchema
            });
            var nFields = nEntity.getFields().toCollection();
            for (var n = 0; n < nFields.size(); n++) {
                (function() {
                    var nField = nFields[n];
                    if (paramsSubject) {
                        var valueDesc = {
                            get: function() {
                                return boxAsJs(nField.value);
                            },
                            set: function(aValue) {
                                nField.value = boxAsJava(aValue);
                            }
                        };
                        Object.defineProperty(published, nField.name, valueDesc);
                        Object.defineProperty(published, n, valueDesc);
                    }
                    // schema
                    var schemaDesc = {
                        value: nField.getPublished()
                    };
                    Object.defineProperty(pSchema, nField.name, schemaDesc);
                    Object.defineProperty(pSchema, n, schemaDesc);
                })();
            }
            if (paramsSubject) {
                Object.defineProperty(published, "length", {
                    get: function() {
                        return nFields.size();
                    }
                });
            } else {
                // entity.params.p1 syntax
                var nParameters = nEntity.getQuery().getParameters();
                var ncParameters = nParameters.toCollection();
                var pParams = {};
                for (var p = 0; p < ncParameters.size(); p++) {
                    var nParameter = ncParameters[p];
                    var pDesc = {
                        get: function() {
                            return boxAsJs(nParameter.value);
                        },
                        set: function(aValue) {
                            nParameter.value = boxAsJava(aValue);
                        }
                    };
                    Object.defineProperty(pParams, nParameter.name, pDesc);
                    Object.defineProperty(pParams, p, pDesc);
                }
                Object.defineProperty(pParams, "length", {value: ncParameters.size()});
                Object.defineProperty(published, "params", {value: pParams});
                // entity.params.schema.p1 syntax
                var pParamsSchema = EngineUtilsClass.unwrap(nParameters.getPublished());
                Object.defineProperty(pParams, "schema", {value: pParamsSchema});
            }
            Object.defineProperty(pSchema, "length", {
                get: function() {
                    return nFields.size();
                }
            });
            Object.defineProperty(aTarget, aName, {
                value: published,
                enumerable: true
            });
        }
        var pEntity = model.getParametersEntity();
        publishEntity(pEntity, "params");
        var entities = model.entities();
        for each (var enEntity in entities) {
            enEntity.validateQuery();
            if (enEntity.name) {
                publishEntity(enEntity, enEntity.name);
            }
        }
        model.createORMDefinitions();
        return aTarget;
    }
    Object.defineProperty(P, "loadModel", {value: loadModel});
    /**
     * @static
     * @param {type} aName
     * @param {type} aModel
     * @param {type} aTarget
     * @returns {P.loadForm.publishTo}
     */
    function loadForm(aName, aModel, aTarget) {
        var designInfo = FormLoaderClass.load(ScriptedResourceClass.getClient(), aName);
        var form = new FormClass(aName, designInfo, aModel.unwrap());
        if (aTarget) {<commit_msg>minor fix in P.loadForm<commit_after>(function() {
    load("classpath:internals.js");
    //this === global;
    var global = this;
    var oldP = global.P;
    global.P = {};
    Object.defineProperty(global.P, "restore", {
        value: function() {
            var ns = global.P;
            global.P = oldP;
            return ns;
        }
    });
    /*
     global.P = this; // global scope of api - for legacy applications
     global.P.restore = function() {
     throw "Legacy api can't restore the global namespace.";
     };
     */

    // core imports
    var ExecutorsClass = Java.type("java.util.concurrent.Executors");
    var Lock = Java.type("java.util.concurrent.locks.ReentrantLock");
    var EngineUtilsClass = Java.type("jdk.nashorn.api.scripting.ScriptUtils");
    var JavaArrayClass = Java.type("java.lang.Object[]");
    var JavaCollectionClass = Java.type("java.util.Collection");
    var FileClass = Java.type("java.io.File");
    var JavaDateClass = Java.type("java.util.Date");
    var LoggerClass = Java.type("java.util.logging.Logger");
    var RowClass = Java.type("com.bearsoft.rowset.Row");
    var FieldsClass = Java.type("com.bearsoft.rowset.metadata.Fields");
    var ParamsClass = Java.type("com.bearsoft.rowset.metadata.Parameters");
    var IDGeneratorClass = Java.type("com.bearsoft.rowset.utils.IDGenerator");
    var RowsetJSAdapterClass = Java.type("com.bearsoft.rowset.events.RowsetJSAdapter");
    var RowsComparatorClass = Java.type("com.bearsoft.rowset.sorting.RowsComparator");
    var ScriptTimerTaskClass = Java.type("com.eas.client.scripts.ScriptTimerTask");
    var ScriptedResourceClass = Java.type("com.eas.client.scripts.PlatypusScriptedResource");
    var DeamonThreadFactoryClass = Java.type("com.eas.concurrent.DeamonThreadFactory");
    var ScriptUtilsClass = Java.type('com.eas.script.ScriptUtils');
    var FileUtilsClass = Java.type("com.eas.util.FileUtils");
    var MD5GeneratorClass = Java.type("com.eas.client.login.MD5Generator");
    var TemplateLoaderClass = Java.type('com.eas.client.reports.store.Dom2ReportDocument');
    var ModelLoaderClass = Java.type('com.eas.client.scripts.store.Dom2ModelDocument');
    var TwoTierModelClass = Java.type('com.eas.client.model.application.ApplicationDbModel');
    var ThreeTierModelClass = Java.type('com.eas.client.model.application.ApplicationPlatypusModel');
    var CreateRequestClass = Java.type('com.eas.client.threetier.requests.CreateServerModuleRequest');
    // gui imports
    var KeyEventClass = Java.type("java.awt.event.KeyEvent");
    var SwingUtilitiesClass = Java.type("javax.swing.SwingUtilities");
    var FileChooserClass = Java.type("javax.swing.JFileChooser");
    var ColorChooserClass = Java.type("javax.swing.JColorChooser");
    var OptionPaneClass = Java.type("javax.swing.JOptionPane");
    try {
        var ColorClass = Java.type("com.eas.gui.ScriptColor");
        var FormClass = Java.type("com.eas.client.forms.Form");
        var FormLoaderClass = Java.type('com.eas.client.forms.store.Dom2FormDocument');
        var IconResourcesClass = Java.type("com.eas.client.forms.IconResources");
        var HorizontalPositionClass = Java.type("com.eas.client.forms.api.HorizontalPosition");
        var VerticalPositionClass = Java.type("com.eas.client.forms.api.VerticalPosition");
        var OrientationClass = Java.type("com.eas.client.forms.api.Orientation");
    } catch (e) {
        //GUI API could not load in server
    }

    //
    Object.defineProperty(P, "HTML5", {value: "HTML5 client"});
    Object.defineProperty(P, "J2SE", {value: "Java SE client/server environment"});
    Object.defineProperty(P, "agent", {value: P.J2SE});
    /** 
     * invokeLater - invokes given function in AWT event thread
     */
    Function.prototype.invokeLater = function() {
        var func = this;
        var args = arguments;
        SwingUtilitiesClass.invokeLater(function() {
            func.apply(func, args);
        });
    };
    /** 
     * Thread - schedules given function in the pool thread
     */
    Function.prototype.invokeDelayed = function() {
        var func = this;
        var args = arguments;
        if (!args || !args.length || args.length < 1)
            throw "invokeDelayed needs at least 1 argument - timeout value.";
        var userArgs = [];
        for (var i = 1; i < args.length; i++) {
            userArgs.push(args[i]);
        }
        ScriptTimerTaskClass.schedule(function() {
            SwingUtilitiesClass.invokeLater(function() {
                try {
                    func.apply(func, userArgs);
                } catch (e) {
                    P.Logger.severe(e);
                }
            });
        }, args[0]);
        // HTML5 client doesn't support cancel feature and so, we don't support it too.
    };
    var fixedThreadPool = null;
    /** 
     * Thread - schedules given function in the thread pool
     */
    Function.prototype.invokeBackground = function() {
        if (!fixedThreadPool) {
            fixedThreadPool = ExecutorsClass.newFixedThreadPool(10, new DeamonThreadFactoryClass());
        }
        var func = this;
        var args = arguments;
        fixedThreadPool.execute(function() {
            func.apply(func, args);
        });
    };
    /** 
     * Swing invokeAndWait - invokes given function in AWT event thread
     * and waits for it's completion
     */
    Function.prototype.invokeAndWait = function() {
        var func = this;
        var args = arguments;
        SwingUtilitiesClass.invokeAndWait(function() {
            func.apply(func, args);
        });
    };
    load("classpath:deps.js");
    load("classpath:http-context.js");

    /**
     * @static
     * @param {type} deps
     * @param {type} aOnSuccess
     * @param {type} aOnFailure
     * @returns {undefined}
     */
    function require(deps, aOnSuccess, aOnFailure) {
        try {
            if (deps) {
                if (Array.isArray(deps)) {
                    for (var i = 0; i < deps.length; i++) {
                        ScriptedResourceClass.executeScriptResource(deps[i]);
                    }
                } else {
                    ScriptedResourceClass.executeScriptResource(deps);
                }
            }
            if (aOnSuccess) {
                aOnSuccess();
            }
        } catch (e) {
            if (aOnFailure)
                aOnFailure(e);
            else
                throw e;
        }
    }
    Object.defineProperty(P, "require", {value: require});
    function extend(Child, Parent) {
        var prevChildProto = {};
        for (var m in Child.prototype) {
            var member = Child.prototype[m];
            if (typeof member === 'function') {
                prevChildProto[m] = member;
            }
        }
        var F = function() {
        };
        F.prototype = Parent.prototype;
        Child.prototype = new F();
        for (var m in prevChildProto)
            Child.prototype[m] = prevChildProto[m];
        Child.prototype.constructor = Child;
        Child.superclass = Parent.prototype;
    }
    Object.defineProperty(P, "extend", {value: extend});

    var cached = {};
    function getModule(aName) {
        if (!cached[aName]) {
            var c = global[aName];
            if (c) {
                cached[aName] = new c();
            } else {
                ScriptedResourceClass.executeScriptResource(aName);
                c = global[aName];
                if (c) {
                    cached[aName] = new c();
                } else {
                    throw 'No function: ' + aName + ' found while Modules.get(...).';
                }
            }
        }
        return cached[aName];
    }
    ;
    ScriptUtilsClass.setGetModuleFunc(getModule);
    var PModules = {};
    Object.defineProperty(P, "Modules", {
        value: PModules
    });
    Object.defineProperty(PModules, "get", {
        value: getModule
    });

    function objectToInsertIniting(aObject) {
        var jsIniting = [];
        for (var pn in aObject) {
            var pName = pn + '';
            jsIniting[jsIniting.length] = pName;
            jsIniting[jsIniting.length] = aObject[pName];
        }
        var initing = new JavaArrayClass(jsIniting.length);
        for (var v = 0; v < jsIniting.length; v++)
            initing[v] = boxAsJava(jsIniting[v]);
        return initing;
    }

    function BoundArray() {
        BoundArray.superclass.constructor.apply(this, arguments);
        var target = this;
        var rowset = this.unwrap().getRowset();
        var adapter = new RowsetJSAdapterClass();
        rowset.addRowsetListener(adapter);
        adapter.rowsetFiltered = function() {
            Array.prototype.splice.call(target, 0, target.length);
            var rows = rowset.current;
            var publishedRows = [];
            for each (var aRow in rows) {
                publishedRows.push(EngineUtilsClass.unwrap(aRow.getPublished()));
            }
            Array.prototype.push.apply(target, publishedRows);
        };
        adapter.rowsetRequeried = function(event) {
            adapter.rowsetFiltered(null);
        };
        adapter.rowsetNextPageFetched = function(event) {
            adapter.rowsetFiltered(null);
        };
        adapter.rowsetSaved = function(event) {
            // ignore
        };
        adapter.rowsetRolledback = function(event) {
            // ignore
        };
        adapter.rowsetScrolled = function(event) {
            // ignore
        };
        adapter.rowsetSorted = function(event) {
            adapter.rowsetFiltered(null);
        };
        adapter.rowInserted = function(event) {
            if (!event.ajusting)
                adapter.rowsetFiltered(null);
        };
        adapter.rowChanged = function(event) {
            if (event.oldRowCount != event.newRowCount) {
                adapter.rowsetFiltered(null);
            }
        };
        adapter.rowDeleted = function(event) {
            if (!event.ajusting)
                adapter.rowsetFiltered(null);
        };

        Object.defineProperty(target, "fill", {
            value: function() {
                throw '\'fill\' is unsupported in BoundArray because of it\'s distinct values requirement';
            }
        });
        Object.defineProperty(target, "pop", {
            value: function() {
                if (!rowset.empty) {
                    var res = rowset.getRow(rowset.size());
                    rowset.deleteAt(rowset.size(), true);
                    Array.prototype.pop.call(target);
                    return res.getPublished();
                }
            }
        });
        Object.defineProperty(target, "push", {
            value: function() {
                if (arguments.length > 1) {
                    for (var a = 0; a < arguments.length; a++) {
                        rowset.insertAt(rowset.size() + 1, a < arguments.length - 1, objectToInsertIniting(arguments[a]));
                    }
                } else if (arguments.length === 1) {
                    var justInserted = rowset.insertAt(rowset.size() + 1, true, objectToInsertIniting(arguments[0]));
                    Array.prototype.push.call(target, justInserted.getPublished());
                }
                return target.length;
            }
        });
        Object.defineProperty(target, "reverse", {
            value: function() {
                rowset.reverse();
            }
        });
        Object.defineProperty(target, "shift", {
            value: function() {
                if (!rowset.empty) {
                    var res = rowset.getRow(1);
                    rowset.deleteAt(1, true);
                    Array.prototype.shift.call(target);
                    return res.getPublished();
                }
            }
        });
        var defaultCompareFunction = function(o1, o2) {
            var s1 = (o1 + '');
            var s2 = (o2 + '');
            return s1 > s2 ? 1 : s1 < s2 ? -1 : 0;
        };
        Object.defineProperty(target, "sort", {
            value: function() {
                if (arguments.length > 0 && arguments[0] instanceof RowsComparatorClass) {
                    rowset.sort(arguments[0]);
                } else {
                    var compareFunc = defaultCompareFunction;
                    if (arguments.length > 0 && typeof arguments[0] === 'function') {
                        compareFunc = arguments[0];
                    }
                    Array.prototype.sort.call(target, compareFunc);
                }
                return target;
            }
        });
        Object.defineProperty(target, "splice", {
            value: function() {
                if (arguments.length > 0) {
                    var beginToDeleteAt = arguments[0];
                    var howManyToDelete = Number.MAX_VALUE;
                    if (arguments.length > 1) {
                        howManyToDelete = arguments[1];
                    }
                    var needToAdd = arguments.length > 2;
                    var deleted = [];
                    while (!rowset.empty && deleted.length < howManyToDelete) {
                        var rowToDelete = rowset.getRow(beginToDeleteAt + 1);
                        deleted.push(rowToDelete);
                        rowset.deleteAt(beginToDeleteAt + 1, needToAdd);
                    }
                    var insertAt = beginToDeleteAt;
                    for (var a = 2; a < arguments.length; a++) {
                        rowset.insertAt(insertAt + 1, a < arguments.length - 1, objectToInsertIniting(arguments[a]));
                        insertAt++;
                    }
                    return deleted;
                } else {
                    return [];
                }
            }
        });

        Object.defineProperty(target, "unshift", {
            value: function() {
                if (arguments.length > 1) {
                    for (var a = 0; a < arguments.length; a++) {
                        rowset.insertAt(a + 1, a < arguments.length - 1, objectToInsertIniting(arguments[a]));
                    }
                } else if (arguments.length === 1) {
                    var justInserted = rowset.insertAt(1, true, objectToInsertIniting(arguments[0]));
                    Array.prototype.unshift.call(target, justInserted.getPublished());
                }
                return target.length;
            }
        });

        Object.defineProperty(target, "insert", {
            value: function() {
                var initing = new JavaArrayClass(arguments.length);
                for (var v = 0; v < arguments.length; v++)
                    initing[v] = boxAsJava(arguments[v]);
                rowset.insert(initing);
            }
        });

        Object.defineProperty(target, "insertAt", {
            value: function() {
                if (arguments.length > 0) {
                    var index = arguments[0];
                    var initing = new JavaArrayClass(arguments.length - 1);
                    for (var v = 1; v < arguments.length; v++)
                        initing[v - 1] = boxAsJava(arguments[v]);
                    rowset.insertAt(index, false, initing);
                }
            }
        });

        Object.defineProperty(target, "createFilter", {
            value: function() {
                var nEntity = this.unwrap();
                var varargs = new JavaArrayClass(arguments.length);
                for (var v = 0; v < arguments.length; v++)
                    varargs[v] = boxAsJava(arguments[v]);
                return boxAsJs(nEntity.createFilter(varargs));
            }
        });

        Object.defineProperty(target, "createSorting", {
            value: function() {
                var nEntity = this.unwrap();
                var varargs = new JavaArrayClass(arguments.length);
                for (var v = 0; v < arguments.length; v++)
                    varargs[v] = boxAsJava(arguments[v]);
                return boxAsJs(nEntity.createSorting(varargs));
            }
        });

        Object.defineProperty(target, "find", {
            value: function() {
                var nEntity = this.unwrap();
                var varargs = new JavaArrayClass(arguments.length);
                for (var v = 0; v < arguments.length; v++)
                    varargs[v] = boxAsJava(arguments[v]);
                var found = nEntity.find(varargs);
                var res = [];
                for (var f = 0; f < found.size(); f++) {
                    res.push(EngineUtilsClass.unwrap(found[f].getPublished()));
                }
                return res;
            }
        });
    }

    RowClass.setPublisher(function(aDelegate) {
        var nnFields = aDelegate.getFields();
        var instanceCTor = nnFields.getInstanceConstructor();
        var target = !!instanceCTor ? new instanceCTor() : {};
        var nFields = nnFields.toCollection();
        // plain mutable properties
        for (var n = 0; n < nFields.size(); n++) {
            (function() {
                var colIndex = n + 1;
                var nField = nFields[n];
                var valueAccessorDesc = {
                    get: function() {
                        return boxAsJs(aDelegate.getColumnObject(colIndex));
                    },
                    set: function(aValue) {
                        aDelegate.setColumnObject(colIndex, boxAsJava(aValue));
                    }
                };
                Object.defineProperty(target, nField.name, {get: valueAccessorDesc.get, set: valueAccessorDesc.set, enumerable: true});
                Object.defineProperty(target, n, valueAccessorDesc);
            })();
        }
        if (!target.schema)
            Object.defineProperty(target, "schema", {value: nnFields.getPublished()});
        // ORM mutable scalar and readonly collection properties
        var ormDefs = nnFields.getOrmDefinitions();
        for each (var o in ormDefs.keySet()) {
            var def = EngineUtilsClass.unwrap(ormDefs.get(o));
            Object.defineProperty(target, o, def);
        }
        Object.defineProperty(target, "unwrap", {
            value: function() {
                return aDelegate;
            }});
        return target;
        // WARNING!!! Don't define target.length, because of possible conflict with subject area data properties.
    });
    FieldsClass.setPublisher(function(aDelegate) {
        var target = {};
        var nFields = aDelegate.toCollection();
        for (var n = 0; n < nFields.size(); n++) {
            (function() {
                var nField = nFields[n];
                var pField = EngineUtilsClass.unwrap(nField.getPublished());
                Object.defineProperty(target, nField.name, {
                    value: pField
                });
                Object.defineProperty(target, n, {
                    value: pField
                });
            })();
        }
        Object.defineProperty(target, "length", {
            value: nFields.size()
        });
        return target;
    });

    extend(BoundArray, Array);
    extend(P.ApplicationDbEntity, BoundArray);
    extend(P.ApplicationPlatypusEntity, BoundArray);
    extend(P.ApplicationDbParametersEntity, BoundArray);
    extend(P.ApplicationPlatypusParametersEntity, BoundArray);

    P.Filter.prototype.apply = function() {
        var varargs = new JavaArrayClass(arguments.length);
        for (var v = 0; v < arguments.length; v++)
            varargs[v] = boxAsJava(arguments[v]);
        var nFilter = this.unwrap();
        nFilter.apply(varargs);
    };

    /**
     * @static
     * @param {type} aName
     * @param {type} aTarget
     * @returns {P.loadModel.publishTo}
     */
    function loadModel(aName, aTarget) {
        var model = ModelLoaderClass.load(ScriptedResourceClass.getClient(), aName);
        var modelCTor;
        if (model instanceof TwoTierModelClass) {
            modelCTor = P.ApplicationDbModel;
        } else if (model instanceof ThreeTierModelClass) {
            modelCTor = P.ApplicationPlatypusModel;
        } else {
            throw "Can't determine model's type.";
        }
        if (aTarget) {
            modelCTor.call(aTarget, model);
        } else {
            aTarget = new modelCTor(model);
        }
        function publishEntity(nEntity, aName) {
            var published = EngineUtilsClass.unwrap(nEntity.getPublished());
            var paramsSubject = published instanceof P.ApplicationDbParametersEntity
                    || published instanceof P.ApplicationPlatypusParametersEntity;
            var pSchema = {};
            Object.defineProperty(published, "schema", {
                value: pSchema
            });
            var nFields = nEntity.getFields().toCollection();
            for (var n = 0; n < nFields.size(); n++) {
                (function() {
                    var nField = nFields[n];
                    if (paramsSubject) {
                        var valueDesc = {
                            get: function() {
                                return boxAsJs(nField.value);
                            },
                            set: function(aValue) {
                                nField.value = boxAsJava(aValue);
                            }
                        };
                        Object.defineProperty(published, nField.name, valueDesc);
                        Object.defineProperty(published, n, valueDesc);
                    }
                    // schema
                    var schemaDesc = {
                        value: nField.getPublished()
                    };
                    Object.defineProperty(pSchema, nField.name, schemaDesc);
                    Object.defineProperty(pSchema, n, schemaDesc);
                })();
            }
            if (paramsSubject) {
                Object.defineProperty(published, "length", {
                    get: function() {
                        return nFields.size();
                    }
                });
            } else {
                // entity.params.p1 syntax
                var nParameters = nEntity.getQuery().getParameters();
                var ncParameters = nParameters.toCollection();
                var pParams = {};
                for (var p = 0; p < ncParameters.size(); p++) {
                    var nParameter = ncParameters[p];
                    var pDesc = {
                        get: function() {
                            return boxAsJs(nParameter.value);
                        },
                        set: function(aValue) {
                            nParameter.value = boxAsJava(aValue);
                        }
                    };
                    Object.defineProperty(pParams, nParameter.name, pDesc);
                    Object.defineProperty(pParams, p, pDesc);
                }
                Object.defineProperty(pParams, "length", {value: ncParameters.size()});
                Object.defineProperty(published, "params", {value: pParams});
                // entity.params.schema.p1 syntax
                var pParamsSchema = EngineUtilsClass.unwrap(nParameters.getPublished());
                Object.defineProperty(pParams, "schema", {value: pParamsSchema});
            }
            Object.defineProperty(pSchema, "length", {
                get: function() {
                    return nFields.size();
                }
            });
            Object.defineProperty(aTarget, aName, {
                value: published,
                enumerable: true
            });
        }
        var pEntity = model.getParametersEntity();
        publishEntity(pEntity, "params");
        var entities = model.entities();
        for each (var enEntity in entities) {
            enEntity.validateQuery();
            if (enEntity.name) {
                publishEntity(enEntity, enEntity.name);
            }
        }
        model.createORMDefinitions();
        return aTarget;
    }
    Object.defineProperty(P, "loadModel", {value: loadModel});
    /**
     * @static
     * @param {type} aName
     * @param {type} aModel
     * @param {type} aTarget
     * @returns {P.loadForm.publishTo}
     */
    function loadForm(aName, aModel, aTarget) {
        var designInfo = FormLoaderClass.load(ScriptedResourceClass.getClient(), aName);
        var form = new FormClass(aName, designInfo, aModel ? aModel.unwrap() : null);
        if (aTarget) {
{'fraction_non_alphanumeric': 0.11548658128721756, 'fraction_numerical': 0.0033444816053511705, 'mean_word_length': 1.6187983978638185, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4249796', 'n_tokens_mistral': 13238, 'n_tokens_neox': 12636, 'n_words': 2593}