diff --git a/build/contactJS.js b/build/contactJS.js index 718e0a73b32d67e03b17e98b1ef60ea6acfa3df6..78ae4cc9ae13eb201a1861f3b97a8373a9f55c14 100644 --- a/build/contactJS.js +++ b/build/contactJS.js @@ -1,10 +1,8 @@ define(['retrievalResult', 'storage', 'aggregator', - 'attributeType', - 'attributeValue', - 'attributeTypeList', - 'attributeValueList', + 'attribute', + 'attributeList', 'parameter', 'parameterList', 'condition', @@ -27,10 +25,8 @@ function(RetrievalResult, Storage, Aggregator, - AttributeType, - AttributeValue, - AttributeTypeList, - AttributeValueList, + Attribute, + AttributeList, Parameter, ParameterList, Condition, @@ -55,15 +51,13 @@ var contactJS = function(obj) { return obj; }; - contactJS.VERSION = '1.1.0'; + contactJS.VERSION = '1.2.0'; // Methods contactJS.RetrievalResult = RetrievalResult; contactJS.Storage = Storage; contactJS.Aggregator = Aggregator; - contactJS.AttributeType = AttributeType; - contactJS.AttributeValue = AttributeValue; - contactJS.AttributeTypeList = AttributeTypeList; - contactJS.AttributeValueList = AttributeValueList; + contactJS.Attribute = Attribute; + contactJS.AttributeList = AttributeList; contactJS.Parameter = Parameter; contactJS.ParameterList = ParameterList; contactJS.Condition = Condition; diff --git a/dist/contactJS.js b/dist/contactJS.js index 8683d1a0b30484f172c7baef59a2ca9f632cd297..9639fe6b52245b91831f144e6de7905a94a41f14 100644 --- a/dist/contactJS.js +++ b/dist/contactJS.js @@ -520,8 +520,6 @@ define('abstractList',[ 'easejs' ], function(easejs) { * @requires easejs */ var AbstractList = AbstractClass('AbstractList', { - - /** * @alias items * @protected @@ -590,19 +588,6 @@ define('abstractList',[ 'easejs' ], function(easejs) { */ 'abstract public equals' : [ 'list' ], - /** - * Verifies whether an item exists for the specified key. - * - * @public - * @alias containsKey - * @memberof AbstractList# - * @param {string} _key Key that should be verified. - * @returns {boolean} - */ - 'public containsKey' : function(_key) { - return !!(typeof _key !== 'undefined' && typeof this.items[_key] !== 'undefined'); - }, - /** * Returns the item for the specified key. * @public @@ -865,8 +850,7 @@ define('parameterList',[ 'easejs', 'abstractList', 'parameter' ], * @requires AbstractList * @requires Parameter */ - var ParameterList = Class('ParameterList').extend(AbstractList,{ - + var ParameterList = Class('ParameterList').extend(AbstractList, { /** * @alias counter * @protected @@ -1010,854 +994,713 @@ define('parameterList',[ 'easejs', 'abstractList', 'parameter' ], /** * This module represents an AttributeType. * AttributeTypes defines name, type (string, double,...) an associated parameter of an attribute. - * + * * @module AttributeType * @fileOverview */ -define('attributeType',['easejs', +define('attribute',['easejs', 'parameterList'], function(easejs, - ParameterList){ - var Class = easejs.Class; - var AttributeType = Class('AttributeType',{ - /** - * @alias name - * @protected - * @type {string} - * @memberof AttributeType# - * @desc Name of the Attribute - */ - 'protected name' : '', - /** - * @alias type - * @protected - * @type {string} - * @memberof AttributeType# - * @desc Defines the type of the Attribute (i.e String, Double,...) - */ - 'protected type' : '', - /** - * @alias parameterList - * @protected - * @type {ParameterList} - * @memberof AttributeType# - * @desc Name of the Attribute - */ - 'protected parameterList' : [], + ParameterList){ - /** - * Constructor: Initializes the ParameterList. - * - * @class AttributeType - * @classdesc AttributeTypes defines name, type (string, double,...) an associated parameter of an attribute. - * @requires easejs - * @requires ParameterList - * @constructs AttributeType - */ - 'public __construct' : function(){ - this.parameterList = new ParameterList(); - }, + /** + * @class Attribute + * @classdesc AttributeValue extends AttributeTypes and adds the associated + * value. + * @requires easejs + * @requires ParameterList + */ + var Class = easejs.Class; + var Attribute = Class('Attribute',{ + /** + * @alias name + * @protected + * @type {string} + * @memberof AttributeType# + * @desc Name of the Attribute + */ + 'protected name' : '', - /** - * Builder for name. - * - * @public - * @alias withName - * @memberof AttributeType# - * @param {String} _name Name - * @returns {AttributeType} - */ - 'public withName' : function(_name){ - this.setName(_name); - return this; - }, + /** + * @alias type + * @protected + * @type {string} + * @memberof AttributeType# + * @desc Defines the type of the Attribute (i.e String, Double,...) + */ + 'protected type' : '', - /** - * Builder for type. - * - * @public - * @alias withType - * @memberof AttributeType# - * @param {String} _type Type - * @returns {AttributeType} - */ - 'public withType' : function(_type){ - this.setType(_type); - return this; - }, - - /** - * Builder for parameterList. - * - * @public - * @alias withParameters - * @memberof AttributeType# - * @param {(ParameterList|Array)} _parameterList ParameterList - * @returns {AttributeType} - */ - 'public withParameters' : function(_parameterList){ - this.setParameters(_parameterList); - return this; - }, - - /** - * Builder for one parameter. - * - * @public - * @alias withParameters - * @memberof AttributeType# - * @param {Parameter} _parameter Parameter - * @returns {AttributeType} - */ - 'public withParameter' : function(_parameter){ - this.addParameter(_parameter); - return this; - }, + /** + * @alias parameterList + * @protected + * @type {ParameterList} + * @memberof AttributeType# + * @desc Name of the Attribute + */ + 'protected parameterList' : [], - /** - * Returns the name. - * - * @public - * @alias getName - * @memberof AttributeType# - * @returns {string} - */ - 'public getName' : function(){ - return this.name; - }, - - /** - * Returns the type. - * - * @public - * @alias getType - * @memberof AttributeType# - * @returns {string} - */ - 'public getType' : function(){ - return this.type; - }, - - /** - * Returns the parameters. - * - * @public - * @alias getParameters - * @memberof AttributeType# - * @returns {ParameterList} - */ - 'public getParameters' : function(){ - return this.parameterList; - }, + /** + * @alias value + * @protected + * @type {string} + * @memberof AttributeValue# + */ + 'protected value' : 'NO_VALUE', - /** - * Sets the name. - * - * @public - * @alias setName - * @memberof AttributeType# - * @param {string} _name Name - */ - 'public setName' : function(_name){ - if(typeof _name === 'string'){ - this.name = _name; - } + /** + * @alias timestamp + * @protected + * @type {Date} + * @memberof AttributeValue# + * @desc Time when the value was set. + */ + 'protected timestamp' : '', + + /** + * Constructor: Initializes the ParameterList. + * + * @class AttributeType + * @classdesc AttributeTypes defines name, type (string, double,...) an associated parameter of an attribute. + * @requires easejs + * @requires ParameterList + * @constructs AttributeType + */ + 'public __construct' : function(){ + this.parameterList = new ParameterList(); }, - /** - * Sets the type. - * - * @public - * @alias setType - * @memberof AttributeType# - * @param {string} _type Type - */ - 'public setType' : function(_type){ - if(typeof _type === 'string'){ - this.type = _type; - } + /** + * Builder for name. + * + * @public + * @alias withName + * @memberof AttributeType# + * @param {String} _name Name + * @returns {AttributeType} + */ + 'public withName' : function(_name){ + this.setName(_name); + return this; }, - - /** - * Adds a parameter. - * - * @public - * @alias addParameter - * @memberof AttributeType# - * @param {Parameter} _parameter Parameter - */ - 'public addParameter' : function(_parameter){ - this.parameterList.put(_parameter); - }, - - /** - * Adds a list of Parameter. - * - * @public - * @alias setParameters - * @memberof AttributeType# - * @param {ParameterList} _parameters ParameterList - */ - 'public setParameters' : function(_parameters){ - this.parameterList.putAll(_parameters); - }, - 'public hasParameters' : function() { - return this.parameterList.size() > 0; + /** + * Builder for type. + * + * @public + * @alias withType + * @memberof AttributeType# + * @param {String} _type Type + * @returns {AttributeType} + */ + 'public withType' : function(_type){ + this.setType(_type); + return this; }, - /** - * Compares this instance with the given one. - * - * @virtual - * @public - * @alias equals - * @memberof AttributeType# - * @param {AttributeType} _attributeType AttributeType that should be compared - * @returns {boolean} - */ - 'virtual public equals' : function(_attributeType) { - if (Class.isA(AttributeType, _attributeType)) { - if (this.getName() == _attributeType.getName() && - this.getType() == _attributeType.getType() && - this.getParameters().equals(_attributeType.getParameters())) - return true; - } - return false; - }, + /** + * Builder for one parameter. + * + * @public + * @alias withParameters + * @memberof AttributeType# + * @param {Parameter} _parameter Parameter + * @returns {AttributeType} + */ + 'public withParameter' : function(_parameter){ + this.addParameter(_parameter); + return this; + }, - 'public hasInputParameter': function() { - return this.hasParameters() && this.parameterList.hasInputParameter(); + /** + * Builder for parameterList. + * + * @public + * @alias withParameters + * @memberof AttributeType# + * @param {(ParameterList|Array)} _parameterList ParameterList + * @returns {AttributeType} + */ + 'public withParameters' : function(_parameterList){ + this.setParameters(_parameterList); + return this; }, - /** - * Returns an identifier that uniquely describes the attribute type and its parameters. - * The identifier can be used to compare two attribute types. <br/> - * Format: (AttributeName:AttributeType)#[FirstParameterName:FirstParameterValue]… - * - * @public - * @alias toString - * @memberof AttributeType# - * @returns {String} - * @example (CI_USER_LOCATION_DISTANCE:FLOAT)#[CP_TARGET_LATITUDE:52][CP_TARGET_LONGITUDE:13][CP_UNIT:KILOMETERS] - */ - 'virtual public toString': function() { - var identifier = "("+this.name+":"+this.type+")"; - if (this.hasParameters()) { - identifier += "#"; - for (var index in this.parameterList.getItems()) { - var theParameter = this.parameterList.getItems()[index]; - identifier += theParameter.toString(); - } - } - return identifier; - } + /** + * Builder for value. + * + * @public + * @alias withValue + * @memberof AttributeValue# + * @param {String} _value value + * @returns {AttributeValue} + */ + 'public withValue' : function(_value) { + this.setValue(_value); + this.setTimestamp(Date.now()); + return this; + }, - }); + /** + * Builder for timestamp. + * + * @public + * @alias withTimestamp + * @memberof AttributeValue# + * @param {Date} _timestamp timestamp + * @returns {AttributeValue} + */ + 'public withTimestamp' : function(_timestamp) { + this.setTimestamp(_timestamp); + return this; + }, - return AttributeType; - -}); -/** - * This module represents an AttributeValue. AttributeValue extends - * AttributeTypes and adds the associated value. - * - * @module AttributeValue - * @fileOverview - */ -define('attributeValue',[ 'easejs', 'attributeType' ], function(easejs, AttributeType) { - var Class = easejs.Class; + /** + * Returns the name. + * + * @public + * @alias getName + * @memberof AttributeType# + * @returns {string} + */ + 'public getName' : function(){ + return this.name; + }, - /** - * @class AttributeValue - * @classdesc AttributeValue extends AttributeTypes and adds the associated - * value. - * @requires easejs - * @requires AttributeType - */ - var AttributeValue = Class('AttributeValue').extend( - AttributeType, - { - /** - * @alias value - * @protected - * @type {string} - * @memberof AttributeValue# - */ - 'protected value' : '', - /** - * @alias timestamp - * @protected - * @type {Date} - * @memberof AttributeValue# - * @desc Time when the value was set. - */ - 'protected timestamp' : '', + /** + * Returns the type. + * + * @public + * @alias getType + * @memberof AttributeType# + * @returns {string} + */ + 'public getType' : function(){ + return this.type; + }, - /** - * Builder for value. - * - * @public - * @alias withValue - * @memberof AttributeValue# - * @param {String} _value value - * @returns {AttributeValue} - */ - 'public withValue' : function(_value) { - this.setValue(_value); - this.setTimestamp(Date.now()); - return this; - }, + /** + * Returns the parameters. + * + * @public + * @alias getParameters + * @memberof AttributeType# + * @returns {ParameterList} + */ + 'public getParameters' : function(){ + return this.parameterList; + }, - /** - * Builder for timestamp. - * - * @public - * @alias withTimestamp - * @memberof AttributeValue# - * @param {Date} _timestamp timestamp - * @returns {AttributeValue} - */ - 'public withTimestamp' : function(_timestamp) { - this.setTimestamp(_timestamp); - return this; - }, + /** + * Sets the name. + * + * @public + * @alias setName + * @memberof AttributeType# + * @param {string} _name Name + */ + 'public setName' : function(_name){ + if(typeof _name === 'string'){ + this.name = _name; + } + }, - /** - * Sets the value. - * - * @public - * @alias setValue - * @memberof AttributeValue# - * @param {string} _value value - */ - 'public setValue' : function(_value) { - this.value = _value; - }, + /** + * Sets the type. + * + * @public + * @alias setType + * @memberof AttributeType# + * @param {string} _type Type + */ + 'public setType' : function(_type){ + if(typeof _type === 'string'){ + this.type = _type; + } + }, - /** - * Returns the value. - * - * @public - * @alias getValue - * @memberof AttributeValue# - * @returns {string} - */ - 'public getValue' : function() { - return this.value; - }, - - /** - * Sets the timestamp. - * - * @public - * @alias setTimestamp - * @memberof AttributeValue# - * @param {Date} _timestamp timestamp - */ - 'public setTimestamp' : function(_time) { - this.timestamp = _time; - }, + /** + * Adds a parameter. + * + * @public + * @alias addParameter + * @memberof AttributeType# + * @param {Parameter} _parameter Parameter + */ + 'public addParameter' : function(_parameter){ + this.parameterList.put(_parameter); + }, - /** - * Returns the timestamp. - * - * @public - * @alias getTimestamp - * @memberof AttributeValue# - * @returns {string} - */ - 'public getTimestamp' : function() { - return this.timestamp; - }, + /** + * Adds a list of Parameter. + * + * @public + * @alias setParameters + * @memberof AttributeType# + * @param {ParameterList} _parameters ParameterList + */ + 'public setParameters' : function(_parameters){ + this.parameterList.putAll(_parameters); + }, - /** - * Compares this instance with the given one. - * - * @public - * @alias equals - * @memberof AttributeValue# - * @param {AttributeValue} _attributeValue AttributeValue that should be compared - * @returns {boolean} - */ - 'override public equals' : function(_attributeValue) { - if (Class.isA(AttributeValue, _attributeValue)) { - if (_attributeValue.getAttributeType().equals(this.getAttributeType()) && - _attributeValue.getValue() == this.getValue()) { - return true; - } - } - return false; - }, + /** + * Returns true if the attribute is parameterized. + * + * @public + * @alias hasParameters + * @memberof Attribute# + * @returns {boolean} + */ + 'public hasParameters' : function() { + return this.parameterList.size() > 0; + }, - /** - * Returns the AttributeType of an AttributeValue. - * - * @public - * @alias getAttributeType - * @memberof AttributeValue# - * @returns {AttributeType} - */ - 'public getAttributeType' : function() { - return new AttributeType().withName(this.name) - .withType(this.type).withParameters( - this.parameterList); - }, + /** + * Sets the value. + * + * @public + * @alias setValue + * @memberof AttributeValue# + * @param {string} _value value + */ + 'public setValue' : function(_value) { + this.value = _value; + }, - /** - * Builds a new AttributeValue from the given type. - * - * @public - * @alias buildFromAttributeType - * @memberof AttributeValue# - * @param {AttributeType} _attributeType AttributeType for build process. - * @returns {AttributeValue} - */ - 'public buildFromAttributeType' : function(_attributeType) { - if (Class.isA(AttributeType, _attributeType)) { - return new AttributeValue().withName(_attributeType.getName()) - .withType(_attributeType.getType()).withParameters(_attributeType.getParameters()).withValue('NO_VALUE'); - } - return null; - }, + /** + * Returns the value. + * + * @public + * @alias getValue + * @memberof AttributeValue# + * @returns {string} + */ + 'public getValue' : function() { + return this.value; + }, - /** - * Returns a string that describes the attribute type and its value. - * - * @public - * @override - * @alias toString - * @memberof AttributeValue# - * @returns {string} - */ - 'override public toString': function() { - return this.__super().toString()+":"+this.getValue(); - } - }); + /** + * Sets the timestamp. + * + * @public + * @alias setTimestamp + * @memberof AttributeValue# + * @param {Date} _timestamp timestamp + */ + 'public setTimestamp' : function(_time) { + this.timestamp = _time; + }, - return AttributeValue; -}); -/** - * This module represents an AttributeTypeList. It is a subclass of AbstractList. - * - * @module AttributeTypeList - * @fileOverview - */ -define('attributeTypeList',[ 'easejs', 'abstractList', 'attributeType', 'parameterList' ], - function(easejs, AbstractList, AttributeType, ParameterList) { - var Class = easejs.Class; - /** - * @class AttributeTypeList - * @classdesc This class represents a list for AttributeType. - * @extends AbstractList - * @requires easejs - * @requires AbstractList - * @requires AttributeType - */ - var AttributeTypeList = Class('AttributeTypeList').extend(AbstractList, { + /** + * Returns the timestamp. + * + * @public + * @alias getTimestamp + * @memberof AttributeValue# + * @returns {string} + */ + 'public getTimestamp' : function() { + return this.timestamp; + }, - /** - * @alias items - * @protected - * @type {AttributeTypeList} - * @memberof AttributeTypeList# - * @desc ItemList - */ - 'protected items' : [], + /** + * + * @public + * @alias hasInputParameter + * @memberof Attribute# + * @returns {boolean} + */ + 'public hasInputParameter': function() { + return this.hasParameters() && this.parameterList.hasInputParameter(); + }, - /** - * Builder for item list. - * - * @public - * @alias withItems - * @memberof AttributeTypeList# - * @param {(AttributeTypeList)} _attributeTypeList AttributeTypeList - * @returns {AttributeTypeList} - */ - 'public withItems' : function(_attributeTypeList) { - var list = []; - if (_attributeTypeList instanceof Array) { - list = _attributeTypeList; - } else if (Class.isA(AttributeTypeList, _attributeTypeList)) { - list = _attributeTypeList.getItems(); - } - this.items = list; - return this; - }, + /** + * Compares this instance with the given one. + * + * @public + * @alias equalsTypeOf + * @memberof Attribute# + * @param {Attribute} _attribute Attribute that should be compared. + * @returns {boolean} + */ + 'public equalsTypeOf' : function(_attribute) { + if (Class.isA(Attribute, _attribute)) { + if (this.getName() == _attribute.getName() && this.getType() == _attribute.getType() && this.getParameters().equals(_attribute.getParameters())) { + return true; + } + } + return false; + }, - /** - * Adds the specified item to the itemList. - * - * @public - * @alias put - * @memberof AttributeTypeList# - * @param {AttributeType} _attributeType AttributeType - */ - 'public put' : function(_attributeType, _multipleInstances) { - var _multipleInstances = typeof _multipleInstances == "undefined" ? false : _multipleInstances; - if (Class.isA(AttributeType, _attributeType)) { - if (_multipleInstances || !(this.contains(_attributeType))) { - this.items.push(_attributeType); - } - } - }, + /** + * + * + * @public + * @alias equalsValueOf + * @memberof Attribute# + * @param _attribute + * @returns {boolean} + */ + 'public equalsValueOf' : function(_attribute) { + if (Class.isA(Attribute, _attribute)) { + if (this.equalsTypeOf(_attribute) && this.getValue() == _attribute.getValue()) { + return true; + } + } + return false; + }, - /** - * Adds all items in the specified list to the - * itemList. - * - * @public - * @alias putAll - * @memberof AttributeTypeList# - * @param {(AttributeTypeList|Array)} _attributeTypeList AttributeTypeList - */ - 'public putAll' : function(_attributeTypeList) { - var list = []; - if (_attributeTypeList instanceof Array) { - list = _attributeTypeList; - } else if (Class.isA(AttributeTypeList, _attributeTypeList)) { - list = _attributeTypeList.getItems(); - } - for ( var i in list) { - this.put(list[i]); - } - }, + /** + * Returns an identifier that uniquely describes the attribute type and its parameters. + * The identifier can be used to compare two attribute types. <br/> + * Format: (AttributeName:AttributeType)#[FirstParameterName:FirstParameterValue]… + * + * @public + * @alias toString + * @memberof AttributeType# + * @returns {String} + * @example (CI_USER_LOCATION_DISTANCE:FLOAT)#[CP_TARGET_LATITUDE:52][CP_TARGET_LONGITUDE:13][CP_UNIT:KILOMETERS] + */ + 'public toString': function(_typeOnly) { + var identifier = "("+this.name+":"+this.type+")"; + if (this.hasParameters()) { + identifier += "#"; + for (var index in this.parameterList.getItems()) { + var theParameter = this.parameterList.getItems()[index]; + identifier += theParameter.toString(); + } + } + if (!_typeOnly) identifier += ":"+this.getValue(); + return identifier; + } + }); - /** - * Verifies whether the given item is included - * in this list. - * - * @public - * @alias contains - * @memberof AttributeTypeList# - * @param {AttributeType} _item AttributeType that should be verified. - * @returns {boolean} - */ - 'public contains' : function(_item) { - if (Class.isA(AttributeType, _item)) { - for (var index in this.items) { - var tmp = this.items[index]; - if (tmp.equals(_item)) { - return true; - } - } - } - return false; - }, + return Attribute; + }); +/** + * This module represents an AttributeList. It is a subclass of AbstractList. + * + * @module AttributeList + * @fileOverview + */ +define('attributeList',['easejs', 'abstractList', 'attribute', 'parameterList' ], + function(easejs, AbstractList, Attribute, ParameterList) { + var Class = easejs.Class; - /** - * Compare the specified AttributeTypeList with this instance. - * - * @public - * @alias equals - * @memberof AttributeTypeList# - * @param {AttributeTypeList} _list AttributeTypeList that should be compared. - * @returns {boolean} - */ - 'public equals' : function(_list) { - if (Class.isA(AttributeTypeList, _list) && _list.size() == this.size()) { - for (var index in _list.getItems()) { - var theAttributeType = _list.getItems()[index]; - if (!this.contains(theAttributeType)) return false; - } - return true; - } - return false; - }, + /** + * @class AttributeList + * @classdesc This class represents a list for Attribute. + * @extends AbstractList + * @requires easejs + * @requires AbstractList + * @requires Attribute + */ + var AttributeList = Class('AttributeList').extend(AbstractList, { + /** + * @alias items + * @protected + * @type {Array.<Attribute>} + * @memberof AttributeList# + * @desc ItemList + */ + 'protected items' : [], - /** - * Creates a clone of the current list. - * - * @public - * @alias clone - * @memberof AttributeTypeList# - * @returns {AttributeTypeList} - */ - 'public clone': function() { - var newList = new AttributeTypeList(); - for (var index in this.items) { - var oldAttributeType = this.items[index]; - var newAttributeType = new AttributeType(). - withName(oldAttributeType.getName()). - withType(oldAttributeType.getType()). - withParameters(oldAttributeType.getParameters()); - newList.put(newAttributeType); + /** + * Builder for item list. + * + * @public + * @alias withItems + * @memberof AttributeList# + * @param {(AttributeList)} _attributeList AttributeList + * @returns {AttributeList} + */ + 'public withItems' : function(_attributeList) { + var list = []; + if (_attributeList instanceof Array) { + list = _attributeList; + } else if (Class.isA(AttributeList, _attributeList)) { + list = _attributeList.getItems(); } - return newList; + this.items = list; + return this; }, - 'public removeAttributeType': function(_attributeType, _allOccurrences) { - _allOccurrences = typeof _allOccurrences == "undefined" ? false : _allOccurrences; - for (var index in this.items) { - var theAttributeType = this.items[index]; - if (theAttributeType.equals(_attributeType)) { - this.items.splice(index, 1); - } - } - if (_allOccurrences && this.contains(_attributeType)) this.removeAttributeType(_attributeType, _allOccurrences); - }, + /** + * Adds the specified item to the itemList. + * + * @public + * @alias put + * @memberof AttributeList# + * @param {AttributeType} _attribute AttributeType + * @param {boolean} _multipleInstances + */ + 'public put' : function(_attribute, _multipleInstances) { + _multipleInstances = typeof _multipleInstances == "undefined" ? false : _multipleInstances; + if (Class.isA(Attribute, _attribute)) { + if (_multipleInstances || !(this.containsTypeOf(_attribute))) { + this.items.push(_attribute); + } else { + this.updateValue(_attribute); + } + } + }, - 'public hasAttributesWithInputParameters': function() { - for (var index in this.items) { - var theAttributeType = this.items[index]; - if (theAttributeType.hasInputParameter()) return true; - } - return false; - }, + /** + * Adds all items in the specified list to the + * itemList. + * + * @public + * @alias putAll + * @memberof AttributeList# + * @param {(AttributeList|Array)} _attributeList AttributeList + */ + 'public putAll' : function(_attributeList) { + var list = []; + if (_attributeList instanceof Array) { + list = _attributeList; + } else if (Class.isA(AttributeList, _attributeList)) { + list = _attributeList.getItems(); + } + for ( var i in list) { + this.put(list[i]); + } + }, - 'public getAttributesWithInputParameters': function() { - var list = new AttributeTypeList(); - for (var index in this.items) { - var theAttributeType = this.items[index]; - if (theAttributeType.hasInputParameter()) list.put(theAttributeType); - } - return list; - } - }); + /** + * + * @param {Attribute} _attribute + * @param {?boolean} _typeOnly + * @returns {*} + */ + 'public contains': function(_attribute, _typeOnly) { + _typeOnly = typeof _typeOnly == "undefined" ? false : _typeOnly; + return _typeOnly ? this.containsTypeOf(_attribute) : this.containsValueOf(_attribute); + }, - return AttributeTypeList; - }); -/** - * This module represents a AttributeValueList. It is a subclass of - * AbstractList. - * - * @module AttributeValueList - * @fileOverview - */ -define('attributeValueList',['easejs', 'abstractList', 'attributeValue', 'attributeType', 'attributeTypeList', 'parameterList'], - function(easejs, AbstractList, AttributeValue, AttributeType, AttributeTypeList, ParameterList) { - var Class = easejs.Class; + /** + * Verifies whether the given item is included + * in this list. + * + * @public + * @alias containsTypeOf + * @memberof AttributeList# + * @param {AttributeType} _attribute AttributeType that should be verified. + * @returns {boolean} + */ + 'public containsTypeOf' : function(_attribute) { + if (Class.isA(Attribute, _attribute)) { + for (var index in this.items) { + var tmp = this.items[index]; + if (tmp.equalsTypeOf(_attribute)) { + return true; + } + } + } + return false; + }, - /** - * @class AttributeValueList - * @classdesc This class represents a list for AttributeValue. - * @extends AbstractList - * @requires easejs - * @requires AbstractList - * @requires AttributeValue - * @requires AttributeType - * @requires AttributeTypeList) - */ - var AttributeValueList = Class('AttributeValueList').extend(AbstractList,{ + /** + * Verifies whether the given item is included + * in the list. + * + * @public + * @alias containsValueOf + * @memberof AttributeList# + * @param {Attribute} _attribute AttributeValue that should be verified. + * @returns {boolean} + */ + 'public containsValueOf' : function(_attribute) { + if (Class.isA(Attribute, _attribute)) { + for (var index in this.items) { + var tmp = this.items[index]; + if (tmp.equalsValueOf(_attribute)) { + return true; + } + } + } + return false; + }, - /** - * @alias items - * @protected - * @type {AttributeValueList} - * @memberof AttributeValueList# - * @desc ItemList. - */ - 'protected items' : [], + 'public equals': function(_attributeList, _typeOnly) { + _typeOnly = typeof _typeOnly == "undefined" ? false : _typeOnly; + return _typeOnly ? this.equalsTypesIn(_attributeList) : this.equalsValuesIn(_attributeList); + }, - /** - * Builder for item list. - * - * @public - * @alias withItems - * @memberof AttributeValueList# - * @param {(AttributeValueListst|Array)} _attributeValueList AttributeValueList - * @returns {AttributeValueList} - */ - 'public withItems' : function(_attributeValueList) { - var list = []; - if (_attributeValueList instanceof Array) { - list = _attributeValueList; - } else if (Class.isA(AttributeValueList, - _attributeValueList)) { - list = _attributeValueList.getItems(); - } - this.items = list; - return this; - }, + /** + * Compare the specified AttributeList with this instance. + * + * @public + * @alias equalsTypesIn + * @memberof AttributeList# + * @param {AttributeList} _attributeList AttributeList that should be compared. + * @returns {boolean} + */ + 'public equalsTypesIn' : function(_attributeList) { + if (Class.isA(AttributeList, _attributeList) && _attributeList.size() == this.size()) { + for (var index in _attributeList.getItems()) { + var theAttributeType = _attributeList.getItems()[index]; + if (!this.containsTypeOf(theAttributeType)) return false; + } + return true; + } + return false; + }, - /** - * Add the specified item to this itemList. - * - * @public - * @alias put - * @memberof AttributeValueList# - * @param {AttributeValue} _attributeValue AttributeValue - */ - 'public put' : function(_attributeValue, _multipleInstances) { - if (Class.isA(AttributeValue, _attributeValue)) { - if (_multipleInstances || !(this.containsAttributeType(_attributeValue.getAttributeType()))) { - this.items.push(_attributeValue); - } else { - this.updateValue(_attributeValue); - } - } - }, + /** + * Compare the specified AttributeList with + * this instance. + * + * @public + * @alias equalsValuesIn + * @memberof AttributeList# + * @param {AttributeList} _attributeList AttributeList that should be compared. + * @returns {boolean} + */ + 'public equalsValuesIn' : function(_attributeList) { + if (Class.isA(AttributeList, _attributeList) && _attributeList.size() == this.size()) { + for (var index in _attributeList.getItems()) { + var theAttribute = _attributeList.getItems()[index]; + if (!this.containsValueOf(theAttribute)) return false; + } + return true; + } + return false; + }, - /** - * Adds all items in the specified list to this. - * itemList - * - * @public - * @alias putAll - * @memberof AttributeValueList# - * @param {AttributeValueList} _attributeValueList AttributeValueList - */ - 'public putAll' : function(_attributeValueList) { - var list = []; - if (_attributeValueList instanceof Array) { - list = _attributeValueList; - } else if (Class.isA(AttributeValueList, _attributeValueList)) { - list = _attributeValueList.getItems(); - } - for (var i in list) { - this.put(list[i]); - } - }, + /** + * Returns only this values that matches to the + * given type. + * + * @public + * @alias getSubset + * @memberof AttributeList# + * @param {(AttributeList|Array)} _attributeList Attributes that should be returned. + * @returns {AttributeList} + */ + 'public getSubset' : function(_attributeList) { + var response = new AttributeList(); + var list = []; + if (_attributeList instanceof Array) { + list = _attributeList; + } else if (Class.isA(AttributeList, _attributeList)) { + list = _attributeList.getItems(); + } + for (var i in list) { + var attribute = list[i]; + if (Class.isA(Attribute, attribute)) { + var attribute = this.getAttributeWithTypeOf(attribute); + if (typeof attribute != "NO_VALUE") { + response.put(attribute); + } + } + } + return response; + }, - /** - * Verifies whether the given item is included - * in the list. - * - * @public - * @alias contains - * @memberof AttributeValueList# - * @param {AttributeValue} _attributeValue AttributeValue that should be verified. - * @returns {boolean} - */ - 'public contains' : function(_attributeValue) { - if (Class.isA(AttributeValue, _attributeValue)) { - for (var index in this.items) { - var tmp = this.items[index]; - if (tmp.equals(_attributeValue)) { - return true; - } - } - } - return false; - }, + /** + * Returns a subset without the given types. + * + * @public + * @alias getSubsetWithoutItems + * @memberof AttributeList# + * @param {(AttributeList|Array)} _attributeList AttributeTypes that should not be included + * @returns {AttributeList} + */ + 'public getSubsetWithoutItems' : function(_attributeList) { + var response = this; + var list = []; + if (_attributeList instanceof Array) { + list = _attributeList; + } else if (Class.isA(AttributeList, _attributeList)) { + list = _attributeList.getItems(); + } + for (var i in list) { + var attribute = list[i]; + if (Class.isA(Attribute, attribute)) { + response.removeAttributeWithTypeOf(attribute); + } + } + return response; + }, - 'public containsAttributeType': function(_attributeType) { - if (Class.isA(AttributeType, _attributeType)) { - for (var index in this.items) { - var tmp = this.items[index].getAttributeType(); - if (tmp.equals(_attributeType)) { - return true; - } - } - } - return false; - }, + /** + * Creates a clone of the current list. + * + * @public + * @alias clone + * @memberof AttributeList# + * @returns {AttributeList} + */ + 'public clone': function(_typeOnly) { + var newList = new AttributeList(); + for (var index in this.items) { + var oldAttribute = this.items[index]; + var newAttribute = new Attribute().withName(oldAttribute.getName()).withType(oldAttribute.getType()).withParameters(oldAttribute.getParameters()); + if (!_typeOnly) newAttribute.setValue(oldAttribute.getValue()); + newList.put(newAttribute); + } + return newList; + }, - /** - * Compare the specified AttributeValueList with - * this instance. - * - * @public - * @alias equals - * @memberof AttributeValueList# - * @param {AttributeValueList} _list AttributeValueList that should be compared. - * @returns {boolean} - */ - 'public equals' : function(_list) { - if (Class.isA(AttributeValueList, _list) && _list.size() == this.size()) { - for (var index in _list.getItems()) { - var theAttributeValue = _list.getItems()[index]; - if (!this.contains(theAttributeValue)) return false; - } - return true; - } - return false; - }, + 'public removeAttributeWithTypeOf': function(_attribute, _allOccurrences) { + _allOccurrences = typeof _allOccurrences == "undefined" ? false : _allOccurrences; + for (var index in this.items) { + var theAttribute = this.items[index]; + if (theAttribute.equalsTypeOf(_attribute)) { + this.items.splice(index, 1); + } + } + if (_allOccurrences && this.contains(_attribute)) this.removeAttributeWithTypeOf(_attribute, _allOccurrences); + }, - /** - * Returns only this values that matches to the - * given type. - * - * @public - * @alias getSubset - * @memberof AttributeValueList# - * @param {(AttributeTypeList|Array)} _attributeTypeList AttributeTypes that should be returned. - * @returns {AttributeValueList} - */ - 'public getSubset' : function(_attributeTypeList) { - var response = new AttributeValueList(); - var list = []; - if (_attributeTypeList instanceof Array) { - list = _attributeTypeList; - } else if (Class.isA(AttributeTypeList, _attributeTypeList)) { - list = _attributeTypeList.getItems(); - } - for ( var i in list) { - var attributeType = list[i]; - if (Class.isA(AttributeType, attributeType)) { - var attribute = this.getValueObjectForAttributeType(attributeType); - if (typeof attribute != "undefined") { - response.put(attribute); - } - } - } - return response; - }, - - /** - * Returns a subset without the given types. - * - * @public - * @alias getSubsetWithoutItems - * @memberof AttributeValueList# - * @param {(AttributeTypeList|Array)} _attributeTypeList AttributeTypes that should not be included - * @returns {AttributeValueList} - */ - 'public getSubsetWithoutItems' : function(_attributeTypeList) { - var response = this; - var list = []; - if (_attributeTypeList instanceof Array) { - list = _attributeTypeList; - } else if (Class.isA(AttributeTypeList, _attributeTypeList)) { - list = _attributeTypeList.getItems(); - } - for (var i in list) { - var attributeType = list[i]; - if (Class.isA(AttributeType, attributeType)) { - response.removeAttributeValuesWithAttributeType(attributeType); - } - } - return response; - }, + 'public hasAttributesWithInputParameters': function() { + for (var index in this.items) { + var theAttribute = this.items[index]; + if (theAttribute.hasInputParameter()) return true; + } + return false; + }, - /** - * Returns the attribute value that matches the provided attribute type. - * - * @public - * @alias getValueForAttributeType - * @memberof AttributeValueList# - * @param {AttributeType} _attributeType - * @returns {AttributeValue} - */ - 'public getValueForAttributeType': function(_attributeType) { - return this.getValueObjectForAttributeType(_attributeType).getValue(); + 'public getAttributesWithInputParameters': function() { + var list = new AttributeList(); + for (var index in this.items) { + var theAttribute = this.items[index]; + if (theAttribute.hasInputParameter()) list.put(theAttribute); + } + return list; }, - 'public getValueObjectForAttributeType': function(_attributeType) { - for (var index in this.getItems()) { - var theAttributeValue = this.getItems()[index]; - if (theAttributeValue.getAttributeType().equals(_attributeType)) return theAttributeValue; - } - }, + /** + * Returns the attribute value that matches the provided attribute type. + * + * @public + * @alias getValueForAttributeWithTypeOf + * @memberof AttributeList# + * @param {AttributeType} _attribute + * @returns {Attribute} + */ + 'public getValueForAttributeWithTypeOf': function(_attribute) { + return this.getAttributeWithTypeOf(_attribute).getValue(); + }, - 'public removeAttributeValuesWithAttributeType': function(_attributeType) { - for (var index in this.items) { - var theAttributeValue = this.items[index]; - if (theAttributeValue.getAttributeType().equals(_attributeType)) this.items.splice(index, 1); - } - }, + 'public getAttributeWithTypeOf': function(_attribute) { + for (var index in this.getItems()) { + var theAttribute = this.getItems()[index]; + if (theAttribute.equalsTypeOf(_attribute)) return theAttribute; + } + }, - 'public updateValue': function(_attributeValue) { - for (var index in this.items) { - var theAttributeValue = this.items[index]; - if (theAttributeValue.getAttributeType().equals(_attributeValue.getAttributeType())) this.items[index] = _attributeValue; - } - } - }); + 'public updateValue': function(_attribute) { + for (var index in this.items) { + var theAttribute = this.items[index]; + if (theAttribute.equalsTypeOf(_attribute)) this.items[index] = _attribute; + } + } - return AttributeValueList; - }); + }); + + return AttributeList; +}); /** * This module representing a Storage. * The Storage handles the access to the database. @@ -1865,9 +1708,9 @@ define('attributeValueList',['easejs', 'abstractList', 'attributeValue', 'attrib * @module Widget * @fileOverview */ -define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeType', +define('storage',['easejs', 'attribute', 'attributeList', 'retrievalResult', 'parameter', 'parameterList'], - function( easejs, AttributeValue, AttributeValueList, AttributeType, + function( easejs, Attribute, AttributeList, RetrievalResult, Parameter, ParameterList){ var Class = easejs.Class; var Storage = Class('Storage', @@ -1892,7 +1735,7 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy /** * @alias data * @private - * @type {AttributeValueList} + * @type {AttributeList} * @memberof Storage# * @desc Cache before storing the new data in the database. */ @@ -1948,8 +1791,8 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy * @class Storage * @classdesc Storage handles the access to the database. * @requires easejs - * @requires AttributeValue - * @requires AttributeValueList + * @requires Attribute + * @requires AttributeList * @requires Parameter * @requires ParameterList * @requires RetrievalResult @@ -1959,7 +1802,7 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy 'public __construct' : function(_name, _time, _counter){ this.initStorage(_name); this.attributes = new RetrievalResult(); - this.data = new AttributeValueList(); + this.data = new AttributeList(); this.dataCount = 0; this.lastFlush = new Date(); if(_time && _time === parseInt(_time) && _time!=0) @@ -2042,18 +1885,18 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy * @private * @alias insertIntoTable * @memberof Storage# - * @param {AttributeValue} _attributeValue Attribute that should be stored. + * @param {Attribute} _attribute Attribute that should be stored. * @param {?function} _function For alternative actions, if an asynchronous function is used. */ - 'private insertIntoTable' : function(_attributeValue, _function){ - if(this.db && _attributeValue && Class.isA(AttributeValue, _attributeValue)){ - var tableName = this.tableName(_attributeValue); + 'private insertIntoTable' : function(_attribute, _function){ + if(this.db && _attribute && Class.isA(Attribute, _attribute)){ + var tableName = this.tableName(_attribute); var statement = 'INSERT INTO "' + tableName + '" (value_, type_, created_) VALUES ("' - + _attributeValue.getValue() + '", "' - + _attributeValue.getType() + '", "' - + _attributeValue.getTimestamp() + '")'; - console.log('INSERT INTO "'+tableName+'" VALUES ('+_attributeValue.getValue()+", "+_attributeValue.getType()+", "+_attributeValue.getTimestamp()); + + _attribute.getValue() + '", "' + + _attribute.getType() + '", "' + + _attribute.getTimestamp() + '")'; + console.log('INSERT INTO "'+tableName+'" VALUES ('+_attribute.getValue()+", "+_attribute.getType()+", "+_attribute.getTimestamp()); if(_function && typeof(_function) == 'function'){ this.db.transaction(function(tx){tx.executeSql(statement);}, this.errorCB, _function); } else { @@ -2158,7 +2001,7 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy * @returns {boolean} */ 'private tableExists' : function(_attribute){ - if(Class.isA(AttributeValue, _attribute) || Class.isA(AttributeType, _attribute)){ + if(Class.isA(Attribute, _attribute)){ var name = this.tableName(_attribute); return this.attributeNames.indexOf(name) > -1; } else if(typeof _attribute === 'string'){ @@ -2177,11 +2020,16 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy * @param {?function} _function For additional actions, if an asynchronous function is used. */ 'public retrieveAttributes' : function(_tableName, _function){ + console.log("retrieveAttributes from "+_tableName); + if(this.db){ var self = this; self.flushStorage(); - this.db.transaction(function(_tx){self.queryValues(_tx,_tableName,self, _function);}, - function(error){self.errorCB(error);} ); + this.db.transaction(function(_tx) { + self.queryValues(_tx,_tableName,self, _function); + }, function(error) { + self.errorCB(error); + }); } }, @@ -2197,9 +2045,10 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy * @param {@this} self * @param {?function} _function For additional actions, if an asynchronous function is used. */ - 'private queryValues' : function(_tx,_tableName,self, _function){ - if(self.tableExists(_tableName)){ - var statement = 'SELECT * FROM ' + _tableName; + 'private queryValues' : function(_tx, _tableName, self, _function){ + if(self.tableExists(_tableName)){ + console.log('SELECT * FROM "' +_tableName+"'"); + var statement = 'SELECT * FROM "' + _tableName+'"'; _tx.executeSql(statement, [], function(_tx,results){self.queryValuesSuccess(_tx,results,_tableName, self, _function);}, function(error){self.errorCB(error);}); @@ -2228,7 +2077,7 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy var attributeName = this.resolveAttributeName(_tableName); var parameterList = this.resolveParameters(_tableName); for(var i=0; i<len; i++){ - var attribute = new AttributeValue(). + var attribute = new Attribute(). withName(attributeName).withValue(results.rows.item(i).value_). withType(results.rows.item(i).type_). withTimestamp(results.rows.item(i).created_). @@ -2271,11 +2120,11 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy * @private * @alias addData * @memberof Storage# - * @param {AttributeValue} _attributeValue Value that should be stored. + * @param {Attribute} _attribute Value that should be stored. */ - 'private addData' : function(_attributeValue){ - if(Class.isA(AttributeValue, _attributeValue)){ - this.data.put(_attributeValue); + 'private addData' : function(_attribute){ + if(Class.isA(Attribute, _attribute)){ + this.data.put(_attribute); this.dataCount++; } }, @@ -2307,7 +2156,7 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy * @memberof Storage# */ 'private resetForFlush' : function(){ - this.data = new AttributeValueList(); + this.data = new AttributeList(); this.dataCount = 0; this.lastFlush = new Date(); }, @@ -2395,7 +2244,7 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy * @returns{String} */ 'private tableName' : function(_attribute){ - return _attribute.getAttributeType().toString(); + return _attribute.toString(true); }, /** @@ -2443,8 +2292,8 @@ define('storage',['easejs', 'attributeValue', 'attributeValueList', 'attributeTy * @module Callback * @fileOverview */ -define('callback',['easejs', 'attributeType', 'attributeTypeList'], - function(easejs, AttributeType, AttributeTypeList){ +define('callback',['easejs', 'attribute', 'attributeList'], + function(easejs, Attribute, AttributeList){ var Class = easejs.Class; var Callback = Class('Callback', @@ -2481,7 +2330,7 @@ define('callback',['easejs', 'attributeType', 'attributeTypeList'], */ 'public __construct': function() { - this.attributeTypes = new AttributeTypeList(); + this.attributeTypes = new AttributeList(); }, /** @@ -2556,19 +2405,19 @@ define('callback',['easejs', 'attributeType', 'attributeTypeList'], * @public * @alias setAttributeTypes * @memberof Callback# - * @param {AttributeTypeList} _attributeTypes AttributeTypeList + * @param {AttributeList} _attributes AttributeTypeList */ - 'public setAttributeTypes' : function(_attributeTypes){ + 'public setAttributeTypes' : function(_attributes){ var list = []; - if(_attributeTypes instanceof Array){ - list = _attributeTypes; - } else if (Class.isA( AttributeTypeList, _attributeTypes)) { - list = _attributeTypes.getItems(); + if(_attributes instanceof Array){ + list = _attributes; + } else if (Class.isA( AttributeList, _attributes)) { + list = _attributes.getItems(); } for(var i in list){ - var attributeType = list[i]; - if(Class.isA( AttributeType, attributeType )){ - this.attributeTypes.put(attributeType); + var theAttribute = list[i]; + if(Class.isA(Attribute, theAttribute)){ + this.attributeTypes.put(theAttribute); } } }, @@ -2579,14 +2428,14 @@ define('callback',['easejs', 'attributeType', 'attributeTypeList'], * @public * @alias addAttributeType * @memberof Callback# - * @param {AttributeType} _attributeType AttributeType + * @param {AttributeType} _attribute AttributeType */ - 'public addAttributeType' : function(_attributeType){ - if(Class.isA( AttributeType, _attributeType )){ - if(!this.attributeTypes.contains(_attributeType)){ - this.attributeTypes.put(_attributeType); + 'public addAttributeType' : function(_attribute){ + if(Class.isA(Attribute, _attribute )){ + if(!this.attributeTypes.containsTypeOf(_attribute)){ + this.attributeTypes.put(_attribute); } - }; + } }, /** @@ -2598,9 +2447,9 @@ define('callback',['easejs', 'attributeType', 'attributeTypeList'], * @param {AttributeType} _attributeType AttributeType */ 'public removeAttributeType' : function(_attributeType){ - if(Class.isA( AttributeType, _attributeType )){ + if(Class.isA(Attribute, _attributeType )){ this.attributeTypes.removeItem(_attributeType.getName()); - }; + } }, /** @@ -2647,9 +2496,7 @@ define('callbackList',['easejs', 'abstractList', 'callback'], * @requires AbstractList * @requires Callback */ - var CallbackList = Class('CallbackList'). - extend(AbstractList,{ - + var CallbackList = Class('CallbackList').extend(AbstractList,{ /** * @alias counter * @protected @@ -2677,18 +2524,10 @@ define('callbackList',['easejs', 'abstractList', 'callback'], * @returns {CallbackList} */ 'public withItems': function(_callbackList){ - var list = []; - if(_callbackList instanceof Array){ - list = _callbackList; + if (_callbackList instanceof Array) { + this.items = _callbackList; } else if (Class.isA(CallbackList, _callbackList)) { - list = _callbackList.getItems(); - } - for(var i in list){ - var callback = list[i]; - if(Class.isA( Callback, callback )){ - this.items[callback.getName()] = callback; - this.counter++; - } + this.items = _callbackList.getItems(); } return this; }, @@ -2702,11 +2541,10 @@ define('callbackList',['easejs', 'abstractList', 'callback'], * @param {Callback} _callback Callback */ 'public put' : function(_callback){ - if(Class.isA(Callback, _callback)){ - if(!(this.containsKey(_callback.getName()))){ - this.counter++; + if (Class.isA(Callback, _callback)) { + if (!(this.contains(_callback))) { + this.items.push(_callback); } - this.items[_callback.getName()] = _callback; } }, @@ -2721,19 +2559,13 @@ define('callbackList',['easejs', 'abstractList', 'callback'], */ 'public putAll' : function(_callbackList){ var list = []; - if(_callbackList instanceof Array){ + if (_callbackList instanceof Array) { list = _callbackList; - } else if (Class.isA(CallbackList, _callbackList)) { + } else if (Class.isA(CallbackList, _callbackList)) { list = _callbackList.getItems(); } - for(var i in list){ - var callback = list[i]; - if(Class.isA(Callback, callback)){ - if(!(this.containsKey(callback.getName()))){ - this.counter++; - } - this.items[callback.getName()] = callback; - } + for (var i in list) { + this.put(list[i]); } }, @@ -2744,16 +2576,18 @@ define('callbackList',['easejs', 'abstractList', 'callback'], * @public * @alias contains * @memberof CallbackList# - * @param {Callback} _item CallbackType that should be verified. + * @param {Callback} _callback CallbackType that should be verified. * @returns {boolean} */ - 'public contains' : function(_item){ - if(Class.isA(Callback,_item)){ - var tmp = this.getItem(_item.getName()); - if(!(typeof tmp === 'undefined') && tmp.equals(_item)){ - return true; + 'public contains' : function(_callback){ + if (Class.isA(Callback, _callback)) { + for (var index in this.items) { + var tmp = this.items[index]; + if (tmp.equals(_callback)) { + return true; + } } - } + } return false; }, @@ -2762,20 +2596,17 @@ define('callbackList',['easejs', 'abstractList', 'callback'], * @public * @alias equals * @memberof CallbackList# - * @param {CallbackList} _list CallbackList that should be compared. + * @param {CallbackList} _callbackList CallbackList that should be compared. * @returns {boolean} */ - 'public equals' : function(_list){ - if(Class.isA(CallbackList,_list) && _list.size() == this.size()){ - var items = _list.getItems(); - for(var i in items){ - var item = items[i]; - if(!this.contains(item)){ - return false; - } + 'public equals' : function(_callbackList){ + if (Class.isA(CallbackList, _callbackList) && _callbackList.size() == this.size()) { + for (var index in _callbackList.getItems()) { + var theCallback = _callbackList.getItems()[index]; + if (!this.contains(theCallback)) return false; } return true; - } + } return false; } @@ -2827,8 +2658,8 @@ define('conditionMethod',['easejs'], * @module Condition * @fileOverview */ -define('condition',['easejs','attributeType','attributeValue', 'conditionMethod'], - function(easejs, AttributeType, AttributeValue, ConditionMethod){ +define('condition',['easejs','attribute', 'conditionMethod'], + function(easejs, Attribute, ConditionMethod){ var Class = easejs.Class; /** * @class Condition @@ -2947,11 +2778,11 @@ define('condition',['easejs','attributeType','attributeValue', 'conditionMethod' * @public * @alias setAttributeType * @memberof Condition# - * @param {AttributeType} _attributeType AttributeType + * @param {Attribute} _attribute AttributeType */ - 'public setAttributeType' : function(_attributeType){ - if(Class.isA(AttributeType,_attributeType)){ - this.attributeType = _attributeType; + 'public setAttributeType' : function(_attribute){ + if(Class.isA(Attribute, _attribute)){ + this.attributeType = _attribute; } }, @@ -3035,21 +2866,20 @@ define('condition',['easejs','attributeType','attributeValue', 'conditionMethod' * @public * @alias compare * @memberof Condition# - * @param {AttributeValue} _newAttributeValue new Attribute that should be compared - * @param {AttributeValue} _oldAttributeValue old Attribute + * @param {Attribute} _newAttributeValue new Attribute that should be compared + * @param {Attribute} _oldAttributeValue old Attribute * @returns {boolean} */ 'public compare' : function(_newAttributeValue, _oldAttributeValue){ - if(!this.attributeType.equals(_newAttributeValue.getAttributeType()) - && !this.attributeType.equals(_oldAttributeValue.getAttributeType())){ + if(!this.attributeType.equalsTypeOf(_newAttributeValue)&& !this.attributeType.equalsTypeOf(_oldAttributeValue)){ return false; - }; + } if(!this.comparisonMethod){ return false; - }; - if(Class.isA(AttributeValue,_newAttributeValue) && Class.isA(AttributeValue,_oldAttributeValue)){ + } + if(Class.isA(Attribute, _newAttributeValue) && Class.isA(Attribute, _oldAttributeValue)){ return this.comparisonMethod.process(this.referenceValue, _newAttributeValue.getValue(), _oldAttributeValue.getValue()); - }; + } return false; }, @@ -3066,7 +2896,7 @@ define('condition',['easejs','attributeType','attributeValue', 'conditionMethod' if(Class.isA(Condition, _condition)){ if(_condition.getName() == this.getName() && _condition.getReferenceValue() == this.getReferenceValue() - && _condition.getAttributeType().equals(this.attributeType) + && _condition.getAttributeType().equalsTypeOf(this.attributeType) && _condition.getComparisonMethod() === this.comparisonMethod){ return true; }; @@ -3127,18 +2957,10 @@ define('conditionList',['easejs','abstractList', 'condition'], * @returns {ConditionList} */ 'public withItems': function(_conditionList){ - var list = new Array(); - if(_conditionList instanceof Array){ - list = _conditionList; + if (_conditionList instanceof Array) { + this.items = _conditionList; } else if (Class.isA(ConditionList, _conditionList)) { - list = _conditionList.getItems(); - } - for(var i in list){ - var condition = list[i]; - if(Class.isA( Condition, condition )){ - this.items[condition.getName()] = condition; - this.counter++; - } + this.items = _conditionList.getItems(); } return this; }, @@ -3152,11 +2974,9 @@ define('conditionList',['easejs','abstractList', 'condition'], * @param {Condition} _condition Condition */ 'public put' : function(_condition){ - if(Class.isA(Condition, _condition)){ - if(!(this.containsKey(_condition.getName()))){ - this.counter++; - } - this.items[_condition.getName()] = _condition; + if (Class.isA(Condition, _condition)) { + if (!(this.contains(_condition))) { + this.items.push(_condition);} } }, @@ -3170,20 +2990,14 @@ define('conditionList',['easejs','abstractList', 'condition'], * @param {(ConditioneList|Array)} _conditionList ConditionList */ 'public putAll' : function(_conditionList){ - var list = new Array(); - if(_conditionList instanceof Array){ + var list = []; + if (_conditionList instanceof Array) { list = _conditionList; - } else if (Class.isA(ConditionList, _conditionList)) { + } else if (Class.isA(ConditionList, _conditionList)) { list = _conditionList.getItems(); } - for(var i in list){ - var condition = list[i]; - if(Class.isA(Condition, condition)){ - if(!(this.containsKey(condition.getName()))){ - this.counter++; - } - this.items[condition.getName()] = condition; - } + for (var i in list) { + this.put(list[i]); } }, @@ -3194,16 +3008,18 @@ define('conditionList',['easejs','abstractList', 'condition'], * @public * @alias contains * @memberof ConditionList# - * @param {Condition} _item Condition that should be verified. + * @param {Condition} _condition Condition that should be verified. * @returns {boolean} */ - 'public contains' : function(_item){ - if(Class.isA(Condition,_item)){ - var tmp = this.getItem(_item.getName()); - if(!(typeof tmp === 'undefined') && tmp.equals(_item)){ - return true; + 'public contains' : function(_condition){ + if (Class.isA(Condition, _condition)) { + for (var index in this.items) { + var theCondition = this.items[index]; + if (theCondition.equals(_condition)) { + return true; + } } - } + } return false; }, @@ -3213,24 +3029,19 @@ define('conditionList',['easejs','abstractList', 'condition'], * @public * @alias equals * @memberof ConditionList# - * @param {ConditionList} _list ConditionList that should be compared. + * @param {ConditionList} _conditionList ConditionList that should be compared. * @returns {boolean} */ - 'public equals' : function(_list){ - if(Class.isA(ConditionList,_list) && _list.size() == this.size()){ - var items = _list.getItems(); - for(var i in items){ - var item = items[i]; - if(!this.contains(item)){ - return false; - } + 'public equals' : function(_conditionList){ + if (Class.isA(ConditionList, _conditionList) && _conditionList.size() == this.size()) { + for (var index in _conditionList.getItems()) { + var theCondition = _conditionList.getItems()[index]; + if (!this.contains(theCondition)) return false; } return true; - } + } return false; - }, - - + } }); @@ -3242,8 +3053,8 @@ define('conditionList',['easejs','abstractList', 'condition'], * @module Subscriber * @fileOverview */ -define('subscriber',['easejs', 'attributeTypeList', 'callbackList', 'condition', 'conditionList'], - function(easejs, AttributeTypeList, CallbackList, Condition, ConditionList){ +define('subscriber',['easejs', 'attributeList', 'callbackList', 'condition', 'conditionList'], + function(easejs, AttributeList, CallbackList, Condition, ConditionList){ /* * Callback: name and associated Attributes @@ -3311,8 +3122,8 @@ define('subscriber',['easejs', 'attributeTypeList', 'callbackList', 'condition', 'virtual public __construct': function() { this.subscriptionCallbacks = new CallbackList(); - this.subscriptionCallbacks = new AttributeTypeList(); - this.attributesSubset = new AttributeTypeList(); + this.subscriptionCallbacks = new AttributeList(); + this.attributesSubset = new AttributeList(); this.conditions = new ConditionList(); }, @@ -3410,7 +3221,7 @@ define('subscriber',['easejs', 'attributeTypeList', 'callbackList', 'condition', 'public setSubscriberName' : function(_subscriberName){ if(typeof _subscriberName === 'string'){ this.subscriberName = _subscriberName; - }; + } }, @@ -3463,7 +3274,7 @@ define('subscriber',['easejs', 'attributeTypeList', 'callbackList', 'condition', 'public setSubscriptionCallbacks' : function(_subscriptionCallbacks){ if(Class.isA(CallbackList, _subscriptionCallbacks)){ this.subscriptionCallbacks = _subscriptionCallbacks; - }; + } }, /** @@ -3484,12 +3295,12 @@ define('subscriber',['easejs', 'attributeTypeList', 'callbackList', 'condition', * @public * @alias setAttributesSubset * @memberof Subscriber# - * @param {AttributeTypeList} _attributesSubset attributesSubset + * @param {AttributeList} _attributesSubset attributesSubset */ 'public setAttributesSubset' : function(_attributesSubset){ - if(Class.isA(AttributeTypeList, _attributesSubset)){ + if(Class.isA(AttributeList, _attributesSubset)){ this.attributesSubset = _attributesSubset; - }; + } }, /** @@ -3628,23 +3439,14 @@ define('subscriberList',['easejs', 'abstractList', 'subscriber'], * @public * @alias withItems * @memberof SubscriberList# - * @param {(SubscriberList|Array)} - * _subscriberList SubscriberList + * @param {(SubscriberList|Array)} _subscriberList SubscriberList * @returns {SubscriberList} */ 'public withItems': function(_subscriberList){ - var list = new Array(); - if(_subscriberList instanceof Array){ - list = _subscriberList; - } else if (Class.isA( SubscriberList, _subscriberList)) { - list = _subscriberList.getItems(); - } - for(var i in list){ - var subscriber = list[i]; - if(Class.isA( Subscriber, subscriber )){ - this.items[subscriber.getSubscriberId()] = subscriber; - this.counter++; - } + if (_subscriberList instanceof Array) { + this.items = _subscriberList; + } else if (Class.isA(SubscriberList, _subscriberList)) { + this.items = _subscriberList.getItems(); } return this; }, @@ -3655,15 +3457,12 @@ define('subscriberList',['easejs', 'abstractList', 'subscriber'], * @public * @alias put * @memberof SubscriberList# - * @param {Subscriber} - * _subscriber Subscriber + * @param {Subscriber} _subscriber Subscriber */ 'public put' : function(_subscriber){ - if(Class.isA(Subscriber, _subscriber)){ - if(!(this.containsKey(_subscriber.getSubscriberId()))){ - this.counter++; - } - this.items[_subscriber.getSubscriberId()] = _subscriber; + if (Class.isA(Subscriber, _subscriber)) { + if (!(this.contains(_subscriber))) { + this.items.push(_subscriber);} } }, @@ -3676,20 +3475,14 @@ define('subscriberList',['easejs', 'abstractList', 'subscriber'], * @param {(SubscriberList|Array)} _subscriberList SubscriberList */ 'public putAll' : function(_subscriberList){ - var list = new Array(); - if(_subscriberList instanceof Array){ + var list = []; + if (_subscriberList instanceof Array) { list = _subscriberList; - } else if (Class.isA(SubscriberList, _subscriberList)) { + } else if (Class.isA(SubscriberList, _subscriberList)) { list = _subscriberList.getItems(); } - for(var i in list){ - var subscriber = list[i]; - if(Class.isA(Subscriber, subscriber)){ - if(!(this.containsKey(subscriber.getSubscriberId()))){ - this.counter++; - } - this.items[subscriber.getSubscriberId()] = subscriber; - } + for (var i in list) { + this.put(list[i]); } }, @@ -3699,17 +3492,18 @@ define('subscriberList',['easejs', 'abstractList', 'subscriber'], * @public * @alias contains * @memberof SubscriberList# - * @param {Subscriber} - * _item Subscriber that should be verified. + * @param {Subscriber}_subscriber Subscriber that should be verified. * @returns {boolean} */ - 'public contains' : function(_item){ - if(Class.isA(Subscriber,_item)){ - var tmp = this.getItem(_item.getSubscriberId()); - if(!(typeof tmp === 'undefined') && tmp.equals(_item)){ - return true; + 'public contains' : function(_subscriber){ + if (Class.isA(Subscriber, _subscriber)) { + for (var index in this.items) { + var tmp = this.items[index]; + if (tmp.equals(_subscriber)) { + return true; + } } - } + } return false; }, @@ -3718,23 +3512,26 @@ define('subscriberList',['easejs', 'abstractList', 'subscriber'], * @public * @alias equals * @memberof SubscriberList# - * @param {SubscriberList} _list SubscriberList that should be compared. + * @param {SubscriberList} _subscriberList SubscriberList that should be compared. * @returns {boolean} */ - 'public equals' : function(_list){ - if(Class.isA(SubscriberList,_list) && _list.size() == this.size()){ - var items = _list.getItems(); - for(var i in items){ - var item = items[i]; - if(!this.contains(item)){ - return false; - } + 'public equals' : function(_subscriberList) { + if (Class.isA(SubscriberList, _subscriberList) && _subscriberList.size() == this.size()) { + for (var index in _subscriberList.getItems()) { + var theSubscriber = _subscriberList.getItems()[index]; + if (!this.contains(theSubscriber)) return false; } return true; - } + } return false; }, + 'public removeSubscriberWithId': function(_subscriberId) { + for (var index in this.items) { + var theSubscriber = this.items[index]; + if (theSubscriber.getSubscriberId() == _subscriberId) this.items.splice(index, 1); + } + } }); return SubscriberList; @@ -3746,8 +3543,8 @@ define('subscriberList',['easejs', 'abstractList', 'subscriber'], * @module WidgetDescription * @fileOverview */ -define('widgetDescription',['easejs', 'attributeTypeList'], - function(easejs, AttributeTypeList){ +define('widgetDescription',['easejs', 'attributeList'], + function(easejs, AttributeList){ var Class = easejs.Class; var WidgetDescription = Class('WidgetDescription',{ @@ -3795,7 +3592,7 @@ define('widgetDescription',['easejs', 'attributeTypeList'], * @constructs WidgetDescription */ 'virtual public __construct' : function(){ - this.outAttributeTypes = new AttributeTypeList(); + this.outAttributeTypes = new AttributeList(); }, /** @@ -3936,7 +3733,7 @@ define('widgetDescription',['easejs', 'attributeTypeList'], * @public * @alias addOutAttributeTypes * @memberof WidgetDescription# - * @param {(AttributeTypeList|Array)} _outAttributeTypes List of AttributeType that are provided + * @param {(AttributeList|Array)} _outAttributeTypes List of AttributeType that are provided */ 'public addOutAttributeTypes' : function(_outAttributeTypes){ this.outAttributeTypes.putAll(_outAttributeTypes); @@ -3956,11 +3753,12 @@ define('widgetDescription',['easejs', 'attributeTypeList'], * @public * @alias doesSatisfyAttributeType * @memberof WidgetDescription# - * @param {AttributeType} _attributeType + * @param {AttributeType} _attribute * @returns {boolean} */ - 'public doesSatisfyAttributeType': function(_attributeType) { - return this.getOutAttributeTypes().contains(_attributeType); + + 'public doesSatisfyAttributeType': function(_attribute) { + return this.getOutAttributeTypes().containsTypeOf(_attribute); } }); @@ -3973,11 +3771,11 @@ define('widgetDescription',['easejs', 'attributeTypeList'], * @module Widget * @fileOverview */ -define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', - 'attributeValue', 'attributeTypeList', 'attributeValueList', 'conditionList', +define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attribute', + 'attributeList', 'conditionList', 'subscriber', 'subscriberList', 'widgetDescription'], - function(easejs, MathUuid, Callback, CallbackList, AttributeType, - AttributeValue, AttributeTypeList, AttributeValueList, ConditionList, + function(easejs, MathUuid, Callback, CallbackList, Attribute, + AttributeList, ConditionList, Subscriber, SubscriberList, WidgetDescription) { var AbstractClass = easejs.AbstractClass; @@ -3999,27 +3797,11 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @desc ID of the Widget. Will be generated. */ 'public id' : '', - /** - * @alias attributeTypes - * @protected - * @type {AttributeTypeList} - * @memberof Widget# - * @desc Types of all available attributes. - */ - 'protected attributeTypes' : [], - /** - * @alias constantAttributeTypes - * @protected - * @type {AttributeTypeList} - * @memberof Widget# - * @desc Types of all available ConstantAttributes. - */ - 'protected constantAttributeTypes' : [], /** * @alias attributes * @protected - * @type {AttributeValueList} + * @type {AttributeList} * @memberof Widget# * @desc All available Attributes and their values. */ @@ -4027,7 +3809,7 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy /** * @alias oldAttributes * @protected - * @type {AttributeValueList} + * @type {AttributeList} * @memberof Widget# * @desc This temporary variable is used for storing the old attribute values. * So these can be used to check conditions. @@ -4036,7 +3818,7 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy /** * @alias constantAttributes * @protected - * @type {AttributeValueList} + * @type {AttributeList} * @memberof Widget# * @desc All available constant Attributes and their values. */ @@ -4079,10 +3861,8 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @requires MathUuid * @requires Callback * @requires CallbackList - * @requires AttributeType - * @requires AttributeValue - * @requires AttributeTypeList - * @requires AttributeValueList + * @requires Attribute + * @requires AttributeList * @requires ConditionList * @requires Subscriber * @requires SubscriberList @@ -4094,10 +3874,8 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy this.id = Math.uuid(); this.discoverer = _discoverer; this.register(); - this.attributeTypes = new AttributeTypeList(); - this.constantAttributeTypes = new AttributeTypeList(); - this.attributes = new AttributeValueList(); - this.constantAttributes = new AttributeValueList(); + this.attributes = new AttributeList(); + this.constantAttributes = new AttributeList(); this.subscribers = new SubscriberList(); this.callbacks = new CallbackList(); this.init(_attributeTypes); @@ -4145,12 +3923,16 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * Returns the available AttributeTypes. * * @public - * @alias getAttributeTypes + * @alias getAttributes * @memberof Widget# - * @returns {AttributeTypeList} + * @returns {AttributeList} */ - 'public getAttributeTypes' : function() { - return this.attributeTypes; + 'public getAttributes' : function(_attributeList) { + if (Class.isA(AttributeList, _attributeList)) { + return this.attributes.getSubset(_attributeList); + } else { + return this.attributes; + } }, /** @@ -4160,27 +3942,14 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @public * @alias getWidgetConstantAttributeTypes * @memberof Widget# - * @returns {AttributeTypeList} - */ - 'public getWidgetConstantAttributeTypes' : function() { - return this.constantAttributeTypes; - }, - - /** - * Returns the last acquired attribute values. - * - * @public - * @alias getAttributes - * @memberof Widget# - * @param {AttributeTypeList} _attributeTypeList - * @returns {AttributeValueList} + * @returns {AttributeList} */ - 'public getAttributeValues' : function(_attributeTypeList) { - if (Class.isA(AttributeTypeList, _attributeTypeList)) { - return this.attributes.getSubset(_attributeTypeList); - } else { - return this.attributes; - } + 'public getConstantAttributes' : function(_attributeList) { + if (Class.isA(AttributeList, _attributeList)) { + return this.constantAttributes.getSubset(_attributeList); + } else { + return this.constantAttributes; + } }, /** @@ -4189,8 +3958,8 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @param {AttributeType} _attributeType The attribute type to return the last value for. * @returns {*} */ - 'public getAttributeValue': function(_attributeType) { - return this.getAttributeValues().getItemForAttributeType(_attributeType).getValue(); + 'public getValueForAttributeWithTypeOf': function(_attributeType) { + return this.getAttributes().getAttributeWithTypeOf(_attributeType).getValue(); }, /** @@ -4199,24 +3968,12 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @private * @alias getOldAttributes * @memberof Widget# - * @returns {AttributeValueList} + * @returns {AttributeList} */ 'public getOldAttributes' : function() { return this.oldAttributes; }, - /** - * Returns the ConstantAttributes. - * - * @public - * @alias getConstantAttributes - * @memberof Widget# - * @returns {AttributeValueList} - */ - 'public getConstantAttributes' : function() { - return this.constantAttributes; - }, - /** * Returns a list of callbacks that can be * subscribed to. @@ -4334,23 +4091,16 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @public * @alias addAttribute * @memberof Widget# - * @param {AttributeValue} - * _attribute AttributeValue - */ - 'public addAttribute' : function(_attribute) { - if (Class.isA(AttributeValue, _attribute)) { - if (!this.attributes.contains(_attribute)) { - - var type = new AttributeType().withName(_attribute.getName()) - .withType(_attribute.getType()) - .withParameters(_attribute.getParameters()); - this.attributeTypes.put(type); - + * @param {Attribute} _attribute AttributeValue + */ + 'public addAttribute' : function(_attribute, _multipleInstances) { + _multipleInstances = typeof _multipleInstances == "undefined" ? false : _multipleInstances; + if (Class.isA(Attribute, _attribute)) { + if (!this.attributes.containsTypeOf(_attribute)) { + this.oldAttributes = this.attributes; + _attribute.setTimestamp(this.getCurrentTime()); + this.attributes.put(_attribute, _multipleInstances); } - this.oldAttributes = this.attributes; - - _attribute.setTimestamp(this.getCurrentTime()); - this.attributes.put(_attribute); } }, @@ -4500,7 +4250,7 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @param {Subscriber} _subscriber Subscriber */ 'public removeSubscriber' : function(_subscriberId) { - this.subscribers.removeItem(_subscriberId); + this.subscribers.removeSubscriberWithId(_subscriberId); }, /** @@ -4527,7 +4277,7 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @returns {boolean} */ 'protected isAttribute' : function(_attribute) { - return !!this.attributeTypes.contains(_attribute.getAttributeType()); + return !!this.attributes.containsTypeOf(_attribute); }, /** @@ -4652,12 +4402,12 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy var list = []; if (_data instanceof Array) { list = _data; - } else if (Class.isA(AttributeValueList, _data)) { + } else if (Class.isA(AttributeList, _data)) { list = _data.getItems(); } for ( var i in list) { var x = list[i]; - if (Class.isA(AttributeValue, x) && this.isAttribute(x)) { + if (Class.isA(Attribute, x) && this.isAttribute(x)) { this.addAttribute(x); } } @@ -4671,11 +4421,11 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @public * @alias queryWidget * @memberof Widget# - * @returns {AttributeValueList} + * @returns {AttributeList} */ 'public queryWidget' : function() { - var response = new AttributeValueList(); - response.putAll(this.getAttributeValues()); + var response = new AttributeList(); + response.putAll(this.getAttributes()); response.putAll(this.getConstantAttributes()); return response; }, @@ -4688,15 +4438,15 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @alias updateAndQueryWidget * @memberof Widget# * @param {?function} _function For alternative actions, because an asynchronous function can be used. - * @returns {?AttributeValueList} + * @returns {?AttributeList} */ 'virtual public updateAndQueryWidget' : function(_function) { if(_function && typeof(_function) === 'function'){ this.queryGenerator(_function); } else { this.queryGenerator(); - var response = new AttributeValueList(); - response.putAll(this.getAttributeValues()); + var response = new AttributeList(); + response.putAll(this.getAttributes()); response.putAll(this.getConstantAttributes()); return response; } @@ -4715,7 +4465,7 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy var subscriberList = this.subscribers.getItems(); for ( var i in subscriberList) { var subscriber = subscriberList[i]; - if (subscriber.getSubscriptionCallbacks().containsKey( _callback.getName())) { + if (subscriber.getSubscriptionCallbacks().contains(_callback)) { if(this.dataValid(subscriber.getConditions())){ var subscriberInstance = this.discoverer.getComponent(subscriber.getSubscriberId()); var callSubset = _callback.getAttributeTypes(); @@ -4771,8 +4521,8 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy */ 'virtual public getDescription' : function() { var description = new WidgetDescription().withId(this.id).withName(this.name); - description.addOutAttributeTypes(this.attributeTypes); - description.addOutAttributeTypes(this.constantAttributeTypes); + description.addOutAttributeTypes(this.attributes); + description.addOutAttributeTypes(this.constantAttributes); var widgetCallbacks = this.callbacks.getItems(); for(var i in widgetCallbacks) { description.addCallbackName(widgetCallbacks[i].getName()); @@ -4850,8 +4600,8 @@ define('widget',[ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeTy * @module InterpreterDescription * @fileOverview */ -define('interpreterDescription',['easejs','attributeTypeList','widgetDescription'], - function(easejs,AttributeTypeList,WidgetDescription){ +define('interpreterDescription',['easejs','attributeList', 'widgetDescription'], + function(easejs,AttributeList, WidgetDescription){ var Class = easejs.Class; var InterpreterDescription = Class('InterpreterDescription'). extend(WidgetDescription, { @@ -4872,13 +4622,13 @@ define('interpreterDescription',['easejs','attributeTypeList','widgetDescription * @classdesc The description of an interpreter and the communication with it. * @extends WidgetDescription * @requires easejs - * @requires AttributeTypeList + * @requires AttributeList * @requires WidgetDescription * @constructs InterpreterDescription */ 'override public __construct' : function(){ this.__super(); - this.inAttributeTypes = new AttributeTypeList(); + this.inAttributeTypes = new AttributeList(); }, /** @@ -4887,7 +4637,7 @@ define('interpreterDescription',['easejs','attributeTypeList','widgetDescription * @public * @alias withInAttributeTypes * @memberof InterpreterDescription# - * @param {(AttributeTypeList|Array)} _inAttributeTypes List of AttributeType that are expected + * @param {(AttributeList|Array)} _inAttributeTypes List of AttributeType that are expected * @returns {InterpreterDescription} */ 'public withInAttributeTypes' : function(_inAttributeTypes){ @@ -4955,8 +4705,8 @@ define('interpreterDescription',['easejs','attributeTypeList','widgetDescription * @module InterpreterResult * @fileOverview */ -define('interpreterResult',['easejs', 'attributeValueList'], - function(easejs, AttributeValueList){ +define('interpreterResult',['easejs', 'attributeList'], + function(easejs, AttributeList){ var Class = easejs.Class; var InterpreterResult = Class('InterpreterResult',{ @@ -5140,10 +4890,10 @@ define('interpreterResult',['easejs', 'attributeValueList'], * @module Interpreter * @fileOverview */ -define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', - 'attributeValue', 'attributeValueList', 'interpreterDescription', 'interpreterResult' ], - function(easejs, MathUuid, AttributeType, AttributeTypeList, - AttributeValue, AttributeValueList, InterpreterDescription, InterpreterResult) { +define('interpreter',[ 'easejs', 'MathUuid', 'attribute', 'attributeList', + 'interpreterDescription', 'interpreterResult' ], + function(easejs, MathUuid, Attribute, AttributeList, + InterpreterDescription, InterpreterResult) { var Class = easejs.Class; var AbstractClass = easejs.AbstractClass; var Interpreter = AbstractClass('Interpreter', @@ -5165,37 +4915,21 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList */ 'public id' : '', /** - * @alias inAttributeTypes + * @alias inAttributes * @protected - * @type {AttributeTypeList} + * @type {AttributeList} * @memberof Interpreter# * @desc Types of all attributes that can be handled. */ - 'protected inAttributeTypes' : [], + 'protected inAttributes' : [], /** - * @alias outAttributeTypes + * @alias outAttributes * @protected - * @type {AttributeTypeList} + * @type {AttributeList} * @memberof Interpreter# * @desc Types of all attributes that will be returned. */ - 'protected outAttributeTypes' : [], - /** - * @alias inAttributeValues - * @protected - * @type {AttributeValueList} - * @memberof Interpreter# - * @desc List of the data that should be interpreted. - */ - 'protected inAttributeValues' : [], - /** - * @alias outAttributeValues - * @protected - * @type {AttributeValueList} - * @memberof Interpreter# - * @desc List of interpreted data. - */ - 'protected outAttributeValues' : [], + 'protected outAttributes' : [], /** * @alias lastInterpretation * @protected @@ -5221,10 +4955,8 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList * @classdesc The Widget handles the access to sensors. * @requires easejs * @requires MathUuid - * @requires AttributeType - * @requires AttributeValue - * @requires AttributeTypeList - * @requires AttributeValueList + * @requires Attribute + * @requires AttributeList * @requires InterpreterDescription * @constructs Interpreter */ @@ -5232,10 +4964,8 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList this.id = Math.uuid(); this.discoverer = _discoverer; this.register(); - this.inAttributeTypes = new AttributeTypeList(); - this.outAttributeTypes = new AttributeTypeList(); - this.inAttributeValues = new AttributeValueList(); - this.outAttributeValues = new AttributeValueList(); + this.inAttributes = new AttributeList(); + this.outAttributes = new AttributeList(); this.initInterpreter(); }, @@ -5315,10 +5045,10 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList * @public * @alias getInAttributeTypes * @memberof Interpreter# - * @returns {AttributeTypeList} + * @returns {AttributeList} */ - 'public getInAttributeTypes' : function() { - return this.inAttributeTypes; + 'public getInAttributes' : function() { + return this.inAttributes; }, /** @@ -5327,53 +5057,46 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList * @protected * @alias setInAttribute * @memberof Interpreter# - * @param {string} _name name of the attribute - * @param {string} _type type of the attribute - * @param {string} _value value of the attribute - * @param {ParameterList|Array} _parameter Parameter of the attribute. */ - 'protected setInAttribute' : function(_name, _type, _value, _parameters) { - var attributeValue = new AttributeValue().withName(_name) - .withValue(_value).withType(_type).withParameters(_parameters); - if (this.isInAttribute(attributeValue)) { - this.inAttributeValues.put(attributeValue); - } + 'protected setInAttribute' : function(_attribute) { + this.inAttributes.put(_attribute); }, /** * Sets an inAttributes. * * @protected - * @alias setInAttributeValues + * @alias setInAttributes * @memberof Interpreter# - * @param {(AttributeValueList|Array)} _attributeValueList Attributes to set. + * @param {(AttributeList|Array)} _attributeList Attributes to set. */ - 'protected setInAttributeValues' : function(_attributeValueList) { - this.inAttributeValues = new AttributeValueList().withItems(_attributeValueList); + 'protected setInAttributes' : function(_attributeList) { + this.inAttributes = new AttributeList().withItems(_attributeList); }, + /** * Verifies whether the specified attribute is contained in inAttributeList. * * @protected * @alias isInAttribute * @memberof Interpreter# - * @param {AttributeValue} _attribute Attribute that should be verified. + * @param {Attribute} _attribute Attribute that should be verified. * @return {boolean} */ 'protected isInAttribute' : function(_attribute) { - return !!this.inAttributeTypes.contains(_attribute.getAttributeType()); + return !!this.inAttributes.containsTypeOf(_attribute); }, /** * Returns the provided outAttributeTypes. * * @public - * @alias getOutAttributeTypes + * @alias getOutAttributes * @memberof Interpreter# - * @returns {AttributeTypeList} + * @returns {AttributeList} */ - 'public getOutAttributeTypes' : function() { - return this.outAttributeTypes; + 'public getOutAttributes' : function() { + return this.outAttributes; }, /** @@ -5382,17 +5105,21 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList * @protected * @alias setOutAttribute * @memberof Interpreter# - * @param {string} _name name of the attribute - * @param {string} _type type of the attribute - * @param {string} _value value of the attribute - * @param {ParameterList|Array} _parameters Parameter of the attribute. */ - 'protected setOutAttribute' : function(_name, _type, _value,_parameters) { - var attributeValue = new AttributeValue().withName(_name) - .withValue(_value).withType(_type).withParameters(_parameters); - if (this.isOutAttribute(attributeValue)) { - this.outAttributeValues.put(attributeValue); - } + 'protected setOutAttribute' : function(_attribute) { + this.outAttributes.put(_attribute); + }, + + /** + * Sets an outAttributes. + * + * @protected + * @alias setOutAttributes + * @memberof Interpreter# + * @param {(AttributeList|Array)} _attributeList Attributes to set. + */ + 'protected setOutAttributes' : function(_attributeList) { + this.outAttributes = new AttributeList().withItems(_attributeList); }, /** @@ -5401,11 +5128,11 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList * @protected * @alias isOutAttribute * @memberof Interpreter# - * @param {AttributeValue} _attribute Attribute that should be verified. + * @param {Attribute} _attribute Attribute that should be verified. * @return {boolean} */ 'protected isOutAttribute' : function(_attribute) { - return !!this.outAttributeTypes.contains(_attribute.getAttributeType()); + return !!this.outAttributes.containsTypeOf(_attribute); }, /** @@ -5414,21 +5141,22 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList * @public * @alias callInterpreter * @memberof Interpreter# - * @param {AttributeValueList} _inAttributeValues Data that should be interpreted. + * @param {AttributeList} _inAttributeValues Data that should be interpreted. + * @param {AttributeList} _outAttributeValues * @param {?function} _function For additional actions, if an asynchronous function is used. */ 'public callInterpreter' : function(_inAttributeValues, _outAttributeValues, _function) { var self = this; - if (!_inAttributeValues || !this.canHandleInAttributeValues(_inAttributeValues)) throw "Empty input attribute list or unhandled input attribute."; - if (!_outAttributeValues || !this.canHandleOutAttributeValues(_outAttributeValues)) throw "Empty output attribute list or unhandled output attribute."; + if (!_inAttributeValues || !this.canHandleInAttributes(_inAttributeValues)) throw "Empty input attribute list or unhandled input attribute."; + if (!_outAttributeValues || !this.canHandleOutAttributes(_outAttributeValues)) throw "Empty output attribute list or unhandled output attribute."; this.interpretData(_inAttributeValues, _outAttributeValues, function(interpretedData) { - var response = new AttributeValueList().withItems(interpretedData); + var response = new AttributeList().withItems(interpretedData); - if (!self.canHandleOutAttributeValues(response)) throw "Unhandled output attribute generated."; + if (!self.canHandleOutAttributes(response)) throw "Unhandled output attribute generated."; - self.setInAttributeValues(_inAttributeValues); + self.setInAttributes(_inAttributeValues); self.lastInterpretation = new Date(); if (_function && typeof(_function) == 'function'){ @@ -5445,27 +5173,27 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList * @public * @alias interpretData * @memberof Interpreter# - * @param {AttributeValueList} _data Data that should be interpreted. + * @param {AttributeList} _data Data that should be interpreted. * @param {?function} _function For additional actions, if an asynchronous function is used. */ - 'abstract protected interpretData' : ['_inAttributeValues', '_outAttributeValues', '_callback'], + 'abstract protected interpretData' : ['_inAttributes', '_outAttributes', '_callback'], /** * Checks whether the specified data match the expected. * * @protected - * @alias canHandleInAttributeValues + * @alias canHandleInAttributes * @memberof Interpreter# - * @param {AttributeValueList|Array.<AttributeValue>} _inAttributeValues Data that should be verified. + * @param {AttributeList|Array.<Attribute>} _inAttributes Data that should be verified. */ - 'protected canHandleInAttributeValues' : function(_inAttributeValues) { + 'protected canHandleInAttributes' : function(_inAttributes) { var list = []; - if (_inAttributeValues instanceof Array) { - list = _inAttributeValues; - } else if (Class.isA(AttributeValueList, _inAttributeValues)) { - list = _inAttributeValues.getItems(); + if (_inAttributes instanceof Array) { + list = _inAttributes; + } else if (Class.isA(AttributeList, _inAttributes)) { + list = _inAttributes.getItems(); } - if (list.length == 0 || _inAttributeValues.size() != this.getInAttributeTypes().size()) { + if (list.length == 0 || _inAttributes.size() != this.getInAttributes().size()) { return false; } for ( var i in list) { @@ -5481,18 +5209,18 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList * Checks whether the specified data match the expected. * * @protected - * @alias canHandle + * @alias canHandleOutAttributes * @memberof Interpreter# - * @param {AttributeValueList|Array.<AttributeValue>} _outAttributeValues Data that should be verified. + * @param {AttributeList|Array.<Attribute>} _outAttributes Data that should be verified. */ - 'protected canHandleOutAttributeValues' : function(_outAttributeValues) { + 'protected canHandleOutAttributes' : function(_outAttributes) { var list = []; - if (_outAttributeValues instanceof Array) { - list = _outAttributeValues; - } else if (Class.isA(AttributeValueList, _outAttributeValues)) { - list = _outAttributeValues.getItems(); + if (_outAttributes instanceof Array) { + list = _outAttributes; + } else if (Class.isA(AttributeList, _outAttributes)) { + list = _outAttributes.getItems(); } - if (list.length == 0 || _outAttributeValues.size() != this.getOutAttributeTypes().size()) { + if (list.length == 0 || _outAttributes.size() != this.getOutAttributes().size()) { return false; } for ( var i in list) { @@ -5525,10 +5253,9 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList * @returns {InterpreterDescription} */ 'virtual public getDescription' : function() { - var description = new InterpreterDescription().withId( - this.id).withName(this.name); - description.addOutAttributeTypes(this.outAttributeTypes); - description.setInAttributeTypes(this.inAttributeTypes); + var description = new InterpreterDescription().withId(this.id).withName(this.name); + description.addOutAttributeTypes(this.outAttributes); + description.setInAttributeTypes(this.inAttributes); return description; }, @@ -5557,7 +5284,6 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList if (this.discoverer) { this.discoverer.registerNewComponent(this); } - }, /** @@ -5565,28 +5291,12 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList * @returns {boolean} */ 'public hasOutAttributesWithInputParameters': function() { - return this.outAttributeTypes.hasAttributesWithInputParameters(); + return this.outAttributes.hasAttributesWithInputParameters(); }, 'public getOutAttributesWithInputParameters': function() { - return this.outAttributeTypes.getAttributesWithInputParameters(); + return this.outAttributes.getAttributesWithInputParameters(); } - -// /** -// * Unregisters the component to the associated discoverer -// * and deletes the reference. -// * -// * @public -// * @alias register -// * @memberof Widget# -// */ -// 'protected unregister' : function() { -// if (this.discoverer) { -// this.discoverer.unregisterComponent(this.getId()); -// this.discoverer = null; -// } -// }, - }); return Interpreter; @@ -5594,13 +5304,13 @@ define('interpreter',[ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList /** * Created by tobias on 15.04.15. */ -define('interpretation',['easejs', 'interpreter', 'attributeTypeList'], - function(easejs, Interpreter, AttributeTypeList) { +define('interpretation',['easejs', 'interpreter', 'attributeList'], + function(easejs, Interpreter, AttributeList) { var Class = easejs.Class; var Interpretation = Class('Interpretation', { 'public interpreterId' : null, - 'public inAttributeTypes' : new AttributeTypeList(), - 'public outAttributeTypes' : new AttributeTypeList(), + 'public inAttributeTypes' : new AttributeList(), + 'public outAttributeTypes' : new AttributeList(), 'public __construct' : function(_interpreterId, _inAttributes, _outAttributes){ this.interpreterId = _interpreterId; @@ -5621,11 +5331,11 @@ define('interpretation',['easejs', 'interpreter', 'attributeTypeList'], * @fileOverview */ define('aggregator',['easejs', 'MathUuid','widget', - 'attributeType', 'attributeValue', 'attributeValueList', 'subscriber', - 'subscriberList', 'callbackList', 'storage', 'widgetDescription', 'interpreter', 'attributeTypeList', 'interpretation'], - function(easejs, MathUuid, Widget, AttributeType, - AttributeValue, AttributeValueList, Subscriber, SubscriberList, - CallbackList, Storage, WidgetDescription, Interpreter, AttributeTypeList, Interpretation){ + 'attribute', 'attributeList', 'subscriber', + 'subscriberList', 'callbackList', 'storage', 'widgetDescription', 'interpreter', 'interpretation'], + function(easejs, MathUuid, Widget, Attribute, + AttributeList, Subscriber, SubscriberList, + CallbackList, Storage, WidgetDescription, Interpreter, Interpretation){ var Class = easejs.Class; var Aggregator = Class('Aggregator'). @@ -5683,21 +5393,20 @@ define('aggregator',['easejs', 'MathUuid','widget', * @requires easejs * @requires MathUuid * @requires CallbackList - * @requires AttributeType - * @requires AttributeValue - * @requires AttributeValueList + * @requires Attribute + * @requires AttributeList * @requires Subscriber * @requires SubscriberList * @requires Storage * @requires Widget * @constructs Aggregator */ - 'override virtual public __construct': function(_discoverer, _attributeTypes) + 'override virtual public __construct': function(_discoverer, _attributes) { this.id = Math.uuid(); this.widgets = []; this.interpretations = []; - this.__super(_discoverer, _attributeTypes); + this.__super(_discoverer, _attributes); }, /** @@ -5713,22 +5422,6 @@ define('aggregator',['easejs', 'MathUuid','widget', 'override public getType' : function(){ return 'Aggregator'; }, - - /** - * Adds new AttributeTypes, useful when a new Widget is subscribed. - * - * @protected - * @alias addAttributeType - * @memberof Aggregator# - * @param {AttributeType} _attributeType attributeType - */ - 'protected addAttributeType' : function(_attributeType, _multipleInstances){ - if(Class.isA( AttributeType, _attributeType )){ - this.attributeTypes.put(_attributeType, _multipleInstances); - var attVal = new AttributeValue().buildFromAttributeType(_attributeType); - this.attributes.put(attVal, _multipleInstances); - } - }, /** * Sets Widget IDs. @@ -5848,10 +5541,10 @@ define('aggregator',['easejs', 'MathUuid','widget', * @public * @alias didFinishInitialization * @memberof Aggregator# - * @param _attributeTypes + * @param _attributes */ - 'override public didFinishInitialization': function(_attributeTypes) { - this.aggregatorSetup(_attributeTypes); + 'override public didFinishInitialization': function(_attributes) { + this.aggregatorSetup(_attributes); }, /** @@ -5862,9 +5555,9 @@ define('aggregator',['easejs', 'MathUuid','widget', * @alias aggregatorSetup * @memberof Aggregator# */ - 'protected aggregatorSetup' : function(_attributeTypes){ + 'protected aggregatorSetup' : function(_attributes){ this.initStorage('DB_'+this.name); - this.setAggregatorAttributeValues(_attributeTypes); + this.setAggregatorAttributeValues(_attributes); this.setAggregatorConstantAttributeValues(); this.setAggregatorCallbacks(); @@ -5881,10 +5574,10 @@ define('aggregator',['easejs', 'MathUuid','widget', * @alias setAggregatorAttributeValues * @memberof Aggregator# */ - 'virtual protected setAggregatorAttributeValues' : function(_attributeTypes) { - for (var index in _attributeTypes) { - var theAttributeType = _attributeTypes[index]; - this.addAttribute(new AttributeValue().buildFromAttributeType(theAttributeType)); + 'virtual protected setAggregatorAttributeValues' : function(_attributes) { + for (var index in _attributes) { + var theAttribute = _attributes[index]; + this.addAttribute(theAttribute); } }, @@ -5922,12 +5615,10 @@ define('aggregator',['easejs', 'MathUuid','widget', * @public * @alias getCurrentData * @memberof Aggregator# - * @returns {AttributeValueList} + * @returns {AttributeList} */ 'public getCurrentData' : function(){ - var response = new AttributeValueList(); - response.putAll(this.attributes); - return response; + return this.attributes; }, /** @@ -6000,7 +5691,7 @@ define('aggregator',['easejs', 'MathUuid','widget', var typeList = singleCallback.getAttributeTypes().getItems(); for(var y in typeList){ var singleType = typeList[y]; - this.addAttributeType(singleType); + this.addAttribute(singleType); } } this.addWidget(_widgetIdOrWidget); @@ -6018,7 +5709,7 @@ define('aggregator',['easejs', 'MathUuid','widget', * @param {String} _widgetId Widget that should be removed. */ 'public unsubscribeFrom' : function(_widgetId){ - if(typeof _widgetId == "string"){ + if(typeof _widgetId == "string") { var widget = this.discoverer.getComponent(_widgetId); if (widget) { console.log('aggregator unsubscribeFrom: ' + widget.getName()); @@ -6035,18 +5726,18 @@ define('aggregator',['easejs', 'MathUuid','widget', * @public * @alias putData * @memberof Aggregator# - * @param {(AttributeValueList|Array)} _data data that shall be input + * @param {(AttributeList|Array)} _data data that shall be input */ 'override public putData' : function(_data){ var list = []; if(_data instanceof Array){ list = _data; - } else if (Class.isA(AttributeValueList, _data)) { + } else if (Class.isA(AttributeList, _data)) { list = _data.getItems(); } for(var i in list){ var x = list[i]; - if(Class.isA( AttributeValue, x ) && this.isAttribute(x)){ + if(Class.isA(Attribute, x ) && this.isAttribute(x)){ this.addAttribute(x); if(this.db){ this.store(x); @@ -6142,8 +5833,8 @@ define('aggregator',['easejs', 'MathUuid','widget', }, /** - * Only actualizes the attributeType cache in th database. - * For an alternativ action can be used a callback. + * Only updates the attribute cache in the database. + * For an alternative action a callback can be used. * * @public * @alias queryTables @@ -6204,16 +5895,16 @@ define('aggregator',['easejs', 'MathUuid','widget', * * @private * @alias doesSatisfyAttributeType - * @param _attributeType + * @param _attribute * @returns {boolean} */ - 'private doesSatisfyAttributeType': function(_attributeType) { + 'private doesSatisfyAttributeType': function(_attribute) { var componentUUIDs = this.getComponentUUIDs(); var doesSatisfy = false; for (var index in componentUUIDs) { var theComponent = this.discoverer.getComponent(componentUUIDs[index]); - if (theComponent.getDescription().doesSatisfyAttributeType(_attributeType)) { + if (theComponent.getDescription().doesSatisfyAttributeType(_attribute)) { doesSatisfy = true; } } @@ -6228,7 +5919,7 @@ define('aggregator',['easejs', 'MathUuid','widget', * @private * @alias getComponentsForUnsatisfiedAttributeTypes * @memberof Aggregator# - * @param {AttributeTypeList} _unsatisfiedAttributes A list of attributes that components should be searched for. + * @param {AttributeList} _unsatisfiedAttributes A list of attributes that components should be searched for. * @param {boolean} _all If true all attributes must be satisfied by a single component. * @param {Array} _componentTypes An array of components classes that should be searched for (e.g. Widget, Interpreter and Aggregator). */ @@ -6256,14 +5947,14 @@ define('aggregator',['easejs', 'MathUuid','widget', for (var widgetOutAttributeIndex in outAttributes) { var widgetOutAttribute = outAttributes[widgetOutAttributeIndex]; // add the attribute type to the aggregators list of handled attribute types - if (!this.getAttributeTypes().contains(widgetOutAttribute)) this.addAttributeType(widgetOutAttribute); + if (!this.getAttributes().containsTypeOf(widgetOutAttribute)) this.addAttribute(widgetOutAttribute); console.log("I can now satisfy attribute "+widgetOutAttribute+" with the help of "+theComponent.getName()+"! That was easy :)"); - _unsatisfiedAttributes.removeAttributeType(widgetOutAttribute); + _unsatisfiedAttributes.removeAttributeWithTypeOf(widgetOutAttribute); } } else if (Class.isA(Interpreter, theComponent)) { // if the component is an interpreter and all its in attributes can be satisfied, add the interpreter console.log("It's an interpreter."); - var inAttributes = theComponent.getInAttributeTypes().getItems(); + var inAttributes = theComponent.getInAttributes().getItems(); var canSatisfyInAttributes = true; // iterate over the attributes needed to satisfy the interpreter @@ -6275,7 +5966,7 @@ define('aggregator',['easejs', 'MathUuid','widget', // if required attribute is not already satisfied by the aggregator search for components that do if (!this.doesSatisfyAttributeType(theInAttribute)) { console.log("It seems that I can't satisfy "+theInAttribute+", but I will search for components that can."); - var newAttributeList = new AttributeTypeList(); + var newAttributeList = new AttributeList(); newAttributeList.put(theInAttribute); this.getComponentsForUnsatisfiedAttributeTypes(newAttributeList, false, [Widget, Interpreter]); // if the attribute still can't be satisfied drop the interpreter @@ -6296,13 +5987,13 @@ define('aggregator',['easejs', 'MathUuid','widget', // add the attribute type to the aggregators list of handled attribute types for (var unsatisfiedAttributeIndex in _unsatisfiedAttributes.getItems()) { var theUnsatisfiedAttribute = _unsatisfiedAttributes.getItems()[unsatisfiedAttributeIndex]; - if (theUnsatisfiedAttribute.equals(interpreterOutAttribute)) { - this.addAttributeType(theUnsatisfiedAttribute); + if (theUnsatisfiedAttribute.equalsTypeOf(interpreterOutAttribute)) { + this.addAttribute(theUnsatisfiedAttribute); console.log("I can now satisfy attribute "+theUnsatisfiedAttribute+" with the help of "+theComponent.getName()+"! Great!"); - this.interpretations.push(new Interpretation(theComponent.getId(), theComponent.getInAttributeTypes(), new AttributeTypeList().withItems([theUnsatisfiedAttribute]))); + this.interpretations.push(new Interpretation(theComponent.getId(), theComponent.getInAttributes(), new AttributeList().withItems([theUnsatisfiedAttribute]))); } } - _unsatisfiedAttributes.removeAttributeType(interpreterOutAttribute, true); + _unsatisfiedAttributes.removeAttributeWithTypeOf(interpreterOutAttribute, true); } } else { console.log("Found interpreter but can't satisfy required attributes."); @@ -6326,7 +6017,7 @@ define('aggregator',['easejs', 'MathUuid','widget', * @memberof Aggregator# */ 'virtual public didFinishSetup': function() { - unsatisfiedAttributes = this.getAttributeTypes().clone(); + unsatisfiedAttributes = this.getAttributes().clone(); // get all widgets that satisfy attribute types this.getComponentsForUnsatisfiedAttributeTypes(unsatisfiedAttributes, false, [Widget]); @@ -6334,7 +6025,7 @@ define('aggregator',['easejs', 'MathUuid','widget', this.getComponentsForUnsatisfiedAttributeTypes(unsatisfiedAttributes, false, [Interpreter]); console.log("Unsatisfied attributes: "+unsatisfiedAttributes.size()); - console.log("Satisfied attributes: "+this.getAttributeTypes().size()); + console.log("Satisfied attributes: "+this.getAttributes().size()); console.log("Interpretations "+this.interpretations.length); }, @@ -6358,14 +6049,14 @@ define('aggregator',['easejs', 'MathUuid','widget', completedQueriesCounter++; if (completedQueriesCounter == self.widgets.length) { if (_callback && typeof(_callback) == 'function') { - _callback(self.getAttributeValues()); + _callback(self.getAttributes()); } } }); } } else { if (_callback && typeof(_callback) == 'function') { - _callback(self.getAttributeValues()); + _callback(self.getAttributes()); } } }, @@ -6386,15 +6077,15 @@ define('aggregator',['easejs', 'MathUuid','widget', for (var index in this.interpretations) { var theInterpretation = this.interpretations[index]; var theInterpreterId = theInterpretation.interpreterId; - var interpretationInAttributeValues = this.getAttributeValues(theInterpretation.inAttributeTypes); - var interpretationOutAttributeValues = this.getAttributeValues(theInterpretation.outAttributeTypes); + var interpretationInAttributeValues = this.getAttributes(theInterpretation.inAttributeTypes); + var interpretationOutAttributeValues = this.getAttributes(theInterpretation.outAttributeTypes); self.interpretData(theInterpreterId, interpretationInAttributeValues, interpretationOutAttributeValues, function(_interpretedData) { for (var j in _interpretedData.getItems()) { var theInterpretedData = _interpretedData.getItems()[j]; self.addAttribute(theInterpretedData); - if(self.db){ + if (self.db){ self.store(theInterpretedData); } } @@ -6402,14 +6093,14 @@ define('aggregator',['easejs', 'MathUuid','widget', completedQueriesCounter++; if (completedQueriesCounter == self.interpretations.length) { if (_callback && typeof(_callback) == 'function') { - _callback(self.getAttributeValues()); + _callback(self.getAttributes()); } } }); } } else { if (_callback && typeof(_callback) == 'function') { - _callback(self.getAttributeValues()); + _callback(self.getAttributes()); } } }, @@ -6525,8 +6216,8 @@ define('unequals',['easejs', 'conditionMethod'], * @module Discoverer * @fileOverview */ -define('discoverer',[ 'easejs', 'attributeTypeList', 'widget', 'interpreter', 'aggregator' ], function(easejs, - AttributeTypeList, Widget, Interpreter, Aggregator) { +define('discoverer',[ 'easejs', 'attributeList', 'widget', 'interpreter', 'aggregator' ], function(easejs, + AttributeList, Widget, Interpreter, Aggregator) { var Class = easejs.Class; var Discoverer = Class('Discoverer', { @@ -6564,7 +6255,7 @@ define('discoverer',[ 'easejs', 'attributeTypeList', 'widget', 'interpreter', 'a * @class Discoverer * @classdesc The Discoverer handles requests for components and attributes. * @requires easejs - * @requires AttributeTypeList + * @requires AttributeList * @constructs Discoverer */ 'public __construct' : function() { @@ -6821,27 +6512,27 @@ define('discoverer',[ 'easejs', 'attributeTypeList', 'widget', 'interpreter', 'a * @public * @alias getComponentsByAttributes * @memberof Discoverer# - * @param {AttributeTypeList} _attributeTypeList list of searched attributes + * @param {AttributeList} _attributeList list of searched attributes * @param {boolean} _all choise of the verification mode * @param {Array} _componentTypes Components types to search for * @returns {Array} */ - 'public getComponentsByAttributes' : function(_attributeTypeList, _all, _componentTypes) { + 'public getComponentsByAttributes' : function(_attributeList, _all, _componentTypes) { var componentList = []; var list = {}; if (typeof _componentTypes == "undefined") _componentTypes = [Widget, Interpreter, Aggregator]; - if (_attributeTypeList instanceof Array) { - list = _attributeTypeList; - } else if (Class.isA(AttributeTypeList, _attributeTypeList)) { - list = _attributeTypeList.getItems(); + if (_attributeList instanceof Array) { + list = _attributeList; + } else if (Class.isA(AttributeList, _attributeList)) { + list = _attributeList.getItems(); } if (typeof list != "undefined") { var descriptions = this.getDescriptions(_componentTypes); for (var i in descriptions) { var description = descriptions[i]; - if(_all && this.containsAllAttributes(description, list)){ + if(_all && this.containsAllAttributes(description, list)) { componentList.push(this.getComponent(description.getId())); - } else if(!_all && this.containsAtLeastOneAttribute(description, list)){ + } else if(!_all && this.containsAtLeastOneAttribute(description, list)) { componentList.push(this.getComponent(description.getId())); } } @@ -6937,10 +6628,8 @@ define('discoverer',[ 'easejs', 'attributeTypeList', 'widget', 'interpreter', 'a define('contactJS',['retrievalResult', 'storage', 'aggregator', - 'attributeType', - 'attributeValue', - 'attributeTypeList', - 'attributeValueList', + 'attribute', + 'attributeList', 'parameter', 'parameterList', 'condition', @@ -6962,10 +6651,8 @@ define('discoverer',[ 'easejs', 'attributeTypeList', 'widget', 'interpreter', 'a function(RetrievalResult, Storage, Aggregator, - AttributeType, - AttributeValue, - AttributeTypeList, - AttributeValueList, + Attribute, + AttributeList, Parameter, ParameterList, Condition, @@ -6989,15 +6676,13 @@ define('discoverer',[ 'easejs', 'attributeTypeList', 'widget', 'interpreter', 'a var contactJS = function(obj) { return obj; }; - contactJS.VERSION = '1.1.0'; + contactJS.VERSION = '1.2.0'; // Methods contactJS.RetrievalResult = RetrievalResult; contactJS.Storage = Storage; contactJS.Aggregator = Aggregator; - contactJS.AttributeType = AttributeType; - contactJS.AttributeValue = AttributeValue; - contactJS.AttributeTypeList = AttributeTypeList; - contactJS.AttributeValueList = AttributeValueList; + contactJS.Attribute = Attribute; + contactJS.AttributeList = AttributeList; contactJS.Parameter = Parameter; contactJS.ParameterList = ParameterList; contactJS.Condition = Condition; diff --git a/examples/GeoLocationWidget.js b/examples/GeoLocationWidget.js index 072c7606e555c10c8bee99e23f5c8908e2ab0722..c8fd8515b90f41e55f693c2374419bb30dd3c37f 100644 --- a/examples/GeoLocationWidget.js +++ b/examples/GeoLocationWidget.js @@ -1,173 +1,62 @@ /** - * This module represents a GeoLocationWidget. It is a subclass of Widget. - * - * @module GeoLocationWidget - * @fileOverview + * Created by tobias on 25.04.15. */ -define([ 'easejs', 'contactJS' ], - function(easejs, contactJS) { - - var Class = easejs.Class; - /** - * @class GeoLocationWidget - * @classdesc This Widget provides the current position of the - * device. - * @extends Widget - * @requires easejs - * @requires Widget - * @requires AttributeType - * @requires AttributeValue - * @requires AttributeTypeList - * @requires AttributeValueList - * @requires Callback - * @requires Parameter - */ - - var GeoLocationWidget = Class('GeoLocationWidget').extend(contactJS.Widget,{ - - /** - * @alias name - * @public - * @type {string} - * @memberof GeoLocationWidget# - * @desc Name of the Widget. In this case: GeoLocationWidget - */ - 'public name' : 'GeoLocationWidget', - - /** - * Initializes attributes. For this class: Latitude and - * Longitude - * - * @protected - * @alias initAttributes - * @memberof GeoLocationWidget# - */ - 'protected initAttributes' : function() { - var latitude = new contactJS.AttributeValue().withName('latitude') - .withType('double') - .withValue('undefined'); - this.addAttribute(latitude); - var longitude = new contactJS.AttributeValue().withName('longitude') - .withType('double') - .withValue('undefined'); - this.addAttribute(longitude); - }, - - /** - * Initializes constantAttributes. For this class: no - * constantAttributes available - * - * @protected - * @alias initConstantAttributes - * @memberof GeoLocationWidget# - */ - 'protected initConstantAttributes' : function() { - }, - - /** - * Initializes Callbacks. For this class: - * UPDATE (latitude and longitude) - * - * @protected - * @alias initCallbacks - * @memberof GeoLocationWidget# - */ - 'protected initCallbacks' : function() { - var list = new contactJS.AttributeTypeList(); - list.put(this.getAttributeTypes().getItem("(latitude:double)")); - list.put(this.getAttributeTypes().getItem("(longitude:double)")); - var call = new contactJS.Callback().withName('UPDATE').withAttributeTypes(list); - this.addCallback(call); - }, - - 'override public notify' : function() { - var callbacks = this.getCallbackList().getItems(); - for(var i in callbacks){ - this.sendToSubscriber(callbacks[i]); - } - }, - - /** - * Implements queryGenerator(). Query latitude and - * longitude by calling - * navigator.geolocation.getCurrentPosition(). - * - * @override - * @protected - * @alias queryGenerator - * @memberof GeoLocationWidget# - */ - 'override protected queryGenerator' : function(_function) { - var self = this; - if(navigator.geolocation){ - navigator.geolocation.getCurrentPosition(function(_position) { - self.onSuccess(_position, self, _function); - }, function(error) { - self.onError(error, self, _function); - }); - } else { - alert("Keine Ortung moeglich"); - } - - }, - - /** - * Success function for navigator.geolocation.getCurrentPosition() used in - * queryGenerator(). Stores the values in the associated attributes. - * - * @callback - * @private - * @alias onSuccess - * @memberof GeoLocationWidget# - * @param _position - * @param {this} self - */ - 'private onSuccess' : function(_position, self, _function) { - var latitude = new contactJS.AttributeValue().withName('latitude') - .withType('double') - .withValue(_position.coords.latitude); - var longitude = new contactJS.AttributeValue().withName('longitude') - .withType('double') - .withValue(_position.coords.longitude); - - var response = new contactJS.AttributeValueList(); - response.put(latitude); - response.put(longitude); - self.putData(response); - self.notify(); - if (_function && typeof(_function) == 'function'){ - _function(); - } - }, +define(['easejs', 'contactJS'], function (easejs, contactJS) { + var Class = easejs.Class; + + var GeoLocationWidget = Class('GeoLocationWidget').extend(contactJS.Widget, { + 'public name': 'GeoLocationWidget', + + 'protected initAttributes': function () { + var latitude = new contactJS.Attribute() + .withName('latitude') + .withType('double'); + + var longitude = new contactJS.Attribute() + .withName('longitude') + .withType('double'); + + this.addAttribute(latitude); + this.addAttribute(longitude); + }, + + 'protected initConstantAttributes': function () { + + }, + + 'protected initCallbacks': function () { + this.addCallback(new contactJS.Callback().withName('UPDATE').withAttributeTypes(this.getAttributes())); + }, + + 'override protected queryGenerator': function (_function) { + var self = this; + var response = new contactJS.AttributeList(); + + if(navigator.geolocation){ + navigator.geolocation.getCurrentPosition(function(_position) { + response.put(self.getAttributes().getItems()[0].setValue(_position.coords.latitude)); + response.put(self.getAttributes().getItems()[1].setValue(_position.coords.longitude)); + + self.sendResponse(response, _function); + }, function(error) { + //TODO: handle error + self.sendResponse(response, _function); + }); + } else { + //TODO: handle error + self.sendResponse(response, _function); + } + }, - /** - * Error function for navigator.geolocation.getCurrentPosition() used in - * queryGenerator(). - * - * @callback - * @private - * @alias onError - * @memberof GeoLocationWidget# - * @param error - * @param {this} self - */ - 'private onError' : function(error, self, _function) { - var latitude = new contactJS.AttributeValue().withName('latitude') - .withType('double') - .withValue("request_error"); - var longitude = new contactJS.AttributeValue().withName('longitude') - .withType('double') - .withValue("request_error"); + 'private sendResponse': function(response, _function) { + this.putData(response); + this.notify(); - var response = new contactJS.AttributeValueList(); - response.put(latitude); - response.put(longitude); - self.putData(response); - self.notify(); - if (_function && typeof(_function) == 'function'){ - _function(); - } + if (_function && typeof(_function) == 'function') { + _function(); } - }); - return GeoLocationWidget; - }); \ No newline at end of file + } + }); + + return GeoLocationWidget; +}); \ No newline at end of file diff --git a/examples/addressInterpreter.js b/examples/addressInterpreter.js index 8b8d42296824587d124ac8d27e40460790d5f074..def370a4aa0024d316d7bdfb578f2110f6171748 100644 --- a/examples/addressInterpreter.js +++ b/examples/addressInterpreter.js @@ -1,162 +1,58 @@ /** - * This module representing an AddressInterpreter. - * - * @module AddressInterpreter - * @fileOverview + * Created by tobias on 25.03.15. */ -define(['easejs', 'jquery', 'contactJS'], - function(easejs, $, contactJS) { +define(['easejs', 'contactJS'], + function(easejs, contactJS) { var Class = easejs.Class; - /** - * @class AddressInterpreter - * @classdesc This Widget returns the address of specified coordinates. - * @extends Interpreter - * @requires easejs - * @requires jquery - * @requires Interpreter - * @requires AttributeType - * @requires AttributeValue - * @requires Parameter - */ - var AddressInterpreter = Class('AddressInterpreter').extend(contactJS.Interpreter,{ - /** - * @alias name - * @public - * @type {String} - * @memberof AddressInterpreter# - * @desc Name of the Interpreter. In this case: AddressInterpreter - */ + + var AddressInterpreter = Class('AddressInterpreter').extend(contactJS.Interpreter, { 'public name' : 'AddressInterpreter', - /** - * @alias adress - * @private - * @type {Array} - * @memberof AddressInterpreter# - */ - 'private address' : [], - /** - * Initializes inAttributes. For this class: Latitude and - * Longitude - * - * @protected - * @alias initInAttributes - * @memberof AddressInterpreter# - */ 'protected initInAttributes' : function() { - var latitude = new contactJS.AttributeType() - .withName('latitude').withType('double'); - this.inAttributeTypes.put(latitude); - var longitude = new contactJS.AttributeType() - .withName('longitude').withType('double'); - this.inAttributeTypes.put(longitude); + this.setInAttributes([ + new contactJS.Attribute() + .withName('latitude') + .withType('double'), + new contactJS.Attribute() + .withName('longitude') + .withType('double') + ]); }, - /** - * Initializes outAttributes. For this class: Address as String - * - * @protected - * @alias initOutAttributes - * @memberof AddressInterpreter# - */ 'protected initOutAttributes' : function() { - var formattedAddress = new contactJS.AttributeType() + this.setOutAttribute( + new contactJS.Attribute() .withName('formattedAddress') - .withType('string'); - this.outAttributeTypes.put(formattedAddress); + .withType('string') + ); }, - /** - * Changes coordinates to address - * - * @protected - * @alias interpretData - * @memberof AddressInterpreter# - * @param {AttributeValueList} _data list of data that should be interpreted - * @param {?function} _function for additional actions, if an asynchronous function is used - */ - 'protected interpretData' : function(_data, _function) { - if(navigator.onLine){ - var self = this; - var lat = _data.getItem('(latitude:double)'); - var lng = _data.getItem('(longitude:double)'); - if (lat.getValue() && lng.getValue()) { - var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" - + lat.getValue()+ ","+ lng.getValue()+ "&sensor=false"; - $.getJSON(url, function(json) {self.createAddress(json, self.response, self, _function);}); - } - } else { - alert("Keine Internetverbindung verfuegbar"); - } - }, + 'protected interpretData' : function(_inAttributeValues, _outAttributeValues, _callback) { + var addressValue = _outAttributeValues.getItems()[0]; - /** - * Success function for callback createAddress() used in interpretData(). - * Sets the outAttributes. - * - * @callback - * @private - * @alias response - * @memberof AddressInterpreter# - * @param {AddressInterpreter} self - * @param {?function} _function for additional actions, if an asynchronous function is used - - */ - 'private response' : function(self, _function) { - self.setOutAttribute('formattedAddress','string', self.address["formatted_address"]); - if (_function && typeof(_function) == 'function'){ - _function(); - } - }, + var latitude = _inAttributeValues.getValueForAttributeWithTypeOf(this.inAttributes.getItems()[0]); + var longitude = _inAttributeValues.getValueForAttributeWithTypeOf(this.inAttributes.getItems()[1]); - /** - * Creates the address. - * - * @callback - * @private - * @alias createAddress - * @memberof AddressInterpreter# - * @param {Array} json - * @param {function} _function for additional actions, because an asynchronous function is used - * @param {AddressInterpreter} self for usage in callback - * @param {?function} secondFunction for additional actions, if an asynchronous function is used - */ - 'private createAddress' : function(json, _function, self, secondFunction) { - if (!self.checkStatus(json)){ - alert("Keine Adresse ermittelbar"); + if(navigator.onLine){ + if (latitude && longitude) { + var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+latitude+","+longitude+"&sensor=false"; + $.getJSON(url, function(json) { + if (!json["status"] == ("OK")) { + //TODO: handle error case + addressValue.setValue("NO_VALUE"); + } else { + addressValue.setValue(json["results"][0]["formatted_address"]); + } + _callback([addressValue]); + }); + } } else { - self.address['formatted_address'] = self.googleGetAddress(json, self); - _function(self, secondFunction); + //TODO: handle error case + addressValue.setValue("NO_VALUE"); + _callback([addressValue]); } - }, - - /** - * Check status. - * - * @private - * @alias checkStatus - * @memberof AddressInterpreter# - * @param {Array} json - */ - 'private checkStatus' : function(json) { - return json["status"] == "OK"; - - }, - - /** - * Stores address in array. - * - * @private - * @alias googleGetAddress - * @memberof AddressInterpreter# - * @param {Array} json - * @param {AddressInterpreter} self - */ - 'private googleGetAddress' : function(json, - self) { - return json["results"][0]["formatted_address"]; } - }); + }); return AddressInterpreter; - }); \ No newline at end of file + }); \ No newline at end of file diff --git a/js/config.js b/js/config.js index d79116981d60980e891abb2668d352c0a4bf169f..4599fb450ae076969efd60982b304894c6c3af5d 100644 --- a/js/config.js +++ b/js/config.js @@ -12,10 +12,8 @@ requirejs.config({ storage: 'modules/aggregator/storage/storage', aggregator: 'modules/aggregator/aggregator', interpretation: 'modules/aggregator/interpretation', - attributeType: 'modules/attribute/attributeType', - attributeValue: 'modules/attribute/attributeValue', - attributeTypeList: 'modules/attribute/attributeTypeList', - attributeValueList: 'modules/attribute/attributeValueList', + attribute: 'modules/attribute/attribute', + attributeList: 'modules/attribute/attributeList', parameter: 'modules/attribute/parameter', parameterList: 'modules/attribute/parameterList', condition: 'modules/subscriber/condition/condition', diff --git a/js/modules/abstractList.js b/js/modules/abstractList.js index 04a65f01393acb8ee1ab1df5c4203c7ff7554c2a..03d78ed7d8f6ce0265f899db0801ee1ca40f1b26 100644 --- a/js/modules/abstractList.js +++ b/js/modules/abstractList.js @@ -13,8 +13,6 @@ define([ 'easejs' ], function(easejs) { * @requires easejs */ var AbstractList = AbstractClass('AbstractList', { - - /** * @alias items * @protected @@ -83,19 +81,6 @@ define([ 'easejs' ], function(easejs) { */ 'abstract public equals' : [ 'list' ], - /** - * Verifies whether an item exists for the specified key. - * - * @public - * @alias containsKey - * @memberof AbstractList# - * @param {string} _key Key that should be verified. - * @returns {boolean} - */ - 'public containsKey' : function(_key) { - return !!(typeof _key !== 'undefined' && typeof this.items[_key] !== 'undefined'); - }, - /** * Returns the item for the specified key. * @public diff --git a/js/modules/aggregator/aggregator.js b/js/modules/aggregator/aggregator.js index 6463b6ac1fc8c194e6a592870ca6ab57919b7a75..5bc1abde455704b8e12d02f451fbee9b49f2128a 100644 --- a/js/modules/aggregator/aggregator.js +++ b/js/modules/aggregator/aggregator.js @@ -6,11 +6,11 @@ * @fileOverview */ define(['easejs', 'MathUuid','widget', - 'attributeType', 'attributeValue', 'attributeValueList', 'subscriber', - 'subscriberList', 'callbackList', 'storage', 'widgetDescription', 'interpreter', 'attributeTypeList', 'interpretation'], - function(easejs, MathUuid, Widget, AttributeType, - AttributeValue, AttributeValueList, Subscriber, SubscriberList, - CallbackList, Storage, WidgetDescription, Interpreter, AttributeTypeList, Interpretation){ + 'attribute', 'attributeList', 'subscriber', + 'subscriberList', 'callbackList', 'storage', 'widgetDescription', 'interpreter', 'interpretation'], + function(easejs, MathUuid, Widget, Attribute, + AttributeList, Subscriber, SubscriberList, + CallbackList, Storage, WidgetDescription, Interpreter, Interpretation){ var Class = easejs.Class; var Aggregator = Class('Aggregator'). @@ -68,21 +68,20 @@ define(['easejs', 'MathUuid','widget', * @requires easejs * @requires MathUuid * @requires CallbackList - * @requires AttributeType - * @requires AttributeValue - * @requires AttributeValueList + * @requires Attribute + * @requires AttributeList * @requires Subscriber * @requires SubscriberList * @requires Storage * @requires Widget * @constructs Aggregator */ - 'override virtual public __construct': function(_discoverer, _attributeTypes) + 'override virtual public __construct': function(_discoverer, _attributes) { this.id = Math.uuid(); this.widgets = []; this.interpretations = []; - this.__super(_discoverer, _attributeTypes); + this.__super(_discoverer, _attributes); }, /** @@ -98,22 +97,6 @@ define(['easejs', 'MathUuid','widget', 'override public getType' : function(){ return 'Aggregator'; }, - - /** - * Adds new AttributeTypes, useful when a new Widget is subscribed. - * - * @protected - * @alias addAttributeType - * @memberof Aggregator# - * @param {AttributeType} _attributeType attributeType - */ - 'protected addAttributeType' : function(_attributeType, _multipleInstances){ - if(Class.isA( AttributeType, _attributeType )){ - this.attributeTypes.put(_attributeType, _multipleInstances); - var attVal = new AttributeValue().buildFromAttributeType(_attributeType); - this.attributes.put(attVal, _multipleInstances); - } - }, /** * Sets Widget IDs. @@ -233,10 +216,10 @@ define(['easejs', 'MathUuid','widget', * @public * @alias didFinishInitialization * @memberof Aggregator# - * @param _attributeTypes + * @param _attributes */ - 'override public didFinishInitialization': function(_attributeTypes) { - this.aggregatorSetup(_attributeTypes); + 'override public didFinishInitialization': function(_attributes) { + this.aggregatorSetup(_attributes); }, /** @@ -247,9 +230,9 @@ define(['easejs', 'MathUuid','widget', * @alias aggregatorSetup * @memberof Aggregator# */ - 'protected aggregatorSetup' : function(_attributeTypes){ + 'protected aggregatorSetup' : function(_attributes){ this.initStorage('DB_'+this.name); - this.setAggregatorAttributeValues(_attributeTypes); + this.setAggregatorAttributeValues(_attributes); this.setAggregatorConstantAttributeValues(); this.setAggregatorCallbacks(); @@ -266,10 +249,10 @@ define(['easejs', 'MathUuid','widget', * @alias setAggregatorAttributeValues * @memberof Aggregator# */ - 'virtual protected setAggregatorAttributeValues' : function(_attributeTypes) { - for (var index in _attributeTypes) { - var theAttributeType = _attributeTypes[index]; - this.addAttribute(new AttributeValue().buildFromAttributeType(theAttributeType)); + 'virtual protected setAggregatorAttributeValues' : function(_attributes) { + for (var index in _attributes) { + var theAttribute = _attributes[index]; + this.addAttribute(theAttribute); } }, @@ -307,12 +290,10 @@ define(['easejs', 'MathUuid','widget', * @public * @alias getCurrentData * @memberof Aggregator# - * @returns {AttributeValueList} + * @returns {AttributeList} */ 'public getCurrentData' : function(){ - var response = new AttributeValueList(); - response.putAll(this.attributes); - return response; + return this.attributes; }, /** @@ -385,7 +366,7 @@ define(['easejs', 'MathUuid','widget', var typeList = singleCallback.getAttributeTypes().getItems(); for(var y in typeList){ var singleType = typeList[y]; - this.addAttributeType(singleType); + this.addAttribute(singleType); } } this.addWidget(_widgetIdOrWidget); @@ -403,7 +384,7 @@ define(['easejs', 'MathUuid','widget', * @param {String} _widgetId Widget that should be removed. */ 'public unsubscribeFrom' : function(_widgetId){ - if(typeof _widgetId == "string"){ + if(typeof _widgetId == "string") { var widget = this.discoverer.getComponent(_widgetId); if (widget) { console.log('aggregator unsubscribeFrom: ' + widget.getName()); @@ -420,18 +401,18 @@ define(['easejs', 'MathUuid','widget', * @public * @alias putData * @memberof Aggregator# - * @param {(AttributeValueList|Array)} _data data that shall be input + * @param {(AttributeList|Array)} _data data that shall be input */ 'override public putData' : function(_data){ var list = []; if(_data instanceof Array){ list = _data; - } else if (Class.isA(AttributeValueList, _data)) { + } else if (Class.isA(AttributeList, _data)) { list = _data.getItems(); } for(var i in list){ var x = list[i]; - if(Class.isA( AttributeValue, x ) && this.isAttribute(x)){ + if(Class.isA(Attribute, x ) && this.isAttribute(x)){ this.addAttribute(x); if(this.db){ this.store(x); @@ -527,8 +508,8 @@ define(['easejs', 'MathUuid','widget', }, /** - * Only actualizes the attributeType cache in th database. - * For an alternativ action can be used a callback. + * Only updates the attribute cache in the database. + * For an alternative action a callback can be used. * * @public * @alias queryTables @@ -589,16 +570,16 @@ define(['easejs', 'MathUuid','widget', * * @private * @alias doesSatisfyAttributeType - * @param _attributeType + * @param _attribute * @returns {boolean} */ - 'private doesSatisfyAttributeType': function(_attributeType) { + 'private doesSatisfyAttributeType': function(_attribute) { var componentUUIDs = this.getComponentUUIDs(); var doesSatisfy = false; for (var index in componentUUIDs) { var theComponent = this.discoverer.getComponent(componentUUIDs[index]); - if (theComponent.getDescription().doesSatisfyAttributeType(_attributeType)) { + if (theComponent.getDescription().doesSatisfyAttributeType(_attribute)) { doesSatisfy = true; } } @@ -613,7 +594,7 @@ define(['easejs', 'MathUuid','widget', * @private * @alias getComponentsForUnsatisfiedAttributeTypes * @memberof Aggregator# - * @param {AttributeTypeList} _unsatisfiedAttributes A list of attributes that components should be searched for. + * @param {AttributeList} _unsatisfiedAttributes A list of attributes that components should be searched for. * @param {boolean} _all If true all attributes must be satisfied by a single component. * @param {Array} _componentTypes An array of components classes that should be searched for (e.g. Widget, Interpreter and Aggregator). */ @@ -641,14 +622,14 @@ define(['easejs', 'MathUuid','widget', for (var widgetOutAttributeIndex in outAttributes) { var widgetOutAttribute = outAttributes[widgetOutAttributeIndex]; // add the attribute type to the aggregators list of handled attribute types - if (!this.getAttributeTypes().contains(widgetOutAttribute)) this.addAttributeType(widgetOutAttribute); + if (!this.getAttributes().containsTypeOf(widgetOutAttribute)) this.addAttribute(widgetOutAttribute); console.log("I can now satisfy attribute "+widgetOutAttribute+" with the help of "+theComponent.getName()+"! That was easy :)"); - _unsatisfiedAttributes.removeAttributeType(widgetOutAttribute); + _unsatisfiedAttributes.removeAttributeWithTypeOf(widgetOutAttribute); } } else if (Class.isA(Interpreter, theComponent)) { // if the component is an interpreter and all its in attributes can be satisfied, add the interpreter console.log("It's an interpreter."); - var inAttributes = theComponent.getInAttributeTypes().getItems(); + var inAttributes = theComponent.getInAttributes().getItems(); var canSatisfyInAttributes = true; // iterate over the attributes needed to satisfy the interpreter @@ -660,7 +641,7 @@ define(['easejs', 'MathUuid','widget', // if required attribute is not already satisfied by the aggregator search for components that do if (!this.doesSatisfyAttributeType(theInAttribute)) { console.log("It seems that I can't satisfy "+theInAttribute+", but I will search for components that can."); - var newAttributeList = new AttributeTypeList(); + var newAttributeList = new AttributeList(); newAttributeList.put(theInAttribute); this.getComponentsForUnsatisfiedAttributeTypes(newAttributeList, false, [Widget, Interpreter]); // if the attribute still can't be satisfied drop the interpreter @@ -681,13 +662,13 @@ define(['easejs', 'MathUuid','widget', // add the attribute type to the aggregators list of handled attribute types for (var unsatisfiedAttributeIndex in _unsatisfiedAttributes.getItems()) { var theUnsatisfiedAttribute = _unsatisfiedAttributes.getItems()[unsatisfiedAttributeIndex]; - if (theUnsatisfiedAttribute.equals(interpreterOutAttribute)) { - this.addAttributeType(theUnsatisfiedAttribute); + if (theUnsatisfiedAttribute.equalsTypeOf(interpreterOutAttribute)) { + this.addAttribute(theUnsatisfiedAttribute); console.log("I can now satisfy attribute "+theUnsatisfiedAttribute+" with the help of "+theComponent.getName()+"! Great!"); - this.interpretations.push(new Interpretation(theComponent.getId(), theComponent.getInAttributeTypes(), new AttributeTypeList().withItems([theUnsatisfiedAttribute]))); + this.interpretations.push(new Interpretation(theComponent.getId(), theComponent.getInAttributes(), new AttributeList().withItems([theUnsatisfiedAttribute]))); } } - _unsatisfiedAttributes.removeAttributeType(interpreterOutAttribute, true); + _unsatisfiedAttributes.removeAttributeWithTypeOf(interpreterOutAttribute, true); } } else { console.log("Found interpreter but can't satisfy required attributes."); @@ -711,7 +692,7 @@ define(['easejs', 'MathUuid','widget', * @memberof Aggregator# */ 'virtual public didFinishSetup': function() { - unsatisfiedAttributes = this.getAttributeTypes().clone(); + unsatisfiedAttributes = this.getAttributes().clone(); // get all widgets that satisfy attribute types this.getComponentsForUnsatisfiedAttributeTypes(unsatisfiedAttributes, false, [Widget]); @@ -719,7 +700,7 @@ define(['easejs', 'MathUuid','widget', this.getComponentsForUnsatisfiedAttributeTypes(unsatisfiedAttributes, false, [Interpreter]); console.log("Unsatisfied attributes: "+unsatisfiedAttributes.size()); - console.log("Satisfied attributes: "+this.getAttributeTypes().size()); + console.log("Satisfied attributes: "+this.getAttributes().size()); console.log("Interpretations "+this.interpretations.length); }, @@ -743,14 +724,14 @@ define(['easejs', 'MathUuid','widget', completedQueriesCounter++; if (completedQueriesCounter == self.widgets.length) { if (_callback && typeof(_callback) == 'function') { - _callback(self.getAttributeValues()); + _callback(self.getAttributes()); } } }); } } else { if (_callback && typeof(_callback) == 'function') { - _callback(self.getAttributeValues()); + _callback(self.getAttributes()); } } }, @@ -771,15 +752,15 @@ define(['easejs', 'MathUuid','widget', for (var index in this.interpretations) { var theInterpretation = this.interpretations[index]; var theInterpreterId = theInterpretation.interpreterId; - var interpretationInAttributeValues = this.getAttributeValues(theInterpretation.inAttributeTypes); - var interpretationOutAttributeValues = this.getAttributeValues(theInterpretation.outAttributeTypes); + var interpretationInAttributeValues = this.getAttributes(theInterpretation.inAttributeTypes); + var interpretationOutAttributeValues = this.getAttributes(theInterpretation.outAttributeTypes); self.interpretData(theInterpreterId, interpretationInAttributeValues, interpretationOutAttributeValues, function(_interpretedData) { for (var j in _interpretedData.getItems()) { var theInterpretedData = _interpretedData.getItems()[j]; self.addAttribute(theInterpretedData); - if(self.db){ + if (self.db){ self.store(theInterpretedData); } } @@ -787,14 +768,14 @@ define(['easejs', 'MathUuid','widget', completedQueriesCounter++; if (completedQueriesCounter == self.interpretations.length) { if (_callback && typeof(_callback) == 'function') { - _callback(self.getAttributeValues()); + _callback(self.getAttributes()); } } }); } } else { if (_callback && typeof(_callback) == 'function') { - _callback(self.getAttributeValues()); + _callback(self.getAttributes()); } } }, diff --git a/js/modules/aggregator/interpretation.js b/js/modules/aggregator/interpretation.js index b18b1f0ac1953255dbd1718cbc716bf0f4018eb0..21a5a10c2af25184a6a5ad28e62edc1aff4795aa 100644 --- a/js/modules/aggregator/interpretation.js +++ b/js/modules/aggregator/interpretation.js @@ -1,13 +1,13 @@ /** * Created by tobias on 15.04.15. */ -define(['easejs', 'interpreter', 'attributeTypeList'], - function(easejs, Interpreter, AttributeTypeList) { +define(['easejs', 'interpreter', 'attributeList'], + function(easejs, Interpreter, AttributeList) { var Class = easejs.Class; var Interpretation = Class('Interpretation', { 'public interpreterId' : null, - 'public inAttributeTypes' : new AttributeTypeList(), - 'public outAttributeTypes' : new AttributeTypeList(), + 'public inAttributeTypes' : new AttributeList(), + 'public outAttributeTypes' : new AttributeList(), 'public __construct' : function(_interpreterId, _inAttributes, _outAttributes){ this.interpreterId = _interpreterId; diff --git a/js/modules/aggregator/storage/storage.js b/js/modules/aggregator/storage/storage.js index 31d84c320f1dfa5eb1418db38db443a37aa9a18e..7ecd5d423b56ce03fad87f8d183e06e6b0c6bd72 100644 --- a/js/modules/aggregator/storage/storage.js +++ b/js/modules/aggregator/storage/storage.js @@ -5,9 +5,9 @@ * @module Widget * @fileOverview */ -define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', +define(['easejs', 'attribute', 'attributeList', 'retrievalResult', 'parameter', 'parameterList'], - function( easejs, AttributeValue, AttributeValueList, AttributeType, + function( easejs, Attribute, AttributeList, RetrievalResult, Parameter, ParameterList){ var Class = easejs.Class; var Storage = Class('Storage', @@ -32,7 +32,7 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', /** * @alias data * @private - * @type {AttributeValueList} + * @type {AttributeList} * @memberof Storage# * @desc Cache before storing the new data in the database. */ @@ -88,8 +88,8 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', * @class Storage * @classdesc Storage handles the access to the database. * @requires easejs - * @requires AttributeValue - * @requires AttributeValueList + * @requires Attribute + * @requires AttributeList * @requires Parameter * @requires ParameterList * @requires RetrievalResult @@ -99,7 +99,7 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', 'public __construct' : function(_name, _time, _counter){ this.initStorage(_name); this.attributes = new RetrievalResult(); - this.data = new AttributeValueList(); + this.data = new AttributeList(); this.dataCount = 0; this.lastFlush = new Date(); if(_time && _time === parseInt(_time) && _time!=0) @@ -182,18 +182,18 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', * @private * @alias insertIntoTable * @memberof Storage# - * @param {AttributeValue} _attributeValue Attribute that should be stored. + * @param {Attribute} _attribute Attribute that should be stored. * @param {?function} _function For alternative actions, if an asynchronous function is used. */ - 'private insertIntoTable' : function(_attributeValue, _function){ - if(this.db && _attributeValue && Class.isA(AttributeValue, _attributeValue)){ - var tableName = this.tableName(_attributeValue); + 'private insertIntoTable' : function(_attribute, _function){ + if(this.db && _attribute && Class.isA(Attribute, _attribute)){ + var tableName = this.tableName(_attribute); var statement = 'INSERT INTO "' + tableName + '" (value_, type_, created_) VALUES ("' - + _attributeValue.getValue() + '", "' - + _attributeValue.getType() + '", "' - + _attributeValue.getTimestamp() + '")'; - console.log('INSERT INTO "'+tableName+'" VALUES ('+_attributeValue.getValue()+", "+_attributeValue.getType()+", "+_attributeValue.getTimestamp()); + + _attribute.getValue() + '", "' + + _attribute.getType() + '", "' + + _attribute.getTimestamp() + '")'; + console.log('INSERT INTO "'+tableName+'" VALUES ('+_attribute.getValue()+", "+_attribute.getType()+", "+_attribute.getTimestamp()); if(_function && typeof(_function) == 'function'){ this.db.transaction(function(tx){tx.executeSql(statement);}, this.errorCB, _function); } else { @@ -298,7 +298,7 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', * @returns {boolean} */ 'private tableExists' : function(_attribute){ - if(Class.isA(AttributeValue, _attribute) || Class.isA(AttributeType, _attribute)){ + if(Class.isA(Attribute, _attribute)){ var name = this.tableName(_attribute); return this.attributeNames.indexOf(name) > -1; } else if(typeof _attribute === 'string'){ @@ -317,11 +317,16 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', * @param {?function} _function For additional actions, if an asynchronous function is used. */ 'public retrieveAttributes' : function(_tableName, _function){ + console.log("retrieveAttributes from "+_tableName); + if(this.db){ var self = this; self.flushStorage(); - this.db.transaction(function(_tx){self.queryValues(_tx,_tableName,self, _function);}, - function(error){self.errorCB(error);} ); + this.db.transaction(function(_tx) { + self.queryValues(_tx,_tableName,self, _function); + }, function(error) { + self.errorCB(error); + }); } }, @@ -337,9 +342,10 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', * @param {@this} self * @param {?function} _function For additional actions, if an asynchronous function is used. */ - 'private queryValues' : function(_tx,_tableName,self, _function){ - if(self.tableExists(_tableName)){ - var statement = 'SELECT * FROM ' + _tableName; + 'private queryValues' : function(_tx, _tableName, self, _function){ + if(self.tableExists(_tableName)){ + console.log('SELECT * FROM "' +_tableName+"'"); + var statement = 'SELECT * FROM "' + _tableName+'"'; _tx.executeSql(statement, [], function(_tx,results){self.queryValuesSuccess(_tx,results,_tableName, self, _function);}, function(error){self.errorCB(error);}); @@ -368,7 +374,7 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', var attributeName = this.resolveAttributeName(_tableName); var parameterList = this.resolveParameters(_tableName); for(var i=0; i<len; i++){ - var attribute = new AttributeValue(). + var attribute = new Attribute(). withName(attributeName).withValue(results.rows.item(i).value_). withType(results.rows.item(i).type_). withTimestamp(results.rows.item(i).created_). @@ -411,11 +417,11 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', * @private * @alias addData * @memberof Storage# - * @param {AttributeValue} _attributeValue Value that should be stored. + * @param {Attribute} _attribute Value that should be stored. */ - 'private addData' : function(_attributeValue){ - if(Class.isA(AttributeValue, _attributeValue)){ - this.data.put(_attributeValue); + 'private addData' : function(_attribute){ + if(Class.isA(Attribute, _attribute)){ + this.data.put(_attribute); this.dataCount++; } }, @@ -447,7 +453,7 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', * @memberof Storage# */ 'private resetForFlush' : function(){ - this.data = new AttributeValueList(); + this.data = new AttributeList(); this.dataCount = 0; this.lastFlush = new Date(); }, @@ -535,7 +541,7 @@ define(['easejs', 'attributeValue', 'attributeValueList', 'attributeType', * @returns{String} */ 'private tableName' : function(_attribute){ - return _attribute.getAttributeType().toString(); + return _attribute.toString(true); }, /** diff --git a/js/modules/attribute/attribute.js b/js/modules/attribute/attribute.js new file mode 100644 index 0000000000000000000000000000000000000000..3c818509fd7332379a40d347ce26ed73d8e0dc13 --- /dev/null +++ b/js/modules/attribute/attribute.js @@ -0,0 +1,386 @@ +/** + * This module represents an AttributeType. + * AttributeTypes defines name, type (string, double,...) an associated parameter of an attribute. + * + * @module AttributeType + * @fileOverview + */ +define(['easejs', + 'parameterList'], + function(easejs, + ParameterList){ + + /** + * @class Attribute + * @classdesc AttributeValue extends AttributeTypes and adds the associated + * value. + * @requires easejs + * @requires ParameterList + */ + var Class = easejs.Class; + var Attribute = Class('Attribute',{ + /** + * @alias name + * @protected + * @type {string} + * @memberof AttributeType# + * @desc Name of the Attribute + */ + 'protected name' : '', + + /** + * @alias type + * @protected + * @type {string} + * @memberof AttributeType# + * @desc Defines the type of the Attribute (i.e String, Double,...) + */ + 'protected type' : '', + + /** + * @alias parameterList + * @protected + * @type {ParameterList} + * @memberof AttributeType# + * @desc Name of the Attribute + */ + 'protected parameterList' : [], + + /** + * @alias value + * @protected + * @type {string} + * @memberof AttributeValue# + */ + 'protected value' : 'NO_VALUE', + + /** + * @alias timestamp + * @protected + * @type {Date} + * @memberof AttributeValue# + * @desc Time when the value was set. + */ + 'protected timestamp' : '', + + /** + * Constructor: Initializes the ParameterList. + * + * @class AttributeType + * @classdesc AttributeTypes defines name, type (string, double,...) an associated parameter of an attribute. + * @requires easejs + * @requires ParameterList + * @constructs AttributeType + */ + 'public __construct' : function(){ + this.parameterList = new ParameterList(); + }, + + /** + * Builder for name. + * + * @public + * @alias withName + * @memberof AttributeType# + * @param {String} _name Name + * @returns {AttributeType} + */ + 'public withName' : function(_name){ + this.setName(_name); + return this; + }, + + /** + * Builder for type. + * + * @public + * @alias withType + * @memberof AttributeType# + * @param {String} _type Type + * @returns {AttributeType} + */ + 'public withType' : function(_type){ + this.setType(_type); + return this; + }, + + /** + * Builder for one parameter. + * + * @public + * @alias withParameters + * @memberof AttributeType# + * @param {Parameter} _parameter Parameter + * @returns {AttributeType} + */ + 'public withParameter' : function(_parameter){ + this.addParameter(_parameter); + return this; + }, + + /** + * Builder for parameterList. + * + * @public + * @alias withParameters + * @memberof AttributeType# + * @param {(ParameterList|Array)} _parameterList ParameterList + * @returns {AttributeType} + */ + 'public withParameters' : function(_parameterList){ + this.setParameters(_parameterList); + return this; + }, + + /** + * Builder for value. + * + * @public + * @alias withValue + * @memberof AttributeValue# + * @param {String} _value value + * @returns {AttributeValue} + */ + 'public withValue' : function(_value) { + this.setValue(_value); + this.setTimestamp(Date.now()); + return this; + }, + + /** + * Builder for timestamp. + * + * @public + * @alias withTimestamp + * @memberof AttributeValue# + * @param {Date} _timestamp timestamp + * @returns {AttributeValue} + */ + 'public withTimestamp' : function(_timestamp) { + this.setTimestamp(_timestamp); + return this; + }, + + /** + * Returns the name. + * + * @public + * @alias getName + * @memberof AttributeType# + * @returns {string} + */ + 'public getName' : function(){ + return this.name; + }, + + /** + * Returns the type. + * + * @public + * @alias getType + * @memberof AttributeType# + * @returns {string} + */ + 'public getType' : function(){ + return this.type; + }, + + /** + * Returns the parameters. + * + * @public + * @alias getParameters + * @memberof AttributeType# + * @returns {ParameterList} + */ + 'public getParameters' : function(){ + return this.parameterList; + }, + + /** + * Sets the name. + * + * @public + * @alias setName + * @memberof AttributeType# + * @param {string} _name Name + */ + 'public setName' : function(_name){ + if(typeof _name === 'string'){ + this.name = _name; + } + }, + + /** + * Sets the type. + * + * @public + * @alias setType + * @memberof AttributeType# + * @param {string} _type Type + */ + 'public setType' : function(_type){ + if(typeof _type === 'string'){ + this.type = _type; + } + }, + + /** + * Adds a parameter. + * + * @public + * @alias addParameter + * @memberof AttributeType# + * @param {Parameter} _parameter Parameter + */ + 'public addParameter' : function(_parameter){ + this.parameterList.put(_parameter); + }, + + /** + * Adds a list of Parameter. + * + * @public + * @alias setParameters + * @memberof AttributeType# + * @param {ParameterList} _parameters ParameterList + */ + 'public setParameters' : function(_parameters){ + this.parameterList.putAll(_parameters); + }, + + /** + * Returns true if the attribute is parameterized. + * + * @public + * @alias hasParameters + * @memberof Attribute# + * @returns {boolean} + */ + 'public hasParameters' : function() { + return this.parameterList.size() > 0; + }, + + /** + * Sets the value. + * + * @public + * @alias setValue + * @memberof AttributeValue# + * @param {string} _value value + */ + 'public setValue' : function(_value) { + this.value = _value; + }, + + /** + * Returns the value. + * + * @public + * @alias getValue + * @memberof AttributeValue# + * @returns {string} + */ + 'public getValue' : function() { + return this.value; + }, + + /** + * Sets the timestamp. + * + * @public + * @alias setTimestamp + * @memberof AttributeValue# + * @param {Date} _timestamp timestamp + */ + 'public setTimestamp' : function(_time) { + this.timestamp = _time; + }, + + /** + * Returns the timestamp. + * + * @public + * @alias getTimestamp + * @memberof AttributeValue# + * @returns {string} + */ + 'public getTimestamp' : function() { + return this.timestamp; + }, + + /** + * + * @public + * @alias hasInputParameter + * @memberof Attribute# + * @returns {boolean} + */ + 'public hasInputParameter': function() { + return this.hasParameters() && this.parameterList.hasInputParameter(); + }, + + /** + * Compares this instance with the given one. + * + * @public + * @alias equalsTypeOf + * @memberof Attribute# + * @param {Attribute} _attribute Attribute that should be compared. + * @returns {boolean} + */ + 'public equalsTypeOf' : function(_attribute) { + if (Class.isA(Attribute, _attribute)) { + if (this.getName() == _attribute.getName() && this.getType() == _attribute.getType() && this.getParameters().equals(_attribute.getParameters())) { + return true; + } + } + return false; + }, + + /** + * + * + * @public + * @alias equalsValueOf + * @memberof Attribute# + * @param _attribute + * @returns {boolean} + */ + 'public equalsValueOf' : function(_attribute) { + if (Class.isA(Attribute, _attribute)) { + if (this.equalsTypeOf(_attribute) && this.getValue() == _attribute.getValue()) { + return true; + } + } + return false; + }, + + /** + * Returns an identifier that uniquely describes the attribute type and its parameters. + * The identifier can be used to compare two attribute types. <br/> + * Format: (AttributeName:AttributeType)#[FirstParameterName:FirstParameterValue]… + * + * @public + * @alias toString + * @memberof AttributeType# + * @returns {String} + * @example (CI_USER_LOCATION_DISTANCE:FLOAT)#[CP_TARGET_LATITUDE:52][CP_TARGET_LONGITUDE:13][CP_UNIT:KILOMETERS] + */ + 'public toString': function(_typeOnly) { + var identifier = "("+this.name+":"+this.type+")"; + if (this.hasParameters()) { + identifier += "#"; + for (var index in this.parameterList.getItems()) { + var theParameter = this.parameterList.getItems()[index]; + identifier += theParameter.toString(); + } + } + if (!_typeOnly) identifier += ":"+this.getValue(); + return identifier; + } + }); + + return Attribute; + + }); \ No newline at end of file diff --git a/js/modules/attribute/attributeList.js b/js/modules/attribute/attributeList.js new file mode 100644 index 0000000000000000000000000000000000000000..b7058347de7f242be71a25dacecacb83efbc2198 --- /dev/null +++ b/js/modules/attribute/attributeList.js @@ -0,0 +1,324 @@ +/** + * This module represents an AttributeList. It is a subclass of AbstractList. + * + * @module AttributeList + * @fileOverview + */ +define(['easejs', 'abstractList', 'attribute', 'parameterList' ], + function(easejs, AbstractList, Attribute, ParameterList) { + var Class = easejs.Class; + + /** + * @class AttributeList + * @classdesc This class represents a list for Attribute. + * @extends AbstractList + * @requires easejs + * @requires AbstractList + * @requires Attribute + */ + var AttributeList = Class('AttributeList').extend(AbstractList, { + /** + * @alias items + * @protected + * @type {Array.<Attribute>} + * @memberof AttributeList# + * @desc ItemList + */ + 'protected items' : [], + + /** + * Builder for item list. + * + * @public + * @alias withItems + * @memberof AttributeList# + * @param {(AttributeList)} _attributeList AttributeList + * @returns {AttributeList} + */ + 'public withItems' : function(_attributeList) { + var list = []; + if (_attributeList instanceof Array) { + list = _attributeList; + } else if (Class.isA(AttributeList, _attributeList)) { + list = _attributeList.getItems(); + } + this.items = list; + return this; + }, + + /** + * Adds the specified item to the itemList. + * + * @public + * @alias put + * @memberof AttributeList# + * @param {AttributeType} _attribute AttributeType + * @param {boolean} _multipleInstances + */ + 'public put' : function(_attribute, _multipleInstances) { + _multipleInstances = typeof _multipleInstances == "undefined" ? false : _multipleInstances; + if (Class.isA(Attribute, _attribute)) { + if (_multipleInstances || !(this.containsTypeOf(_attribute))) { + this.items.push(_attribute); + } else { + this.updateValue(_attribute); + } + } + }, + + /** + * Adds all items in the specified list to the + * itemList. + * + * @public + * @alias putAll + * @memberof AttributeList# + * @param {(AttributeList|Array)} _attributeList AttributeList + */ + 'public putAll' : function(_attributeList) { + var list = []; + if (_attributeList instanceof Array) { + list = _attributeList; + } else if (Class.isA(AttributeList, _attributeList)) { + list = _attributeList.getItems(); + } + for ( var i in list) { + this.put(list[i]); + } + }, + + /** + * + * @param {Attribute} _attribute + * @param {?boolean} _typeOnly + * @returns {*} + */ + 'public contains': function(_attribute, _typeOnly) { + _typeOnly = typeof _typeOnly == "undefined" ? false : _typeOnly; + return _typeOnly ? this.containsTypeOf(_attribute) : this.containsValueOf(_attribute); + }, + + /** + * Verifies whether the given item is included + * in this list. + * + * @public + * @alias containsTypeOf + * @memberof AttributeList# + * @param {AttributeType} _attribute AttributeType that should be verified. + * @returns {boolean} + */ + 'public containsTypeOf' : function(_attribute) { + if (Class.isA(Attribute, _attribute)) { + for (var index in this.items) { + var tmp = this.items[index]; + if (tmp.equalsTypeOf(_attribute)) { + return true; + } + } + } + return false; + }, + + /** + * Verifies whether the given item is included + * in the list. + * + * @public + * @alias containsValueOf + * @memberof AttributeList# + * @param {Attribute} _attribute AttributeValue that should be verified. + * @returns {boolean} + */ + 'public containsValueOf' : function(_attribute) { + if (Class.isA(Attribute, _attribute)) { + for (var index in this.items) { + var tmp = this.items[index]; + if (tmp.equalsValueOf(_attribute)) { + return true; + } + } + } + return false; + }, + + 'public equals': function(_attributeList, _typeOnly) { + _typeOnly = typeof _typeOnly == "undefined" ? false : _typeOnly; + return _typeOnly ? this.equalsTypesIn(_attributeList) : this.equalsValuesIn(_attributeList); + }, + + /** + * Compare the specified AttributeList with this instance. + * + * @public + * @alias equalsTypesIn + * @memberof AttributeList# + * @param {AttributeList} _attributeList AttributeList that should be compared. + * @returns {boolean} + */ + 'public equalsTypesIn' : function(_attributeList) { + if (Class.isA(AttributeList, _attributeList) && _attributeList.size() == this.size()) { + for (var index in _attributeList.getItems()) { + var theAttributeType = _attributeList.getItems()[index]; + if (!this.containsTypeOf(theAttributeType)) return false; + } + return true; + } + return false; + }, + + /** + * Compare the specified AttributeList with + * this instance. + * + * @public + * @alias equalsValuesIn + * @memberof AttributeList# + * @param {AttributeList} _attributeList AttributeList that should be compared. + * @returns {boolean} + */ + 'public equalsValuesIn' : function(_attributeList) { + if (Class.isA(AttributeList, _attributeList) && _attributeList.size() == this.size()) { + for (var index in _attributeList.getItems()) { + var theAttribute = _attributeList.getItems()[index]; + if (!this.containsValueOf(theAttribute)) return false; + } + return true; + } + return false; + }, + + /** + * Returns only this values that matches to the + * given type. + * + * @public + * @alias getSubset + * @memberof AttributeList# + * @param {(AttributeList|Array)} _attributeList Attributes that should be returned. + * @returns {AttributeList} + */ + 'public getSubset' : function(_attributeList) { + var response = new AttributeList(); + var list = []; + if (_attributeList instanceof Array) { + list = _attributeList; + } else if (Class.isA(AttributeList, _attributeList)) { + list = _attributeList.getItems(); + } + for (var i in list) { + var attribute = list[i]; + if (Class.isA(Attribute, attribute)) { + var attribute = this.getAttributeWithTypeOf(attribute); + if (typeof attribute != "NO_VALUE") { + response.put(attribute); + } + } + } + return response; + }, + + /** + * Returns a subset without the given types. + * + * @public + * @alias getSubsetWithoutItems + * @memberof AttributeList# + * @param {(AttributeList|Array)} _attributeList AttributeTypes that should not be included + * @returns {AttributeList} + */ + 'public getSubsetWithoutItems' : function(_attributeList) { + var response = this; + var list = []; + if (_attributeList instanceof Array) { + list = _attributeList; + } else if (Class.isA(AttributeList, _attributeList)) { + list = _attributeList.getItems(); + } + for (var i in list) { + var attribute = list[i]; + if (Class.isA(Attribute, attribute)) { + response.removeAttributeWithTypeOf(attribute); + } + } + return response; + }, + + /** + * Creates a clone of the current list. + * + * @public + * @alias clone + * @memberof AttributeList# + * @returns {AttributeList} + */ + 'public clone': function(_typeOnly) { + var newList = new AttributeList(); + for (var index in this.items) { + var oldAttribute = this.items[index]; + var newAttribute = new Attribute().withName(oldAttribute.getName()).withType(oldAttribute.getType()).withParameters(oldAttribute.getParameters()); + if (!_typeOnly) newAttribute.setValue(oldAttribute.getValue()); + newList.put(newAttribute); + } + return newList; + }, + + 'public removeAttributeWithTypeOf': function(_attribute, _allOccurrences) { + _allOccurrences = typeof _allOccurrences == "undefined" ? false : _allOccurrences; + for (var index in this.items) { + var theAttribute = this.items[index]; + if (theAttribute.equalsTypeOf(_attribute)) { + this.items.splice(index, 1); + } + } + if (_allOccurrences && this.contains(_attribute)) this.removeAttributeWithTypeOf(_attribute, _allOccurrences); + }, + + 'public hasAttributesWithInputParameters': function() { + for (var index in this.items) { + var theAttribute = this.items[index]; + if (theAttribute.hasInputParameter()) return true; + } + return false; + }, + + 'public getAttributesWithInputParameters': function() { + var list = new AttributeList(); + for (var index in this.items) { + var theAttribute = this.items[index]; + if (theAttribute.hasInputParameter()) list.put(theAttribute); + } + return list; + }, + + /** + * Returns the attribute value that matches the provided attribute type. + * + * @public + * @alias getValueForAttributeWithTypeOf + * @memberof AttributeList# + * @param {AttributeType} _attribute + * @returns {Attribute} + */ + 'public getValueForAttributeWithTypeOf': function(_attribute) { + return this.getAttributeWithTypeOf(_attribute).getValue(); + }, + + 'public getAttributeWithTypeOf': function(_attribute) { + for (var index in this.getItems()) { + var theAttribute = this.getItems()[index]; + if (theAttribute.equalsTypeOf(_attribute)) return theAttribute; + } + }, + + 'public updateValue': function(_attribute) { + for (var index in this.items) { + var theAttribute = this.items[index]; + if (theAttribute.equalsTypeOf(_attribute)) this.items[index] = _attribute; + } + } + + }); + + return AttributeList; +}); \ No newline at end of file diff --git a/js/modules/attribute/attributeTypeList.js b/js/modules/attribute/attributeTypeList.js deleted file mode 100644 index d7201396d3c904c42de9267f5807f2d12e9e6d54..0000000000000000000000000000000000000000 --- a/js/modules/attribute/attributeTypeList.js +++ /dev/null @@ -1,181 +0,0 @@ -/** - * This module represents an AttributeTypeList. It is a subclass of AbstractList. - * - * @module AttributeTypeList - * @fileOverview - */ -define([ 'easejs', 'abstractList', 'attributeType', 'parameterList' ], - function(easejs, AbstractList, AttributeType, ParameterList) { - var Class = easejs.Class; - /** - * @class AttributeTypeList - * @classdesc This class represents a list for AttributeType. - * @extends AbstractList - * @requires easejs - * @requires AbstractList - * @requires AttributeType - */ - var AttributeTypeList = Class('AttributeTypeList').extend(AbstractList, { - - /** - * @alias items - * @protected - * @type {AttributeTypeList} - * @memberof AttributeTypeList# - * @desc ItemList - */ - 'protected items' : [], - - /** - * Builder for item list. - * - * @public - * @alias withItems - * @memberof AttributeTypeList# - * @param {(AttributeTypeList)} _attributeTypeList AttributeTypeList - * @returns {AttributeTypeList} - */ - 'public withItems' : function(_attributeTypeList) { - var list = []; - if (_attributeTypeList instanceof Array) { - list = _attributeTypeList; - } else if (Class.isA(AttributeTypeList, _attributeTypeList)) { - list = _attributeTypeList.getItems(); - } - this.items = list; - return this; - }, - - /** - * Adds the specified item to the itemList. - * - * @public - * @alias put - * @memberof AttributeTypeList# - * @param {AttributeType} _attributeType AttributeType - */ - 'public put' : function(_attributeType, _multipleInstances) { - var _multipleInstances = typeof _multipleInstances == "undefined" ? false : _multipleInstances; - if (Class.isA(AttributeType, _attributeType)) { - if (_multipleInstances || !(this.contains(_attributeType))) { - this.items.push(_attributeType); - } - } - }, - - /** - * Adds all items in the specified list to the - * itemList. - * - * @public - * @alias putAll - * @memberof AttributeTypeList# - * @param {(AttributeTypeList|Array)} _attributeTypeList AttributeTypeList - */ - 'public putAll' : function(_attributeTypeList) { - var list = []; - if (_attributeTypeList instanceof Array) { - list = _attributeTypeList; - } else if (Class.isA(AttributeTypeList, _attributeTypeList)) { - list = _attributeTypeList.getItems(); - } - for ( var i in list) { - this.put(list[i]); - } - }, - - /** - * Verifies whether the given item is included - * in this list. - * - * @public - * @alias contains - * @memberof AttributeTypeList# - * @param {AttributeType} _item AttributeType that should be verified. - * @returns {boolean} - */ - 'public contains' : function(_item) { - if (Class.isA(AttributeType, _item)) { - for (var index in this.items) { - var tmp = this.items[index]; - if (tmp.equals(_item)) { - return true; - } - } - } - return false; - }, - - - /** - * Compare the specified AttributeTypeList with this instance. - * - * @public - * @alias equals - * @memberof AttributeTypeList# - * @param {AttributeTypeList} _list AttributeTypeList that should be compared. - * @returns {boolean} - */ - 'public equals' : function(_list) { - if (Class.isA(AttributeTypeList, _list) && _list.size() == this.size()) { - for (var index in _list.getItems()) { - var theAttributeType = _list.getItems()[index]; - if (!this.contains(theAttributeType)) return false; - } - return true; - } - return false; - }, - - /** - * Creates a clone of the current list. - * - * @public - * @alias clone - * @memberof AttributeTypeList# - * @returns {AttributeTypeList} - */ - 'public clone': function() { - var newList = new AttributeTypeList(); - for (var index in this.items) { - var oldAttributeType = this.items[index]; - var newAttributeType = new AttributeType(). - withName(oldAttributeType.getName()). - withType(oldAttributeType.getType()). - withParameters(oldAttributeType.getParameters()); - newList.put(newAttributeType); - } - return newList; - }, - - 'public removeAttributeType': function(_attributeType, _allOccurrences) { - _allOccurrences = typeof _allOccurrences == "undefined" ? false : _allOccurrences; - for (var index in this.items) { - var theAttributeType = this.items[index]; - if (theAttributeType.equals(_attributeType)) { - this.items.splice(index, 1); - } - } - if (_allOccurrences && this.contains(_attributeType)) this.removeAttributeType(_attributeType, _allOccurrences); - }, - - 'public hasAttributesWithInputParameters': function() { - for (var index in this.items) { - var theAttributeType = this.items[index]; - if (theAttributeType.hasInputParameter()) return true; - } - return false; - }, - - 'public getAttributesWithInputParameters': function() { - var list = new AttributeTypeList(); - for (var index in this.items) { - var theAttributeType = this.items[index]; - if (theAttributeType.hasInputParameter()) list.put(theAttributeType); - } - return list; - } - }); - - return AttributeTypeList; - }); \ No newline at end of file diff --git a/js/modules/attribute/attributeValue.js b/js/modules/attribute/attributeValue.js deleted file mode 100644 index 9fa6abb77645f4c20533722933614c47190aaf6a..0000000000000000000000000000000000000000 --- a/js/modules/attribute/attributeValue.js +++ /dev/null @@ -1,179 +0,0 @@ -/** - * This module represents an AttributeValue. AttributeValue extends - * AttributeTypes and adds the associated value. - * - * @module AttributeValue - * @fileOverview - */ -define([ 'easejs', 'attributeType' ], function(easejs, AttributeType) { - var Class = easejs.Class; - - /** - * @class AttributeValue - * @classdesc AttributeValue extends AttributeTypes and adds the associated - * value. - * @requires easejs - * @requires AttributeType - */ - var AttributeValue = Class('AttributeValue').extend( - AttributeType, - { - /** - * @alias value - * @protected - * @type {string} - * @memberof AttributeValue# - */ - 'protected value' : '', - /** - * @alias timestamp - * @protected - * @type {Date} - * @memberof AttributeValue# - * @desc Time when the value was set. - */ - 'protected timestamp' : '', - - /** - * Builder for value. - * - * @public - * @alias withValue - * @memberof AttributeValue# - * @param {String} _value value - * @returns {AttributeValue} - */ - 'public withValue' : function(_value) { - this.setValue(_value); - this.setTimestamp(Date.now()); - return this; - }, - - /** - * Builder for timestamp. - * - * @public - * @alias withTimestamp - * @memberof AttributeValue# - * @param {Date} _timestamp timestamp - * @returns {AttributeValue} - */ - 'public withTimestamp' : function(_timestamp) { - this.setTimestamp(_timestamp); - return this; - }, - - /** - * Sets the value. - * - * @public - * @alias setValue - * @memberof AttributeValue# - * @param {string} _value value - */ - 'public setValue' : function(_value) { - this.value = _value; - }, - - /** - * Returns the value. - * - * @public - * @alias getValue - * @memberof AttributeValue# - * @returns {string} - */ - 'public getValue' : function() { - return this.value; - }, - - /** - * Sets the timestamp. - * - * @public - * @alias setTimestamp - * @memberof AttributeValue# - * @param {Date} _timestamp timestamp - */ - 'public setTimestamp' : function(_time) { - this.timestamp = _time; - }, - - /** - * Returns the timestamp. - * - * @public - * @alias getTimestamp - * @memberof AttributeValue# - * @returns {string} - */ - 'public getTimestamp' : function() { - return this.timestamp; - }, - - /** - * Compares this instance with the given one. - * - * @public - * @alias equals - * @memberof AttributeValue# - * @param {AttributeValue} _attributeValue AttributeValue that should be compared - * @returns {boolean} - */ - 'override public equals' : function(_attributeValue) { - if (Class.isA(AttributeValue, _attributeValue)) { - if (_attributeValue.getAttributeType().equals(this.getAttributeType()) && - _attributeValue.getValue() == this.getValue()) { - return true; - } - } - return false; - }, - - /** - * Returns the AttributeType of an AttributeValue. - * - * @public - * @alias getAttributeType - * @memberof AttributeValue# - * @returns {AttributeType} - */ - 'public getAttributeType' : function() { - return new AttributeType().withName(this.name) - .withType(this.type).withParameters( - this.parameterList); - }, - - /** - * Builds a new AttributeValue from the given type. - * - * @public - * @alias buildFromAttributeType - * @memberof AttributeValue# - * @param {AttributeType} _attributeType AttributeType for build process. - * @returns {AttributeValue} - */ - 'public buildFromAttributeType' : function(_attributeType) { - if (Class.isA(AttributeType, _attributeType)) { - return new AttributeValue().withName(_attributeType.getName()) - .withType(_attributeType.getType()).withParameters(_attributeType.getParameters()).withValue('NO_VALUE'); - } - return null; - }, - - /** - * Returns a string that describes the attribute type and its value. - * - * @public - * @override - * @alias toString - * @memberof AttributeValue# - * @returns {string} - */ - 'override public toString': function() { - return this.__super().toString()+":"+this.getValue(); - } - }); - - return AttributeValue; -}); \ No newline at end of file diff --git a/js/modules/attribute/attributeValueList.js b/js/modules/attribute/attributeValueList.js deleted file mode 100644 index 5280c6cc49a052a8feaae9f8708d842aef87ef6d..0000000000000000000000000000000000000000 --- a/js/modules/attribute/attributeValueList.js +++ /dev/null @@ -1,240 +0,0 @@ -/** - * This module represents a AttributeValueList. It is a subclass of - * AbstractList. - * - * @module AttributeValueList - * @fileOverview - */ -define(['easejs', 'abstractList', 'attributeValue', 'attributeType', 'attributeTypeList', 'parameterList'], - function(easejs, AbstractList, AttributeValue, AttributeType, AttributeTypeList, ParameterList) { - var Class = easejs.Class; - - /** - * @class AttributeValueList - * @classdesc This class represents a list for AttributeValue. - * @extends AbstractList - * @requires easejs - * @requires AbstractList - * @requires AttributeValue - * @requires AttributeType - * @requires AttributeTypeList) - */ - var AttributeValueList = Class('AttributeValueList').extend(AbstractList,{ - - /** - * @alias items - * @protected - * @type {AttributeValueList} - * @memberof AttributeValueList# - * @desc ItemList. - */ - 'protected items' : [], - - /** - * Builder for item list. - * - * @public - * @alias withItems - * @memberof AttributeValueList# - * @param {(AttributeValueListst|Array)} _attributeValueList AttributeValueList - * @returns {AttributeValueList} - */ - 'public withItems' : function(_attributeValueList) { - var list = []; - if (_attributeValueList instanceof Array) { - list = _attributeValueList; - } else if (Class.isA(AttributeValueList, - _attributeValueList)) { - list = _attributeValueList.getItems(); - } - this.items = list; - return this; - }, - - /** - * Add the specified item to this itemList. - * - * @public - * @alias put - * @memberof AttributeValueList# - * @param {AttributeValue} _attributeValue AttributeValue - */ - 'public put' : function(_attributeValue, _multipleInstances) { - if (Class.isA(AttributeValue, _attributeValue)) { - if (_multipleInstances || !(this.containsAttributeType(_attributeValue.getAttributeType()))) { - this.items.push(_attributeValue); - } else { - this.updateValue(_attributeValue); - } - } - }, - - /** - * Adds all items in the specified list to this. - * itemList - * - * @public - * @alias putAll - * @memberof AttributeValueList# - * @param {AttributeValueList} _attributeValueList AttributeValueList - */ - 'public putAll' : function(_attributeValueList) { - var list = []; - if (_attributeValueList instanceof Array) { - list = _attributeValueList; - } else if (Class.isA(AttributeValueList, _attributeValueList)) { - list = _attributeValueList.getItems(); - } - for (var i in list) { - this.put(list[i]); - } - }, - - /** - * Verifies whether the given item is included - * in the list. - * - * @public - * @alias contains - * @memberof AttributeValueList# - * @param {AttributeValue} _attributeValue AttributeValue that should be verified. - * @returns {boolean} - */ - 'public contains' : function(_attributeValue) { - if (Class.isA(AttributeValue, _attributeValue)) { - for (var index in this.items) { - var tmp = this.items[index]; - if (tmp.equals(_attributeValue)) { - return true; - } - } - } - return false; - }, - - 'public containsAttributeType': function(_attributeType) { - if (Class.isA(AttributeType, _attributeType)) { - for (var index in this.items) { - var tmp = this.items[index].getAttributeType(); - if (tmp.equals(_attributeType)) { - return true; - } - } - } - return false; - }, - - /** - * Compare the specified AttributeValueList with - * this instance. - * - * @public - * @alias equals - * @memberof AttributeValueList# - * @param {AttributeValueList} _list AttributeValueList that should be compared. - * @returns {boolean} - */ - 'public equals' : function(_list) { - if (Class.isA(AttributeValueList, _list) && _list.size() == this.size()) { - for (var index in _list.getItems()) { - var theAttributeValue = _list.getItems()[index]; - if (!this.contains(theAttributeValue)) return false; - } - return true; - } - return false; - }, - - /** - * Returns only this values that matches to the - * given type. - * - * @public - * @alias getSubset - * @memberof AttributeValueList# - * @param {(AttributeTypeList|Array)} _attributeTypeList AttributeTypes that should be returned. - * @returns {AttributeValueList} - */ - 'public getSubset' : function(_attributeTypeList) { - var response = new AttributeValueList(); - var list = []; - if (_attributeTypeList instanceof Array) { - list = _attributeTypeList; - } else if (Class.isA(AttributeTypeList, _attributeTypeList)) { - list = _attributeTypeList.getItems(); - } - for ( var i in list) { - var attributeType = list[i]; - if (Class.isA(AttributeType, attributeType)) { - var attribute = this.getValueObjectForAttributeType(attributeType); - if (typeof attribute != "undefined") { - response.put(attribute); - } - } - } - return response; - }, - - /** - * Returns a subset without the given types. - * - * @public - * @alias getSubsetWithoutItems - * @memberof AttributeValueList# - * @param {(AttributeTypeList|Array)} _attributeTypeList AttributeTypes that should not be included - * @returns {AttributeValueList} - */ - 'public getSubsetWithoutItems' : function(_attributeTypeList) { - var response = this; - var list = []; - if (_attributeTypeList instanceof Array) { - list = _attributeTypeList; - } else if (Class.isA(AttributeTypeList, _attributeTypeList)) { - list = _attributeTypeList.getItems(); - } - for (var i in list) { - var attributeType = list[i]; - if (Class.isA(AttributeType, attributeType)) { - response.removeAttributeValuesWithAttributeType(attributeType); - } - } - return response; - }, - - /** - * Returns the attribute value that matches the provided attribute type. - * - * @public - * @alias getValueForAttributeType - * @memberof AttributeValueList# - * @param {AttributeType} _attributeType - * @returns {AttributeValue} - */ - 'public getValueForAttributeType': function(_attributeType) { - return this.getValueObjectForAttributeType(_attributeType).getValue(); - }, - - 'public getValueObjectForAttributeType': function(_attributeType) { - for (var index in this.getItems()) { - var theAttributeValue = this.getItems()[index]; - if (theAttributeValue.getAttributeType().equals(_attributeType)) return theAttributeValue; - } - }, - - 'public removeAttributeValuesWithAttributeType': function(_attributeType) { - for (var index in this.items) { - var theAttributeValue = this.items[index]; - if (theAttributeValue.getAttributeType().equals(_attributeType)) this.items.splice(index, 1); - } - }, - - 'public updateValue': function(_attributeValue) { - for (var index in this.items) { - var theAttributeValue = this.items[index]; - if (theAttributeValue.getAttributeType().equals(_attributeValue.getAttributeType())) this.items[index] = _attributeValue; - } - } - }); - - return AttributeValueList; - }); \ No newline at end of file diff --git a/js/modules/attribute/parameterList.js b/js/modules/attribute/parameterList.js index a78daa14d047acc412037150b9fd72a5cb573899..ba9f5fceab9dae508b22cf91c2cf5498ed982299 100644 --- a/js/modules/attribute/parameterList.js +++ b/js/modules/attribute/parameterList.js @@ -15,8 +15,7 @@ define([ 'easejs', 'abstractList', 'parameter' ], * @requires AbstractList * @requires Parameter */ - var ParameterList = Class('ParameterList').extend(AbstractList,{ - + var ParameterList = Class('ParameterList').extend(AbstractList, { /** * @alias counter * @protected diff --git a/js/modules/descriptions/interpreterDescription.js b/js/modules/descriptions/interpreterDescription.js index afb433f45a2a03d23b4f52047ff0fa990c565d9a..1e5b45a9a5d9cb65a5f607caab1e7d68b9a36e09 100644 --- a/js/modules/descriptions/interpreterDescription.js +++ b/js/modules/descriptions/interpreterDescription.js @@ -5,8 +5,8 @@ * @module InterpreterDescription * @fileOverview */ -define(['easejs','attributeTypeList','widgetDescription'], - function(easejs,AttributeTypeList,WidgetDescription){ +define(['easejs','attributeList', 'widgetDescription'], + function(easejs,AttributeList, WidgetDescription){ var Class = easejs.Class; var InterpreterDescription = Class('InterpreterDescription'). extend(WidgetDescription, { @@ -27,13 +27,13 @@ define(['easejs','attributeTypeList','widgetDescription'], * @classdesc The description of an interpreter and the communication with it. * @extends WidgetDescription * @requires easejs - * @requires AttributeTypeList + * @requires AttributeList * @requires WidgetDescription * @constructs InterpreterDescription */ 'override public __construct' : function(){ this.__super(); - this.inAttributeTypes = new AttributeTypeList(); + this.inAttributeTypes = new AttributeList(); }, /** @@ -42,7 +42,7 @@ define(['easejs','attributeTypeList','widgetDescription'], * @public * @alias withInAttributeTypes * @memberof InterpreterDescription# - * @param {(AttributeTypeList|Array)} _inAttributeTypes List of AttributeType that are expected + * @param {(AttributeList|Array)} _inAttributeTypes List of AttributeType that are expected * @returns {InterpreterDescription} */ 'public withInAttributeTypes' : function(_inAttributeTypes){ diff --git a/js/modules/descriptions/widgetDescription.js b/js/modules/descriptions/widgetDescription.js index f6db9b37d5ace4b8dccf3e640ad15ae64201dd2d..6bd148c23addb07432e6a3aebd48c6097b981832 100644 --- a/js/modules/descriptions/widgetDescription.js +++ b/js/modules/descriptions/widgetDescription.js @@ -5,8 +5,8 @@ * @module WidgetDescription * @fileOverview */ -define(['easejs', 'attributeTypeList'], - function(easejs, AttributeTypeList){ +define(['easejs', 'attributeList'], + function(easejs, AttributeList){ var Class = easejs.Class; var WidgetDescription = Class('WidgetDescription',{ @@ -54,7 +54,7 @@ define(['easejs', 'attributeTypeList'], * @constructs WidgetDescription */ 'virtual public __construct' : function(){ - this.outAttributeTypes = new AttributeTypeList(); + this.outAttributeTypes = new AttributeList(); }, /** @@ -195,7 +195,7 @@ define(['easejs', 'attributeTypeList'], * @public * @alias addOutAttributeTypes * @memberof WidgetDescription# - * @param {(AttributeTypeList|Array)} _outAttributeTypes List of AttributeType that are provided + * @param {(AttributeList|Array)} _outAttributeTypes List of AttributeType that are provided */ 'public addOutAttributeTypes' : function(_outAttributeTypes){ this.outAttributeTypes.putAll(_outAttributeTypes); @@ -215,11 +215,12 @@ define(['easejs', 'attributeTypeList'], * @public * @alias doesSatisfyAttributeType * @memberof WidgetDescription# - * @param {AttributeType} _attributeType + * @param {AttributeType} _attribute * @returns {boolean} */ - 'public doesSatisfyAttributeType': function(_attributeType) { - return this.getOutAttributeTypes().contains(_attributeType); + + 'public doesSatisfyAttributeType': function(_attribute) { + return this.getOutAttributeTypes().containsTypeOf(_attribute); } }); diff --git a/js/modules/discoverer/discoverer.js b/js/modules/discoverer/discoverer.js index 557a7921ac77f2c8b7d2574460d49967ca84ed61..5c2c511e6bdceff2a700c8d0e9fafbaab73a648d 100644 --- a/js/modules/discoverer/discoverer.js +++ b/js/modules/discoverer/discoverer.js @@ -4,8 +4,8 @@ * @module Discoverer * @fileOverview */ -define([ 'easejs', 'attributeTypeList', 'widget', 'interpreter', 'aggregator' ], function(easejs, - AttributeTypeList, Widget, Interpreter, Aggregator) { +define([ 'easejs', 'attributeList', 'widget', 'interpreter', 'aggregator' ], function(easejs, + AttributeList, Widget, Interpreter, Aggregator) { var Class = easejs.Class; var Discoverer = Class('Discoverer', { @@ -52,7 +52,7 @@ define([ 'easejs', 'attributeTypeList', 'widget', 'interpreter', 'aggregator' ], * @class Discoverer * @classdesc The Discoverer handles requests for components and attributes. * @requires easejs - * @requires AttributeTypeList + * @requires AttributeList * @constructs Discoverer */ 'public __construct' : function(_translations) { @@ -310,27 +310,27 @@ define([ 'easejs', 'attributeTypeList', 'widget', 'interpreter', 'aggregator' ], * @public * @alias getComponentsByAttributes * @memberof Discoverer# - * @param {AttributeTypeList} _attributeTypeList list of searched attributes + * @param {AttributeList} _attributeList list of searched attributes * @param {boolean} _all choise of the verification mode * @param {Array} _componentTypes Components types to search for * @returns {Array} */ - 'public getComponentsByAttributes' : function(_attributeTypeList, _all, _componentTypes) { + 'public getComponentsByAttributes' : function(_attributeList, _all, _componentTypes) { var componentList = []; var list = {}; if (typeof _componentTypes == "undefined") _componentTypes = [Widget, Interpreter, Aggregator]; - if (_attributeTypeList instanceof Array) { - list = _attributeTypeList; - } else if (Class.isA(AttributeTypeList, _attributeTypeList)) { - list = _attributeTypeList.getItems(); + if (_attributeList instanceof Array) { + list = _attributeList; + } else if (Class.isA(AttributeList, _attributeList)) { + list = _attributeList.getItems(); } if (typeof list != "undefined") { var descriptions = this.getDescriptions(_componentTypes); for (var i in descriptions) { var description = descriptions[i]; - if(_all && this.containsAllAttributes(description, list)){ + if(_all && this.containsAllAttributes(description, list)) { componentList.push(this.getComponent(description.getId())); - } else if(!_all && this.containsAtLeastOneAttribute(description, list)){ + } else if(!_all && this.containsAtLeastOneAttribute(description, list)) { componentList.push(this.getComponent(description.getId())); } } diff --git a/js/modules/interpreter/interpreter.js b/js/modules/interpreter/interpreter.js index 1342d95d318f14229d633836f395363868099a2e..e3aabf602a5db2331001223273f3eaef3adafd63 100644 --- a/js/modules/interpreter/interpreter.js +++ b/js/modules/interpreter/interpreter.js @@ -4,10 +4,10 @@ * @module Interpreter * @fileOverview */ -define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', - 'attributeValue', 'attributeValueList', 'interpreterDescription', 'interpreterResult' ], - function(easejs, MathUuid, AttributeType, AttributeTypeList, - AttributeValue, AttributeValueList, InterpreterDescription, InterpreterResult) { +define([ 'easejs', 'MathUuid', 'attribute', 'attributeList', + 'interpreterDescription', 'interpreterResult' ], + function(easejs, MathUuid, Attribute, AttributeList, + InterpreterDescription, InterpreterResult) { var Class = easejs.Class; var AbstractClass = easejs.AbstractClass; var Interpreter = AbstractClass('Interpreter', @@ -29,37 +29,21 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', */ 'public id' : '', /** - * @alias inAttributeTypes + * @alias inAttributes * @protected - * @type {AttributeTypeList} + * @type {AttributeList} * @memberof Interpreter# * @desc Types of all attributes that can be handled. */ - 'protected inAttributeTypes' : [], + 'protected inAttributes' : [], /** - * @alias outAttributeTypes + * @alias outAttributes * @protected - * @type {AttributeTypeList} + * @type {AttributeList} * @memberof Interpreter# * @desc Types of all attributes that will be returned. */ - 'protected outAttributeTypes' : [], - /** - * @alias inAttributeValues - * @protected - * @type {AttributeValueList} - * @memberof Interpreter# - * @desc List of the data that should be interpreted. - */ - 'protected inAttributeValues' : [], - /** - * @alias outAttributeValues - * @protected - * @type {AttributeValueList} - * @memberof Interpreter# - * @desc List of interpreted data. - */ - 'protected outAttributeValues' : [], + 'protected outAttributes' : [], /** * @alias lastInterpretation * @protected @@ -85,10 +69,8 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', * @classdesc The Widget handles the access to sensors. * @requires easejs * @requires MathUuid - * @requires AttributeType - * @requires AttributeValue - * @requires AttributeTypeList - * @requires AttributeValueList + * @requires Attribute + * @requires AttributeList * @requires InterpreterDescription * @constructs Interpreter */ @@ -96,10 +78,8 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', this.id = Math.uuid(); this.discoverer = _discoverer; this.register(); - this.inAttributeTypes = new AttributeTypeList(); - this.outAttributeTypes = new AttributeTypeList(); - this.inAttributeValues = new AttributeValueList(); - this.outAttributeValues = new AttributeValueList(); + this.inAttributes = new AttributeList(); + this.outAttributes = new AttributeList(); this.initInterpreter(); }, @@ -179,10 +159,10 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', * @public * @alias getInAttributeTypes * @memberof Interpreter# - * @returns {AttributeTypeList} + * @returns {AttributeList} */ - 'public getInAttributeTypes' : function() { - return this.inAttributeTypes; + 'public getInAttributes' : function() { + return this.inAttributes; }, /** @@ -191,53 +171,46 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', * @protected * @alias setInAttribute * @memberof Interpreter# - * @param {string} _name name of the attribute - * @param {string} _type type of the attribute - * @param {string} _value value of the attribute - * @param {ParameterList|Array} _parameter Parameter of the attribute. */ - 'protected setInAttribute' : function(_name, _type, _value, _parameters) { - var attributeValue = new AttributeValue().withName(_name) - .withValue(_value).withType(_type).withParameters(_parameters); - if (this.isInAttribute(attributeValue)) { - this.inAttributeValues.put(attributeValue); - } + 'protected setInAttribute' : function(_attribute) { + this.inAttributes.put(_attribute); }, /** * Sets an inAttributes. * * @protected - * @alias setInAttributeValues + * @alias setInAttributes * @memberof Interpreter# - * @param {(AttributeValueList|Array)} _attributeValueList Attributes to set. + * @param {(AttributeList|Array)} _attributeList Attributes to set. */ - 'protected setInAttributeValues' : function(_attributeValueList) { - this.inAttributeValues = new AttributeValueList().withItems(_attributeValueList); + 'protected setInAttributes' : function(_attributeList) { + this.inAttributes = new AttributeList().withItems(_attributeList); }, + /** * Verifies whether the specified attribute is contained in inAttributeList. * * @protected * @alias isInAttribute * @memberof Interpreter# - * @param {AttributeValue} _attribute Attribute that should be verified. + * @param {Attribute} _attribute Attribute that should be verified. * @return {boolean} */ 'protected isInAttribute' : function(_attribute) { - return !!this.inAttributeTypes.contains(_attribute.getAttributeType()); + return !!this.inAttributes.containsTypeOf(_attribute); }, /** * Returns the provided outAttributeTypes. * * @public - * @alias getOutAttributeTypes + * @alias getOutAttributes * @memberof Interpreter# - * @returns {AttributeTypeList} + * @returns {AttributeList} */ - 'public getOutAttributeTypes' : function() { - return this.outAttributeTypes; + 'public getOutAttributes' : function() { + return this.outAttributes; }, /** @@ -246,17 +219,21 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', * @protected * @alias setOutAttribute * @memberof Interpreter# - * @param {string} _name name of the attribute - * @param {string} _type type of the attribute - * @param {string} _value value of the attribute - * @param {ParameterList|Array} _parameters Parameter of the attribute. */ - 'protected setOutAttribute' : function(_name, _type, _value,_parameters) { - var attributeValue = new AttributeValue().withName(_name) - .withValue(_value).withType(_type).withParameters(_parameters); - if (this.isOutAttribute(attributeValue)) { - this.outAttributeValues.put(attributeValue); - } + 'protected setOutAttribute' : function(_attribute) { + this.outAttributes.put(_attribute); + }, + + /** + * Sets an outAttributes. + * + * @protected + * @alias setOutAttributes + * @memberof Interpreter# + * @param {(AttributeList|Array)} _attributeList Attributes to set. + */ + 'protected setOutAttributes' : function(_attributeList) { + this.outAttributes = new AttributeList().withItems(_attributeList); }, /** @@ -265,11 +242,11 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', * @protected * @alias isOutAttribute * @memberof Interpreter# - * @param {AttributeValue} _attribute Attribute that should be verified. + * @param {Attribute} _attribute Attribute that should be verified. * @return {boolean} */ 'protected isOutAttribute' : function(_attribute) { - return !!this.outAttributeTypes.contains(_attribute.getAttributeType()); + return !!this.outAttributes.containsTypeOf(_attribute); }, /** @@ -278,21 +255,22 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', * @public * @alias callInterpreter * @memberof Interpreter# - * @param {AttributeValueList} _inAttributeValues Data that should be interpreted. + * @param {AttributeList} _inAttributeValues Data that should be interpreted. + * @param {AttributeList} _outAttributeValues * @param {?function} _function For additional actions, if an asynchronous function is used. */ 'public callInterpreter' : function(_inAttributeValues, _outAttributeValues, _function) { var self = this; - if (!_inAttributeValues || !this.canHandleInAttributeValues(_inAttributeValues)) throw "Empty input attribute list or unhandled input attribute."; - if (!_outAttributeValues || !this.canHandleOutAttributeValues(_outAttributeValues)) throw "Empty output attribute list or unhandled output attribute."; + if (!_inAttributeValues || !this.canHandleInAttributes(_inAttributeValues)) throw "Empty input attribute list or unhandled input attribute."; + if (!_outAttributeValues || !this.canHandleOutAttributes(_outAttributeValues)) throw "Empty output attribute list or unhandled output attribute."; this.interpretData(_inAttributeValues, _outAttributeValues, function(interpretedData) { - var response = new AttributeValueList().withItems(interpretedData); + var response = new AttributeList().withItems(interpretedData); - if (!self.canHandleOutAttributeValues(response)) throw "Unhandled output attribute generated."; + if (!self.canHandleOutAttributes(response)) throw "Unhandled output attribute generated."; - self.setInAttributeValues(_inAttributeValues); + self.setInAttributes(_inAttributeValues); self.lastInterpretation = new Date(); if (_function && typeof(_function) == 'function'){ @@ -309,27 +287,27 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', * @public * @alias interpretData * @memberof Interpreter# - * @param {AttributeValueList} _data Data that should be interpreted. + * @param {AttributeList} _data Data that should be interpreted. * @param {?function} _function For additional actions, if an asynchronous function is used. */ - 'abstract protected interpretData' : ['_inAttributeValues', '_outAttributeValues', '_callback'], + 'abstract protected interpretData' : ['_inAttributes', '_outAttributes', '_callback'], /** * Checks whether the specified data match the expected. * * @protected - * @alias canHandleInAttributeValues + * @alias canHandleInAttributes * @memberof Interpreter# - * @param {AttributeValueList|Array.<AttributeValue>} _inAttributeValues Data that should be verified. + * @param {AttributeList|Array.<Attribute>} _inAttributes Data that should be verified. */ - 'protected canHandleInAttributeValues' : function(_inAttributeValues) { + 'protected canHandleInAttributes' : function(_inAttributes) { var list = []; - if (_inAttributeValues instanceof Array) { - list = _inAttributeValues; - } else if (Class.isA(AttributeValueList, _inAttributeValues)) { - list = _inAttributeValues.getItems(); + if (_inAttributes instanceof Array) { + list = _inAttributes; + } else if (Class.isA(AttributeList, _inAttributes)) { + list = _inAttributes.getItems(); } - if (list.length == 0 || _inAttributeValues.size() != this.getInAttributeTypes().size()) { + if (list.length == 0 || _inAttributes.size() != this.getInAttributes().size()) { return false; } for ( var i in list) { @@ -345,18 +323,18 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', * Checks whether the specified data match the expected. * * @protected - * @alias canHandle + * @alias canHandleOutAttributes * @memberof Interpreter# - * @param {AttributeValueList|Array.<AttributeValue>} _outAttributeValues Data that should be verified. + * @param {AttributeList|Array.<Attribute>} _outAttributes Data that should be verified. */ - 'protected canHandleOutAttributeValues' : function(_outAttributeValues) { + 'protected canHandleOutAttributes' : function(_outAttributes) { var list = []; - if (_outAttributeValues instanceof Array) { - list = _outAttributeValues; - } else if (Class.isA(AttributeValueList, _outAttributeValues)) { - list = _outAttributeValues.getItems(); + if (_outAttributes instanceof Array) { + list = _outAttributes; + } else if (Class.isA(AttributeList, _outAttributes)) { + list = _outAttributes.getItems(); } - if (list.length == 0 || _outAttributeValues.size() != this.getOutAttributeTypes().size()) { + if (list.length == 0 || _outAttributes.size() != this.getOutAttributes().size()) { return false; } for ( var i in list) { @@ -389,10 +367,9 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', * @returns {InterpreterDescription} */ 'virtual public getDescription' : function() { - var description = new InterpreterDescription().withId( - this.id).withName(this.name); - description.addOutAttributeTypes(this.outAttributeTypes); - description.setInAttributeTypes(this.inAttributeTypes); + var description = new InterpreterDescription().withId(this.id).withName(this.name); + description.addOutAttributeTypes(this.outAttributes); + description.setInAttributeTypes(this.inAttributes); return description; }, @@ -421,7 +398,6 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', if (this.discoverer) { this.discoverer.registerNewComponent(this); } - }, /** @@ -429,28 +405,12 @@ define([ 'easejs', 'MathUuid', 'attributeType', 'attributeTypeList', * @returns {boolean} */ 'public hasOutAttributesWithInputParameters': function() { - return this.outAttributeTypes.hasAttributesWithInputParameters(); + return this.outAttributes.hasAttributesWithInputParameters(); }, 'public getOutAttributesWithInputParameters': function() { - return this.outAttributeTypes.getAttributesWithInputParameters(); + return this.outAttributes.getAttributesWithInputParameters(); } - -// /** -// * Unregisters the component to the associated discoverer -// * and deletes the reference. -// * -// * @public -// * @alias register -// * @memberof Widget# -// */ -// 'protected unregister' : function() { -// if (this.discoverer) { -// this.discoverer.unregisterComponent(this.getId()); -// this.discoverer = null; -// } -// }, - }); return Interpreter; diff --git a/js/modules/interpreter/interpreterResult.js b/js/modules/interpreter/interpreterResult.js index 363119c24bb8c769ab9ea285f3a1f30540d4a873..caaef4237cbc71dc33326b355171133ed9bcb6ee 100644 --- a/js/modules/interpreter/interpreterResult.js +++ b/js/modules/interpreter/interpreterResult.js @@ -4,8 +4,8 @@ * @module InterpreterResult * @fileOverview */ -define(['easejs', 'attributeValueList'], - function(easejs, AttributeValueList){ +define(['easejs', 'attributeList'], + function(easejs, AttributeList){ var Class = easejs.Class; var InterpreterResult = Class('InterpreterResult',{ diff --git a/js/modules/subscriber/callback.js b/js/modules/subscriber/callback.js index 1b66d5de5f1c57522219d78b8d7c7cc875a48ee3..6a3326ecae9240772bdf8d5d390aeea452cfe191 100644 --- a/js/modules/subscriber/callback.js +++ b/js/modules/subscriber/callback.js @@ -5,8 +5,8 @@ * @module Callback * @fileOverview */ -define(['easejs', 'attributeType', 'attributeTypeList'], - function(easejs, AttributeType, AttributeTypeList){ +define(['easejs', 'attribute', 'attributeList'], + function(easejs, Attribute, AttributeList){ var Class = easejs.Class; var Callback = Class('Callback', @@ -43,7 +43,7 @@ define(['easejs', 'attributeType', 'attributeTypeList'], */ 'public __construct': function() { - this.attributeTypes = new AttributeTypeList(); + this.attributeTypes = new AttributeList(); }, /** @@ -118,19 +118,19 @@ define(['easejs', 'attributeType', 'attributeTypeList'], * @public * @alias setAttributeTypes * @memberof Callback# - * @param {AttributeTypeList} _attributeTypes AttributeTypeList + * @param {AttributeList} _attributes AttributeTypeList */ - 'public setAttributeTypes' : function(_attributeTypes){ + 'public setAttributeTypes' : function(_attributes){ var list = []; - if(_attributeTypes instanceof Array){ - list = _attributeTypes; - } else if (Class.isA( AttributeTypeList, _attributeTypes)) { - list = _attributeTypes.getItems(); + if(_attributes instanceof Array){ + list = _attributes; + } else if (Class.isA( AttributeList, _attributes)) { + list = _attributes.getItems(); } for(var i in list){ - var attributeType = list[i]; - if(Class.isA( AttributeType, attributeType )){ - this.attributeTypes.put(attributeType); + var theAttribute = list[i]; + if(Class.isA(Attribute, theAttribute)){ + this.attributeTypes.put(theAttribute); } } }, @@ -141,14 +141,14 @@ define(['easejs', 'attributeType', 'attributeTypeList'], * @public * @alias addAttributeType * @memberof Callback# - * @param {AttributeType} _attributeType AttributeType + * @param {AttributeType} _attribute AttributeType */ - 'public addAttributeType' : function(_attributeType){ - if(Class.isA( AttributeType, _attributeType )){ - if(!this.attributeTypes.contains(_attributeType)){ - this.attributeTypes.put(_attributeType); + 'public addAttributeType' : function(_attribute){ + if(Class.isA(Attribute, _attribute )){ + if(!this.attributeTypes.containsTypeOf(_attribute)){ + this.attributeTypes.put(_attribute); } - }; + } }, /** @@ -160,9 +160,9 @@ define(['easejs', 'attributeType', 'attributeTypeList'], * @param {AttributeType} _attributeType AttributeType */ 'public removeAttributeType' : function(_attributeType){ - if(Class.isA( AttributeType, _attributeType )){ + if(Class.isA(Attribute, _attributeType )){ this.attributeTypes.removeItem(_attributeType.getName()); - }; + } }, /** diff --git a/js/modules/subscriber/callbackList.js b/js/modules/subscriber/callbackList.js index 8dfbe6598039cb54c278745b0b09c0132e72908e..d48a3884afc1bf55682a51806bfdd685016d9d84 100644 --- a/js/modules/subscriber/callbackList.js +++ b/js/modules/subscriber/callbackList.js @@ -16,9 +16,7 @@ define(['easejs', 'abstractList', 'callback'], * @requires AbstractList * @requires Callback */ - var CallbackList = Class('CallbackList'). - extend(AbstractList,{ - + var CallbackList = Class('CallbackList').extend(AbstractList,{ /** * @alias counter * @protected @@ -46,18 +44,10 @@ define(['easejs', 'abstractList', 'callback'], * @returns {CallbackList} */ 'public withItems': function(_callbackList){ - var list = []; - if(_callbackList instanceof Array){ - list = _callbackList; + if (_callbackList instanceof Array) { + this.items = _callbackList; } else if (Class.isA(CallbackList, _callbackList)) { - list = _callbackList.getItems(); - } - for(var i in list){ - var callback = list[i]; - if(Class.isA( Callback, callback )){ - this.items[callback.getName()] = callback; - this.counter++; - } + this.items = _callbackList.getItems(); } return this; }, @@ -71,11 +61,10 @@ define(['easejs', 'abstractList', 'callback'], * @param {Callback} _callback Callback */ 'public put' : function(_callback){ - if(Class.isA(Callback, _callback)){ - if(!(this.containsKey(_callback.getName()))){ - this.counter++; + if (Class.isA(Callback, _callback)) { + if (!(this.contains(_callback))) { + this.items.push(_callback); } - this.items[_callback.getName()] = _callback; } }, @@ -90,19 +79,13 @@ define(['easejs', 'abstractList', 'callback'], */ 'public putAll' : function(_callbackList){ var list = []; - if(_callbackList instanceof Array){ + if (_callbackList instanceof Array) { list = _callbackList; - } else if (Class.isA(CallbackList, _callbackList)) { + } else if (Class.isA(CallbackList, _callbackList)) { list = _callbackList.getItems(); } - for(var i in list){ - var callback = list[i]; - if(Class.isA(Callback, callback)){ - if(!(this.containsKey(callback.getName()))){ - this.counter++; - } - this.items[callback.getName()] = callback; - } + for (var i in list) { + this.put(list[i]); } }, @@ -113,16 +96,18 @@ define(['easejs', 'abstractList', 'callback'], * @public * @alias contains * @memberof CallbackList# - * @param {Callback} _item CallbackType that should be verified. + * @param {Callback} _callback CallbackType that should be verified. * @returns {boolean} */ - 'public contains' : function(_item){ - if(Class.isA(Callback,_item)){ - var tmp = this.getItem(_item.getName()); - if(!(typeof tmp === 'undefined') && tmp.equals(_item)){ - return true; + 'public contains' : function(_callback){ + if (Class.isA(Callback, _callback)) { + for (var index in this.items) { + var tmp = this.items[index]; + if (tmp.equals(_callback)) { + return true; + } } - } + } return false; }, @@ -131,20 +116,17 @@ define(['easejs', 'abstractList', 'callback'], * @public * @alias equals * @memberof CallbackList# - * @param {CallbackList} _list CallbackList that should be compared. + * @param {CallbackList} _callbackList CallbackList that should be compared. * @returns {boolean} */ - 'public equals' : function(_list){ - if(Class.isA(CallbackList,_list) && _list.size() == this.size()){ - var items = _list.getItems(); - for(var i in items){ - var item = items[i]; - if(!this.contains(item)){ - return false; - } + 'public equals' : function(_callbackList){ + if (Class.isA(CallbackList, _callbackList) && _callbackList.size() == this.size()) { + for (var index in _callbackList.getItems()) { + var theCallback = _callbackList.getItems()[index]; + if (!this.contains(theCallback)) return false; } return true; - } + } return false; } diff --git a/js/modules/subscriber/condition/condition.js b/js/modules/subscriber/condition/condition.js index 791a29dfdce06829ccb6c9caae828eba7b8c926d..9a454870ff953aa7f35127f4f17c04ce8c81c892 100644 --- a/js/modules/subscriber/condition/condition.js +++ b/js/modules/subscriber/condition/condition.js @@ -6,8 +6,8 @@ * @module Condition * @fileOverview */ -define(['easejs','attributeType','attributeValue', 'conditionMethod'], - function(easejs, AttributeType, AttributeValue, ConditionMethod){ +define(['easejs','attribute', 'conditionMethod'], + function(easejs, Attribute, ConditionMethod){ var Class = easejs.Class; /** * @class Condition @@ -126,11 +126,11 @@ define(['easejs','attributeType','attributeValue', 'conditionMethod'], * @public * @alias setAttributeType * @memberof Condition# - * @param {AttributeType} _attributeType AttributeType + * @param {Attribute} _attribute AttributeType */ - 'public setAttributeType' : function(_attributeType){ - if(Class.isA(AttributeType,_attributeType)){ - this.attributeType = _attributeType; + 'public setAttributeType' : function(_attribute){ + if(Class.isA(Attribute, _attribute)){ + this.attributeType = _attribute; } }, @@ -214,21 +214,20 @@ define(['easejs','attributeType','attributeValue', 'conditionMethod'], * @public * @alias compare * @memberof Condition# - * @param {AttributeValue} _newAttributeValue new Attribute that should be compared - * @param {AttributeValue} _oldAttributeValue old Attribute + * @param {Attribute} _newAttributeValue new Attribute that should be compared + * @param {Attribute} _oldAttributeValue old Attribute * @returns {boolean} */ 'public compare' : function(_newAttributeValue, _oldAttributeValue){ - if(!this.attributeType.equals(_newAttributeValue.getAttributeType()) - && !this.attributeType.equals(_oldAttributeValue.getAttributeType())){ + if(!this.attributeType.equalsTypeOf(_newAttributeValue)&& !this.attributeType.equalsTypeOf(_oldAttributeValue)){ return false; - }; + } if(!this.comparisonMethod){ return false; - }; - if(Class.isA(AttributeValue,_newAttributeValue) && Class.isA(AttributeValue,_oldAttributeValue)){ + } + if(Class.isA(Attribute, _newAttributeValue) && Class.isA(Attribute, _oldAttributeValue)){ return this.comparisonMethod.process(this.referenceValue, _newAttributeValue.getValue(), _oldAttributeValue.getValue()); - }; + } return false; }, @@ -245,7 +244,7 @@ define(['easejs','attributeType','attributeValue', 'conditionMethod'], if(Class.isA(Condition, _condition)){ if(_condition.getName() == this.getName() && _condition.getReferenceValue() == this.getReferenceValue() - && _condition.getAttributeType().equals(this.attributeType) + && _condition.getAttributeType().equalsTypeOf(this.attributeType) && _condition.getComparisonMethod() === this.comparisonMethod){ return true; }; diff --git a/js/modules/subscriber/condition/conditionList.js b/js/modules/subscriber/condition/conditionList.js index 2c38a27ea715278b8a458280f461fedf21092f86..54e5a58c5712b437243e08ba969f3be155201fe2 100644 --- a/js/modules/subscriber/condition/conditionList.js +++ b/js/modules/subscriber/condition/conditionList.js @@ -45,18 +45,10 @@ define(['easejs','abstractList', 'condition'], * @returns {ConditionList} */ 'public withItems': function(_conditionList){ - var list = new Array(); - if(_conditionList instanceof Array){ - list = _conditionList; + if (_conditionList instanceof Array) { + this.items = _conditionList; } else if (Class.isA(ConditionList, _conditionList)) { - list = _conditionList.getItems(); - } - for(var i in list){ - var condition = list[i]; - if(Class.isA( Condition, condition )){ - this.items[condition.getName()] = condition; - this.counter++; - } + this.items = _conditionList.getItems(); } return this; }, @@ -70,11 +62,9 @@ define(['easejs','abstractList', 'condition'], * @param {Condition} _condition Condition */ 'public put' : function(_condition){ - if(Class.isA(Condition, _condition)){ - if(!(this.containsKey(_condition.getName()))){ - this.counter++; - } - this.items[_condition.getName()] = _condition; + if (Class.isA(Condition, _condition)) { + if (!(this.contains(_condition))) { + this.items.push(_condition);} } }, @@ -88,20 +78,14 @@ define(['easejs','abstractList', 'condition'], * @param {(ConditioneList|Array)} _conditionList ConditionList */ 'public putAll' : function(_conditionList){ - var list = new Array(); - if(_conditionList instanceof Array){ + var list = []; + if (_conditionList instanceof Array) { list = _conditionList; - } else if (Class.isA(ConditionList, _conditionList)) { + } else if (Class.isA(ConditionList, _conditionList)) { list = _conditionList.getItems(); } - for(var i in list){ - var condition = list[i]; - if(Class.isA(Condition, condition)){ - if(!(this.containsKey(condition.getName()))){ - this.counter++; - } - this.items[condition.getName()] = condition; - } + for (var i in list) { + this.put(list[i]); } }, @@ -112,16 +96,18 @@ define(['easejs','abstractList', 'condition'], * @public * @alias contains * @memberof ConditionList# - * @param {Condition} _item Condition that should be verified. + * @param {Condition} _condition Condition that should be verified. * @returns {boolean} */ - 'public contains' : function(_item){ - if(Class.isA(Condition,_item)){ - var tmp = this.getItem(_item.getName()); - if(!(typeof tmp === 'undefined') && tmp.equals(_item)){ - return true; + 'public contains' : function(_condition){ + if (Class.isA(Condition, _condition)) { + for (var index in this.items) { + var theCondition = this.items[index]; + if (theCondition.equals(_condition)) { + return true; + } } - } + } return false; }, @@ -131,24 +117,19 @@ define(['easejs','abstractList', 'condition'], * @public * @alias equals * @memberof ConditionList# - * @param {ConditionList} _list ConditionList that should be compared. + * @param {ConditionList} _conditionList ConditionList that should be compared. * @returns {boolean} */ - 'public equals' : function(_list){ - if(Class.isA(ConditionList,_list) && _list.size() == this.size()){ - var items = _list.getItems(); - for(var i in items){ - var item = items[i]; - if(!this.contains(item)){ - return false; - } + 'public equals' : function(_conditionList){ + if (Class.isA(ConditionList, _conditionList) && _conditionList.size() == this.size()) { + for (var index in _conditionList.getItems()) { + var theCondition = _conditionList.getItems()[index]; + if (!this.contains(theCondition)) return false; } return true; - } + } return false; - }, - - + } }); diff --git a/js/modules/subscriber/subscriber.js b/js/modules/subscriber/subscriber.js index 2f15aca2130d48ef26cbcdbaf93a3e3e84c5d9ba..f2becf4474395fb55527975c193abd812b59b1a9 100644 --- a/js/modules/subscriber/subscriber.js +++ b/js/modules/subscriber/subscriber.js @@ -4,8 +4,8 @@ * @module Subscriber * @fileOverview */ -define(['easejs', 'attributeTypeList', 'callbackList', 'condition', 'conditionList'], - function(easejs, AttributeTypeList, CallbackList, Condition, ConditionList){ +define(['easejs', 'attributeList', 'callbackList', 'condition', 'conditionList'], + function(easejs, AttributeList, CallbackList, Condition, ConditionList){ /* * Callback: name and associated Attributes @@ -73,8 +73,8 @@ define(['easejs', 'attributeTypeList', 'callbackList', 'condition', 'conditionLi 'virtual public __construct': function() { this.subscriptionCallbacks = new CallbackList(); - this.subscriptionCallbacks = new AttributeTypeList(); - this.attributesSubset = new AttributeTypeList(); + this.subscriptionCallbacks = new AttributeList(); + this.attributesSubset = new AttributeList(); this.conditions = new ConditionList(); }, @@ -172,7 +172,7 @@ define(['easejs', 'attributeTypeList', 'callbackList', 'condition', 'conditionLi 'public setSubscriberName' : function(_subscriberName){ if(typeof _subscriberName === 'string'){ this.subscriberName = _subscriberName; - }; + } }, @@ -225,7 +225,7 @@ define(['easejs', 'attributeTypeList', 'callbackList', 'condition', 'conditionLi 'public setSubscriptionCallbacks' : function(_subscriptionCallbacks){ if(Class.isA(CallbackList, _subscriptionCallbacks)){ this.subscriptionCallbacks = _subscriptionCallbacks; - }; + } }, /** @@ -246,12 +246,12 @@ define(['easejs', 'attributeTypeList', 'callbackList', 'condition', 'conditionLi * @public * @alias setAttributesSubset * @memberof Subscriber# - * @param {AttributeTypeList} _attributesSubset attributesSubset + * @param {AttributeList} _attributesSubset attributesSubset */ 'public setAttributesSubset' : function(_attributesSubset){ - if(Class.isA(AttributeTypeList, _attributesSubset)){ + if(Class.isA(AttributeList, _attributesSubset)){ this.attributesSubset = _attributesSubset; - }; + } }, /** diff --git a/js/modules/subscriber/subscriberList.js b/js/modules/subscriber/subscriberList.js index b241e84df1c134412698998322114c33d020a05b..2af2efa5a696a83a0ef37fae8675393db8dae587 100644 --- a/js/modules/subscriber/subscriberList.js +++ b/js/modules/subscriber/subscriberList.js @@ -42,23 +42,14 @@ define(['easejs', 'abstractList', 'subscriber'], * @public * @alias withItems * @memberof SubscriberList# - * @param {(SubscriberList|Array)} - * _subscriberList SubscriberList + * @param {(SubscriberList|Array)} _subscriberList SubscriberList * @returns {SubscriberList} */ 'public withItems': function(_subscriberList){ - var list = new Array(); - if(_subscriberList instanceof Array){ - list = _subscriberList; - } else if (Class.isA( SubscriberList, _subscriberList)) { - list = _subscriberList.getItems(); - } - for(var i in list){ - var subscriber = list[i]; - if(Class.isA( Subscriber, subscriber )){ - this.items[subscriber.getSubscriberId()] = subscriber; - this.counter++; - } + if (_subscriberList instanceof Array) { + this.items = _subscriberList; + } else if (Class.isA(SubscriberList, _subscriberList)) { + this.items = _subscriberList.getItems(); } return this; }, @@ -69,15 +60,12 @@ define(['easejs', 'abstractList', 'subscriber'], * @public * @alias put * @memberof SubscriberList# - * @param {Subscriber} - * _subscriber Subscriber + * @param {Subscriber} _subscriber Subscriber */ 'public put' : function(_subscriber){ - if(Class.isA(Subscriber, _subscriber)){ - if(!(this.containsKey(_subscriber.getSubscriberId()))){ - this.counter++; - } - this.items[_subscriber.getSubscriberId()] = _subscriber; + if (Class.isA(Subscriber, _subscriber)) { + if (!(this.contains(_subscriber))) { + this.items.push(_subscriber);} } }, @@ -90,20 +78,14 @@ define(['easejs', 'abstractList', 'subscriber'], * @param {(SubscriberList|Array)} _subscriberList SubscriberList */ 'public putAll' : function(_subscriberList){ - var list = new Array(); - if(_subscriberList instanceof Array){ + var list = []; + if (_subscriberList instanceof Array) { list = _subscriberList; - } else if (Class.isA(SubscriberList, _subscriberList)) { + } else if (Class.isA(SubscriberList, _subscriberList)) { list = _subscriberList.getItems(); } - for(var i in list){ - var subscriber = list[i]; - if(Class.isA(Subscriber, subscriber)){ - if(!(this.containsKey(subscriber.getSubscriberId()))){ - this.counter++; - } - this.items[subscriber.getSubscriberId()] = subscriber; - } + for (var i in list) { + this.put(list[i]); } }, @@ -113,17 +95,18 @@ define(['easejs', 'abstractList', 'subscriber'], * @public * @alias contains * @memberof SubscriberList# - * @param {Subscriber} - * _item Subscriber that should be verified. + * @param {Subscriber}_subscriber Subscriber that should be verified. * @returns {boolean} */ - 'public contains' : function(_item){ - if(Class.isA(Subscriber,_item)){ - var tmp = this.getItem(_item.getSubscriberId()); - if(!(typeof tmp === 'undefined') && tmp.equals(_item)){ - return true; + 'public contains' : function(_subscriber){ + if (Class.isA(Subscriber, _subscriber)) { + for (var index in this.items) { + var tmp = this.items[index]; + if (tmp.equals(_subscriber)) { + return true; + } } - } + } return false; }, @@ -132,23 +115,26 @@ define(['easejs', 'abstractList', 'subscriber'], * @public * @alias equals * @memberof SubscriberList# - * @param {SubscriberList} _list SubscriberList that should be compared. + * @param {SubscriberList} _subscriberList SubscriberList that should be compared. * @returns {boolean} */ - 'public equals' : function(_list){ - if(Class.isA(SubscriberList,_list) && _list.size() == this.size()){ - var items = _list.getItems(); - for(var i in items){ - var item = items[i]; - if(!this.contains(item)){ - return false; - } + 'public equals' : function(_subscriberList) { + if (Class.isA(SubscriberList, _subscriberList) && _subscriberList.size() == this.size()) { + for (var index in _subscriberList.getItems()) { + var theSubscriber = _subscriberList.getItems()[index]; + if (!this.contains(theSubscriber)) return false; } return true; - } + } return false; }, + 'public removeSubscriberWithId': function(_subscriberId) { + for (var index in this.items) { + var theSubscriber = this.items[index]; + if (theSubscriber.getSubscriberId() == _subscriberId) this.items.splice(index, 1); + } + } }); return SubscriberList; diff --git a/js/modules/widget/widget.js b/js/modules/widget/widget.js index b63b0a67045e1ef759aeb59ab4fd7f022067ebfb..cab418964be6fbddd8e51d86edd459fff8291117 100644 --- a/js/modules/widget/widget.js +++ b/js/modules/widget/widget.js @@ -4,11 +4,11 @@ * @module Widget * @fileOverview */ -define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', - 'attributeValue', 'attributeTypeList', 'attributeValueList', 'conditionList', +define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attribute', + 'attributeList', 'conditionList', 'subscriber', 'subscriberList', 'widgetDescription'], - function(easejs, MathUuid, Callback, CallbackList, AttributeType, - AttributeValue, AttributeTypeList, AttributeValueList, ConditionList, + function(easejs, MathUuid, Callback, CallbackList, Attribute, + AttributeList, ConditionList, Subscriber, SubscriberList, WidgetDescription) { var AbstractClass = easejs.AbstractClass; @@ -30,27 +30,11 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * @desc ID of the Widget. Will be generated. */ 'public id' : '', - /** - * @alias attributeTypes - * @protected - * @type {AttributeTypeList} - * @memberof Widget# - * @desc Types of all available attributes. - */ - 'protected attributeTypes' : [], - /** - * @alias constantAttributeTypes - * @protected - * @type {AttributeTypeList} - * @memberof Widget# - * @desc Types of all available ConstantAttributes. - */ - 'protected constantAttributeTypes' : [], /** * @alias attributes * @protected - * @type {AttributeValueList} + * @type {AttributeList} * @memberof Widget# * @desc All available Attributes and their values. */ @@ -58,7 +42,7 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', /** * @alias oldAttributes * @protected - * @type {AttributeValueList} + * @type {AttributeList} * @memberof Widget# * @desc This temporary variable is used for storing the old attribute values. * So these can be used to check conditions. @@ -67,7 +51,7 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', /** * @alias constantAttributes * @protected - * @type {AttributeValueList} + * @type {AttributeList} * @memberof Widget# * @desc All available constant Attributes and their values. */ @@ -110,10 +94,8 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * @requires MathUuid * @requires Callback * @requires CallbackList - * @requires AttributeType - * @requires AttributeValue - * @requires AttributeTypeList - * @requires AttributeValueList + * @requires Attribute + * @requires AttributeList * @requires ConditionList * @requires Subscriber * @requires SubscriberList @@ -125,10 +107,8 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', this.id = Math.uuid(); this.discoverer = _discoverer; this.register(); - this.attributeTypes = new AttributeTypeList(); - this.constantAttributeTypes = new AttributeTypeList(); - this.attributes = new AttributeValueList(); - this.constantAttributes = new AttributeValueList(); + this.attributes = new AttributeList(); + this.constantAttributes = new AttributeList(); this.subscribers = new SubscriberList(); this.callbacks = new CallbackList(); this.init(_attributeTypes); @@ -176,12 +156,16 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * Returns the available AttributeTypes. * * @public - * @alias getAttributeTypes + * @alias getAttributes * @memberof Widget# - * @returns {AttributeTypeList} + * @returns {AttributeList} */ - 'public getAttributeTypes' : function() { - return this.attributeTypes; + 'public getAttributes' : function(_attributeList) { + if (Class.isA(AttributeList, _attributeList)) { + return this.attributes.getSubset(_attributeList); + } else { + return this.attributes; + } }, /** @@ -191,27 +175,14 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * @public * @alias getWidgetConstantAttributeTypes * @memberof Widget# - * @returns {AttributeTypeList} - */ - 'public getWidgetConstantAttributeTypes' : function() { - return this.constantAttributeTypes; - }, - - /** - * Returns the last acquired attribute values. - * - * @public - * @alias getAttributes - * @memberof Widget# - * @param {AttributeTypeList} _attributeTypeList - * @returns {AttributeValueList} + * @returns {AttributeList} */ - 'public getAttributeValues' : function(_attributeTypeList) { - if (Class.isA(AttributeTypeList, _attributeTypeList)) { - return this.attributes.getSubset(_attributeTypeList); - } else { - return this.attributes; - } + 'public getConstantAttributes' : function(_attributeList) { + if (Class.isA(AttributeList, _attributeList)) { + return this.constantAttributes.getSubset(_attributeList); + } else { + return this.constantAttributes; + } }, /** @@ -220,8 +191,8 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * @param {AttributeType} _attributeType The attribute type to return the last value for. * @returns {*} */ - 'public getAttributeValue': function(_attributeType) { - return this.getAttributeValues().getItemForAttributeType(_attributeType).getValue(); + 'public getValueForAttributeWithTypeOf': function(_attributeType) { + return this.getAttributes().getAttributeWithTypeOf(_attributeType).getValue(); }, /** @@ -230,24 +201,12 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * @private * @alias getOldAttributes * @memberof Widget# - * @returns {AttributeValueList} + * @returns {AttributeList} */ 'public getOldAttributes' : function() { return this.oldAttributes; }, - /** - * Returns the ConstantAttributes. - * - * @public - * @alias getConstantAttributes - * @memberof Widget# - * @returns {AttributeValueList} - */ - 'public getConstantAttributes' : function() { - return this.constantAttributes; - }, - /** * Returns a list of callbacks that can be * subscribed to. @@ -365,23 +324,16 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * @public * @alias addAttribute * @memberof Widget# - * @param {AttributeValue} - * _attribute AttributeValue + * @param {Attribute} _attribute AttributeValue */ - 'public addAttribute' : function(_attribute) { - if (Class.isA(AttributeValue, _attribute)) { - if (!this.attributes.contains(_attribute)) { - - var type = new AttributeType().withName(_attribute.getName()) - .withType(_attribute.getType()) - .withParameters(_attribute.getParameters()); - this.attributeTypes.put(type); - + 'public addAttribute' : function(_attribute, _multipleInstances) { + _multipleInstances = typeof _multipleInstances == "undefined" ? false : _multipleInstances; + if (Class.isA(Attribute, _attribute)) { + if (!this.attributes.containsTypeOf(_attribute)) { + this.oldAttributes = this.attributes; + _attribute.setTimestamp(this.getCurrentTime()); + this.attributes.put(_attribute, _multipleInstances); } - this.oldAttributes = this.attributes; - - _attribute.setTimestamp(this.getCurrentTime()); - this.attributes.put(_attribute); } }, @@ -531,7 +483,7 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * @param {Subscriber} _subscriber Subscriber */ 'public removeSubscriber' : function(_subscriberId) { - this.subscribers.removeItem(_subscriberId); + this.subscribers.removeSubscriberWithId(_subscriberId); }, /** @@ -558,7 +510,7 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * @returns {boolean} */ 'protected isAttribute' : function(_attribute) { - return !!this.attributeTypes.contains(_attribute.getAttributeType()); + return !!this.attributes.containsTypeOf(_attribute); }, /** @@ -683,12 +635,12 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', var list = []; if (_data instanceof Array) { list = _data; - } else if (Class.isA(AttributeValueList, _data)) { + } else if (Class.isA(AttributeList, _data)) { list = _data.getItems(); } for ( var i in list) { var x = list[i]; - if (Class.isA(AttributeValue, x) && this.isAttribute(x)) { + if (Class.isA(Attribute, x) && this.isAttribute(x)) { this.addAttribute(x); } } @@ -702,11 +654,11 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * @public * @alias queryWidget * @memberof Widget# - * @returns {AttributeValueList} + * @returns {AttributeList} */ 'public queryWidget' : function() { - var response = new AttributeValueList(); - response.putAll(this.getAttributeValues()); + var response = new AttributeList(); + response.putAll(this.getAttributes()); response.putAll(this.getConstantAttributes()); return response; }, @@ -719,15 +671,15 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', * @alias updateAndQueryWidget * @memberof Widget# * @param {?function} _function For alternative actions, because an asynchronous function can be used. - * @returns {?AttributeValueList} + * @returns {?AttributeList} */ 'virtual public updateAndQueryWidget' : function(_function) { if(_function && typeof(_function) === 'function'){ this.queryGenerator(_function); } else { this.queryGenerator(); - var response = new AttributeValueList(); - response.putAll(this.getAttributeValues()); + var response = new AttributeList(); + response.putAll(this.getAttributes()); response.putAll(this.getConstantAttributes()); return response; } @@ -746,7 +698,7 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', var subscriberList = this.subscribers.getItems(); for ( var i in subscriberList) { var subscriber = subscriberList[i]; - if (subscriber.getSubscriptionCallbacks().containsKey( _callback.getName())) { + if (subscriber.getSubscriptionCallbacks().contains(_callback)) { if(this.dataValid(subscriber.getConditions())){ var subscriberInstance = this.discoverer.getComponent(subscriber.getSubscriberId()); var callSubset = _callback.getAttributeTypes(); @@ -802,8 +754,8 @@ define([ 'easejs', 'MathUuid', 'callback', 'callbackList', 'attributeType', */ 'virtual public getDescription' : function() { var description = new WidgetDescription().withId(this.id).withName(this.name); - description.addOutAttributeTypes(this.attributeTypes); - description.addOutAttributeTypes(this.constantAttributeTypes); + description.addOutAttributeTypes(this.attributes); + description.addOutAttributeTypes(this.constantAttributes); var widgetCallbacks = this.callbacks.getItems(); for(var i in widgetCallbacks) { description.addCallbackName(widgetCallbacks[i].getName()); diff --git a/libs/qunit/qunit.css b/libs/qunit/qunit.css index 9437b4b60c6b0a5ab719bcc825293e80781a98ee..f1dcd4e1ccf8632e6840a607157ed0b2c7b7ab03 100644 --- a/libs/qunit/qunit.css +++ b/libs/qunit/qunit.css @@ -1,12 +1,12 @@ /*! - * QUnit 1.15.0 + * QUnit 1.18.0 * http://qunitjs.com/ * - * Copyright 2014 jQuery Foundation and other contributors + * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * - * Date: 2014-08-08T16:00Z + * Date: 2015-04-03T10:23Z */ /** Font Family and Sizes */ @@ -77,6 +77,18 @@ #qunit-modulefilter-container { float: right; + padding: 0.2em; +} + +.qunit-url-config { + display: inline-block; + padding: 0.1em; +} + +.qunit-filter { + display: block; + float: right; + margin-left: 1em; } /** Tests: Pass/Fail */ @@ -91,19 +103,46 @@ list-style-position: inside; } -#qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running { +#qunit-tests > li { display: none; } +#qunit-tests li.running, +#qunit-tests li.pass, +#qunit-tests li.fail, +#qunit-tests li.skipped { + display: list-item; +} + +#qunit-tests.hidepass li.running, +#qunit-tests.hidepass li.pass { + visibility: hidden; + position: absolute; + width: 0px; + height: 0px; + padding: 0; + border: 0; + margin: 0; +} + #qunit-tests li strong { cursor: pointer; } +#qunit-tests li.skipped strong { + cursor: default; +} + #qunit-tests li a { padding: 0.5em; color: #C2CCD1; text-decoration: none; } + +#qunit-tests li p a { + padding: 0.25em; + color: #6B6464; +} #qunit-tests li a:hover, #qunit-tests li a:focus { color: #000; @@ -211,6 +250,21 @@ #qunit-banner.qunit-fail { background-color: #EE5757; } +/*** Skipped tests */ + +#qunit-tests .skipped { + background-color: #EBECE9; +} + +#qunit-tests .qunit-skipped-label { + background-color: #F4FF77; + display: inline-block; + font-style: normal; + color: #366097; + line-height: 1.8em; + padding: 0 0.5em; + margin: -0.4em 0.4em -0.4em 0; +} /** Result */ diff --git a/libs/qunit/qunit.js b/libs/qunit/qunit.js index 474cfe55f39c91feaee4915afc27740c0a9d8701..f3542ca9d4c2495b5fe73cf8685cce3b32405de1 100644 --- a/libs/qunit/qunit.js +++ b/libs/qunit/qunit.js @@ -1,12 +1,12 @@ /*! - * QUnit 1.15.0 + * QUnit 1.18.0 * http://qunitjs.com/ * - * Copyright 2014 jQuery Foundation and other contributors + * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * - * Date: 2014-08-08T16:00Z + * Date: 2015-04-03T10:23Z */ (function( window ) { @@ -14,6 +14,7 @@ var QUnit, config, onErrorFnPrev, + loggingCallbacks = {}, fileName = ( sourceFromStacktrace( 0 ) || "" ).replace( /(:\d+)+\)?/, "" ).replace( /.+\//, "" ), toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, @@ -22,11 +23,13 @@ var QUnit, now = Date.now || function() { return new Date().getTime(); }, + globalStartCalled = false, + runStarted = false, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, defined = { - document: typeof window.document !== "undefined", - setTimeout: typeof window.setTimeout !== "undefined", + document: window.document !== undefined, + setTimeout: window.setTimeout !== undefined, sessionStorage: (function() { var x = "qunit-test-string"; try { @@ -86,132 +89,7 @@ var QUnit, return vals; }; -// Root QUnit object. -// `QUnit` initialized at top of scope -QUnit = { - - // call on start of module test to prepend name to all tests - module: function( name, testEnvironment ) { - config.currentModule = name; - config.currentModuleTestEnvironment = testEnvironment; - config.modules[ name ] = true; - }, - - asyncTest: function( testName, expected, callback ) { - if ( arguments.length === 2 ) { - callback = expected; - expected = null; - } - - QUnit.test( testName, expected, callback, true ); - }, - - test: function( testName, expected, callback, async ) { - var test; - - if ( arguments.length === 2 ) { - callback = expected; - expected = null; - } - - test = new Test({ - testName: testName, - expected: expected, - async: async, - callback: callback, - module: config.currentModule, - moduleTestEnvironment: config.currentModuleTestEnvironment, - stack: sourceFromStacktrace( 2 ) - }); - - if ( !validTest( test ) ) { - return; - } - - test.queue(); - }, - - start: function( count ) { - var message; - - // QUnit hasn't been initialized yet. - // Note: RequireJS (et al) may delay onLoad - if ( config.semaphore === undefined ) { - QUnit.begin(function() { - // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first - setTimeout(function() { - QUnit.start( count ); - }); - }); - return; - } - - config.semaphore -= count || 1; - // don't start until equal number of stop-calls - if ( config.semaphore > 0 ) { - return; - } - - // Set the starting time when the first test is run - QUnit.config.started = QUnit.config.started || now(); - // ignore if start is called more often then stop - if ( config.semaphore < 0 ) { - config.semaphore = 0; - - message = "Called start() while already started (QUnit.config.semaphore was 0 already)"; - - if ( config.current ) { - QUnit.pushFailure( message, sourceFromStacktrace( 2 ) ); - } else { - throw new Error( message ); - } - - return; - } - // A slight delay, to avoid any current callbacks - if ( defined.setTimeout ) { - setTimeout(function() { - if ( config.semaphore > 0 ) { - return; - } - if ( config.timeout ) { - clearTimeout( config.timeout ); - } - - config.blocking = false; - process( true ); - }, 13 ); - } else { - config.blocking = false; - process( true ); - } - }, - - stop: function( count ) { - config.semaphore += count || 1; - config.blocking = true; - - if ( config.testTimeout && defined.setTimeout ) { - clearTimeout( config.timeout ); - config.timeout = setTimeout(function() { - QUnit.ok( false, "Test timed out" ); - config.semaphore = 1; - QUnit.start(); - }, config.testTimeout ); - } - } -}; - -// We use the prototype to distinguish between properties that should -// be exposed as globals (and in exports) and those that shouldn't -(function() { - function F() {} - F.prototype = QUnit; - QUnit = new F(); - - // Make F QUnit's constructor so that we can add to the prototype later - QUnit.constructor = F; -}()); +QUnit = {}; /** * Config object: Maintain internal state @@ -225,10 +103,6 @@ config = { // block until document ready blocking: true, - // when enabled, show only failing tests - // gets persisted through sessionStorage and can be changed in UI via checkbox - hidepassed: false, - // by default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, @@ -242,27 +116,46 @@ config = { // when enabled, all tests must call expect() requireExpects: false, + // depth up-to which object will be dumped + maxDepth: 5, + // add checkboxes that are persisted in the query-string // when enabled, the id is set to `true` as a `QUnit.config` property urlConfig: [ + { + id: "hidepassed", + label: "Hide passed tests", + tooltip: "Only show tests and assertions that fail. Stored as query-strings." + }, { id: "noglobals", label: "Check for Globals", - tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings." + tooltip: "Enabling this will test if any test introduces new properties on the " + + "`window` object. Stored as query-strings." }, { id: "notrycatch", label: "No try-catch", - tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings." + tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + + "exceptions in IE reasonable. Stored as query-strings." } ], // Set of all modules. - modules: {}, + modules: [], + + // The first unnamed module + currentModule: { + name: "", + tests: [] + }, callbacks: {} }; +// Push a loose unnamed module to the modules collection +config.modules.push( config.currentModule ); + // Initialize more QUnit.config and QUnit.urlParams (function() { var i, current, @@ -286,31 +179,162 @@ config = { } } + if ( urlParams.filter === true ) { + delete urlParams.filter; + } + QUnit.urlParams = urlParams; // String search anywhere in moduleName+testName config.filter = urlParams.filter; - // Exact match of the module name - config.module = urlParams.module; + if ( urlParams.maxDepth ) { + config.maxDepth = parseInt( urlParams.maxDepth, 10 ) === -1 ? + Number.POSITIVE_INFINITY : + urlParams.maxDepth; + } - config.testNumber = []; - if ( urlParams.testNumber ) { + config.testId = []; + if ( urlParams.testId ) { - // Ensure that urlParams.testNumber is an array - urlParams.testNumber = [].concat( urlParams.testNumber ); - for ( i = 0; i < urlParams.testNumber.length; i++ ) { - current = urlParams.testNumber[ i ]; - config.testNumber.push( parseInt( current, 10 ) ); + // Ensure that urlParams.testId is an array + urlParams.testId = decodeURIComponent( urlParams.testId ).split( "," ); + for ( i = 0; i < urlParams.testId.length; i++ ) { + config.testId.push( urlParams.testId[ i ] ); } } // Figure out if we're running the tests from a server or not QUnit.isLocal = location.protocol === "file:"; + + // Expose the current QUnit version + QUnit.version = "1.18.0"; }()); +// Root QUnit object. +// `QUnit` initialized at top of scope extend( QUnit, { + // call on start of module test to prepend name to all tests + module: function( name, testEnvironment ) { + var currentModule = { + name: name, + testEnvironment: testEnvironment, + tests: [] + }; + + // DEPRECATED: handles setup/teardown functions, + // beforeEach and afterEach should be used instead + if ( testEnvironment && testEnvironment.setup ) { + testEnvironment.beforeEach = testEnvironment.setup; + delete testEnvironment.setup; + } + if ( testEnvironment && testEnvironment.teardown ) { + testEnvironment.afterEach = testEnvironment.teardown; + delete testEnvironment.teardown; + } + + config.modules.push( currentModule ); + config.currentModule = currentModule; + }, + + // DEPRECATED: QUnit.asyncTest() will be removed in QUnit 2.0. + asyncTest: function( testName, expected, callback ) { + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + QUnit.test( testName, expected, callback, true ); + }, + + test: function( testName, expected, callback, async ) { + var test; + + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + test = new Test({ + testName: testName, + expected: expected, + async: async, + callback: callback + }); + + test.queue(); + }, + + skip: function( testName ) { + var test = new Test({ + testName: testName, + skip: true + }); + + test.queue(); + }, + + // DEPRECATED: The functionality of QUnit.start() will be altered in QUnit 2.0. + // In QUnit 2.0, invoking it will ONLY affect the `QUnit.config.autostart` blocking behavior. + start: function( count ) { + var globalStartAlreadyCalled = globalStartCalled; + + if ( !config.current ) { + globalStartCalled = true; + + if ( runStarted ) { + throw new Error( "Called start() outside of a test context while already started" ); + } else if ( globalStartAlreadyCalled || count > 1 ) { + throw new Error( "Called start() outside of a test context too many times" ); + } else if ( config.autostart ) { + throw new Error( "Called start() outside of a test context when " + + "QUnit.config.autostart was true" ); + } else if ( !config.pageLoaded ) { + + // The page isn't completely loaded yet, so bail out and let `QUnit.load` handle it + config.autostart = true; + return; + } + } else { + + // If a test is running, adjust its semaphore + config.current.semaphore -= count || 1; + + // Don't start until equal number of stop-calls + if ( config.current.semaphore > 0 ) { + return; + } + + // throw an Error if start is called more often than stop + if ( config.current.semaphore < 0 ) { + config.current.semaphore = 0; + + QUnit.pushFailure( + "Called start() while already started (test's semaphore was 0 already)", + sourceFromStacktrace( 2 ) + ); + return; + } + } + + resumeProcessing(); + }, + + // DEPRECATED: QUnit.stop() will be removed in QUnit 2.0. + stop: function( count ) { + + // If there isn't a test running, don't allow QUnit.stop() to be called + if ( !config.current ) { + throw new Error( "Called stop() outside of a test context" ); + } + + // If a test is running, adjust its semaphore + config.current.semaphore += count || 1; + + pauseProcessing(); + }, + config: config, // Safe object type checking @@ -351,78 +375,65 @@ extend( QUnit, { return undefined; }, - url: function( params ) { - params = extend( extend( {}, QUnit.urlParams ), params ); - var key, - querystring = "?"; - - for ( key in params ) { - if ( hasOwn.call( params, key ) ) { - querystring += encodeURIComponent( key ) + "=" + - encodeURIComponent( params[ key ] ) + "&"; - } - } - return window.location.protocol + "//" + window.location.host + - window.location.pathname + querystring.slice( 0, -1 ); - }, - - extend: extend -}); + extend: extend, -/** - * @deprecated: Created for backwards compatibility with test runner that set the hook function - * into QUnit.{hook}, instead of invoking it and passing the hook function. - * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. - * Doing this allows us to tell if the following methods have been overwritten on the actual - * QUnit object. - */ -extend( QUnit.constructor.prototype, { - - // Logging callbacks; all receive a single argument with the listed properties - // run test/logs.html for any related changes - begin: registerLoggingCallback( "begin" ), + load: function() { + config.pageLoaded = true; - // done: { failed, passed, total, runtime } - done: registerLoggingCallback( "done" ), + // Initialize the configuration options + extend( config, { + stats: { all: 0, bad: 0 }, + moduleStats: { all: 0, bad: 0 }, + started: 0, + updateRate: 1000, + autostart: true, + filter: "" + }, true ); - // log: { result, actual, expected, message } - log: registerLoggingCallback( "log" ), + config.blocking = false; - // testStart: { name } - testStart: registerLoggingCallback( "testStart" ), + if ( config.autostart ) { + resumeProcessing(); + } + } +}); - // testDone: { name, failed, passed, total, runtime } - testDone: registerLoggingCallback( "testDone" ), +// Register logging callbacks +(function() { + var i, l, key, + callbacks = [ "begin", "done", "log", "testStart", "testDone", + "moduleStart", "moduleDone" ]; + + function registerLoggingCallback( key ) { + var loggingCallback = function( callback ) { + if ( QUnit.objectType( callback ) !== "function" ) { + throw new Error( + "QUnit logging methods require a callback function as their first parameters." + ); + } - // moduleStart: { name } - moduleStart: registerLoggingCallback( "moduleStart" ), + config.callbacks[ key ].push( callback ); + }; - // moduleDone: { name, failed, passed, total } - moduleDone: registerLoggingCallback( "moduleDone" ) -}); + // DEPRECATED: This will be removed on QUnit 2.0.0+ + // Stores the registered functions allowing restoring + // at verifyLoggingCallbacks() if modified + loggingCallbacks[ key ] = loggingCallback; -QUnit.load = function() { - runLoggingCallbacks( "begin", { - totalTests: Test.count - }); + return loggingCallback; + } - // Initialize the configuration options - extend( config, { - stats: { all: 0, bad: 0 }, - moduleStats: { all: 0, bad: 0 }, - started: 0, - updateRate: 1000, - autostart: true, - filter: "", - semaphore: 1 - }, true ); + for ( i = 0, l = callbacks.length; i < l; i++ ) { + key = callbacks[ i ]; - config.blocking = false; + // Initialize key collection of logging callback + if ( QUnit.objectType( config.callbacks[ key ] ) === "undefined" ) { + config.callbacks[ key ] = []; + } - if ( config.autostart ) { - QUnit.start(); + QUnit[ key ] = registerLoggingCallback( key ); } -}; +})(); // `onErrorFnPrev` initialized at top of scope // Preserve other handlers @@ -448,7 +459,7 @@ window.onerror = function( error, filePath, linerNr ) { } else { QUnit.test( "global failure", extend(function() { QUnit.pushFailure( error, filePath + ":" + linerNr ); - }, { validTest: validTest } ) ); + }, { validTest: true } ) ); } return false; } @@ -457,21 +468,25 @@ window.onerror = function( error, filePath, linerNr ) { }; function done() { + var runtime, passed; + config.autorun = true; // Log the last module results if ( config.previousModule ) { runLoggingCallbacks( "moduleDone", { - name: config.previousModule, + name: config.previousModule.name, + tests: config.previousModule.tests, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, - total: config.moduleStats.all + total: config.moduleStats.all, + runtime: now() - config.moduleStats.started }); } delete config.previousModule; - var runtime = now() - config.started, - passed = config.stats.all - config.stats.bad; + runtime = now() - config.started; + passed = config.stats.all - config.stats.bad; runLoggingCallbacks( "done", { failed: config.stats.bad, @@ -481,61 +496,14 @@ function done() { }); } -/** @return Boolean: true if this test should be ran */ -function validTest( test ) { - var include, - filter = config.filter && config.filter.toLowerCase(), - module = config.module && config.module.toLowerCase(), - fullName = ( test.module + ": " + test.testName ).toLowerCase(); - - // Internally-generated tests are always valid - if ( test.callback && test.callback.validTest === validTest ) { - delete test.callback.validTest; - return true; - } - - if ( config.testNumber.length > 0 ) { - if ( inArray( test.testNumber, config.testNumber ) < 0 ) { - return false; - } - } - - if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { - return false; - } - - if ( !filter ) { - return true; - } - - include = filter.charAt( 0 ) !== "!"; - if ( !include ) { - filter = filter.slice( 1 ); - } - - // If the filter matches, we need to honour include - if ( fullName.indexOf( filter ) !== -1 ) { - return include; - } - - // Otherwise, do the opposite - return !include; -} - -// Doesn't support IE6 to IE9 +// Doesn't support IE6 to IE9, it will return undefined on these browsers // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack function extractStacktrace( e, offset ) { offset = offset === undefined ? 4 : offset; var stack, include, i; - if ( e.stacktrace ) { - - // Opera 12.x - return e.stacktrace.split( "\n" )[ offset + 3 ]; - } else if ( e.stack ) { - - // Firefox, Chrome, Safari 6+, IE10+, PhantomJS and Node + if ( e.stack ) { stack = e.stack.split( "\n" ); if ( /^error$/i.test( stack[ 0 ] ) ) { stack.shift(); @@ -553,9 +521,10 @@ function extractStacktrace( e, offset ) { } } return stack[ offset ]; + + // Support: Safari <=6 only } else if ( e.sourceURL ) { - // Safari < 6 // exclude useless self-reference for generated Error objects if ( /qunit.js$/.test( e.sourceURL ) ) { return; @@ -565,15 +534,30 @@ function extractStacktrace( e, offset ) { return e.sourceURL + ":" + e.line; } } + function sourceFromStacktrace( offset ) { - try { - throw new Error(); - } catch ( e ) { - return extractStacktrace( e, offset ); + var error = new Error(); + + // Support: Safari <=7 only, IE <=10 - 11 only + // Not all browsers generate the `stack` property for `new Error()`, see also #636 + if ( !error.stack ) { + try { + throw error; + } catch ( err ) { + error = err; + } } + + return extractStacktrace( error, offset ); } function synchronize( callback, last ) { + if ( QUnit.objectType( callback ) === "array" ) { + while ( callback.length ) { + synchronize( callback.shift() ); + } + return; + } config.queue.push( callback ); if ( config.autorun && !config.blocking ) { @@ -586,10 +570,16 @@ function process( last ) { process( last ); } var start = now(); - config.depth = config.depth ? config.depth + 1 : 1; + config.depth = ( config.depth || 0 ) + 1; while ( config.queue.length && !config.blocking ) { - if ( !defined.setTimeout || config.updateRate <= 0 || ( ( now() - start ) < config.updateRate ) ) { + if ( !defined.setTimeout || config.updateRate <= 0 || + ( ( now() - start ) < config.updateRate ) ) { + if ( config.current ) { + + // Reset async tracking for each phase of the Test lifecycle + config.current.usedAsync = false; + } config.queue.shift()(); } else { setTimeout( next, 13 ); @@ -602,6 +592,79 @@ function process( last ) { } } +function begin() { + var i, l, + modulesLog = []; + + // If the test run hasn't officially begun yet + if ( !config.started ) { + + // Record the time of the test run's beginning + config.started = now(); + + verifyLoggingCallbacks(); + + // Delete the loose unnamed module if unused. + if ( config.modules[ 0 ].name === "" && config.modules[ 0 ].tests.length === 0 ) { + config.modules.shift(); + } + + // Avoid unnecessary information by not logging modules' test environments + for ( i = 0, l = config.modules.length; i < l; i++ ) { + modulesLog.push({ + name: config.modules[ i ].name, + tests: config.modules[ i ].tests + }); + } + + // The test run is officially beginning now + runLoggingCallbacks( "begin", { + totalTests: Test.count, + modules: modulesLog + }); + } + + config.blocking = false; + process( true ); +} + +function resumeProcessing() { + runStarted = true; + + // A slight delay to allow this iteration of the event loop to finish (more assertions, etc.) + if ( defined.setTimeout ) { + setTimeout(function() { + if ( config.current && config.current.semaphore > 0 ) { + return; + } + if ( config.timeout ) { + clearTimeout( config.timeout ); + } + + begin(); + }, 13 ); + } else { + begin(); + } +} + +function pauseProcessing() { + config.blocking = true; + + if ( config.testTimeout && defined.setTimeout ) { + clearTimeout( config.timeout ); + config.timeout = setTimeout(function() { + if ( config.current ) { + config.current.semaphore = 0; + QUnit.pushFailure( "Test timed out", sourceFromStacktrace( 2 ) ); + } else { + throw new Error( "Test timed out" ); + } + resumeProcessing(); + }, config.testTimeout ); + } +} + function saveGlobal() { config.pollution = []; @@ -671,18 +734,6 @@ function extend( a, b, undefOnly ) { return a; } -function registerLoggingCallback( key ) { - - // Initialize key collection of logging callback - if ( QUnit.objectType( config.callbacks[ key ] ) === "undefined" ) { - config.callbacks[ key ] = []; - } - - return function( callback ) { - config.callbacks[ key ].push( callback ); - }; -} - function runLoggingCallbacks( key, args ) { var i, l, callbacks; @@ -692,6 +743,34 @@ function runLoggingCallbacks( key, args ) { } } +// DEPRECATED: This will be removed on 2.0.0+ +// This function verifies if the loggingCallbacks were modified by the user +// If so, it will restore it, assign the given callback and print a console warning +function verifyLoggingCallbacks() { + var loggingCallback, userCallback; + + for ( loggingCallback in loggingCallbacks ) { + if ( QUnit[ loggingCallback ] !== loggingCallbacks[ loggingCallback ] ) { + + userCallback = QUnit[ loggingCallback ]; + + // Restore the callback function + QUnit[ loggingCallback ] = loggingCallbacks[ loggingCallback ]; + + // Assign the deprecated given callback + QUnit[ loggingCallback ]( userCallback ); + + if ( window.console && window.console.warn ) { + window.console.warn( + "QUnit." + loggingCallback + " was replaced with a new value.\n" + + "Please, check out the documentation on how to apply logging callbacks.\n" + + "Reference: http://api.qunitjs.com/category/callbacks/" + ); + } + } + } +} + // from jquery.js function inArray( elem, array ) { if ( array.indexOf ) { @@ -708,16 +787,46 @@ function inArray( elem, array ) { } function Test( settings ) { + var i, l; + + ++Test.count; + extend( this, settings ); - this.assert = new Assert( this ); this.assertions = []; - this.testNumber = ++Test.count; + this.semaphore = 0; + this.usedAsync = false; + this.module = config.currentModule; + this.stack = sourceFromStacktrace( 3 ); + + // Register unique strings + for ( i = 0, l = this.module.tests; i < l.length; i++ ) { + if ( this.module.tests[ i ].name === this.testName ) { + this.testName += " "; + } + } + + this.testId = generateHash( this.module.name, this.testName ); + + this.module.tests.push({ + name: this.testName, + testId: this.testId + }); + + if ( settings.skip ) { + + // Skipped tests will fully ignore any sent callback + this.callback = function() {}; + this.async = false; + this.expected = 0; + } else { + this.assert = new Assert( this ); + } } Test.count = 0; Test.prototype = { - setup: function() { + before: function() { if ( // Emit moduleStart when we're switching from one module to another @@ -731,47 +840,43 @@ Test.prototype = { ) { if ( hasOwn.call( config, "previousModule" ) ) { runLoggingCallbacks( "moduleDone", { - name: config.previousModule, + name: config.previousModule.name, + tests: config.previousModule.tests, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, - total: config.moduleStats.all + total: config.moduleStats.all, + runtime: now() - config.moduleStats.started }); } config.previousModule = this.module; - config.moduleStats = { all: 0, bad: 0 }; + config.moduleStats = { all: 0, bad: 0, started: now() }; runLoggingCallbacks( "moduleStart", { - name: this.module + name: this.module.name, + tests: this.module.tests }); } config.current = this; - this.testEnvironment = extend({ - setup: function() {}, - teardown: function() {} - }, this.moduleTestEnvironment ); + this.testEnvironment = extend( {}, this.module.testEnvironment ); + delete this.testEnvironment.beforeEach; + delete this.testEnvironment.afterEach; this.started = now(); runLoggingCallbacks( "testStart", { name: this.testName, - module: this.module, - testNumber: this.testNumber + module: this.module.name, + testId: this.testId }); if ( !config.pollution ) { saveGlobal(); } - if ( config.notrycatch ) { - this.testEnvironment.setup.call( this.testEnvironment, this.assert ); - return; - } - try { - this.testEnvironment.setup.call( this.testEnvironment, this.assert ); - } catch ( e ) { - this.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); - } }, + run: function() { + var promise; + config.current = this; if ( this.async ) { @@ -781,18 +886,17 @@ Test.prototype = { this.callbackStarted = now(); if ( config.notrycatch ) { - this.callback.call( this.testEnvironment, this.assert ); - this.callbackRuntime = now() - this.callbackStarted; + promise = this.callback.call( this.testEnvironment, this.assert ); + this.resolvePromise( promise ); return; } try { - this.callback.call( this.testEnvironment, this.assert ); - this.callbackRuntime = now() - this.callbackStarted; + promise = this.callback.call( this.testEnvironment, this.assert ); + this.resolvePromise( promise ); } catch ( e ) { - this.callbackRuntime = now() - this.callbackStarted; - - this.pushFailure( "Died on test #" + ( this.assertions.length + 1 ) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); + this.pushFailure( "Died on test #" + ( this.assertions.length + 1 ) + " " + + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); // else next test will carry the responsibility saveGlobal(); @@ -803,31 +907,59 @@ Test.prototype = { } } }, - teardown: function() { - config.current = this; - if ( config.notrycatch ) { - if ( typeof this.callbackRuntime === "undefined" ) { - this.callbackRuntime = now() - this.callbackStarted; + + after: function() { + checkPollution(); + }, + + queueHook: function( hook, hookName ) { + var promise, + test = this; + return function runHook() { + config.current = test; + if ( config.notrycatch ) { + promise = hook.call( test.testEnvironment, test.assert ); + test.resolvePromise( promise, hookName ); + return; } - this.testEnvironment.teardown.call( this.testEnvironment, this.assert ); - return; - } else { try { - this.testEnvironment.teardown.call( this.testEnvironment, this.assert ); - } catch ( e ) { - this.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); + promise = hook.call( test.testEnvironment, test.assert ); + test.resolvePromise( promise, hookName ); + } catch ( error ) { + test.pushFailure( hookName + " failed on " + test.testName + ": " + + ( error.message || error ), extractStacktrace( error, 0 ) ); } + }; + }, + + // Currently only used for module level hooks, can be used to add global level ones + hooks: function( handler ) { + var hooks = []; + + // Hooks are ignored on skipped tests + if ( this.skip ) { + return hooks; } - checkPollution(); + + if ( this.module.testEnvironment && + QUnit.objectType( this.module.testEnvironment[ handler ] ) === "function" ) { + hooks.push( this.queueHook( this.module.testEnvironment[ handler ], handler ) ); + } + + return hooks; }, + finish: function() { config.current = this; if ( config.requireExpects && this.expected === null ) { - this.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack ); + this.pushFailure( "Expected number of assertions to be defined, but expect() was " + + "not called.", this.stack ); } else if ( this.expected !== null && this.expected !== this.assertions.length ) { - this.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); + this.pushFailure( "Expected " + this.expected + " assertions, but " + + this.assertions.length + " were run", this.stack ); } else if ( this.expected === null && !this.assertions.length ) { - this.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); + this.pushFailure( "Expected at least one assertion, but none were run - call " + + "expect(0) to accept zero assertions.", this.stack ); } var i, @@ -847,7 +979,8 @@ Test.prototype = { runLoggingCallbacks( "testDone", { name: this.testName, - module: this.module, + module: this.module.name, + skipped: !!this.skip, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length, @@ -855,12 +988,17 @@ Test.prototype = { // HTML Reporter use assertions: this.assertions, - testNumber: this.testNumber, + testId: this.testId, // DEPRECATED: this property will be removed in 2.0.0, use runtime instead duration: this.runtime }); + // QUnit.reset() is deprecated and will be replaced for a new + // fixture reset function on QUnit 2.0/2.1. + // It's still called here for backwards compatibility handling + QUnit.reset(); + config.current = undefined; }, @@ -868,26 +1006,39 @@ Test.prototype = { var bad, test = this; + if ( !this.valid() ) { + return; + } + function run() { + // each of these can by async - synchronize(function() { - test.setup(); - }); - synchronize(function() { - test.run(); - }); - synchronize(function() { - test.teardown(); - }); - synchronize(function() { - test.finish(); - }); + synchronize([ + function() { + test.before(); + }, + + test.hooks( "beforeEach" ), + + function() { + test.run(); + }, + + test.hooks( "afterEach" ).reverse(), + + function() { + test.after(); + }, + function() { + test.finish(); + } + ]); } // `bad` initialized at top of scope // defer when previous test run passed, if storage is available bad = QUnit.config.reorder && defined.sessionStorage && - +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); + +sessionStorage.getItem( "qunit-test-" + this.module.name + "-" + this.testName ); if ( bad ) { run(); @@ -899,13 +1050,14 @@ Test.prototype = { push: function( result, actual, expected, message ) { var source, details = { - module: this.module, + module: this.module.name, name: this.testName, result: result, message: message, actual: actual, expected: expected, - testNumber: this.testNumber + testId: this.testId, + runtime: now() - this.started }; if ( !result ) { @@ -926,16 +1078,18 @@ Test.prototype = { pushFailure: function( message, source, actual ) { if ( !this instanceof Test ) { - throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace( 2 ) ); + throw new Error( "pushFailure() assertion outside test context, was " + + sourceFromStacktrace( 2 ) ); } var details = { - module: this.module, + module: this.module.name, name: this.testName, result: false, message: message || "error", actual: actual || null, - testNumber: this.testNumber + testId: this.testId, + runtime: now() - this.started }; if ( source ) { @@ -948,19 +1102,131 @@ Test.prototype = { result: false, message: message }); + }, + + resolvePromise: function( promise, phase ) { + var then, message, + test = this; + if ( promise != null ) { + then = promise.then; + if ( QUnit.objectType( then ) === "function" ) { + QUnit.stop(); + then.call( + promise, + QUnit.start, + function( error ) { + message = "Promise rejected " + + ( !phase ? "during" : phase.replace( /Each$/, "" ) ) + + " " + test.testName + ": " + ( error.message || error ); + test.pushFailure( message, extractStacktrace( error, 0 ) ); + + // else next test will carry the responsibility + saveGlobal(); + + // Unblock + QUnit.start(); + } + ); + } + } + }, + + valid: function() { + var include, + filter = config.filter && config.filter.toLowerCase(), + module = QUnit.urlParams.module && QUnit.urlParams.module.toLowerCase(), + fullName = ( this.module.name + ": " + this.testName ).toLowerCase(); + + // Internally-generated tests are always valid + if ( this.callback && this.callback.validTest ) { + return true; + } + + if ( config.testId.length > 0 && inArray( this.testId, config.testId ) < 0 ) { + return false; + } + + if ( module && ( !this.module.name || this.module.name.toLowerCase() !== module ) ) { + return false; + } + + if ( !filter ) { + return true; + } + + include = filter.charAt( 0 ) !== "!"; + if ( !include ) { + filter = filter.slice( 1 ); + } + + // If the filter matches, we need to honour include + if ( fullName.indexOf( filter ) !== -1 ) { + return include; + } + + // Otherwise, do the opposite + return !include; + } + +}; + +// Resets the test setup. Useful for tests that modify the DOM. +/* +DEPRECATED: Use multiple tests instead of resetting inside a test. +Use testStart or testDone for custom cleanup. +This method will throw an error in 2.0, and will be removed in 2.1 +*/ +QUnit.reset = function() { + + // Return on non-browser environments + // This is necessary to not break on node tests + if ( typeof window === "undefined" ) { + return; + } + + var fixture = defined.document && document.getElementById && + document.getElementById( "qunit-fixture" ); + + if ( fixture ) { + fixture.innerHTML = config.fixture; } }; QUnit.pushFailure = function() { if ( !QUnit.config.current ) { - throw new Error( "pushFailure() assertion outside test context, in " + sourceFromStacktrace( 2 ) ); + throw new Error( "pushFailure() assertion outside test context, in " + + sourceFromStacktrace( 2 ) ); } // Gets current test obj - var currentTest = QUnit.config.current.assert.test; + var currentTest = QUnit.config.current; + + return currentTest.pushFailure.apply( currentTest, arguments ); +}; + +// Based on Java's String.hashCode, a simple but not +// rigorously collision resistant hashing function +function generateHash( module, testName ) { + var hex, + i = 0, + hash = 0, + str = module + "\x1C" + testName, + len = str.length; + + for ( ; i < len; i++ ) { + hash = ( ( hash << 5 ) - hash ) + str.charCodeAt( i ); + hash |= 0; + } + + // Convert the possibly negative integer hash code into an 8 character hex string, which isn't + // strictly necessary but increases user understanding that the id is a SHA-like hash + hex = ( 0x100000000 + hash ).toString( 16 ); + if ( hex.length < 8 ) { + hex = "0000000" + hex; + } - return currentTest.pushFailure.apply( currentTest, arguments ); -}; + return hex.slice( -8 ); +} function Assert( testContext ) { this.test = testContext; @@ -969,7 +1235,8 @@ function Assert( testContext ) { // Assert helpers QUnit.assert = Assert.prototype = { - // Specify the number of expected assertions to guarantee that failed test (no assertions are run at all) don't slip through. + // Specify the number of expected assertions to guarantee that failed test + // (no assertions are run at all) don't slip through. expect: function( asserts ) { if ( arguments.length === 1 ) { this.test.expected = asserts; @@ -978,109 +1245,101 @@ QUnit.assert = Assert.prototype = { } }, + // Increment this Test's semaphore counter, then return a single-use function that + // decrements that counter a maximum of once. + async: function() { + var test = this.test, + popped = false; + + test.semaphore += 1; + test.usedAsync = true; + pauseProcessing(); + + return function done() { + if ( !popped ) { + test.semaphore -= 1; + popped = true; + resumeProcessing(); + } else { + test.pushFailure( "Called the callback returned from `assert.async` more than once", + sourceFromStacktrace( 2 ) ); + } + }; + }, + // Exports test.push() to the user API - push: function() { - var assert = this; + push: function( /* result, actual, expected, message */ ) { + var assert = this, + currentTest = ( assert instanceof Assert && assert.test ) || QUnit.config.current; // Backwards compatibility fix. // Allows the direct use of global exported assertions and QUnit.assert.* // Although, it's use is not recommended as it can leak assertions // to other tests from async tests, because we only get a reference to the current test, // not exactly the test where assertion were intended to be called. - if ( !QUnit.config.current ) { + if ( !currentTest ) { throw new Error( "assertion outside test context, in " + sourceFromStacktrace( 2 ) ); } + + if ( currentTest.usedAsync === true && currentTest.semaphore === 0 ) { + currentTest.pushFailure( "Assertion after the final `assert.async` was resolved", + sourceFromStacktrace( 2 ) ); + + // Allow this assertion to continue running anyway... + } + if ( !( assert instanceof Assert ) ) { - assert = QUnit.config.current.assert; + assert = currentTest.assert; } return assert.test.push.apply( assert.test, arguments ); }, - /** - * Asserts rough true-ish result. - * @name ok - * @function - * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); - */ ok: function( result, message ) { message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " + QUnit.dump.parse( result ) ); - if ( !!result ) { - this.push( true, result, true, message ); - } else { - this.test.pushFailure( message, null, result ); - } + this.push( !!result, result, true, message ); + }, + + notOk: function( result, message ) { + message = message || ( !result ? "okay" : "failed, expected argument to be falsy, was: " + + QUnit.dump.parse( result ) ); + this.push( !result, result, false, message ); }, - /** - * Assert that the first two arguments are equal, with an optional message. - * Prints out both actual and expected values. - * @name equal - * @function - * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); - */ equal: function( actual, expected, message ) { /*jshint eqeqeq:false */ this.push( expected == actual, actual, expected, message ); }, - /** - * @name notEqual - * @function - */ notEqual: function( actual, expected, message ) { /*jshint eqeqeq:false */ this.push( expected != actual, actual, expected, message ); }, - /** - * @name propEqual - * @function - */ propEqual: function( actual, expected, message ) { actual = objectValues( actual ); expected = objectValues( expected ); this.push( QUnit.equiv( actual, expected ), actual, expected, message ); }, - /** - * @name notPropEqual - * @function - */ notPropEqual: function( actual, expected, message ) { actual = objectValues( actual ); expected = objectValues( expected ); this.push( !QUnit.equiv( actual, expected ), actual, expected, message ); }, - /** - * @name deepEqual - * @function - */ deepEqual: function( actual, expected, message ) { this.push( QUnit.equiv( actual, expected ), actual, expected, message ); }, - /** - * @name notDeepEqual - * @function - */ notDeepEqual: function( actual, expected, message ) { this.push( !QUnit.equiv( actual, expected ), actual, expected, message ); }, - /** - * @name strictEqual - * @function - */ strictEqual: function( actual, expected, message ) { this.push( expected === actual, actual, expected, message ); }, - /** - * @name notStrictEqual - * @function - */ notStrictEqual: function( actual, expected, message ) { this.push( expected !== actual, actual, expected, message ); }, @@ -1088,7 +1347,8 @@ QUnit.assert = Assert.prototype = { "throws": function( block, expected, message ) { var actual, expectedType, expectedOutput = expected, - ok = false; + ok = false, + currentTest = ( this instanceof Assert && this.test ) || QUnit.config.current; // 'expected' is optional unless doing string comparison if ( message == null && typeof expected === "string" ) { @@ -1096,13 +1356,13 @@ QUnit.assert = Assert.prototype = { expected = null; } - this.test.ignoreGlobalErrors = true; + currentTest.ignoreGlobalErrors = true; try { - block.call( this.test.testEnvironment ); + block.call( currentTest.testEnvironment ); } catch (e) { actual = e; } - this.test.ignoreGlobalErrors = false; + currentTest.ignoreGlobalErrors = false; if ( actual ) { expectedType = QUnit.objectType( expected ); @@ -1135,14 +1395,19 @@ QUnit.assert = Assert.prototype = { expectedOutput = null; ok = true; } - - this.push( ok, actual, expectedOutput, message ); - } else { - this.test.pushFailure( message, null, "No exception was thrown." ); } + + currentTest.assert.push( ok, actual, expectedOutput, message ); } }; +// Provide an alternative to assert.throws(), for enviroments that consider throws a reserved word +// Known to us are: Closure Compiler, Narwhal +(function() { + /*jshint sub:true */ + Assert.prototype.raises = Assert.prototype[ "throws" ]; +}()); + // Test for equality any JavaScript type. // Author: Philippe Rathé <prathe@gmail.com> QUnit.equiv = (function() { @@ -1356,7 +1621,8 @@ QUnit.equiv = (function() { } // apply transition with (1..n) arguments - }( args[ 0 ], args[ 1 ] ) ) && innerEquiv.apply( this, args.splice( 1, args.length - 1 ) ) ); + }( args[ 0 ], args[ 1 ] ) ) && + innerEquiv.apply( this, args.splice( 1, args.length - 1 ) ) ); }; return innerEquiv; @@ -1386,6 +1652,11 @@ QUnit.dump = (function() { function array( arr, stack ) { var i = arr.length, ret = new Array( i ); + + if ( dump.maxDepth && dump.depth > dump.maxDepth ) { + return "[object Array]"; + } + this.up(); while ( i-- ) { ret[ i ] = this.parse( arr[ i ], undefined, stack ); @@ -1396,25 +1667,28 @@ QUnit.dump = (function() { var reName = /^function (\w+)/, dump = { - // type is used mostly internally, you can fix a (custom)type in advance - parse: function( obj, type, stack ) { - stack = stack || []; - var inStack, res, - parser = this.parsers[ type || this.typeOf( obj ) ]; - type = typeof parser; - inStack = inArray( obj, stack ); + // objType is used mostly internally, you can fix a (custom) type in advance + parse: function( obj, objType, stack ) { + stack = stack || []; + var res, parser, parserType, + inStack = inArray( obj, stack ); if ( inStack !== -1 ) { return "recursion(" + ( inStack - stack.length ) + ")"; } - if ( type === "function" ) { + + objType = objType || this.typeOf( obj ); + parser = this.parsers[ objType ]; + parserType = typeof parser; + + if ( parserType === "function" ) { stack.push( obj ); res = parser.call( this, obj, stack ); stack.pop(); return res; } - return ( type === "string" ) ? parser : this.parsers.error; + return ( parserType === "string" ) ? parser : this.parsers.error; }, typeOf: function( obj ) { var type; @@ -1428,7 +1702,9 @@ QUnit.dump = (function() { type = "date"; } else if ( QUnit.is( "function", obj ) ) { type = "function"; - } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { + } else if ( obj.setInterval !== undefined && + obj.document !== undefined && + obj.nodeType === undefined ) { type = "window"; } else if ( obj.nodeType === 9 ) { type = "document"; @@ -1440,7 +1716,9 @@ QUnit.dump = (function() { toString.call( obj ) === "[object Array]" || // NodeList objects - ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item( 0 ) === obj[ 0 ] : ( obj.item( 0 ) === null && typeof obj[ 0 ] === "undefined" ) ) ) + ( typeof obj.length === "number" && obj.item !== undefined && + ( obj.length ? obj.item( 0 ) === obj[ 0 ] : ( obj.item( 0 ) === null && + obj[ 0 ] === undefined ) ) ) ) { type = "array"; } else if ( obj.constructor === Error.prototype.constructor ) { @@ -1451,7 +1729,7 @@ QUnit.dump = (function() { return type; }, separator: function() { - return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? " " : " "; + return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? " " : " "; }, // extra can be a number, shortcut for increasing-calling-decreasing indent: function( extra ) { @@ -1460,7 +1738,7 @@ QUnit.dump = (function() { } var chr = this.indentChar; if ( this.HTML ) { - chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); + chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); } return new Array( this.depth + ( extra || 0 ) ).join( chr ); }, @@ -1479,6 +1757,8 @@ QUnit.dump = (function() { join: join, // depth: 1, + maxDepth: QUnit.config.maxDepth, + // This is the list of parsers, to modify them, use dump.setParser parsers: { window: "[Window]", @@ -1491,6 +1771,7 @@ QUnit.dump = (function() { "undefined": "undefined", "function": function( fn ) { var ret = "function", + // functions never have name in IE name = "name" in fn ? fn.name : ( reName.exec( fn ) || [] )[ 1 ]; @@ -1506,8 +1787,13 @@ QUnit.dump = (function() { nodelist: array, "arguments": array, object: function( map, stack ) { - /*jshint forin:false */ - var ret = [], keys, key, val, i, nonEnumerableProperties; + var keys, key, val, i, nonEnumerableProperties, + ret = []; + + if ( dump.maxDepth && dump.depth > dump.maxDepth ) { + return "[object Object]"; + } + dump.up(); keys = []; for ( key in map ) { @@ -1518,7 +1804,7 @@ QUnit.dump = (function() { nonEnumerableProperties = [ "message", "name" ]; for ( i in nonEnumerableProperties ) { key = nonEnumerableProperties[ i ]; - if ( key in map && !( key in keys ) ) { + if ( key in map && inArray( key, keys ) < 0 ) { keys.push( key ); } } @@ -1526,7 +1812,8 @@ QUnit.dump = (function() { for ( i = 0; i < keys.length; i++ ) { key = keys[ i ]; val = map[ key ]; - ret.push( dump.parse( key, "key" ) + ": " + dump.parse( val, undefined, stack ) ); + ret.push( dump.parse( key, "key" ) + ": " + + dump.parse( val, undefined, stack ) ); } dump.down(); return join( "{", ret, "}" ); @@ -1543,10 +1830,12 @@ QUnit.dump = (function() { for ( i = 0, len = attrs.length; i < len; i++ ) { val = attrs[ i ].nodeValue; - // IE6 includes all attributes in .attributes, even ones not explicitly set. - // Those have values like undefined, null, 0, false, "" or "inherit". + // IE6 includes all attributes in .attributes, even ones not explicitly + // set. Those have values like undefined, null, 0, false, "" or + // "inherit". if ( val && val !== "inherit" ) { - ret += " " + attrs[ i ].nodeName + "=" + dump.parse( val, "attribute" ); + ret += " " + attrs[ i ].nodeName + "=" + + dump.parse( val, "attribute" ); } } } @@ -1634,6 +1923,7 @@ if ( typeof window !== "undefined" ) { "start", "stop", "ok", + "notOk", "equal", "notEqual", "propEqual", @@ -1653,9 +1943,24 @@ if ( typeof window !== "undefined" ) { window.QUnit = QUnit; } -// For CommonJS environments, export everything -if ( typeof module !== "undefined" && module.exports ) { +// For nodejs +if ( typeof module !== "undefined" && module && module.exports ) { module.exports = QUnit; + + // For consistency with CommonJS environments' exports + module.exports.QUnit = QUnit; +} + +// For CommonJS with exports, but without module.exports, like Rhino +if ( typeof exports !== "undefined" && exports ) { + exports.QUnit = QUnit; +} + +if ( typeof define === "function" && define.amd ) { + define( function() { + return QUnit; + } ); + QUnit.config.autostart = false; } // Get a reference to the global object, like window in browsers @@ -1664,152 +1969,1092 @@ if ( typeof module !== "undefined" && module.exports ) { })() )); /*istanbul ignore next */ +// jscs:disable maximumLineLength /* - * Javascript Diff Algorithm - * By John Resig (http://ejohn.org/) - * Modified by Chu Alan "sprite" + * This file is a modified version of google-diff-match-patch's JavaScript implementation + * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js), + * modifications are licensed as more fully set forth in LICENSE.txt. + * + * The original source of google-diff-match-patch is attributable and licensed as follows: * - * Released under the MIT license. + * Copyright 2006 Google Inc. + * http://code.google.com/p/google-diff-match-patch/ + * + * 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. * * More Info: - * http://ejohn.org/projects/javascript-diff-algorithm/ + * https://code.google.com/p/google-diff-match-patch/ * * Usage: QUnit.diff(expected, actual) * - * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" + * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) === "the quick <del>brown </del> fox jump<ins>s</ins><del>ed</del over" */ QUnit.diff = (function() { - var hasOwn = Object.prototype.hasOwnProperty; - - /*jshint eqeqeq:false, eqnull:true */ - function diff( o, n ) { - var i, - ns = {}, - os = {}; - - for ( i = 0; i < n.length; i++ ) { - if ( !hasOwn.call( ns, n[ i ] ) ) { - ns[ n[ i ] ] = { - rows: [], - o: null - }; - } - ns[ n[ i ] ].rows.push( i ); - } - - for ( i = 0; i < o.length; i++ ) { - if ( !hasOwn.call( os, o[ i ] ) ) { - os[ o[ i ] ] = { - rows: [], - n: null - }; - } - os[ o[ i ] ].rows.push( i ); - } - - for ( i in ns ) { - if ( hasOwn.call( ns, i ) ) { - if ( ns[ i ].rows.length === 1 && hasOwn.call( os, i ) && os[ i ].rows.length === 1 ) { - n[ ns[ i ].rows[ 0 ] ] = { - text: n[ ns[ i ].rows[ 0 ] ], - row: os[ i ].rows[ 0 ] - }; - o[ os[ i ].rows[ 0 ] ] = { - text: o[ os[ i ].rows[ 0 ] ], - row: ns[ i ].rows[ 0 ] - }; - } - } - } - - for ( i = 0; i < n.length - 1; i++ ) { - if ( n[ i ].text != null && n[ i + 1 ].text == null && n[ i ].row + 1 < o.length && o[ n[ i ].row + 1 ].text == null && - n[ i + 1 ] == o[ n[ i ].row + 1 ] ) { - - n[ i + 1 ] = { - text: n[ i + 1 ], - row: n[ i ].row + 1 - }; - o[ n[ i ].row + 1 ] = { - text: o[ n[ i ].row + 1 ], - row: i + 1 - }; - } - } - - for ( i = n.length - 1; i > 0; i-- ) { - if ( n[ i ].text != null && n[ i - 1 ].text == null && n[ i ].row > 0 && o[ n[ i ].row - 1 ].text == null && - n[ i - 1 ] == o[ n[ i ].row - 1 ] ) { - - n[ i - 1 ] = { - text: n[ i - 1 ], - row: n[ i ].row - 1 - }; - o[ n[ i ].row - 1 ] = { - text: o[ n[ i ].row - 1 ], - row: i - 1 - }; - } - } - - return { - o: o, - n: n - }; - } - - return function( o, n ) { - o = o.replace( /\s+$/, "" ); - n = n.replace( /\s+$/, "" ); - - var i, pre, - str = "", - out = diff( o === "" ? [] : o.split( /\s+/ ), n === "" ? [] : n.split( /\s+/ ) ), - oSpace = o.match( /\s+/g ), - nSpace = n.match( /\s+/g ); - - if ( oSpace == null ) { - oSpace = [ " " ]; - } else { - oSpace.push( " " ); - } - - if ( nSpace == null ) { - nSpace = [ " " ]; - } else { - nSpace.push( " " ); - } - - if ( out.n.length === 0 ) { - for ( i = 0; i < out.o.length; i++ ) { - str += "<del>" + out.o[ i ] + oSpace[ i ] + "</del>"; - } - } else { - if ( out.n[ 0 ].text == null ) { - for ( n = 0; n < out.o.length && out.o[ n ].text == null; n++ ) { - str += "<del>" + out.o[ n ] + oSpace[ n ] + "</del>"; - } - } - for ( i = 0; i < out.n.length; i++ ) { - if ( out.n[ i ].text == null ) { - str += "<ins>" + out.n[ i ] + nSpace[ i ] + "</ins>"; - } else { - - // `pre` initialized at top of scope - pre = ""; - - for ( n = out.n[ i ].row + 1; n < out.o.length && out.o[ n ].text == null; n++ ) { - pre += "<del>" + out.o[ n ] + oSpace[ n ] + "</del>"; - } - str += " " + out.n[ i ].text + nSpace[ i ] + pre; - } - } - } - - return str; - }; + function DiffMatchPatch() { + + // Defaults. + // Redefine these in your program to override the defaults. + + // Number of seconds to map a diff before giving up (0 for infinity). + this.DiffTimeout = 1.0; + // Cost of an empty edit operation in terms of edit characters. + this.DiffEditCost = 4; + } + + // DIFF FUNCTIONS + + /** + * The data structure representing a diff is an array of tuples: + * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] + * which means: delete 'Hello', add 'Goodbye' and keep ' world.' + */ + var DIFF_DELETE = -1, + DIFF_INSERT = 1, + DIFF_EQUAL = 0; + + /** + * Find the differences between two texts. Simplifies the problem by stripping + * any common prefix or suffix off the texts before diffing. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {boolean=} optChecklines Optional speedup flag. If present and false, + * then don't run a line-level diff first to identify the changed areas. + * Defaults to true, which does a faster, slightly less optimal diff. + * @param {number} optDeadline Optional time when the diff should be complete + * by. Used internally for recursive calls. Users should set DiffTimeout + * instead. + * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. + */ + DiffMatchPatch.prototype.DiffMain = function( text1, text2, optChecklines, optDeadline ) { + var deadline, checklines, commonlength, + commonprefix, commonsuffix, diffs; + // Set a deadline by which time the diff must be complete. + if ( typeof optDeadline === "undefined" ) { + if ( this.DiffTimeout <= 0 ) { + optDeadline = Number.MAX_VALUE; + } else { + optDeadline = ( new Date() ).getTime() + this.DiffTimeout * 1000; + } + } + deadline = optDeadline; + + // Check for null inputs. + if ( text1 === null || text2 === null ) { + throw new Error( "Null input. (DiffMain)" ); + } + + // Check for equality (speedup). + if ( text1 === text2 ) { + if ( text1 ) { + return [ + [ DIFF_EQUAL, text1 ] + ]; + } + return []; + } + + if ( typeof optChecklines === "undefined" ) { + optChecklines = true; + } + + checklines = optChecklines; + + // Trim off common prefix (speedup). + commonlength = this.diffCommonPrefix( text1, text2 ); + commonprefix = text1.substring( 0, commonlength ); + text1 = text1.substring( commonlength ); + text2 = text2.substring( commonlength ); + + // Trim off common suffix (speedup). + ///////// + commonlength = this.diffCommonSuffix( text1, text2 ); + commonsuffix = text1.substring( text1.length - commonlength ); + text1 = text1.substring( 0, text1.length - commonlength ); + text2 = text2.substring( 0, text2.length - commonlength ); + + // Compute the diff on the middle block. + diffs = this.diffCompute( text1, text2, checklines, deadline ); + + // Restore the prefix and suffix. + if ( commonprefix ) { + diffs.unshift( [ DIFF_EQUAL, commonprefix ] ); + } + if ( commonsuffix ) { + diffs.push( [ DIFF_EQUAL, commonsuffix ] ); + } + this.diffCleanupMerge( diffs ); + return diffs; + }; + + /** + * Reduce the number of edits by eliminating operationally trivial equalities. + * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples. + */ + DiffMatchPatch.prototype.diffCleanupEfficiency = function( diffs ) { + var changes, equalities, equalitiesLength, lastequality, + pointer, preIns, preDel, postIns, postDel; + changes = false; + equalities = []; // Stack of indices where equalities are found. + equalitiesLength = 0; // Keeping our own length var is faster in JS. + /** @type {?string} */ + lastequality = null; + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + pointer = 0; // Index of current position. + // Is there an insertion operation before the last equality. + preIns = false; + // Is there a deletion operation before the last equality. + preDel = false; + // Is there an insertion operation after the last equality. + postIns = false; + // Is there a deletion operation after the last equality. + postDel = false; + while ( pointer < diffs.length ) { + if ( diffs[ pointer ][ 0 ] === DIFF_EQUAL ) { // Equality found. + if ( diffs[ pointer ][ 1 ].length < this.DiffEditCost && ( postIns || postDel ) ) { + // Candidate found. + equalities[ equalitiesLength++ ] = pointer; + preIns = postIns; + preDel = postDel; + lastequality = diffs[ pointer ][ 1 ]; + } else { + // Not a candidate, and can never become one. + equalitiesLength = 0; + lastequality = null; + } + postIns = postDel = false; + } else { // An insertion or deletion. + if ( diffs[ pointer ][ 0 ] === DIFF_DELETE ) { + postDel = true; + } else { + postIns = true; + } + /* + * Five types to be split: + * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> + * <ins>A</ins>X<ins>C</ins><del>D</del> + * <ins>A</ins><del>B</del>X<ins>C</ins> + * <ins>A</del>X<ins>C</ins><del>D</del> + * <ins>A</ins><del>B</del>X<del>C</del> + */ + if ( lastequality && ( ( preIns && preDel && postIns && postDel ) || + ( ( lastequality.length < this.DiffEditCost / 2 ) && + ( preIns + preDel + postIns + postDel ) === 3 ) ) ) { + // Duplicate record. + diffs.splice( equalities[equalitiesLength - 1], 0, [ DIFF_DELETE, lastequality ] ); + // Change second copy to insert. + diffs[ equalities[ equalitiesLength - 1 ] + 1 ][ 0 ] = DIFF_INSERT; + equalitiesLength--; // Throw away the equality we just deleted; + lastequality = null; + if (preIns && preDel) { + // No changes made which could affect previous entry, keep going. + postIns = postDel = true; + equalitiesLength = 0; + } else { + equalitiesLength--; // Throw away the previous equality. + pointer = equalitiesLength > 0 ? equalities[ equalitiesLength - 1 ] : -1; + postIns = postDel = false; + } + changes = true; + } + } + pointer++; + } + + if ( changes ) { + this.diffCleanupMerge( diffs ); + } + }; + + /** + * Convert a diff array into a pretty HTML report. + * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples. + * @param {integer} string to be beautified. + * @return {string} HTML representation. + */ + DiffMatchPatch.prototype.diffPrettyHtml = function( diffs ) { + var op, data, x, html = []; + for ( x = 0; x < diffs.length; x++ ) { + op = diffs[x][0]; // Operation (insert, delete, equal) + data = diffs[x][1]; // Text of change. + switch ( op ) { + case DIFF_INSERT: + html[x] = "<ins>" + data + "</ins>"; + break; + case DIFF_DELETE: + html[x] = "<del>" + data + "</del>"; + break; + case DIFF_EQUAL: + html[x] = "<span>" + data + "</span>"; + break; + } + } + return html.join(""); + }; + + /** + * Determine the common prefix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the start of each + * string. + */ + DiffMatchPatch.prototype.diffCommonPrefix = function( text1, text2 ) { + var pointermid, pointermax, pointermin, pointerstart; + // Quick check for common null cases. + if ( !text1 || !text2 || text1.charAt(0) !== text2.charAt(0) ) { + return 0; + } + // Binary search. + // Performance analysis: http://neil.fraser.name/news/2007/10/09/ + pointermin = 0; + pointermax = Math.min( text1.length, text2.length ); + pointermid = pointermax; + pointerstart = 0; + while ( pointermin < pointermid ) { + if ( text1.substring( pointerstart, pointermid ) === text2.substring( pointerstart, pointermid ) ) { + pointermin = pointermid; + pointerstart = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin ); + } + return pointermid; + }; + + /** + * Determine the common suffix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of each string. + */ + DiffMatchPatch.prototype.diffCommonSuffix = function( text1, text2 ) { + var pointermid, pointermax, pointermin, pointerend; + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) { + return 0; + } + // Binary search. + // Performance analysis: http://neil.fraser.name/news/2007/10/09/ + pointermin = 0; + pointermax = Math.min(text1.length, text2.length); + pointermid = pointermax; + pointerend = 0; + while ( pointermin < pointermid ) { + if (text1.substring( text1.length - pointermid, text1.length - pointerend ) === + text2.substring( text2.length - pointermid, text2.length - pointerend ) ) { + pointermin = pointermid; + pointerend = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin ); + } + return pointermid; + }; + + /** + * Find the differences between two texts. Assumes that the texts do not + * have any common prefix or suffix. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {boolean} checklines Speedup flag. If false, then don't run a + * line-level diff first to identify the changed areas. + * If true, then run a faster, slightly less optimal diff. + * @param {number} deadline Time when the diff should be complete by. + * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffCompute = function( text1, text2, checklines, deadline ) { + var diffs, longtext, shorttext, i, hm, + text1A, text2A, text1B, text2B, + midCommon, diffsA, diffsB; + + if ( !text1 ) { + // Just add some text (speedup). + return [ + [ DIFF_INSERT, text2 ] + ]; + } + + if (!text2) { + // Just delete some text (speedup). + return [ + [ DIFF_DELETE, text1 ] + ]; + } + + longtext = text1.length > text2.length ? text1 : text2; + shorttext = text1.length > text2.length ? text2 : text1; + i = longtext.indexOf( shorttext ); + if ( i !== -1 ) { + // Shorter text is inside the longer text (speedup). + diffs = [ + [ DIFF_INSERT, longtext.substring( 0, i ) ], + [ DIFF_EQUAL, shorttext ], + [ DIFF_INSERT, longtext.substring( i + shorttext.length ) ] + ]; + // Swap insertions for deletions if diff is reversed. + if ( text1.length > text2.length ) { + diffs[0][0] = diffs[2][0] = DIFF_DELETE; + } + return diffs; + } + + if ( shorttext.length === 1 ) { + // Single character string. + // After the previous speedup, the character can't be an equality. + return [ + [ DIFF_DELETE, text1 ], + [ DIFF_INSERT, text2 ] + ]; + } + + // Check to see if the problem can be split in two. + hm = this.diffHalfMatch(text1, text2); + if (hm) { + // A half-match was found, sort out the return data. + text1A = hm[0]; + text1B = hm[1]; + text2A = hm[2]; + text2B = hm[3]; + midCommon = hm[4]; + // Send both pairs off for separate processing. + diffsA = this.DiffMain(text1A, text2A, checklines, deadline); + diffsB = this.DiffMain(text1B, text2B, checklines, deadline); + // Merge the results. + return diffsA.concat([ + [ DIFF_EQUAL, midCommon ] + ], diffsB); + } + + if (checklines && text1.length > 100 && text2.length > 100) { + return this.diffLineMode(text1, text2, deadline); + } + + return this.diffBisect(text1, text2, deadline); + }; + + /** + * Do the two texts share a substring which is at least half the length of the + * longer text? + * This speedup can produce non-minimal diffs. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {Array.<string>} Five element Array, containing the prefix of + * text1, the suffix of text1, the prefix of text2, the suffix of + * text2 and the common middle. Or null if there was no match. + * @private + */ + DiffMatchPatch.prototype.diffHalfMatch = function(text1, text2) { + var longtext, shorttext, dmp, + text1A, text2B, text2A, text1B, midCommon, + hm1, hm2, hm; + if (this.DiffTimeout <= 0) { + // Don't risk returning a non-optimal diff if we have unlimited time. + return null; + } + longtext = text1.length > text2.length ? text1 : text2; + shorttext = text1.length > text2.length ? text2 : text1; + if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { + return null; // Pointless. + } + dmp = this; // 'this' becomes 'window' in a closure. + + /** + * Does a substring of shorttext exist within longtext such that the substring + * is at least half the length of longtext? + * Closure, but does not reference any external variables. + * @param {string} longtext Longer string. + * @param {string} shorttext Shorter string. + * @param {number} i Start index of quarter length substring within longtext. + * @return {Array.<string>} Five element Array, containing the prefix of + * longtext, the suffix of longtext, the prefix of shorttext, the suffix + * of shorttext and the common middle. Or null if there was no match. + * @private + */ + function diffHalfMatchI(longtext, shorttext, i) { + var seed, j, bestCommon, prefixLength, suffixLength, + bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB; + // Start with a 1/4 length substring at position i as a seed. + seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); + j = -1; + bestCommon = ""; + while ((j = shorttext.indexOf(seed, j + 1)) !== -1) { + prefixLength = dmp.diffCommonPrefix(longtext.substring(i), + shorttext.substring(j)); + suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), + shorttext.substring(0, j)); + if (bestCommon.length < suffixLength + prefixLength) { + bestCommon = shorttext.substring(j - suffixLength, j) + + shorttext.substring(j, j + prefixLength); + bestLongtextA = longtext.substring(0, i - suffixLength); + bestLongtextB = longtext.substring(i + prefixLength); + bestShorttextA = shorttext.substring(0, j - suffixLength); + bestShorttextB = shorttext.substring(j + prefixLength); + } + } + if (bestCommon.length * 2 >= longtext.length) { + return [ bestLongtextA, bestLongtextB, + bestShorttextA, bestShorttextB, bestCommon + ]; + } else { + return null; + } + } + + // First check if the second quarter is the seed for a half-match. + hm1 = diffHalfMatchI(longtext, shorttext, + Math.ceil(longtext.length / 4)); + // Check again based on the third quarter. + hm2 = diffHalfMatchI(longtext, shorttext, + Math.ceil(longtext.length / 2)); + if (!hm1 && !hm2) { + return null; + } else if (!hm2) { + hm = hm1; + } else if (!hm1) { + hm = hm2; + } else { + // Both matched. Select the longest. + hm = hm1[4].length > hm2[4].length ? hm1 : hm2; + } + + // A half-match was found, sort out the return data. + text1A, text1B, text2A, text2B; + if (text1.length > text2.length) { + text1A = hm[0]; + text1B = hm[1]; + text2A = hm[2]; + text2B = hm[3]; + } else { + text2A = hm[0]; + text2B = hm[1]; + text1A = hm[2]; + text1B = hm[3]; + } + midCommon = hm[4]; + return [ text1A, text1B, text2A, text2B, midCommon ]; + }; + + /** + * Do a quick line-level diff on both strings, then rediff the parts for + * greater accuracy. + * This speedup can produce non-minimal diffs. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} deadline Time when the diff should be complete by. + * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffLineMode = function(text1, text2, deadline) { + var a, diffs, linearray, pointer, countInsert, + countDelete, textInsert, textDelete, j; + // Scan the text on a line-by-line basis first. + a = this.diffLinesToChars(text1, text2); + text1 = a.chars1; + text2 = a.chars2; + linearray = a.lineArray; + + diffs = this.DiffMain(text1, text2, false, deadline); + + // Convert the diff back to original text. + this.diffCharsToLines(diffs, linearray); + // Eliminate freak matches (e.g. blank lines) + this.diffCleanupSemantic(diffs); + + // Rediff any replacement blocks, this time character-by-character. + // Add a dummy entry at the end. + diffs.push( [ DIFF_EQUAL, "" ] ); + pointer = 0; + countDelete = 0; + countInsert = 0; + textDelete = ""; + textInsert = ""; + while (pointer < diffs.length) { + switch ( diffs[pointer][0] ) { + case DIFF_INSERT: + countInsert++; + textInsert += diffs[pointer][1]; + break; + case DIFF_DELETE: + countDelete++; + textDelete += diffs[pointer][1]; + break; + case DIFF_EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (countDelete >= 1 && countInsert >= 1) { + // Delete the offending records and add the merged ones. + diffs.splice(pointer - countDelete - countInsert, + countDelete + countInsert); + pointer = pointer - countDelete - countInsert; + a = this.DiffMain(textDelete, textInsert, false, deadline); + for (j = a.length - 1; j >= 0; j--) { + diffs.splice( pointer, 0, a[j] ); + } + pointer = pointer + a.length; + } + countInsert = 0; + countDelete = 0; + textDelete = ""; + textInsert = ""; + break; + } + pointer++; + } + diffs.pop(); // Remove the dummy entry at the end. + + return diffs; + }; + + /** + * Find the 'middle snake' of a diff, split the problem in two + * and return the recursively constructed diff. + * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} deadline Time at which to bail if not yet complete. + * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffBisect = function(text1, text2, deadline) { + var text1Length, text2Length, maxD, vOffset, vLength, + v1, v2, x, delta, front, k1start, k1end, k2start, + k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2; + // Cache the text lengths to prevent multiple calls. + text1Length = text1.length; + text2Length = text2.length; + maxD = Math.ceil((text1Length + text2Length) / 2); + vOffset = maxD; + vLength = 2 * maxD; + v1 = new Array(vLength); + v2 = new Array(vLength); + // Setting all elements to -1 is faster in Chrome & Firefox than mixing + // integers and undefined. + for (x = 0; x < vLength; x++) { + v1[x] = -1; + v2[x] = -1; + } + v1[vOffset + 1] = 0; + v2[vOffset + 1] = 0; + delta = text1Length - text2Length; + // If the total number of characters is odd, then the front path will collide + // with the reverse path. + front = (delta % 2 !== 0); + // Offsets for start and end of k loop. + // Prevents mapping of space beyond the grid. + k1start = 0; + k1end = 0; + k2start = 0; + k2end = 0; + for (d = 0; d < maxD; d++) { + // Bail out if deadline is reached. + if ((new Date()).getTime() > deadline) { + break; + } + + // Walk the front path one step. + for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { + k1Offset = vOffset + k1; + if ( k1 === -d || ( k1 !== d && v1[ k1Offset - 1 ] < v1[ k1Offset + 1 ] ) ) { + x1 = v1[k1Offset + 1]; + } else { + x1 = v1[k1Offset - 1] + 1; + } + y1 = x1 - k1; + while (x1 < text1Length && y1 < text2Length && + text1.charAt(x1) === text2.charAt(y1)) { + x1++; + y1++; + } + v1[k1Offset] = x1; + if (x1 > text1Length) { + // Ran off the right of the graph. + k1end += 2; + } else if (y1 > text2Length) { + // Ran off the bottom of the graph. + k1start += 2; + } else if (front) { + k2Offset = vOffset + delta - k1; + if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) { + // Mirror x2 onto top-left coordinate system. + x2 = text1Length - v2[k2Offset]; + if (x1 >= x2) { + // Overlap detected. + return this.diffBisectSplit(text1, text2, x1, y1, deadline); + } + } + } + } + + // Walk the reverse path one step. + for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { + k2Offset = vOffset + k2; + if ( k2 === -d || (k2 !== d && v2[ k2Offset - 1 ] < v2[ k2Offset + 1 ] ) ) { + x2 = v2[k2Offset + 1]; + } else { + x2 = v2[k2Offset - 1] + 1; + } + y2 = x2 - k2; + while (x2 < text1Length && y2 < text2Length && + text1.charAt(text1Length - x2 - 1) === + text2.charAt(text2Length - y2 - 1)) { + x2++; + y2++; + } + v2[k2Offset] = x2; + if (x2 > text1Length) { + // Ran off the left of the graph. + k2end += 2; + } else if (y2 > text2Length) { + // Ran off the top of the graph. + k2start += 2; + } else if (!front) { + k1Offset = vOffset + delta - k2; + if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) { + x1 = v1[k1Offset]; + y1 = vOffset + x1 - k1Offset; + // Mirror x2 onto top-left coordinate system. + x2 = text1Length - x2; + if (x1 >= x2) { + // Overlap detected. + return this.diffBisectSplit(text1, text2, x1, y1, deadline); + } + } + } + } + } + // Diff took too long and hit the deadline or + // number of diffs equals number of characters, no commonality at all. + return [ + [ DIFF_DELETE, text1 ], + [ DIFF_INSERT, text2 ] + ]; + }; + + /** + * Given the location of the 'middle snake', split the diff in two parts + * and recurse. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} x Index of split point in text1. + * @param {number} y Index of split point in text2. + * @param {number} deadline Time at which to bail if not yet complete. + * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffBisectSplit = function( text1, text2, x, y, deadline ) { + var text1a, text1b, text2a, text2b, diffs, diffsb; + text1a = text1.substring(0, x); + text2a = text2.substring(0, y); + text1b = text1.substring(x); + text2b = text2.substring(y); + + // Compute both diffs serially. + diffs = this.DiffMain(text1a, text2a, false, deadline); + diffsb = this.DiffMain(text1b, text2b, false, deadline); + + return diffs.concat(diffsb); + }; + + /** + * Reduce the number of edits by eliminating semantically trivial equalities. + * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples. + */ + DiffMatchPatch.prototype.diffCleanupSemantic = function(diffs) { + var changes, equalities, equalitiesLength, lastequality, + pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, + lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2; + changes = false; + equalities = []; // Stack of indices where equalities are found. + equalitiesLength = 0; // Keeping our own length var is faster in JS. + /** @type {?string} */ + lastequality = null; + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + pointer = 0; // Index of current position. + // Number of characters that changed prior to the equality. + lengthInsertions1 = 0; + lengthDeletions1 = 0; + // Number of characters that changed after the equality. + lengthInsertions2 = 0; + lengthDeletions2 = 0; + while (pointer < diffs.length) { + if (diffs[pointer][0] === DIFF_EQUAL) { // Equality found. + equalities[equalitiesLength++] = pointer; + lengthInsertions1 = lengthInsertions2; + lengthDeletions1 = lengthDeletions2; + lengthInsertions2 = 0; + lengthDeletions2 = 0; + lastequality = diffs[pointer][1]; + } else { // An insertion or deletion. + if (diffs[pointer][0] === DIFF_INSERT) { + lengthInsertions2 += diffs[pointer][1].length; + } else { + lengthDeletions2 += diffs[pointer][1].length; + } + // Eliminate an equality that is smaller or equal to the edits on both + // sides of it. + if (lastequality && (lastequality.length <= + Math.max(lengthInsertions1, lengthDeletions1)) && + (lastequality.length <= Math.max(lengthInsertions2, + lengthDeletions2))) { + // Duplicate record. + diffs.splice( equalities[ equalitiesLength - 1 ], 0, [ DIFF_DELETE, lastequality ] ); + // Change second copy to insert. + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; + // Throw away the equality we just deleted. + equalitiesLength--; + // Throw away the previous equality (it needs to be reevaluated). + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + lengthInsertions1 = 0; // Reset the counters. + lengthDeletions1 = 0; + lengthInsertions2 = 0; + lengthDeletions2 = 0; + lastequality = null; + changes = true; + } + } + pointer++; + } + + // Normalize the diff. + if (changes) { + this.diffCleanupMerge(diffs); + } + + // Find any overlaps between deletions and insertions. + // e.g: <del>abcxxx</del><ins>xxxdef</ins> + // -> <del>abc</del>xxx<ins>def</ins> + // e.g: <del>xxxabc</del><ins>defxxx</ins> + // -> <ins>def</ins>xxx<del>abc</del> + // Only extract an overlap if it is as big as the edit ahead or behind it. + pointer = 1; + while (pointer < diffs.length) { + if (diffs[pointer - 1][0] === DIFF_DELETE && + diffs[pointer][0] === DIFF_INSERT) { + deletion = diffs[pointer - 1][1]; + insertion = diffs[pointer][1]; + overlapLength1 = this.diffCommonOverlap(deletion, insertion); + overlapLength2 = this.diffCommonOverlap(insertion, deletion); + if (overlapLength1 >= overlapLength2) { + if (overlapLength1 >= deletion.length / 2 || + overlapLength1 >= insertion.length / 2) { + // Overlap found. Insert an equality and trim the surrounding edits. + diffs.splice( pointer, 0, [ DIFF_EQUAL, insertion.substring( 0, overlapLength1 ) ] ); + diffs[pointer - 1][1] = + deletion.substring(0, deletion.length - overlapLength1); + diffs[pointer + 1][1] = insertion.substring(overlapLength1); + pointer++; + } + } else { + if (overlapLength2 >= deletion.length / 2 || + overlapLength2 >= insertion.length / 2) { + // Reverse overlap found. + // Insert an equality and swap and trim the surrounding edits. + diffs.splice( pointer, 0, [ DIFF_EQUAL, deletion.substring( 0, overlapLength2 ) ] ); + diffs[pointer - 1][0] = DIFF_INSERT; + diffs[pointer - 1][1] = + insertion.substring(0, insertion.length - overlapLength2); + diffs[pointer + 1][0] = DIFF_DELETE; + diffs[pointer + 1][1] = + deletion.substring(overlapLength2); + pointer++; + } + } + pointer++; + } + pointer++; + } + }; + + /** + * Determine if the suffix of one string is the prefix of another. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of the first + * string and the start of the second string. + * @private + */ + DiffMatchPatch.prototype.diffCommonOverlap = function(text1, text2) { + var text1Length, text2Length, textLength, + best, length, pattern, found; + // Cache the text lengths to prevent multiple calls. + text1Length = text1.length; + text2Length = text2.length; + // Eliminate the null case. + if (text1Length === 0 || text2Length === 0) { + return 0; + } + // Truncate the longer string. + if (text1Length > text2Length) { + text1 = text1.substring(text1Length - text2Length); + } else if (text1Length < text2Length) { + text2 = text2.substring(0, text1Length); + } + textLength = Math.min(text1Length, text2Length); + // Quick check for the worst case. + if (text1 === text2) { + return textLength; + } + + // Start by looking for a single character match + // and increase length until no match is found. + // Performance analysis: http://neil.fraser.name/news/2010/11/04/ + best = 0; + length = 1; + while (true) { + pattern = text1.substring(textLength - length); + found = text2.indexOf(pattern); + if (found === -1) { + return best; + } + length += found; + if (found === 0 || text1.substring(textLength - length) === + text2.substring(0, length)) { + best = length; + length++; + } + } + }; + + /** + * Split two texts into an array of strings. Reduce the texts to a string of + * hashes where each Unicode character represents one line. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}} + * An object containing the encoded text1, the encoded text2 and + * the array of unique strings. + * The zeroth element of the array of unique strings is intentionally blank. + * @private + */ + DiffMatchPatch.prototype.diffLinesToChars = function(text1, text2) { + var lineArray, lineHash, chars1, chars2; + lineArray = []; // e.g. lineArray[4] === 'Hello\n' + lineHash = {}; // e.g. lineHash['Hello\n'] === 4 + + // '\x00' is a valid character, but various debuggers don't like it. + // So we'll insert a junk entry to avoid generating a null character. + lineArray[0] = ""; + + /** + * Split a text into an array of strings. Reduce the texts to a string of + * hashes where each Unicode character represents one line. + * Modifies linearray and linehash through being a closure. + * @param {string} text String to encode. + * @return {string} Encoded string. + * @private + */ + function diffLinesToCharsMunge(text) { + var chars, lineStart, lineEnd, lineArrayLength, line; + chars = ""; + // Walk the text, pulling out a substring for each line. + // text.split('\n') would would temporarily double our memory footprint. + // Modifying text would create many large strings to garbage collect. + lineStart = 0; + lineEnd = -1; + // Keeping our own length variable is faster than looking it up. + lineArrayLength = lineArray.length; + while (lineEnd < text.length - 1) { + lineEnd = text.indexOf("\n", lineStart); + if (lineEnd === -1) { + lineEnd = text.length - 1; + } + line = text.substring(lineStart, lineEnd + 1); + lineStart = lineEnd + 1; + + if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : + (lineHash[line] !== undefined)) { + chars += String.fromCharCode( lineHash[ line ] ); + } else { + chars += String.fromCharCode(lineArrayLength); + lineHash[line] = lineArrayLength; + lineArray[lineArrayLength++] = line; + } + } + return chars; + } + + chars1 = diffLinesToCharsMunge(text1); + chars2 = diffLinesToCharsMunge(text2); + return { + chars1: chars1, + chars2: chars2, + lineArray: lineArray + }; + }; + + /** + * Rehydrate the text in a diff from a string of line hashes to real lines of + * text. + * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples. + * @param {!Array.<string>} lineArray Array of unique strings. + * @private + */ + DiffMatchPatch.prototype.diffCharsToLines = function( diffs, lineArray ) { + var x, chars, text, y; + for ( x = 0; x < diffs.length; x++ ) { + chars = diffs[x][1]; + text = []; + for ( y = 0; y < chars.length; y++ ) { + text[y] = lineArray[chars.charCodeAt(y)]; + } + diffs[x][1] = text.join(""); + } + }; + + /** + * Reorder and merge like edit sections. Merge equalities. + * Any edit section can move as long as it doesn't cross an equality. + * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples. + */ + DiffMatchPatch.prototype.diffCleanupMerge = function(diffs) { + var pointer, countDelete, countInsert, textInsert, textDelete, + commonlength, changes; + diffs.push( [ DIFF_EQUAL, "" ] ); // Add a dummy entry at the end. + pointer = 0; + countDelete = 0; + countInsert = 0; + textDelete = ""; + textInsert = ""; + commonlength; + while (pointer < diffs.length) { + switch ( diffs[ pointer ][ 0 ] ) { + case DIFF_INSERT: + countInsert++; + textInsert += diffs[pointer][1]; + pointer++; + break; + case DIFF_DELETE: + countDelete++; + textDelete += diffs[pointer][1]; + pointer++; + break; + case DIFF_EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (countDelete + countInsert > 1) { + if (countDelete !== 0 && countInsert !== 0) { + // Factor out any common prefixies. + commonlength = this.diffCommonPrefix(textInsert, textDelete); + if (commonlength !== 0) { + if ((pointer - countDelete - countInsert) > 0 && + diffs[pointer - countDelete - countInsert - 1][0] === + DIFF_EQUAL) { + diffs[pointer - countDelete - countInsert - 1][1] += + textInsert.substring(0, commonlength); + } else { + diffs.splice( 0, 0, [ DIFF_EQUAL, + textInsert.substring( 0, commonlength ) + ] ); + pointer++; + } + textInsert = textInsert.substring(commonlength); + textDelete = textDelete.substring(commonlength); + } + // Factor out any common suffixies. + commonlength = this.diffCommonSuffix(textInsert, textDelete); + if (commonlength !== 0) { + diffs[pointer][1] = textInsert.substring(textInsert.length - + commonlength) + diffs[pointer][1]; + textInsert = textInsert.substring(0, textInsert.length - + commonlength); + textDelete = textDelete.substring(0, textDelete.length - + commonlength); + } + } + // Delete the offending records and add the merged ones. + if (countDelete === 0) { + diffs.splice( pointer - countInsert, + countDelete + countInsert, [ DIFF_INSERT, textInsert ] ); + } else if (countInsert === 0) { + diffs.splice( pointer - countDelete, + countDelete + countInsert, [ DIFF_DELETE, textDelete ] ); + } else { + diffs.splice( pointer - countDelete - countInsert, + countDelete + countInsert, [ DIFF_DELETE, textDelete ], [ DIFF_INSERT, textInsert ] ); + } + pointer = pointer - countDelete - countInsert + + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1; + } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { + // Merge this equality with the previous one. + diffs[pointer - 1][1] += diffs[pointer][1]; + diffs.splice(pointer, 1); + } else { + pointer++; + } + countInsert = 0; + countDelete = 0; + textDelete = ""; + textInsert = ""; + break; + } + } + if (diffs[diffs.length - 1][1] === "") { + diffs.pop(); // Remove the dummy entry at the end. + } + + // Second pass: look for single edits surrounded on both sides by equalities + // which can be shifted sideways to eliminate an equality. + // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC + changes = false; + pointer = 1; + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1][0] === DIFF_EQUAL && + diffs[pointer + 1][0] === DIFF_EQUAL) { + // This is a single edit surrounded by equalities. + if ( diffs[ pointer ][ 1 ].substring( diffs[ pointer ][ 1 ].length - + diffs[ pointer - 1 ][ 1 ].length ) === diffs[ pointer - 1 ][ 1 ] ) { + // Shift the edit over the previous equality. + diffs[pointer][1] = diffs[pointer - 1][1] + + diffs[pointer][1].substring(0, diffs[pointer][1].length - + diffs[pointer - 1][1].length); + diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; + diffs.splice(pointer - 1, 1); + changes = true; + } else if ( diffs[ pointer ][ 1 ].substring( 0, diffs[ pointer + 1 ][ 1 ].length ) === + diffs[ pointer + 1 ][ 1 ] ) { + // Shift the edit over the next equality. + diffs[pointer - 1][1] += diffs[pointer + 1][1]; + diffs[pointer][1] = + diffs[pointer][1].substring(diffs[pointer + 1][1].length) + + diffs[pointer + 1][1]; + diffs.splice(pointer + 1, 1); + changes = true; + } + } + pointer++; + } + // If shifts were made, the diff needs reordering and another shift sweep. + if (changes) { + this.diffCleanupMerge(diffs); + } + }; + + return function(o, n) { + var diff, output, text; + diff = new DiffMatchPatch(); + output = diff.DiffMain(o, n); + //console.log(output); + diff.diffCleanupEfficiency(output); + text = diff.diffPrettyHtml(output); + + return text; + }; }()); +// jscs:enable (function() { @@ -1828,7 +3073,6 @@ QUnit.init = function() { config.autorun = false; config.filter = ""; config.queue = []; - config.semaphore = 1; // Return on non-browser environments // This is necessary to not break on node tests @@ -1867,27 +3111,7 @@ QUnit.init = function() { result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests ); - result.innerHTML = "Running...<br/> "; - } -}; - -// Resets the test setup. Useful for tests that modify the DOM. -/* -DEPRECATED: Use multiple tests instead of resetting inside a test. -Use testStart or testDone for custom cleanup. -This method will throw an error in 2.0, and will be removed in 2.1 -*/ -QUnit.reset = function() { - - // Return on non-browser environments - // This is necessary to not break on node tests - if ( typeof window === "undefined" ) { - return; - } - - var fixture = id( "qunit-fixture" ); - if ( fixture ) { - fixture.innerHTML = config.fixture; + result.innerHTML = "Running...<br /> "; } }; @@ -1899,7 +3123,7 @@ if ( typeof window === "undefined" ) { var config = QUnit.config, hasOwn = Object.prototype.hasOwnProperty, defined = { - document: typeof window.document !== "undefined", + document: window.document !== undefined, sessionStorage: (function() { var x = "qunit-test-string"; try { @@ -1910,7 +3134,8 @@ var config = QUnit.config, return false; } }()) - }; + }, + modulesList = []; /** * Escape text for attribute or text content. @@ -1951,7 +3176,14 @@ function addEvent( elem, type, fn ) { } else if ( elem.attachEvent ) { // support: IE <9 - elem.attachEvent( "on" + type, fn ); + elem.attachEvent( "on" + type, function() { + var event = window.event; + if ( !event.target ) { + event.target = event.srcElement || document; + } + + fn.call( elem, event ); + }); } } @@ -2020,13 +3252,16 @@ function getUrlConfigHtml() { escaped = escapeText( val.id ); escapedTooltip = escapeText( val.tooltip ); - config[ val.id ] = QUnit.urlParams[ val.id ]; + if ( config[ val.id ] === undefined ) { + config[ val.id ] = QUnit.urlParams[ val.id ]; + } + if ( !val.value || typeof val.value === "string" ) { urlConfigHtml += "<input id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' type='checkbox'" + ( val.value ? " value='" + escapeText( val.value ) + "'" : "" ) + ( config[ val.id ] ? " checked='checked'" : "" ) + - " title='" + escapedTooltip + "'><label for='qunit-urlconfig-" + escaped + + " title='" + escapedTooltip + "' /><label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + "</label>"; } else { urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + @@ -2064,69 +3299,149 @@ function getUrlConfigHtml() { return urlConfigHtml; } +// Handle "click" events on toolbar checkboxes and "change" for select menus. +// Updates the URL with the new state of `config.urlConfig` values. +function toolbarChanged() { + var updatedUrl, value, + field = this, + params = {}; + + // Detect if field is a select menu or a checkbox + if ( "selectedIndex" in field ) { + value = field.options[ field.selectedIndex ].value || undefined; + } else { + value = field.checked ? ( field.defaultValue || true ) : undefined; + } + + params[ field.name ] = value; + updatedUrl = setUrl( params ); + + if ( "hidepassed" === field.name && "replaceState" in window.history ) { + config[ field.name ] = value || false; + if ( value ) { + addClass( id( "qunit-tests" ), "hidepass" ); + } else { + removeClass( id( "qunit-tests" ), "hidepass" ); + } + + // It is not necessary to refresh the whole page + window.history.replaceState( null, "", updatedUrl ); + } else { + window.location = updatedUrl; + } +} + +function setUrl( params ) { + var key, + querystring = "?"; + + params = QUnit.extend( QUnit.extend( {}, QUnit.urlParams ), params ); + + for ( key in params ) { + if ( hasOwn.call( params, key ) ) { + if ( params[ key ] === undefined ) { + continue; + } + querystring += encodeURIComponent( key ); + if ( params[ key ] !== true ) { + querystring += "=" + encodeURIComponent( params[ key ] ); + } + querystring += "&"; + } + } + return location.protocol + "//" + location.host + + location.pathname + querystring.slice( 0, -1 ); +} + +function applyUrlParams() { + var selectedModule, + modulesList = id( "qunit-modulefilter" ), + filter = id( "qunit-filter-input" ).value; + + selectedModule = modulesList ? + decodeURIComponent( modulesList.options[ modulesList.selectedIndex ].value ) : + undefined; + + window.location = setUrl({ + module: ( selectedModule === "" ) ? undefined : selectedModule, + filter: ( filter === "" ) ? undefined : filter, + + // Remove testId filter + testId: undefined + }); +} + function toolbarUrlConfigContainer() { var urlConfigContainer = document.createElement( "span" ); urlConfigContainer.innerHTML = getUrlConfigHtml(); + addClass( urlConfigContainer, "qunit-url-config" ); // For oldIE support: // * Add handlers to the individual elements instead of the container // * Use "click" instead of "change" for checkboxes - // * Fallback from event.target to event.srcElement - addEvents( urlConfigContainer.getElementsByTagName( "input" ), "click", function( event ) { - var params = {}, - target = event.target || event.srcElement; - params[ target.name ] = target.checked ? - target.defaultValue || true : - undefined; - window.location = QUnit.url( params ); - }); - addEvents( urlConfigContainer.getElementsByTagName( "select" ), "change", function( event ) { - var params = {}, - target = event.target || event.srcElement; - params[ target.name ] = target.options[ target.selectedIndex ].value || undefined; - window.location = QUnit.url( params ); - }); + addEvents( urlConfigContainer.getElementsByTagName( "input" ), "click", toolbarChanged ); + addEvents( urlConfigContainer.getElementsByTagName( "select" ), "change", toolbarChanged ); return urlConfigContainer; } -function getModuleNames() { - var i, - moduleNames = []; +function toolbarLooseFilter() { + var filter = document.createElement( "form" ), + label = document.createElement( "label" ), + input = document.createElement( "input" ), + button = document.createElement( "button" ); + + addClass( filter, "qunit-filter" ); + + label.innerHTML = "Filter: "; + + input.type = "text"; + input.value = config.filter || ""; + input.name = "filter"; + input.id = "qunit-filter-input"; - for ( i in config.modules ) { - if ( config.modules.hasOwnProperty( i ) ) { - moduleNames.push( i ); + button.innerHTML = "Go"; + + label.appendChild( input ); + + filter.appendChild( label ); + filter.appendChild( button ); + addEvent( filter, "submit", function( ev ) { + applyUrlParams(); + + if ( ev && ev.preventDefault ) { + ev.preventDefault(); } - } - moduleNames.sort(function( a, b ) { - return a.localeCompare( b ); + return false; }); - return moduleNames; + return filter; } function toolbarModuleFilterHtml() { var i, - moduleFilterHtml = "", - moduleNames = getModuleNames(); + moduleFilterHtml = ""; - if ( moduleNames.length <= 1 ) { + if ( !modulesList.length ) { return false; } + modulesList.sort(function( a, b ) { + return a.localeCompare( b ); + }); + moduleFilterHtml += "<label for='qunit-modulefilter'>Module: </label>" + "<select id='qunit-modulefilter' name='modulefilter'><option value='' " + - ( config.module === undefined ? "selected='selected'" : "" ) + + ( QUnit.urlParams.module === undefined ? "selected='selected'" : "" ) + ">< All Modules ></option>"; - for ( i = 0; i < moduleNames.length; i++ ) { + for ( i = 0; i < modulesList.length; i++ ) { moduleFilterHtml += "<option value='" + - escapeText( encodeURIComponent( moduleNames[ i ] ) ) + "' " + - ( config.module === moduleNames[ i ] ? "selected='selected'" : "" ) + - ">" + escapeText( moduleNames[ i ] ) + "</option>"; + escapeText( encodeURIComponent( modulesList[ i ] ) ) + "' " + + ( QUnit.urlParams.module === modulesList[ i ] ? "selected='selected'" : "" ) + + ">" + escapeText( modulesList[ i ] ) + "</option>"; } moduleFilterHtml += "</select>"; @@ -2134,85 +3449,38 @@ function toolbarModuleFilterHtml() { } function toolbarModuleFilter() { - var moduleFilter = document.createElement( "span" ), + var toolbar = id( "qunit-testrunner-toolbar" ), + moduleFilter = document.createElement( "span" ), moduleFilterHtml = toolbarModuleFilterHtml(); - if ( !moduleFilterHtml ) { + if ( !toolbar || !moduleFilterHtml ) { return false; } moduleFilter.setAttribute( "id", "qunit-modulefilter-container" ); moduleFilter.innerHTML = moduleFilterHtml; - addEvent( moduleFilter.lastChild, "change", function() { - var selectBox = moduleFilter.getElementsByTagName( "select" )[ 0 ], - selectedModule = decodeURIComponent( selectBox.options[ selectBox.selectedIndex ].value ); - - window.location = QUnit.url({ - module: ( selectedModule === "" ) ? undefined : selectedModule, - - // Remove any existing filters - filter: undefined, - testNumber: undefined - }); - }); - - return moduleFilter; -} - -function toolbarFilter() { - var testList = id( "qunit-tests" ), - filter = document.createElement( "input" ); - - filter.type = "checkbox"; - filter.id = "qunit-filter-pass"; - - addEvent( filter, "click", function() { - if ( filter.checked ) { - addClass( testList, "hidepass" ); - if ( defined.sessionStorage ) { - sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); - } - } else { - removeClass( testList, "hidepass" ); - if ( defined.sessionStorage ) { - sessionStorage.removeItem( "qunit-filter-passed-tests" ); - } - } - }); - - if ( config.hidepassed || defined.sessionStorage && - sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { - filter.checked = true; - - addClass( testList, "hidepass" ); - } - - return filter; -} + addEvent( moduleFilter.lastChild, "change", applyUrlParams ); -function toolbarLabel() { - var label = document.createElement( "label" ); - label.setAttribute( "for", "qunit-filter-pass" ); - label.setAttribute( "title", "Only show tests and assertions that fail. Stored in sessionStorage." ); - label.innerHTML = "Hide passed tests"; - - return label; + toolbar.appendChild( moduleFilter ); } function appendToolbar() { - var moduleFilter, - toolbar = id( "qunit-testrunner-toolbar" ); + var toolbar = id( "qunit-testrunner-toolbar" ); if ( toolbar ) { - toolbar.appendChild( toolbarFilter() ); - toolbar.appendChild( toolbarLabel() ); toolbar.appendChild( toolbarUrlConfigContainer() ); + toolbar.appendChild( toolbarLooseFilter() ); + } +} - moduleFilter = toolbarModuleFilter(); - if ( moduleFilter ) { - toolbar.appendChild( moduleFilter ); - } +function appendHeader() { + var header = id( "qunit-header" ); + + if ( header ) { + header.innerHTML = "<a href='" + + setUrl({ filter: undefined, module: undefined, testId: undefined }) + + "'>" + header.innerHTML + "</a> "; } } @@ -2221,9 +3489,6 @@ function appendBanner() { if ( banner ) { banner.className = ""; - banner.innerHTML = "<a href='" + - QUnit.url({ filter: undefined, module: undefined, testNumber: undefined }) + - "'>" + banner.innerHTML + "</a> "; } } @@ -2241,7 +3506,7 @@ function appendTestResults() { result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests ); - result.innerHTML = "Running...<br> "; + result.innerHTML = "Running...<br /> "; } } @@ -2254,29 +3519,90 @@ function storeFixture() { function appendUserAgent() { var userAgent = id( "qunit-userAgent" ); + if ( userAgent ) { - userAgent.innerHTML = navigator.userAgent; + userAgent.innerHTML = ""; + userAgent.appendChild( + document.createTextNode( + "QUnit " + QUnit.version + "; " + navigator.userAgent + ) + ); + } +} + +function appendTestsList( modules ) { + var i, l, x, z, test, moduleObj; + + for ( i = 0, l = modules.length; i < l; i++ ) { + moduleObj = modules[ i ]; + + if ( moduleObj.name ) { + modulesList.push( moduleObj.name ); + } + + for ( x = 0, z = moduleObj.tests.length; x < z; x++ ) { + test = moduleObj.tests[ x ]; + + appendTest( test.name, test.testId, moduleObj.name ); + } + } +} + +function appendTest( name, testId, moduleName ) { + var title, rerunTrigger, testBlock, assertList, + tests = id( "qunit-tests" ); + + if ( !tests ) { + return; } + + title = document.createElement( "strong" ); + title.innerHTML = getNameHtml( name, moduleName ); + + rerunTrigger = document.createElement( "a" ); + rerunTrigger.innerHTML = "Rerun"; + rerunTrigger.href = setUrl({ testId: testId }); + + testBlock = document.createElement( "li" ); + testBlock.appendChild( title ); + testBlock.appendChild( rerunTrigger ); + testBlock.id = "qunit-test-output-" + testId; + + assertList = document.createElement( "ol" ); + assertList.className = "qunit-assert-list"; + + testBlock.appendChild( assertList ); + + tests.appendChild( testBlock ); } // HTML Reporter initialization and load -QUnit.begin(function() { +QUnit.begin(function( details ) { var qunit = id( "qunit" ); + // Fixture is the only one necessary to run without the #qunit element + storeFixture(); + if ( qunit ) { qunit.innerHTML = - "<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" + - "<h2 id='qunit-banner'></h2>" + - "<div id='qunit-testrunner-toolbar'></div>" + - "<h2 id='qunit-userAgent'></h2>" + - "<ol id='qunit-tests'></ol>"; + "<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" + + "<h2 id='qunit-banner'></h2>" + + "<div id='qunit-testrunner-toolbar'></div>" + + "<h2 id='qunit-userAgent'></h2>" + + "<ol id='qunit-tests'></ol>"; } + appendHeader(); appendBanner(); appendTestResults(); appendUserAgent(); appendToolbar(); - storeFixture(); + appendTestsList( details.modules ); + toolbarModuleFilter(); + + if ( qunit && config.hidepassed ) { + addClass( qunit.lastChild, "hidepass" ); + } }); QUnit.done(function( details ) { @@ -2286,7 +3612,7 @@ QUnit.done(function( details ) { html = [ "Tests completed in ", details.runtime, - " milliseconds.<br>", + " milliseconds.<br />", "<span class='passed'>", details.passed, "</span> assertions of <span class='total'>", @@ -2343,35 +3669,26 @@ function getNameHtml( name, module ) { } QUnit.testStart(function( details ) { - var a, b, li, running, assertList, - name = getNameHtml( details.name, details.module ), - tests = id( "qunit-tests" ); - - if ( tests ) { - b = document.createElement( "strong" ); - b.innerHTML = name; - - a = document.createElement( "a" ); - a.innerHTML = "Rerun"; - a.href = QUnit.url({ testNumber: details.testNumber }); + var running, testBlock, bad; - li = document.createElement( "li" ); - li.appendChild( b ); - li.appendChild( a ); - li.className = "running"; - li.id = "qunit-test-output" + details.testNumber; - - assertList = document.createElement( "ol" ); - assertList.className = "qunit-assert-list"; - - li.appendChild( assertList ); + testBlock = id( "qunit-test-output-" + details.testId ); + if ( testBlock ) { + testBlock.className = "running"; + } else { - tests.appendChild( li ); + // Report later registered tests + appendTest( details.name, details.testId, details.module ); } running = id( "qunit-testresult" ); if ( running ) { - running.innerHTML = "Running: <br>" + name; + bad = QUnit.config.reorder && defined.sessionStorage && + +sessionStorage.getItem( "qunit-test-" + details.module + "-" + details.name ); + + running.innerHTML = ( bad ? + "Rerunning previously failed test: <br />" : + "Running: <br />" ) + + getNameHtml( details.name, details.module ); } }); @@ -2379,7 +3696,7 @@ QUnit.testStart(function( details ) { QUnit.log(function( details ) { var assertList, assertLi, message, expected, actual, - testItem = id( "qunit-test-output" + details.testNumber ); + testItem = id( "qunit-test-output-" + details.testId ); if ( !testItem ) { return; @@ -2387,6 +3704,7 @@ QUnit.log(function( details ) { message = escapeText( details.message ) || ( details.result ? "okay" : "failed" ); message = "<span class='test-message'>" + message + "</span>"; + message += "<span class='runtime'>@ " + details.runtime + " ms</span>"; // pushFailure doesn't provide details.expected // when it calls, it's implicit to also not show expected and diff stuff @@ -2403,6 +3721,15 @@ QUnit.log(function( details ) { actual + "</pre></td></tr>" + "<tr class='test-diff'><th>Diff: </th><td><pre>" + QUnit.diff( expected, actual ) + "</pre></td></tr>"; + } else { + if ( expected.indexOf( "[object Array]" ) !== -1 || + expected.indexOf( "[object Object]" ) !== -1 ) { + message += "<tr class='test-message'><th>Message: </th><td>" + + "Diff suppressed as the depth of object is more than current max depth (" + + QUnit.config.maxDepth + ").<p>Hint: Use <code>QUnit.dump.maxDepth</code> to " + + " run with a higher max depth or <a href='" + setUrl({ maxDepth: -1 }) + "'>" + + "Rerun</a> without max depth.</p></td></tr>"; + } } if ( details.source ) { @@ -2430,19 +3757,15 @@ QUnit.log(function( details ) { QUnit.testDone(function( details ) { var testTitle, time, testItem, assertList, - good, bad, testCounts, + good, bad, testCounts, skipped, tests = id( "qunit-tests" ); - // QUnit.reset() is deprecated and will be replaced for a new - // fixture reset function on QUnit 2.0/2.1. - // It's still called here for backwards compatibility handling - QUnit.reset(); - if ( !tests ) { return; } - testItem = id( "qunit-test-output" + details.testNumber ); + testItem = id( "qunit-test-output-" + details.testId ); + assertList = testItem.getElementsByTagName( "ol" )[ 0 ]; good = details.passed; @@ -2471,25 +3794,35 @@ QUnit.testDone(function( details ) { testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>"; - addEvent( testTitle, "click", function() { - toggleClass( assertList, "qunit-collapsed" ); - }); - - time = document.createElement( "span" ); - time.className = "runtime"; - time.innerHTML = details.runtime + " ms"; + if ( details.skipped ) { + testItem.className = "skipped"; + skipped = document.createElement( "em" ); + skipped.className = "qunit-skipped-label"; + skipped.innerHTML = "skipped"; + testItem.insertBefore( skipped, testTitle ); + } else { + addEvent( testTitle, "click", function() { + toggleClass( assertList, "qunit-collapsed" ); + }); - testItem.className = bad ? "fail" : "pass"; + testItem.className = bad ? "fail" : "pass"; - testItem.insertBefore( time, assertList ); + time = document.createElement( "span" ); + time.className = "runtime"; + time.innerHTML = details.runtime + " ms"; + testItem.insertBefore( time, assertList ); + } }); -if ( !defined.document || document.readyState === "complete" ) { - config.autorun = true; -} - if ( defined.document ) { - addEvent( window, "load", QUnit.load ); + if ( document.readyState === "complete" ) { + QUnit.load(); + } else { + addEvent( window, "load", QUnit.load ); + } +} else { + config.pageLoaded = true; + config.autorun = true; } })(); diff --git a/qunitTest/aggregatorTest.js b/qunitTest/aggregatorTest.js index eed973ad28f568452a7ca45e69f61e918dae7d54..ce072d6ca72e047bacf50a55ab11e23befc80064 100644 --- a/qunitTest/aggregatorTest.js +++ b/qunitTest/aggregatorTest.js @@ -3,38 +3,30 @@ require(['configTest'], function() { function(GeoLocationWidget, contactJS){ QUnit.test( "TestAggregator ", function( assert ) { + var latitudeType = new contactJS.Attribute().withName('latitude').withType('double'); + var longitudeType = new contactJS.Attribute().withName('longitude').withType('double'); + //initializes the infrastructure var discoverer = new contactJS.Discoverer(); var testAggregator = new contactJS.Aggregator(discoverer); - var geoLocationWidget = new GeoLocationWidget(discoverer); + new GeoLocationWidget(discoverer); var aggregatorId = testAggregator.getId(); - assert.ok( aggregatorId && aggregatorId !== "null" && aggregatorId !== "undefined","Passed!: id is not null" ); - assert.equal( testAggregator.getType(), 'Aggregator',"Passed!: type -> Aggregator"); - assert.equal( testAggregator.getName(), 'Aggregator',"Passed!: name -> Aggregator"); + assert.ok(aggregatorId && aggregatorId !== "null" && aggregatorId !== "undefined","Passed!: id is not null" ); + assert.equal(testAggregator.getType(), 'Aggregator',"Passed!: type -> Aggregator"); + assert.equal(testAggregator.getName(), 'Aggregator',"Passed!: name -> Aggregator"); var aggregatorData = testAggregator.getCurrentData(); - assert.equal( aggregatorData.size(), 0, "Passed!: no available attributes" ); + assert.equal(aggregatorData.size(), 0, "Passed!: no available attributes" ); var widgetIds = testAggregator.getWidgets(); - assert.equal( widgetIds.length, 0,"Passed!: no subscribed Widgets" ); + assert.equal(widgetIds.length, 0,"Passed!: no subscribed Widgets" ); //subscription var widgetDescriptions = discoverer.getDescriptions([contactJS.Widget]); - - var latitudeType = new contactJS.AttributeType().withName('latitude') - .withType('double'); - var longitudeType = new contactJS.AttributeType().withName('longitude') - .withType('double'); - var list = new contactJS.AttributeTypeList(); - list.put(latitudeType); - list.put(longitudeType); - - var call = new contactJS.Callback().withName('UPDATE').withAttributeTypes(list); - var callarray = []; - callarray.push(call); - var callList = new contactJS.CallbackList().withItems(callarray); + var list = new contactJS.AttributeList().withItems([latitudeType, longitudeType]); + var callList = new contactJS.CallbackList().withItems([new contactJS.Callback().withName('UPDATE').withAttributeTypes(list)]); testAggregator.addWidgetSubscription(widgetDescriptions[0], callList); widgetIds = testAggregator.getWidgets(); @@ -45,15 +37,15 @@ require(['configTest'], function() { assert.equal(subscriber.size(), 1,"subscribe Passed!: one subscribed Widget in geolocationWidget too"); - var values = testAggregator.getAttributeValues(); + var values = testAggregator.getAttributes(); assert.equal( values.size(), 2, "Passed!: two available attributes" ); - var latitude = values.getItem('(latitude:double)'); + var latitude = values.getAttributeWithTypeOf(latitudeType); assert.equal(latitude.getName(), 'latitude',"subscribed Attributes Passed!: latitude exists" ); - assert.equal(latitude.getValue(), 'undefined',"subscribed Attributes Passed!: value of latitude is undefined" ); + assert.equal(latitude.getValue(), 'NO_VALUE',"subscribed Attributes Passed!: value of latitude is NO_VALUE" ); - var longitude =values.getItem('(longitude:double)'); + var longitude =values.getAttributeWithTypeOf(longitudeType); assert.equal(longitude.getName(), 'longitude',"subscribed Attributes Passed!: longitude exists" ); - assert.equal(longitude.getValue(), 'undefined',"subscribed Attributes Passed!: value of longitude is undefined" ); + assert.equal(longitude.getValue(), 'NO_VALUE',"subscribed Attributes Passed!: value of longitude is NO_VALUE" ); //unsubscribe testAggregator.unsubscribeFrom(widgetIds[0]); diff --git a/qunitTest/attributeTypeListTest.js b/qunitTest/attributeTypeListTest.js index 14965bc71bd9237f7d38470cde1492fd15706544..7cccf20d6f70a99bf73f0c1cafde898a6dc57b31 100644 --- a/qunitTest/attributeTypeListTest.js +++ b/qunitTest/attributeTypeListTest.js @@ -6,20 +6,17 @@ require(['configTest'], function() { var parameter = new contactJS.Parameter().withKey('testKey').withValue('testValue'); - var latitudeType = new contactJS.AttributeType().withName('latitude') - .withType('double').withParameter(parameter); - var longitudeType = new contactJS.AttributeType().withName('longitude') - .withType('double'); - var attributeType = new contactJS.AttributeType().withName('testName') - .withType('integer'); + var latitudeType = new contactJS.Attribute().withName('latitude').withType('double').withParameter(parameter); + var longitudeType = new contactJS.Attribute().withName('longitude').withType('double'); + var attributeType = new contactJS.Attribute().withName('testName').withType('integer'); var array = []; array.push(latitudeType); array.push(longitudeType); - var list = new contactJS.AttributeTypeList().withItems(array); + var list = new contactJS.AttributeList().withItems(array); assert.equal( list.size(), 2, "Passed!: Builder (withItems)" ); - var list2 = new contactJS.AttributeTypeList(); + var list2 = new contactJS.AttributeList(); list2.put(attributeType); assert.equal( list2.size(), 1, "Passed!: Put type to list (put)" ); @@ -35,33 +32,24 @@ require(['configTest'], function() { assert.ok( list2.equals(list2), "Passed!: equals -> true" ); assert.ok( !list.equals(list2), "Passed!: equals -> false" ); - //containsKey - assert.ok( list2.containsKey('(testName:integer)'), "Passed!: containsKey -> true" ); - assert.ok( !list.containsKey('(testName:integer)'), "Passed!: containsKey -> false" ); - //getItem - assert.ok( list2.getItem('(testName:integer)').equals(attributeType), "Passed!: getItem" ); - assert.ok( !list.getItem('(testName:integer)'), "Passed!: getItem -> undefined" ); + assert.ok( list2.getAttributeWithTypeOf(attributeType).equalsTypeOf(attributeType), "Passed!: getItem" ); + assert.ok( !list.getAttributeWithTypeOf(attributeType), "Passed!: getItem -> undefined" ); //removeItem - list2.removeItem('(testName:integer)'); + list2.removeAttributeWithTypeOf(attributeType); assert.equal( list2.size(),2, "Passed!: removeItem" ); assert.ok( !list2.getItem('(testName:integer)'), "Passed!: item removed" ); - list.removeItem('(testName:integer)'); + list.removeAttributeWithTypeOf(attributeType); assert.equal( list.size(), 2, "Passed!: removeItem: key does not exist" ); - //getKeys - assert.equal( list2.getKeys().length, 2, "Passed!: getKeys" ); - assert.equal( list2.getKeys()[0], '(latitude:double)#[testKey:testValue]', "Passed!: getKeys -> latitude" ); - assert.equal( list2.getKeys()[1], '(longitude:double)', "Passed!: getKeys -> longitude" ); - //getItems assert.equal( list2.getItems().length, 2, "Passed!: getItems" ); - assert.ok( list2.getItems()[0].equals(latitudeType), "Passed!: getItems -> latitude" ); - assert.ok( list2.getItems()[1].equals(longitudeType), "Passed!: getItems -> longitude" ); + assert.ok( list2.getItems()[0].equalsTypeOf(latitudeType), "Passed!: getItems -> latitude" ); + assert.ok( list2.getItems()[1].equalsTypeOf(longitudeType), "Passed!: getItems -> longitude" ); //empty - var list3 = new contactJS.AttributeTypeList(); + var list3 = new contactJS.AttributeList(); assert.ok( !list2.isEmpty(), "Passed!: isEmpty ->true" ); assert.ok( list3.isEmpty(), "Passed!: isEmpty ->false" ); diff --git a/qunitTest/attributeTypeTest.js b/qunitTest/attributeTypeTest.js index 5e5c6a5ceab5cbb03d669e316d8f1e8e6c4d1370..74d2e30b9d4adb4e8d9b3118dcb0016f1a0c6bac 100644 --- a/qunitTest/attributeTypeTest.js +++ b/qunitTest/attributeTypeTest.js @@ -3,14 +3,15 @@ require(['configTest'], function() { QUnit.test( "AttributeType", function( assert ) { - var attributeType = new contactJS.AttributeType(); + var attributeType = new contactJS.Attribute(); var parameter = new contactJS.Parameter().withKey('testKey').withValue('testValue'); - var attributeType2 = new contactJS.AttributeType().withName('testName'). + var attributeType2 = new contactJS.Attribute().withName('testName'). withType('integer').withParameter(parameter); - assert.ok( attributeType2.equals(attributeType2),"Passed!: equals -> true" ); - assert.ok( !attributeType2.equals(attributeType),"Passed!: equals -> false" ); + + assert.ok( attributeType2.equalsTypeOf(attributeType2),"Passed!: equals -> true" ); + assert.ok( !attributeType2.equalsTypeOf(attributeType),"Passed!: equals -> false" ); }); }); diff --git a/qunitTest/attributeValueListTest.js b/qunitTest/attributeValueListTest.js index e2879a1321cc3fc3edb55c321367a2ecf0d4c2a6..b40102c8111f39461b97e562f8214019fdea1e27 100644 --- a/qunitTest/attributeValueListTest.js +++ b/qunitTest/attributeValueListTest.js @@ -7,20 +7,20 @@ require(['configTest'], function() { var parameter = new contactJS.Parameter().withKey('testKey').withValue('testValue'); - var latitudeValue = new contactJS.AttributeValue().withName('latitude') + var latitudeValue = new contactJS.Attribute().withName('latitude') .withType('double').withValue('there').withParameter(parameter); - var longitudeValue = new contactJS.AttributeValue().withName('longitude') + var longitudeValue = new contactJS.Attribute().withName('longitude') .withType('double').withValue('here'); - var attributeValue = new contactJS.AttributeValue().withName('testName') + var attributeValue = new contactJS.Attribute().withName('testName') .withType('integer'); - var array = new Array(); + var array = []; array.push(latitudeValue); array.push(longitudeValue); - var list = new contactJS.AttributeValueList().withItems(array); + var list = new contactJS.AttributeList().withItems(array); assert.ok( list.size() == 2, "Passed!: Builder (withItems)" ); - var list2 = new contactJS.AttributeValueList(); + var list2 = new contactJS.AttributeList(); list2.put(attributeValue); assert.equal( list2.size(), 1, "Passed!: Put type to list (put)" ); @@ -37,8 +37,8 @@ require(['configTest'], function() { assert.ok( !list.equals(list2), "Passed!: equals -> false" ); //getSubset - var sublist = new contactJS.AttributeTypeList(); - sublist.put(latitudeValue.getAttributeType()); + var sublist = new contactJS.AttributeList(); + sublist.put(latitudeValue); var subset = list.getSubset(sublist); assert.equal( subset.size(), 1, "Passed!: Subset contains only one value" ); assert.ok( subset.contains(latitudeValue), "Passed!: subset contains latitude" ); diff --git a/qunitTest/attributeValueTest.js b/qunitTest/attributeValueTest.js index bb6c1f7ca340ff38f5bca7c03d033c9fa38d3610..9083fdc73b95db90003e0454bf0d03508028809e 100644 --- a/qunitTest/attributeValueTest.js +++ b/qunitTest/attributeValueTest.js @@ -4,35 +4,35 @@ require(['configTest'], function() { QUnit.test( "AttributeValue", function( assert ) { - var attributeValue = new contactJS.AttributeValue(); + var attributeValue = new contactJS.Attribute(); var parameter = new contactJS.Parameter().withKey('testKey').withValue('testValue'); var date = new Date(); - var attributeValue2 = new contactJS.AttributeValue().withName('testName'). + var attributeValue2 = new contactJS.Attribute().withName('testName'). withType('integer').withParameter(parameter). withValue('testValue').withTimestamp(date); - var attributeValue3 = new contactJS.AttributeValue().withName('testName').withType('integer') + var attributeValue3 = new contactJS.Attribute().withName('testName').withType('integer') .withParameter(parameter).withValue('testValue') .withTimestamp(date); assert.equal( attributeValue2.getParameters().size(), 1, "Passed!: withParameter() -> size == 1" ); - assert.ok( attributeValue2.equals(attributeValue3),"Passed!: equals -> true" ); - assert.ok( !attributeValue2.equals(attributeValue),"Passed!: equals -> false" ); + assert.ok( attributeValue2.equalsValueOf(attributeValue3),"Passed!: equals -> true" ); + assert.ok( !attributeValue2.equalsValueOf(attributeValue),"Passed!: equals -> false" ); - var attributeValue3 = new contactJS.AttributeValue().withName('testName'). + var attributeValue3 = new contactJS.Attribute().withName('testName'). withType('integer').withParameter(parameter). withValue('testValue').withTimestamp(new Date()); - assert.ok( attributeValue2.equals(attributeValue3),"Passed!: equals -> date is not verified" ); + assert.ok( attributeValue2.equalsValueOf(attributeValue3),"Passed!: equals -> date is not verified" ); /* * getAttributeType */ - var attributeType = new contactJS.AttributeType().withName('testName'). + var attributeType = new contactJS.Attribute().withName('testName'). withType('integer').withParameter(parameter); - assert.ok( attributeValue2.getAttributeType().equals(attributeType),"Passed!: getAttributeType()" ); + assert.ok( attributeValue2.equalsTypeOf(attributeType),"Passed!: getAttributeType()" ); }); diff --git a/qunitTest/callbackListTest.js b/qunitTest/callbackListTest.js index 549fb835dd34c3ea9354c350f55aba0f948758cb..166557fb1c441528c211233f1ebbfcd46bcdd291 100644 --- a/qunitTest/callbackListTest.js +++ b/qunitTest/callbackListTest.js @@ -4,21 +4,21 @@ require(['configTest'], function() { QUnit.test( "CallbackList", function( assert ) { - var attributeType = new contactJS.AttributeType(); + var attribute = new contactJS.Attribute(); var parameter = new contactJS.Parameter().withKey('testKey').withValue('testValue'); - var attributeType2 = new contactJS.AttributeType().withName('testName'). - withType('integer').withParameter(parameter); - var array = new Array(); - array.push(attributeType); - var attList = new contactJS.AttributeTypeList().withItems(array); + var attribute2 = new contactJS.Attribute().withName('testName').withType('integer').withParameter(parameter); + + var array = []; + array.push(attribute); + var attList = new contactJS.AttributeList().withItems(array); var call = new contactJS.Callback().withName('test').withAttributeTypes(array); var call2 = new contactJS.Callback().withName('test2').withAttributeTypes(attList); var call3 = new contactJS.Callback().withName('test3').withAttributeTypes(attList); - var array = new Array(); + var array = []; array.push(call2); array.push(call3); var list = new contactJS.CallbackList().withItems(array); diff --git a/qunitTest/callbackTest.js b/qunitTest/callbackTest.js index 5dfef016081c29e3b15156dee6040ec03c8562b2..b6c9045daa72dd88bb128b1c0b0eab472dcda794 100644 --- a/qunitTest/callbackTest.js +++ b/qunitTest/callbackTest.js @@ -3,20 +3,20 @@ require(['configTest'], function() { QUnit.test( "Callback", function( assert ) { - var attributeType = new contactJS.AttributeType(); + var attributeType = new contactJS.Attribute(); var parameter = new contactJS.Parameter().withKey('testKey').withValue('testValue'); - var attributeType2 = new contactJS.AttributeType().withName('testName'). - withType('integer').withParameter(parameter); - var array = new Array(); + var attributeType2 = new contactJS.Attribute().withName('testName').withType('integer').withParameter(parameter); + + var array = []; array.push(attributeType); - var attList = new contactJS.AttributeTypeList().withItems(array); + var attList = new contactJS.AttributeList().withItems(array); var call = new contactJS.Callback().withName('test').withAttributeTypes(array); var call2 = new contactJS.Callback().withName('test').withAttributeTypes(attList); array.push(attributeType2); - var attList2 = new contactJS.AttributeTypeList().withItems(array); + var attList2 = new contactJS.AttributeList().withItems(array); var call3 = new contactJS.Callback().withName('test').withAttributeTypes(attList2); var call4 = new contactJS.Callback().withName('test1').withAttributeTypes(attList2); diff --git a/qunitTest/conditionListTest.js b/qunitTest/conditionListTest.js index 40b003bf02f05ae13bc4d8a5e93fad8c9a3479fd..179272cc45e3add97d566cbb07e062a09106d5da 100644 --- a/qunitTest/conditionListTest.js +++ b/qunitTest/conditionListTest.js @@ -3,8 +3,8 @@ require(['configTest'], function() { QUnit.test( "ConditionList", function( assert ) { - var type = new contactJS.AttributeType().withName('test').withType('string'); - var type2 = new contactJS.AttributeType().withName('test').withType('string'); + var type = new contactJS.Attribute().withName('test').withType('string'); + var type2 = new contactJS.Attribute().withName('test').withType('string'); var method = new contactJS.Equals(); var method2 = new contactJS.UnEquals(); @@ -15,19 +15,16 @@ require(['configTest'], function() { .withComparisonMethod(method); var condition3 = new contactJS.Condition().withName('condition3').withAttributeType(type) .withComparisonMethod(method2); - - var array = new Array(); - array.push(condition2); - array.push(condition3); - var list = new contactJS.ConditionList().withItems(array); - assert.equal( list.size(), 2, "Passed!: Builder (withItems)" ); + + var list = new contactJS.ConditionList().withItems([condition2, condition3]); + assert.equal(list.size(), 2, "Passed!: Builder (withItems)" ); var list2 = new contactJS.ConditionList(); list2.put(condition); assert.equal( list2.size(), 1, "Passed!: Put type to list (put)" ); - list2.putAll(array); + list2.putAll([condition2, condition3]); assert.equal( list2.size(), 3, "Passed!: Put another two type to list (putAll)" ); //contains diff --git a/qunitTest/conditionTest.js b/qunitTest/conditionTest.js index dd6fd7014f29336927782d32e91de39b1b839f3e..8347572b88361a305c53fbc0da55285923650a96 100644 --- a/qunitTest/conditionTest.js +++ b/qunitTest/conditionTest.js @@ -3,19 +3,15 @@ require(['configTest'], function() { QUnit.test( "Condition", function( assert ) { - var testA = new contactJS.AttributeValue().withName('test').withType('string').withValue('blubb'); - var testA2 = new contactJS.AttributeValue().withName('test').withType('string').withValue('blubb2'); + var testA = new contactJS.Attribute().withName('test').withType('string').withValue('blubb'); + var testA2 = new contactJS.Attribute().withName('test').withType('string').withValue('blubb2'); var method = new contactJS.Equals(); var method2 = new contactJS.UnEquals(); - var conditionTest = new contactJS.Condition().withAttributeType(testA.getAttributeType()) - .withComparisonMethod(method); - var conditionTest2 = new contactJS.Condition().withAttributeType(testA.getAttributeType()) - .withComparisonMethod(method); - var conditionTest3 = new contactJS.Condition().withAttributeType(testA.getAttributeType()) - .withComparisonMethod(method2); - + var conditionTest = new contactJS.Condition().withAttributeType(testA).withComparisonMethod(method); + var conditionTest2 = new contactJS.Condition().withAttributeType(testA).withComparisonMethod(method); + var conditionTest3 = new contactJS.Condition().withAttributeType(testA).withComparisonMethod(method2); assert.ok( conditionTest.equals(conditionTest2),"Passed!: equals -> true" ); assert.ok( !conditionTest.equals(conditionTest3),"Passed!: equals -> false" ); diff --git a/qunitTest/configTest.js b/qunitTest/configTest.js index 28ec310a769314664c12f2b90f1ae5a9df2dbfcb..1a7c6ea14e568b031ab55b2150cd4143d0ff7293 100644 --- a/qunitTest/configTest.js +++ b/qunitTest/configTest.js @@ -8,6 +8,7 @@ requirejs.config({ jquery: '../libs/jquery/jquery', easejs: '../libs/ease.js/ease-full', MathUuid: '../libs/uuid/Math.uuid', + qunit: "../libs/qunit/qunit", contactJS: '../dist/contactJS' }, @@ -17,10 +18,9 @@ requirejs.config({ }, 'jquery' : { exports : '$' - }, + }, 'MathUuid' : { exports : 'MathUuid' - } + } } - }); \ No newline at end of file diff --git a/qunitTest/discovererTest.js b/qunitTest/discovererTest.js index ef6be7507d8e1ac985fed2f6927fc45bbd4f72d2..dcbd9984a1d3de9c5c481449e0bca2e15302ddb1 100644 --- a/qunitTest/discovererTest.js +++ b/qunitTest/discovererTest.js @@ -2,13 +2,13 @@ require(['configTest'], function() { require(['contactJS', '../examples/AddressInterpreter', '../examples/GeoLocationWidget'], function(contactJS, AddressInterpreter, GeoLocationWidget){ - QUnit.test( "Discoverer", function( assert ) { + QUnit.test("Discoverer", function(assert) { var discoverer = new contactJS.Discoverer(); //type - assert.equal( discoverer.getType(), 'Discoverer',"Passed!: type -> Discoverer" ); + assert.equal(discoverer.getType(), 'Discoverer', "Passed!: type -> Discoverer" ); //register Widget - var geo = new GeoLocationWidget(discoverer); + new GeoLocationWidget(discoverer); //initWidgets ->geoLocationWidget expected //tested with getWidgetDescriptions @@ -31,7 +31,8 @@ require(['configTest'], function() { assert.equal( widget2.getName(), 'GeoLocationWidget',"getComponent passed!: name of the instance is te expected one" ); //register Interpreter - var testInterpreter = new AddressInterpreter(discoverer); + new AddressInterpreter(discoverer); + //tested with getWidgetDescriptions var iDescs = discoverer.getDescriptions([contactJS.Interpreter]); assert.equal( iDescs.length, 1,"getInterpreterDescriptions passed!: One Interpreter is registered" ); @@ -52,7 +53,7 @@ require(['configTest'], function() { //register Aggregator new contactJS.Aggregator(discoverer, [ - new contactJS.AttributeType().withName('formattedAddress').withType('string') + new contactJS.Attribute().withName('formattedAddress').withType('string') ]); //tested with getWidgetDescriptions var aDescs = discoverer.getDescriptions([contactJS.Aggregator]); @@ -75,12 +76,10 @@ require(['configTest'], function() { //getComponentByAttribute var testParameter = new contactJS.Parameter().withKey('foo').withValue('bar'); - var latitudeType = new contactJS.AttributeType().withName('latitude') - .withType('double').withParameter(testParameter); - var longitudeType = new contactJS.AttributeType().withName('longitude') - .withType('double'); - var array = []; - array.push(longitudeType); + var latitudeType = new contactJS.Attribute().withName('latitude').withType('double').withParameter(testParameter); + var longitudeType = new contactJS.Attribute().withName('longitude').withType('double'); + + var array = [longitudeType]; //one searched attribute var list = discoverer.getComponentsByAttributes(array, false); diff --git a/qunitTest/interpret_AggregatorInterpreterTest.js b/qunitTest/interpret_AggregatorInterpreterTest.js index bc2c4b7df67e4e368798a2e9435cdf14db548837..6c96a4d2835f2ec83b2fb5e74c238c93c0207cc7 100644 --- a/qunitTest/interpret_AggregatorInterpreterTest.js +++ b/qunitTest/interpret_AggregatorInterpreterTest.js @@ -8,46 +8,41 @@ require(['configTest'], function() { var discoverer = new contactJS.Discoverer(); new GeoLocationWidget(discoverer); new AddressInterpreter(discoverer); + + var formattedAddressType = new contactJS.Attribute().withName('formattedAddress').withType('string'); + var testAggregator = new contactJS.Aggregator(discoverer, [ - new contactJS.AttributeType().withName('formattedAddress').withType('string') + formattedAddressType ]); var interpreter = discoverer.getDescriptions([contactJS.Interpreter]); //put data into aggregator - var latitudeValue = new contactJS.AttributeValue().withName('latitude') - .withType('double').withValue(52.3992404); - var longitudeValue = new contactJS.AttributeValue().withName('longitude') - .withType('double').withValue(13.066132); + var latitudeValue = new contactJS.Attribute().withName('latitude').withType('double').withValue(52.3992404); + var longitudeValue = new contactJS.Attribute().withName('longitude').withType('double').withValue(13.066132); - var list = new contactJS.AttributeValueList(); - list.put(latitudeValue); - list.put(longitudeValue); + var list = new contactJS.AttributeList().withItems([latitudeValue, longitudeValue]); testAggregator.putData(list); //if aggregator provides more attributes - var typeList = new contactJS.AttributeTypeList(); - typeList.put(latitudeValue.getAttributeType()); - typeList.put(longitudeValue.getAttributeType()); - + var typeList = new contactJS.AttributeList().withItems([latitudeValue, longitudeValue]); + var aggData = testAggregator.getCurrentData(); var data = aggData.getSubset(typeList); assert.equal( data.size(), 2, "Passed!: two available attributes" ); //call Interpreter - var callFunktion = function(){ - var interpret = testAggregator.getInterpretedData(interpreter[0].getId()); - var formattedAddress = interpret.getOutAttributes(); - testAggregator.addAttribute(formattedAddress.getItem('formattedAddress')); + var callFunktion = function(interpret){ + testAggregator.addAttribute(interpret.getAttributeWithTypeOf(formattedAddressType)); var data2 = testAggregator.getCurrentData(); assert.equal( data2.size(), 3,"Passed!: three available attributes" ); - var item = data2.getItem('(formattedAddress:string)'); + var item = data2.getAttributeWithTypeOf(formattedAddressType); assert.ok(item,"Callback passed!: interpreted data exists" ); var add = "Charlottenstraße 70, 14467 Potsdam, Deutschland"; assert.equal(item.getValue(), add ,"Passed!: interpreted data equals expected value" ); }; - testAggregator.interpretData(interpreter[0].getId(), function () {callFunktion(); QUnit.start();}); + testAggregator.interpretData(interpreter[0].getId(), typeList, new contactJS.AttributeList().withItems([formattedAddressType]), function (result) {callFunktion(result); QUnit.start();}); }); diff --git a/qunitTest/interpreterTest.js b/qunitTest/interpreterTest.js index d09b6a5c88e795f2620c21a161c432e5f2b76ca6..ad95cfeb35b31028145f3dcf4239e7eae6560a02 100644 --- a/qunitTest/interpreterTest.js +++ b/qunitTest/interpreterTest.js @@ -3,33 +3,31 @@ require(['configTest'], function() { function(AddressInterpreter, contactJS){ QUnit.asyncTest( "AddressInterpreter", function( assert ) { - var testInterpreter = new AddressInterpreter(); + var discoverer = new contactJS.Discoverer(); + var testInterpreter = new AddressInterpreter(discoverer); var id = testInterpreter.getId(); assert.ok( id && id !== "null" && id !== "undefined","Passed!: id is not null" ); assert.equal( testInterpreter.getType(), 'Interpreter',"Passed!: type -> Interpreter" ); //getInAttributeTypes - var latitudeType = new contactJS.AttributeType().withName('latitude') - .withType('double'); - var longitudeType = new contactJS.AttributeType().withName('longitude') - .withType('double'); - var inTypes = testInterpreter.getInAttributeTypes(); + var latitudeType = new contactJS.Attribute().withName('latitude').withType('double'); + var longitudeType = new contactJS.Attribute().withName('longitude').withType('double'); + var inTypes = testInterpreter.getInAttributes(); assert.ok( inTypes.size() == 2,"Passed!: 2 defined type in addressInterpreter" ); - assert.ok( inTypes.getItem('(latitude:double)'),"Passed!:type latitude exists" ); - assert.ok( inTypes.getItem('(latitude:double)').equals(latitudeType),"Passed!:type latitude equals expected type" ); - assert.ok( inTypes.getItem('(longitude:double)'),"Passed!:type longitude exists" ); - assert.ok( inTypes.getItem('(longitude:double)').equals(longitudeType),"Passed!: longitude equals expected type" ); + assert.ok( inTypes.getAttributeWithTypeOf(latitudeType),"Passed!:type latitude exists" ); + assert.ok( inTypes.getAttributeWithTypeOf(latitudeType).equalsTypeOf(latitudeType),"Passed!:type latitude equals expected type" ); + assert.ok( inTypes.getAttributeWithTypeOf(longitudeType),"Passed!:type longitude exists" ); + assert.ok( inTypes.getAttributeWithTypeOf(longitudeType).equalsTypeOf(longitudeType),"Passed!: longitude equals expected type" ); //getOutAttributeTypes - var formattedAddress = new contactJS.AttributeType().withName('formattedAddress').withType('string'); - var outTypes = testInterpreter.getOutAttributeTypes(); + var formattedAddress = new contactJS.Attribute().withName('formattedAddress').withType('string'); + var outTypes = testInterpreter.getOutAttributes(); assert.ok( outTypes.size() == 1,"Passed!: 1 defined outType in addressInterpreter" ); - assert.ok( outTypes.getItem('(formattedAddress:string)'),"Passed!: formattedAddress exists" ); - assert.ok( outTypes.getItem('(formattedAddress:string)').equals(formattedAddress),"Passed!: formattedAddress equals expected type" ); - - + assert.ok( outTypes.getAttributeWithTypeOf(formattedAddress),"Passed!: formattedAddress exists" ); + assert.ok( outTypes.getAttributeWithTypeOf(formattedAddress).equalsTypeOf(formattedAddress),"Passed!: formattedAddress equals expected type" ); + //interpreterDescription var desc = testInterpreter.getDescription(); assert.ok( desc,"Passed!: InterpreterDescription exists" ); @@ -40,34 +38,25 @@ require(['configTest'], function() { //callInterpreter && getInterpretedData with callback - var latitudeValue = new contactJS.AttributeValue().withName('latitude') - .withType('double').withValue(52.3992404); - var longitudeValue = new contactJS.AttributeValue().withName('longitude') - .withType('double').withValue(13.066132); - - var array = []; - array.push(latitudeValue); - array.push(longitudeValue); - var attributeList = new contactJS.AttributeValueList().withItems(array); + var latitudeValue = new contactJS.Attribute().withName('latitude').withType('double').withValue(52.3992404); + var longitudeValue = new contactJS.Attribute().withName('longitude').withType('double').withValue(13.066132); + + var attributeList = new contactJS.AttributeList().withItems([latitudeValue, longitudeValue]); - var assertData2 = function(){ - var result = testInterpreter.getInterpretedData(); - var data = result.getOutAttributes(); - var data2 = result.getInAttributes(); - assert.ok( testInterpreter.getLastInterpretionTime(),"Callback passed!: getLastInterpretionTime exists" ); - assert.equal(data.size(), 1, "Callback passed!: one outAttribute"); - assert.equal(data2.size(), 2, "Callback passed!: two inAttributes"); - var list = data.getItems(); - for(var i in list){ + var assertData2 = function(result){ + assert.ok(testInterpreter.getLastInterpretionTime(),"Callback passed!: getLastInterpretionTime exists" ); + assert.equal(result.size(), 1, "Callback passed!: one outAttribute"); + var list = result.getItems(); + for(var i in list){ var att = list[i]; assert.ok(att,"Callback passed!: interpreted data exists" ); - assert.ok(att.getAttributeType().equals(formattedAddress),"Callback passed!: interpreted data equals expected type" ); + assert.ok(att.equalsTypeOf(formattedAddress),"Callback passed!: interpreted data equals expected type" ); var add = "Charlottenstraße 70, 14467 Potsdam, Deutschland"; assert.equal(att.getValue(), add ,"Passed!: interpreted data equals expected value" ); } }; - testInterpreter.callInterpreter(attributeList, function () {assertData2(); QUnit.start();}); + testInterpreter.callInterpreter(attributeList, outTypes, function (result) {assertData2(result); QUnit.start();}); }); diff --git a/qunitTest/notify_AggregatorWidgetTest.js b/qunitTest/notify_AggregatorWidgetTest.js index a4d9e06e35e670395cd2f966b0b18ad1f4b6f1df..082a056d270fcd011243badcfb2eb1346ff9d491 100644 --- a/qunitTest/notify_AggregatorWidgetTest.js +++ b/qunitTest/notify_AggregatorWidgetTest.js @@ -6,10 +6,8 @@ require(['configTest'], function() { var discoverer = new contactJS.Discoverer(); new GeoLocationWidget(discoverer); - var latitudeType = new contactJS.AttributeType().withName('latitude') - .withType('double'); - var longitudeType = new contactJS.AttributeType().withName('longitude') - .withType('double'); + var latitudeType = new contactJS.Attribute().withName('latitude').withType('double'); + var longitudeType = new contactJS.Attribute().withName('longitude').withType('double'); //initializes the Infrastructure var testAggregator = new contactJS.Aggregator(discoverer, [ @@ -21,11 +19,11 @@ require(['configTest'], function() { var checkValues = function(newValues){ assert.equal( newValues.size(), 2,"notify Passed!: two available attributes" ); - var latitude = newValues.getItem('(latitude:double)'); + var latitude = newValues.getAttributeWithTypeOf(latitudeType); assert.equal(latitude.getName(), 'latitude', "notify Passed!: latitude exists" ); assert.notEqual(latitude.getValue(), 'undefined', "notify Passed!: value of latitude is no longer undefined" ); - var longitude = newValues.getItem('(longitude:double)'); + var longitude = newValues.getAttributeWithTypeOf(longitudeType); assert.equal(longitude.getName(), 'longitude',"notify Passed!: longitude exists" ); assert.notEqual(longitude.getValue(), 'undefined',"notify Passed!: value of longitude is no longer undefined" ); }; diff --git a/qunitTest/qunitTest.html b/qunitTest/qunitTest.html index 57b856e3d52e0dee487a36ee9ed4e116b4a50611..64ae942d58261659276762768300f88aaf18b768 100644 --- a/qunitTest/qunitTest.html +++ b/qunitTest/qunitTest.html @@ -3,13 +3,12 @@ <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>QUnit contactJS</title> -<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.15.0.css"> +<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.18.0.css"> </head> <body> <div id="qunit"></div> <div id="qunit-fixture"></div> <script data-main="test" src="../libs/require.js/require.js"></script> -<script src="../libs/qunit/qunit.js"></script> <script src="parameterTest.js"></script> <script src="parameterListTest.js"></script> <script src="attributeTypeTest.js"></script> diff --git a/qunitTest/storageTableContentTest.js b/qunitTest/storageTableContentTest.js index 88d1c7b4e4f7e1056582c65cf126b609d66bcc0c..321a41c83c69d9b1aa3e23d06c57e9dd19a08d2d 100644 --- a/qunitTest/storageTableContentTest.js +++ b/qunitTest/storageTableContentTest.js @@ -6,35 +6,29 @@ require(['configTest'], function() { var discoverer = new contactJS.Discoverer(); //initializes the test environment var testAggregator = new contactJS.Aggregator(discoverer, [ - new contactJS.AttributeType().withName('latitude').withType('double'), - new contactJS.AttributeType().withName('longitude').withType('double') + new contactJS.Attribute().withName('latitude').withType('double'), + new contactJS.Attribute().withName('longitude').withType('double') ]); //put data into aggregator - var latitudeValue = new contactJS.AttributeValue().withName('latitude').withType('double').withValue(52.3992404); - var longitudeValue = new contactJS.AttributeValue().withName('longitude').withType('double').withValue(13.066132); + var latitudeValue = new contactJS.Attribute().withName('latitude').withType('double').withValue(52.3992404); + var longitudeValue = new contactJS.Attribute().withName('longitude').withType('double').withValue(13.066132); - var list = new contactJS.AttributeValueList(); - list.put(latitudeValue); - list.put(longitudeValue); - testAggregator.putData(list); + testAggregator.putData(new contactJS.AttributeList().withItems([latitudeValue, longitudeValue])); var data = testAggregator.getCurrentData(); assert.equal(data.size(), 2, "Passed!: two available attributes"); var assertion = function(){ var retrievalResult = testAggregator.retrieveStorage(); - assert.ok(retrievalResult,"Passed!: retrievalResult exists"); - assert.equal(retrievalResult.getName(), 'latitude', "Passed!: name of retrievalResult is latitude"); + assert.ok(retrievalResult ,"Passed!: retrievalResult exists"); + assert.equal(retrievalResult.getName(), '(latitude:double)', "Passed!: name of retrievalResult is latitude"); var data = retrievalResult.getValues(); assert.ok(data,"Passed!: entries exists" ); - assert.equal(data[0].getName(), 'latitude', "Passed!: attributes name is latitude"); + assert.equal(data[0].getName(), '(latitude:double)', "Passed!: attributes name is latitude"); }; - testAggregator.queryAttribute('latitude', function () {assertion(); QUnit.start();}); + testAggregator.queryAttribute('(latitude:double)', function () {assertion(); QUnit.start();}); }); - - - }); }); \ No newline at end of file diff --git a/qunitTest/storageTableTest.js b/qunitTest/storageTableTest.js index b79bbba5adde76d31d1fb22548a3d5f0f6665cd9..b730e1c2f08b6d0b045cd61ce3d1256bdd97efe4 100644 --- a/qunitTest/storageTableTest.js +++ b/qunitTest/storageTableTest.js @@ -7,18 +7,15 @@ require(['configTest'], function() { var discoverer = new contactJS.Discoverer(); //initializes the test environment var testAggregator = new contactJS.Aggregator(discoverer, [ - new contactJS.AttributeType().withName('latitude').withType('double'), - new contactJS.AttributeType().withName('longitude').withType('double') + new contactJS.Attribute().withName('latitude').withType('double'), + new contactJS.Attribute().withName('longitude').withType('double') ]); //put data into aggregator - var latitudeValue = new contactJS.AttributeValue().withName('latitude') - .withType('double').withValue(52.3992404); - var longitudeValue = new contactJS.AttributeValue().withName('longitude') - .withType('double').withValue(13.066132); - var list = new contactJS.AttributeValueList(); - list.put(latitudeValue); - list.put(longitudeValue); + var latitudeValue = new contactJS.Attribute().withName('latitude').withType('double').withValue(52.3992404); + var longitudeValue = new contactJS.Attribute().withName('longitude').withType('double').withValue(13.066132); + + var list = new contactJS.AttributeList().withItems([latitudeValue, longitudeValue]); testAggregator.putData(list); var data = testAggregator.getCurrentData(); @@ -30,10 +27,8 @@ require(['configTest'], function() { assert.notEqual(jQuery.inArray('latitude', tables), '-1', "Passed!: table latitude exists" ); assert.notEqual(jQuery.inArray('longitude', tables), '-1', "Passed!: table longitude exists" ); }; + testAggregator.queryTables(function () {assertion(); QUnit.start();}); }); - - - }); }); \ No newline at end of file diff --git a/qunitTest/subscriberListTest.js b/qunitTest/subscriberListTest.js index 41a04e266ced72c71396aebdc69b562f28be9232..d6d7dba50ae5155e0215ea9484da403cab18e20d 100644 --- a/qunitTest/subscriberListTest.js +++ b/qunitTest/subscriberListTest.js @@ -4,34 +4,27 @@ require(['configTest'], function() { QUnit.test( "SubscriberList", function( assert ) { - var attributeType2 = new contactJS.AttributeType().withName('testName'). - withType('integer'); - var attArray = new Array(); - attArray.push(attributeType2); - var attList = new contactJS.AttributeTypeList().withItems(attArray); - var call = new contactJS.Callback().withName('test').withAttributeTypes(attList); - - var callArray = new Array(); - callArray.push(call); - var callList = new contactJS.CallbackList().withItems(callArray); + var attributeType2 = new contactJS.Attribute().withName('testName').withType('integer'); + + var attList = new contactJS.AttributeList().withItems([attributeType2]); + + var call = new contactJS.Callback().withName('test').withAttributeTypes(attList); + var callList = new contactJS.CallbackList().withItems([call]); - var subscriber = new contactJS.Subscriber().withSubscriberName('test') + var subscriber = new contactJS.Subscriber().withSubscriberName('test') .withSubscriberId('test') .withSubscriptionCallbacks(callList) .withAttributesSubset(attList); - var subscriber2 = new contactJS.Subscriber().withSubscriberName('test1') + var subscriber2 = new contactJS.Subscriber().withSubscriberName('test1') .withSubscriberId('test1') .withSubscriptionCallbacks(callList) .withAttributesSubset(attList); - var subscriber3 = new contactJS.Subscriber().withSubscriberName('test2') + var subscriber3 = new contactJS.Subscriber().withSubscriberName('test2') .withSubscriberId('test2') .withSubscriptionCallbacks(callList); - - var array = new Array(); - array.push(subscriber2); - array.push(subscriber3); - var list = new contactJS.SubscriberList().withItems(array); + + var list = new contactJS.SubscriberList().withItems([subscriber2, subscriber3]); assert.ok( list.size() == 2, "Passed!: Builder (withItems)" ); var list2 = new contactJS.SubscriberList(); @@ -39,7 +32,7 @@ require(['configTest'], function() { assert.ok( list2.size() == 1, "Passed!: Put type to list (put)" ); - list2.putAll(array); + list2.putAll([subscriber2, subscriber3]); assert.ok( list2.size() == 3, "Passed!: Put another two type to list (putAll)" ); //contains diff --git a/qunitTest/subscriberTest.js b/qunitTest/subscriberTest.js index 75abec3856c38a43b66f3627138d034c117a8a7c..59bf91625ef828193a9661900e23bf5c232d8cbe 100644 --- a/qunitTest/subscriberTest.js +++ b/qunitTest/subscriberTest.js @@ -5,20 +5,15 @@ require(['configTest'], function() { var parameter = new contactJS.Parameter().withKey('testKey').withValue('testValue'); - var attributeType = new contactJS.AttributeType(); - var attributeType2 = new contactJS.AttributeType().withName('testName'). - withType('integer').withParameter(parameter); - var attArray = new Array(); - attArray.push(attributeType); - var attList = new contactJS.AttributeTypeList().withItems(attArray); - - attArray.push(attributeType2); - var attList2 = new contactJS.AttributeTypeList().withItems(attArray); + var attributeType = new contactJS.Attribute(); + var attributeType2 = new contactJS.Attribute().withName('testName').withType('integer').withParameter(parameter); + + var attList = new contactJS.AttributeList().withItems([attributeType]); + var attList2 = new contactJS.AttributeList().withItems([attributeType, attributeType2]); + var call = new contactJS.Callback().withName('test').withAttributeTypes(attList2); - - var callArray = new Array(); - callArray.push(call); - var callList = new contactJS.CallbackList().withItems(callArray); + + var callList = new contactJS.CallbackList().withItems([call]); var subscriber = new contactJS.Subscriber().withSubscriberName('test') .withSubscriberId('test2') @@ -29,13 +24,14 @@ require(['configTest'], function() { .withSubscriberId('test2') .withSubscriptionCallbacks(callList) .withAttributesSubset(attList); + var subscriber3 = new contactJS.Subscriber().withSubscriberName('test') .withSubscriberId('test3') .withSubscriptionCallbacks(callList); + var test = subscriber.getAttributesSubset(); - - - assert.ok(test.size() == 1,"Passed!: AttributeSubset.size() == 1"); + + assert.equal(test.size(), 1, "Passed!: AttributeSubset.size() == 1"); assert.ok( subscriber.equals(subscriber2),"Passed!: equals -> true" ); assert.ok( !subscriber.equals(subscriber3),"Passed!: equals -> false" ); diff --git a/qunitTest/test.js b/qunitTest/test.js index 9d1f608e9ebcb0cef5eb72c8749bb694d3331ec7..e84aa1ec4a99c301c7da56d7d0f17187b9d2f5b3 100644 --- a/qunitTest/test.js +++ b/qunitTest/test.js @@ -1,6 +1,6 @@ -require(['configTest'], function() { +require(['configTest', 'qunit'], function() { + QUnit.start(); QUnit.test( "hello test", function( assert ) { assert.ok( 1 == "1", "Passed!" ); }); - }); diff --git a/qunitTest/widgetTest.js b/qunitTest/widgetTest.js index d0d36310592e9c22f9b1109e5fe1d5d11189f100..b042e5895d4650b4b658ab02c0ea2b661814700d 100644 --- a/qunitTest/widgetTest.js +++ b/qunitTest/widgetTest.js @@ -5,16 +5,19 @@ require(['configTest'], function() { QUnit.asyncTest( "GeoLocationWidget ", function( assert ) { var discoverer = new contactJS.Discoverer(); var testWidget = new GeoLocationWidget(discoverer); - + + var latitudeType = new contactJS.Attribute().withName('latitude').withType('double'); + var longitudeType = new contactJS.Attribute().withName('longitude').withType('double'); + var id = testWidget.getId(); assert.ok( id && id !== "null" && id !== "undefined", "Passed!: id is not null" ); assert.equal( testWidget.getType(), 'Widget', "Passed!: type -> Widget" ); assert.equal( testWidget.getName(), 'GeoLocationWidget', "Passed!: name -> GeoLocationWidget" ); //attributeTypes - var types = testWidget.getAttributeTypes(); + var types = testWidget.getAttributes(); assert.equal(types.size(), 2,"getWidgetAttributeTypes Passed!: two types were returned" ); - var constantTypes = testWidget.getWidgetConstantAttributeTypes(); + var constantTypes = testWidget.getConstantAttributes(); assert.equal(constantTypes.size(), 0,"getWidgetConstantAttributeTypes Passed!: zero constantTypes was returned" ); //callbacks @@ -26,36 +29,36 @@ require(['configTest'], function() { assert.equal(subscriber.size(), 0,"getSubscriber Passed!: zero subscriber was returned" ); //attributes - var attributes= testWidget.getAttributeValues(); + var attributes = testWidget.getAttributes(); assert.equal(attributes.size(), 2,"queryAttributes Passed!: two attributes were returned" ); - var latitude = attributes.getItem('(latitude:double)'); + var latitude = attributes.getAttributeWithTypeOf(latitudeType); assert.equal(latitude.getName(), 'latitude',"queryAttributes Passed!: latitude exists" ); - assert.equal(latitude.getValue(), 'undefined',"queryAttributes Passed!: value of latitude is undefined" ); + assert.equal(latitude.getValue(), 'NO_VALUE',"queryAttributes Passed!: value of latitude is undefined" ); - var longitude = attributes.getItem('(longitude:double)'); + var longitude = attributes.getAttributeWithTypeOf(longitudeType); assert.equal(longitude.getName(), 'longitude',"queryAttributes Passed!: longitude exists" ); - assert.equal(longitude.getValue(), 'undefined',"queryAttributes Passed!: value of longitude is undefined" ); + assert.equal(longitude.getValue(), 'NO_VALUE',"queryAttributes Passed!: value of longitude is undefined" ); //updateAndQuery without callback var attributes2 = testWidget.updateAndQueryWidget(); assert.equal(attributes2.size(), 2,"updateAndQueryWidget without callback Passed!: two attributes were returned" ); - var latitude2 = attributes2.getItem('(latitude:double)'); + var latitude2 = attributes2.getAttributeWithTypeOf(latitudeType); assert.equal(latitude2.getName(), 'latitude',"updateAndQueryWidget without callbackPassed!: latitude exists" ); - assert.equal(latitude2.getValue(), 'undefined',"value of latitude is not updated yet: " +latitude2.getValue() ); + assert.equal(latitude2.getValue(), 'NO_VALUE',"value of latitude is not updated yet: " +latitude2.getValue() ); - var longitude2 = attributes.getItem('(longitude:double)'); + var longitude2 = attributes.getAttributeWithTypeOf(longitudeType); assert.equal(longitude2.getName(), 'longitude',"updateAndQueryWidget without callbackPassed!: longitude exists" ); - assert.equal(longitude2.getValue(), 'undefined',"value of longitude is not updated yet: " + longitude2.getValue() ); + assert.equal(longitude2.getValue(), 'NO_VALUE',"value of longitude is not updated yet: " + longitude2.getValue() ); //updateAndQuery with callback var testUpdateAndQuery = function(){ var attributes2 = testWidget.queryWidget(); assert.equal(attributes2.size(), 2, "updateAndQueryWidget with callback Passed!: two attributes were returned" ); - var latitude2 = attributes2.getItem('(latitude:double)'); + var latitude2 = attributes2.getAttributeWithTypeOf(latitudeType); assert.equal(latitude2.getName(), 'latitude', "updateAndQueryWidget with callback Passed!: latitude exists" ); assert.notEqual(latitude2.getValue(), 'undefined', "value of latitude is: " +latitude2.getValue() ); - var longitude2 = attributes.getItem('(longitude:double)'); + var longitude2 = attributes.getAttributeWithTypeOf(longitudeType); assert.equal(longitude2.getName(), 'longitude',"updateAndQueryWidget with callback Passed!: longitude exists" ); assert.notEqual(longitude2.getValue(), 'undefined', "value of longitude is: " + longitude2.getValue() ); };