From 6be04c39ed4f0aef8923443399e37e989f5a2897 Mon Sep 17 00:00:00 2001 From: Ahmed Zamil Date: Wed, 21 Jul 2021 12:18:01 +0300 Subject: [PATCH] 1.4.0 --- bin/esiur.dart | 65 +++- lib/builder.dart | 24 +- lib/esiur.dart | 1 + lib/src/Core/AsyncBag.dart | 19 +- lib/src/Core/AsyncQueue.dart | 2 +- lib/src/Core/AsyncReply.dart | 9 +- lib/src/Data/AutoList.dart | 297 ++++++++---------- lib/src/Data/Codec.dart | 49 ++- lib/src/Data/Guid.dart | 5 +- lib/src/Data/KeyList.dart | 172 ++++------ lib/src/Data/Record.dart | 2 +- lib/src/Net/IIP/DistributedConnection.dart | 44 ++- lib/src/Net/IIP/DistributedResource.dart | 62 ++-- lib/src/Net/IIP/DistributedServer.dart | 2 +- lib/src/Net/Sockets/TCPSocket.dart | 6 +- lib/src/Proxy/TemplateGenerator.dart | 171 +++++++--- lib/src/Resource/FactoryEntry.dart | 7 + lib/src/Resource/IResource.dart | 2 +- lib/src/Resource/Template/MemberTemplate.dart | 2 +- .../Resource/Template/PropertyTemplate.dart | 2 +- .../Resource/Template/TemplateDataType.dart | 4 +- .../Resource/Template/TemplateDescriber.dart | 11 +- lib/src/Resource/Template/TypeTemplate.dart | 99 +++--- lib/src/Resource/Warehouse.dart | 76 +++-- pubspec.lock | 21 ++ pubspec.yaml | 5 +- test/main.dart | 13 - 27 files changed, 659 insertions(+), 513 deletions(-) create mode 100644 lib/src/Resource/FactoryEntry.dart diff --git a/bin/esiur.dart b/bin/esiur.dart index 9d52f2a..0a901b9 100644 --- a/bin/esiur.dart +++ b/bin/esiur.dart @@ -1,19 +1,13 @@ -import 'package:args/args.dart'; +import 'dart:io'; -void main(List arguments) { +import 'package:args/args.dart'; +import 'package:pubspec_parse/pubspec_parse.dart'; +import '../lib/src/Proxy/TemplateGenerator.dart'; + +void main(List arguments) async { if (arguments.length == 0) { - // print help - print("Esiur package command line"); - print(""); - print("Usage: [arguments]"); - print(""); - print("Available commands:"); - print("\tget-template\tGet a template from an IIP link."); - print("\tversion: print esiur version."); - print(""); - print("Global options:"); - print("\t-u, --username\tAuthentication username"); - print("\t-p, --password\tAuthentication password"); + printUsage(); + return; } var cmd = arguments[0]; @@ -27,15 +21,54 @@ void main(List arguments) { var link = arguments[1]; final parser = ArgParser() - ..addFlag('username', abbr: 'u') - ..addFlag('password', abbr: 'p'); + ..addOption('username', abbr: 'u') + ..addOption('password', abbr: 'p') + ..addOption('dir', abbr: 'd'); var results = parser.parse(arguments.skip(2)); var username = results['username']; var password = results['password']; + var dir = results['dir']; + + //print("Username ${username} password ${password} dir ${dir}"); // make template + var destDir = + await TemplateGenerator.getTemplate(link, dir, username, password); + print("Generated directory `${destDir}`"); + + return; + } else if (cmd == "version") { + await printVersion(); + } else { + printUsage(); } } + +printUsage() { + // print help + print("Esiur package command line"); + print(""); + print("Usage: [arguments]"); + print(""); + print("Available commands:"); + print("\tget-template\tGet a template from an IIP link."); + print("\tversion: print esiur version."); + print(""); + print("Global options:"); + print("\t-u, --username\tAuthentication username"); + print("\t-p, --password\tAuthentication password"); + print("\t-d, --dir\tName of the directory to generate model inside."); +} + +printVersion() async { + var p = Platform.script.pathSegments; + var path = p.take(p.length - 2).join('/') + "/pubspec.yaml"; + var yaml = await File(path).readAsString(); + var pub = Pubspec.parse(yaml); + print("${pub.name} ${pub.version}"); + print("\t${pub.description}"); + print("\t${pub.homepage}"); +} diff --git a/lib/builder.dart b/lib/builder.dart index a88476e..018ded1 100644 --- a/lib/builder.dart +++ b/lib/builder.dart @@ -2,9 +2,9 @@ import 'package:source_gen/source_gen.dart'; import 'package:build/build.dart'; import 'package:yaml/yaml.dart'; -Builder iipService(BuilderOptions options) { - return LibraryBuilder(TemplateGenerator(), generatedExtension: '.info.dart'); -} +//Builder iipService(BuilderOptions options) { + //return LibraryBuilder(TemplateBuilder(), generatedExtension: '.info.dart'); +//} class TemplateBuilder implements Builder { //BuilderOptions options; @@ -36,12 +36,12 @@ class TemplateBuilder implements Builder { } } -class TemplateGenerator extends Generator { - @override - String generate(LibraryReader library, BuildStep buildStep) { - return ''' -// Source library: ${library.element.source.uri} -const Testinggggg = 3; -'''; - } -} +// class TemplateBuilder extends Generator { +// @override +// String generate(LibraryReader library, BuildStep buildStep) { +// return ''' +// // Source library: ${library.element.source.uri} +// const Testinggggg = 3; +// '''; +// } +// } diff --git a/lib/esiur.dart b/lib/esiur.dart index baf5845..1594476 100644 --- a/lib/esiur.dart +++ b/lib/esiur.dart @@ -14,6 +14,7 @@ export 'src/Resource/Template/MemberType.dart'; export 'src/Resource/Template/PropertyPermission.dart'; export 'src/Resource/Template/PropertyTemplate.dart'; export 'src/Resource/Template/TypeTemplate.dart'; +export 'src/Resource/Template/TemplateDescriber.dart'; // ----------------------------------------------------------------- // Core diff --git a/lib/src/Core/AsyncBag.dart b/lib/src/Core/AsyncBag.dart index a895129..6f2a93a 100644 --- a/lib/src/Core/AsyncBag.dart +++ b/lib/src/Core/AsyncBag.dart @@ -1,14 +1,16 @@ import 'AsyncReply.dart'; +import '../Resource/Warehouse.dart'; + class AsyncBag extends AsyncReply> { - List> _replies = new List>(); + List> _replies = >[]; List _results = []; int _count = 0; bool _sealedBag = false; Type arrayType; - + seal() { //print("SEALED"); @@ -16,7 +18,7 @@ class AsyncBag extends AsyncReply> { _sealedBag = true; - if (_results.length == 0) trigger(new List()); + if (_results.length == 0) trigger([]); for (var i = 0; i < _results.length; i++) { var k = _replies[i]; @@ -25,8 +27,15 @@ class AsyncBag extends AsyncReply> { k.then((r) { _results[index] = r; _count++; - //print("Seal ${_count}/${_results.length}"); - if (_count == _results.length) trigger(_results); + if (_count == _results.length) { + if (arrayType != null) { + var ar = Warehouse.createArray(arrayType); + _results.forEach(ar.add); + trigger(ar); + } else { + trigger(_results); + } + } }).error((ex) { triggerError(ex); }); diff --git a/lib/src/Core/AsyncQueue.dart b/lib/src/Core/AsyncQueue.dart index f4c3c0b..02884b7 100644 --- a/lib/src/Core/AsyncQueue.dart +++ b/lib/src/Core/AsyncQueue.dart @@ -3,7 +3,7 @@ library esiur; import 'AsyncReply.dart'; class AsyncQueue extends AsyncReply { - List> _list = new List>(); + List> _list = >[]; // object queueLock = new object(); diff --git a/lib/src/Core/AsyncReply.dart b/lib/src/Core/AsyncReply.dart index ba4e80d..e01a3f2 100644 --- a/lib/src/Core/AsyncReply.dart +++ b/lib/src/Core/AsyncReply.dart @@ -27,17 +27,16 @@ import 'AsyncException.dart'; import 'ProgressType.dart'; class AsyncReply implements Future { - List _callbacks = new List(); + List _callbacks = []; T _result; - List _errorCallbacks = - new List(); + List _errorCallbacks = []; List _progressCallbacks = - new List(); + []; - List _chunkCallbacks = new List(); + List _chunkCallbacks = []; bool _resultReady = false; AsyncException _exception; diff --git a/lib/src/Data/AutoList.dart b/lib/src/Data/AutoList.dart index 246a9be..472d296 100644 --- a/lib/src/Data/AutoList.dart +++ b/lib/src/Data/AutoList.dart @@ -2,198 +2,165 @@ import '../Core/IDestructible.dart'; import 'Codec.dart'; import 'dart:collection'; -class AutoList extends IDestructible with IterableMixin -{ +class AutoList extends IDestructible with IterableMixin { + List _list = []; - List _list = new List(); + ST _state; + bool _removableList; + sort(Function comparer) { + _list.sort(comparer); + } - ST _state; - bool _removableList; + Iterator get iterator => _list.iterator; - sort(Function comparer) - { - _list.sort(comparer); - } + /// + /// Convert AutoList to array + /// + /// Array + //List toList() + //{ + // list.OrderBy() + // return _list; + //} - Iterator get iterator => _list.iterator; + /// Create a new instance of AutoList + /// State object to be included when an event is raised. + AutoList([ST state, List values]) { + this._state = state; + this._removableList = Codec.implementsInterface(); + if (values != null) addRange(values); - /// - /// Convert AutoList to array - /// - /// Array - //List toList() - //{ - // list.OrderBy() - // return _list; - //} + register("modified"); + register("added"); + register("removed"); + register("cleared"); + } - - /// Create a new instance of AutoList - /// State object to be included when an event is raised. - AutoList([ST state, List values]) - { - this._state = state; - this._removableList = Codec.implementsInterface(); + /// + /// Synchronization lock of the list + /// + //public object SyncRoot + //{ + // get + // { + // return syncRoot; + // } + //} - if (values != null) - addRange(values); + /// + /// First item in the list + /// + //T first() + //{ + // return _list.first; + //} - register("modified"); - register("added"); - register("removed"); - register("cleared"); - } + operator [](index) { + return _list[index]; + } - + operator []=(index, value) { + var oldValue = _list[index]; - /// - /// Synchronization lock of the list - /// - //public object SyncRoot - //{ - // get - // { - // return syncRoot; - // } - //} + if (_removableList) { + if (oldValue != null) + (oldValue as IDestructible).off("destroy", _itemDestroyed); + if (value != null) value.on("destroy", _itemDestroyed); + } - /// - /// First item in the list - /// - //T first() - //{ - // return _list.first; - //} + //lock (syncRoot) + _list[index] = value; - operator [](index) - { - return _list[index]; - } + emitArgs("modified", [_state, index, oldValue, value]); + } - operator []=(index, value) - { - var oldValue = _list[index]; + /// + /// Add item to the list + /// + add(T value) { + if (_removableList) if (value != null) + (value as IDestructible).on("destroy", _itemDestroyed); - if (_removableList) - { - if (oldValue != null) - (oldValue as IDestructible).off("destroy", _itemDestroyed); - if (value != null) - value.on("destroy", _itemDestroyed); - } + // lock (syncRoot) + _list.add(value); - //lock (syncRoot) - _list[index] = value; + emitArgs("add", [_state, value]); + } - emitArgs("modified", [_state, index, oldValue, value]); - } + /// + /// Add an array of items to the list + /// + addRange(List values) { + values.forEach((x) => add(x)); + } - /// - /// Add item to the list - /// - add(T value) - { - if (_removableList) - if (value != null) - (value as IDestructible).on("destroy", _itemDestroyed); + _itemDestroyed(T sender) { + remove(sender); + } - // lock (syncRoot) - _list.add(value); + /// + /// Clear the list + /// + clear() { + if (_removableList) + _list + .forEach((x) => (x as IDestructible)?.off("destroy", _itemDestroyed)); - emitArgs("add",[_state, value]); - } - - /// - /// Add an array of items to the list - /// - addRange(List values) - { - values.forEach((x)=>add(x)); - } - - _itemDestroyed(T sender) - { - remove(sender); - } - - /// - /// Clear the list - /// - clear() - { - if (_removableList) - _list.forEach((x)=>(x as IDestructible)?.off("destroy", _itemDestroyed)); - - // lock (syncRoot) - _list.clear(); + _list.clear(); - emitArgs("cleared", [_state]); + emitArgs("cleared", [_state]); + } + + /// + /// Remove an item from the list + /// Item to remove + /// + remove(T value) { + if (!_list.contains(value)) return; + + if (_removableList) if (value != null) + (value as IDestructible).off("destroy", _itemDestroyed); + + //lock (syncRoot) + _list.remove(value); + + emitArgs("removed", [_state, value]); + } + + /// + /// Number of items in the list + /// + get count => _list.length; + get length => _list.length; + + /// + /// Check if an item exists in the list + /// + /// Item to check if exists + //contains(T value) => _list.contains(value); + + /// + /// Check if any item of the given array is in the list + /// + /// Array of items + containsAny(values) { + if (values is List) { + for (var v in values) { + if (_list.contains(v)) return true; } - - /// - /// Remove an item from the list - /// Item to remove - /// - remove(T value) - { - if (!_list.contains(value)) - return; - - if (_removableList) - if (value != null) - (value as IDestructible).off("destroy", _itemDestroyed); - - //lock (syncRoot) - _list.remove(value); - - emitArgs("removed", [_state, value]); + } else if (values is AutoList) { + for (var v in values._list) { + if (_list.contains(v)) return true; } + } - /// - /// Number of items in the list - /// - get count => _list.length; - get length => _list.length; - + return false; + } - /// - /// Check if an item exists in the list - /// - /// Item to check if exists - //contains(T value) => _list.contains(value); - - /// - /// Check if any item of the given array is in the list - /// - /// Array of items - containsAny(values) - { - - if (values is List) - { - for(var v in values) - { - if (_list.contains(v)) - return true; - } - } - else if (values is AutoList) - { - - for(var v in values._list) - { - if (_list.contains(v)) - return true; - } - } - - return false; - } - - @override + @override void destroy() { clear(); } diff --git a/lib/src/Data/Codec.dart b/lib/src/Data/Codec.dart index 98b9a19..dd7d08b 100644 --- a/lib/src/Data/Codec.dart +++ b/lib/src/Data/Codec.dart @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import 'package:esiur/src/Resource/Template/TemplateType.dart'; +import '../Resource/Template/TemplateType.dart'; import 'DataType.dart'; import 'Guid.dart'; @@ -78,10 +78,11 @@ class Codec { static List getStructureDateTypes( Structure structure, DistributedConnection connection) { var keys = structure.getKeys(); - var types = new List(keys.length); + var types = new List.generate( + keys.length, (i) => Codec.getDataType(structure[keys[i]], connection)); - for (var i = 0; i < keys.length; i++) - types[i] = Codec.getDataType(structure[keys[i]], connection); + // for (var i = 0; i < keys.length; i++) + // types[i] = Codec.getDataType(structure[keys[i]], connection); return types; } @@ -325,7 +326,7 @@ class Codec { record.deserialize(value); - reply.trigger(null); + reply.trigger(record); } else { var record = new Record(); @@ -336,8 +337,8 @@ class Codec { } }); } else { - connection.getTemplate(classId).then((tmp) { - parseVarArray(data, offset, length, connection).then((ar) { + connection.getTemplate(classId).then((tmp) { + parseVarArray(data, offset, length, connection).then((ar) { var record = new Record(); for (var i = 0; i < tmp.properties.length; i++) @@ -619,8 +620,8 @@ class Codec { { var reply = new AsyncReply(); var bag = new AsyncBag(); - var keylist = new List(); - var typelist = new List(); + var keylist = []; + var typelist = []; var sizeObject = new SizeObject(); if (keys == null) { @@ -888,10 +889,9 @@ class Codec { /// True, if the resource owner is the given connection, otherwise False. static bool isLocalResource( IResource resource, DistributedConnection connection) { - if (resource is DistributedResource) if ((resource as DistributedResource) - .connection == - connection) return true; - + if (resource is DistributedResource) { + if (resource.connection == connection) return true; + } return false; } @@ -1010,7 +1010,26 @@ class Codec { var end = offset + length; // - var result = data[offset++]; + + // Is typed array ? + var type = (data[offset] & 0xF0); + + var result = data[offset++] & 0xF; + + if (type == ResourceArrayType.Wrapper) { + var classId = data.getGuid(offset); + offset += 16; + var tmp = Warehouse.getTemplateByClassId(classId, TemplateType.Resource); + // not mine, look if the type is elsewhere + if (tmp == null) + Warehouse.getTemplateByClassId(classId, TemplateType.Wrapper); + reply.arrayType = tmp?.definedType; + } else if (type == ResourceArrayType.Static) { + var classId = data.getGuid(offset); + offset += 16; + var tmp = Warehouse.getTemplateByClassId(classId, TemplateType.Wrapper); + reply.arrayType = tmp?.definedType; + } AsyncReply previous = null; @@ -1036,7 +1055,7 @@ class Codec { } else if (result == ResourceComparisonResult.Same) { current = previous; } else if (result == ResourceComparisonResult.Local) { - current = Warehouse.get(data.getUint32(offset)); + current = Warehouse.getById(data.getUint32(offset)); offset += 4; } else if (result == ResourceComparisonResult.Distributed) { current = connection.fetch(data.getUint32(offset)); diff --git a/lib/src/Data/Guid.dart b/lib/src/Data/Guid.dart index a42431b..5b74928 100644 --- a/lib/src/Data/Guid.dart +++ b/lib/src/Data/Guid.dart @@ -9,7 +9,7 @@ class Guid { DC get value => _data; - bool operator ==(Object other) { + bool operator ==(other) { if (other is Guid) return _data.sequenceEqual(other._data); else @@ -20,4 +20,7 @@ class Guid { String toString() { return _data.getString(0, _data.length); } + + @override + int get hashCode => _data.toString().hashCode; } diff --git a/lib/src/Data/KeyList.dart b/lib/src/Data/KeyList.dart index 0720361..9794c83 100644 --- a/lib/src/Data/KeyList.dart +++ b/lib/src/Data/KeyList.dart @@ -27,130 +27,96 @@ import '../Core/IDestructible.dart'; import 'dart:collection'; import 'Codec.dart'; -class KeyList extends IEventHandler with MapMixin -{ +class KeyList extends IEventHandler with MapMixin { + dynamic owner; - dynamic owner; - - Map _map = new Map(); - - Iterator get iterator => _map.keys.iterator; + Map _map = new Map(); - Iterable get keys => _map.keys; - Iterable get values => _map.values; - + Iterator get iterator => _map.keys.iterator; - operator[](index) => _map[index]; + Iterable get keys => _map.keys; + Iterable get values => _map.values; - operator []= (index, value) => add(index, value); - + operator [](index) => _map[index]; - at(int index) => _map.values.elementAt(index); + operator []=(index, value) => add(index, value); - - bool _removableList; + at(int index) => _map.values.elementAt(index); + bool _removableList; - T take(KT key) - { - if (_map.containsKey(key)) - { - var v = _map[key]; - remove(key); - return v; - } - else - return null; + T take(KT key) { + if (_map.containsKey(key)) { + var v = _map[key]; + remove(key); + return v; + } else + return null; + } + + List toArray() => _map.values.toList(); + + void add(KT key, T value) { + if (_removableList) if (value != null) + (value as IDestructible).on("destroy", _itemDestroyed); + + if (_map.containsKey(key)) { + var oldValue = _map[key]; + if (_removableList) if (oldValue != null) + (oldValue as IDestructible).off("destroy", _itemDestroyed); + + _map[key] = value; + + emitArgs("modified", [key, oldValue, value, this]); + } else { + _map[key] = value; + + emitArgs("add", [value, this]); } + } - - List toArray() => _map.values.toList(); + _itemDestroyed(T sender) { + removeValue(sender); + } - void add(KT key, T value) - { - if (_removableList) - if (value != null) - (value as IDestructible).on("destroy", _itemDestroyed); + removeValue(T value) { + var toRemove = []; + for (var k in _map.keys) if (_map[k] == value) toRemove.add(k); - if (_map.containsKey(key)) - { - var oldValue = _map[key]; - if (_removableList) - if (oldValue != null) - (oldValue as IDestructible).off("destroy", _itemDestroyed); + for (var k in toRemove) remove(k); + } - _map[key] = value; + clear() { + if (_removableList) + for (var v in _map.values) + (v as IDestructible)?.off("destroy", _itemDestroyed); - emitArgs("modified", [key, oldValue, value, this]); - } - else - { - _map[key] = value; + _map.clear(); - emitArgs("add", [value, this]); + emitArgs("cleared", [this]); + } - } - - } + T remove(key) { + if (!_map.containsKey(key)) return null; - _itemDestroyed(T sender) - { - removeValue(sender); - } + var value = _map[key]; - removeValue(T value) - { - var toRemove = new List(); - for (var k in _map.keys) - if (_map[k] == value) - toRemove.add(k); + if (_removableList) + (value as IDestructible)?.off("destroy", _itemDestroyed); - for (var k in toRemove) - remove(k); - } + _map.remove(key); - clear() - { - if (_removableList) - for (var v in _map.values) - (v as IDestructible)?.off("destroy", _itemDestroyed); - - _map.clear(); + emitArgs("removed", [key, value, this]); - emitArgs("cleared", [this]); - - } + return value; + } + int get count => _map.length; + bool contains(KT key) => _map.containsKey(key); - T remove(key) - { - if (!_map.containsKey(key)) - return null; - - var value = _map[key]; - - if (_removableList) - (value as IDestructible)?.off("destroy", _itemDestroyed); - - - _map.remove(key); - - emitArgs("removed", [key, value, this]); - - return value; - } - - - - int get count => _map.length; - - bool contains(KT key) => _map.containsKey(key); - - - KeyList([owner = null]) - { - _removableList = Codec.implementsInterface(); - this.owner = owner; - } -} \ No newline at end of file + KeyList([owner = null]) { + _removableList = Codec.implementsInterface(); + this.owner = owner; + } +} diff --git a/lib/src/Data/Record.dart b/lib/src/Data/Record.dart index cb8fed6..8689466 100644 --- a/lib/src/Data/Record.dart +++ b/lib/src/Data/Record.dart @@ -1,4 +1,4 @@ -import 'package:esiur/src/Resource/Template/TemplateDescriber.dart'; +import '../Resource/Template/TemplateDescriber.dart'; import 'IRecord.dart'; import 'KeyList.dart'; diff --git a/lib/src/Net/IIP/DistributedConnection.dart b/lib/src/Net/IIP/DistributedConnection.dart index f2252c3..fa92116 100644 --- a/lib/src/Net/IIP/DistributedConnection.dart +++ b/lib/src/Net/IIP/DistributedConnection.dart @@ -22,13 +22,10 @@ SOFTWARE. */ -import 'dart:ffi'; -import 'dart:typed_data'; -import 'package:esiur/esiur.dart'; -import 'package:esiur/src/Resource/Template/TemplateDescriber.dart'; -import 'package:esiur/src/Resource/Template/TemplateType.dart'; -import 'package:esiur/src/Security/Authority/AuthenticationMethod.dart'; +import '../../Resource/Template/TemplateDescriber.dart'; +import '../../Resource/Template/TemplateType.dart'; +import '../../Security/Authority/AuthenticationMethod.dart'; import '../../Core/AsyncBag.dart'; @@ -44,7 +41,7 @@ import '../../Core/ExceptionCode.dart'; import '../../Core/ErrorType.dart'; import '../../Resource/Warehouse.dart'; -import '../Sockets/SocketState.dart'; + import 'dart:math'; import '../../Resource/IStore.dart'; import '../../Resource/IResource.dart'; @@ -434,9 +431,8 @@ class DistributedConnection extends NetworkConnection with IStore { String link(IResource resource) { if (resource is DistributedResource) { - var r = resource as DistributedResource; - if (r.instance.store == this) - return this.instance.name + "/" + r.id.toString(); + if (resource.instance.store == this) + return this.instance.name + "/" + resource.id.toString(); } return null; @@ -445,9 +441,9 @@ class DistributedConnection extends NetworkConnection with IStore { void init() { _queue.then((x) { if (x.type == DistributedResourceQueueItemType.Event) - x.resource.emitEventByIndex(x.index, x.value); + x.resource.internal_emitEventByIndex(x.index, x.value); else - x.resource.updatePropertyByIndex(x.index, x.value); + x.resource.internal_updatePropertyByIndex(x.index, x.value); }); var r = new Random(); @@ -663,8 +659,7 @@ class DistributedConnection extends NetworkConnection with IStore { case IIPPacketAction.TemplateFromClassName: case IIPPacketAction.TemplateFromClassId: case IIPPacketAction.TemplateFromResourceId: - iipReply( - packet.callbackId, [TypeTemplate.parse(packet.content)]); + iipReply(packet.callbackId, [TypeTemplate.parse(packet.content)]); break; case IIPPacketAction.QueryLink: @@ -1285,7 +1280,7 @@ class DistributedConnection extends NetworkConnection with IStore { .addUint16(link.length) .addDC(link) .addDC(Codec.composePropertyValueArray( - (r as DistributedResource).serialize(), this, true)) + (r as DistributedResource).internal_serialize(), this, true)) .done(); } else { // reply ok @@ -1883,7 +1878,7 @@ class DistributedConnection extends NetworkConnection with IStore { if (ft != null) { if (r is DistributedResource) { var rt = (r as DistributedResource) - .invokeByArrayArguments(index, arguments); + .internal_invokeByArrayArguments(index, arguments); if (rt != null) { rt.then((res) { sendReply(IIPPacketAction.InvokeFunctionArrayArguments, @@ -1922,7 +1917,7 @@ class DistributedConnection extends NetworkConnection with IStore { if (ft != null) { if (r is DistributedResource) { var rt = (r as DistributedResource) - .invokeByNamedArguments(index, namedArgs); + .internal_invokeByNamedArguments(index, namedArgs); if (rt != null) { rt.then((res) { sendReply(IIPPacketAction.InvokeFunctionNamedArguments, @@ -2215,8 +2210,7 @@ class DistributedConnection extends NetworkConnection with IStore { .done() .then((rt) { _templateRequests.remove(classId); - _templates[(rt[0] as TypeTemplate).classId] = - rt[0] as TypeTemplate; + _templates[(rt[0] as TypeTemplate).classId] = rt[0] as TypeTemplate; Warehouse.putTemplate(rt[0] as TypeTemplate); reply.trigger(rt[0]); }).error((ex) { @@ -2316,12 +2310,14 @@ class DistributedConnection extends NetworkConnection with IStore { DistributedResource dr; if (resource == null) { - var template = Warehouse.getTemplateByClassId(rt[0], TemplateType.Wrapper); + var template = + Warehouse.getTemplateByClassId(rt[0], TemplateType.Wrapper); if (template?.definedType != null) { dr = Warehouse.createInstance(template?.definedType); - dr.init(this, id, rt[1], rt[2]); + dr.internal_init(this, id, rt[1], rt[2]); } else { - dr = new DistributedResource(this, id, rt[1], rt[2]); + dr = new DistributedResource(); + dr.internal_init(this, id, rt[1], rt[2]); } } else dr = resource; @@ -2338,7 +2334,7 @@ class DistributedConnection extends NetworkConnection with IStore { Warehouse.put(id.toString(), dr, this, null, tmp).then((ok) { Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) { //print("attached"); - dr.attach(ar); + dr.internal_attach(ar); _resourceRequests.remove(id); reply.trigger(dr); }); @@ -2346,7 +2342,7 @@ class DistributedConnection extends NetworkConnection with IStore { } else { Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) { //print("attached"); - dr.attach(ar); + dr.internal_attach(ar); _resourceRequests.remove(id); reply.trigger(dr); }); diff --git a/lib/src/Net/IIP/DistributedResource.dart b/lib/src/Net/IIP/DistributedResource.dart index 1b47dc9..b6a96db 100644 --- a/lib/src/Net/IIP/DistributedResource.dart +++ b/lib/src/Net/IIP/DistributedResource.dart @@ -22,8 +22,13 @@ SOFTWARE. */ -import 'package:esiur/esiur.dart'; -import 'package:esiur/src/Data/KeyValuePair.dart'; +import '../../Core/AsyncException.dart'; +import '../../Core/ErrorType.dart'; +import '../../Core/ExceptionCode.dart'; + +import '../../Resource/ResourceTrigger.dart'; + +import '../../Data/KeyValuePair.dart'; import '../../Resource/IResource.dart'; import '../../Core/AsyncReply.dart'; @@ -33,6 +38,9 @@ import '../../Data/Codec.dart'; import './DistributedConnection.dart'; import '../Packets/IIPPacketAction.dart'; +import '../../Resource/Template/EventTemplate.dart'; + + class DistributedResource extends IResource { int _instanceId; DistributedConnection _connection; @@ -107,32 +115,28 @@ class DistributedResource extends IResource { /// Resource template. /// Instance Id given by the other end. /// Resource age. - DistributedResource( - DistributedConnection connection, int instanceId, int age, String link) { - this._link = link; - this._connection = connection; - this._instanceId = instanceId; - this._age = age; - } - void init( - DistributedConnection connection, int instanceId, int age, String link) { - this._link = link; - this._connection = connection; - this._instanceId = instanceId; - this._age = age; - } - - //void _ready() - //{ - // _isReady = true; + // DistributedResource( + // DistributedConnection connection, int instanceId, int age, String link) { + // this._link = link; + // this._connection = connection; + // this._instanceId = instanceId; + // this._age = age; // } + void internal_init( + DistributedConnection connection, int instanceId, int age, String link) { + this._link = link; + this._connection = connection; + this._instanceId = instanceId; + this._age = age; + } + /// /// Export all properties with ResourceProperty attributed as bytes array. /// /// - List serialize() { + List internal_serialize() { var props = new List(_properties.length); for (var i = 0; i < _properties.length; i++) @@ -142,7 +146,7 @@ class DistributedResource extends IResource { return props; } - bool attach(List properties) { + bool internal_attach(List properties) { if (_attached) return false; else { @@ -168,7 +172,7 @@ class DistributedResource extends IResource { if (_queued_updates.length > 0) { _queued_updates - .forEach((kv) => updatePropertyByIndex(kv.key, kv.value)); + .forEach((kv) => internal_updatePropertyByIndex(kv.key, kv.value)); _queued_updates.clear(); } } @@ -207,7 +211,7 @@ class DistributedResource extends IResource { return connection.sendUnlistenRequest(_instanceId, et.index); } - void emitEventByIndex(int index, dynamic args) { + void internal_emitEventByIndex(int index, dynamic args) { // neglect events when the object is not yet attached if (!_attached) return; @@ -217,7 +221,7 @@ class DistributedResource extends IResource { instance.emitResourceEvent(null, null, et.name, args); } - AsyncReply invokeByNamedArguments(int index, Structure namedArgs) { + AsyncReply internal_invokeByNamedArguments(int index, Structure namedArgs) { if (_destroyed) throw new Exception("Trying to access destroyed object"); if (_suspended) throw new Exception("Trying to access suspended object"); @@ -228,7 +232,7 @@ class DistributedResource extends IResource { return connection.sendInvokeByNamedArguments(_instanceId, index, namedArgs); } - AsyncReply invokeByArrayArguments(int index, List args) { + AsyncReply internal_invokeByArrayArguments(int index, List args) { if (_destroyed) throw new Exception("Trying to access destroyed object"); if (_suspended) throw new Exception("Trying to access suspended object"); @@ -270,9 +274,9 @@ class DistributedResource extends IResource { for (var p in invocation.namedArguments.keys) namedArgs[_getMemberName(p)] = invocation.namedArguments[p]; - return invokeByNamedArguments(ft.index, namedArgs); + return internal_invokeByNamedArguments(ft.index, namedArgs); } else { - return invokeByArrayArguments( + return internal_invokeByArrayArguments( ft.index, invocation.positionalArguments); } } @@ -304,7 +308,7 @@ class DistributedResource extends IResource { return _properties[index]; } - void updatePropertyByIndex(int index, dynamic value) { + void internal_updatePropertyByIndex(int index, dynamic value) { if (!_attached) { _queued_updates.add(KeyValuePair(index, value)); } else { diff --git a/lib/src/Net/IIP/DistributedServer.dart b/lib/src/Net/IIP/DistributedServer.dart index 16792c8..78e245e 100644 --- a/lib/src/Net/IIP/DistributedServer.dart +++ b/lib/src/Net/IIP/DistributedServer.dart @@ -1,4 +1,4 @@ -import 'package:esiur/src/Resource/Template/TemplateDescriber.dart'; +import '../../Resource/Template/TemplateDescriber.dart'; import '../../Resource/IResource.dart'; import '../../Core/AsyncReply.dart'; diff --git a/lib/src/Net/Sockets/TCPSocket.dart b/lib/src/Net/Sockets/TCPSocket.dart index 56e773e..a78c8e3 100644 --- a/lib/src/Net/Sockets/TCPSocket.dart +++ b/lib/src/Net/Sockets/TCPSocket.dart @@ -23,7 +23,11 @@ SOFTWARE. */ import 'dart:io'; -import 'package:esiur/esiur.dart'; + +import '../../Core/ErrorType.dart'; +import '../../Core/ExceptionCode.dart'; + +import '../../Core/AsyncException.dart'; import 'ISocket.dart'; import '../../Data/DC.dart'; diff --git a/lib/src/Proxy/TemplateGenerator.dart b/lib/src/Proxy/TemplateGenerator.dart index e7fe427..a3e8398 100644 --- a/lib/src/Proxy/TemplateGenerator.dart +++ b/lib/src/Proxy/TemplateGenerator.dart @@ -10,19 +10,19 @@ import '../Resource/Template/TemplateDataType.dart'; import '../Resource/Template/TypeTemplate.dart'; class TemplateGenerator { -// static RegExp urlRegex = new RegExp("^(?:([\S]*)://([^/]*)/?)"); +// static RegExp urlRegex = RegExp("^(?:([\S]*)://([^/]*)/?)"); static final _urlRegex = RegExp(r'^(?:([^\s|:]*):\/\/([^\/]*)\/?(.*))'); static String generateRecord( TypeTemplate template, List templates) { var className = template.className.split('.').last; - var rt = new StringBuffer(); + var rt = StringBuffer(); rt.writeln("class ${className} extends IRecord {"); template.properties.forEach((p) { var ptTypeName = getTypeName(template, p.valueType, templates); - rt.writeln("${ptTypeName} ${p.name};"); + rt.writeln("${ptTypeName}? ${p.name};"); rt.writeln(); }); @@ -48,40 +48,78 @@ class TemplateGenerator { rt.writeln("return rt;"); rt.writeln("}"); + + // add template + var descProps = template.properties.map((p) { + var isArray = p.valueType.type & 0x80 == 0x80; + var ptType = p.valueType.type & 0x7F; + var ptTypeName = getTypeName( + template, TemplateDataType(ptType, p.valueType.typeGuid), templates); +// return "Prop(\"${p.name}\", ${ptTypeName}, ${isArray})"; + return "Prop('${p.name}', ${ptTypeName}, ${isArray}, ${_escape(p.readExpansion)}, ${_escape(p.writeExpansion)})"; + }).join(', '); + + rt.writeln("""@override + TemplateDescriber get template => TemplateDescriber('${template.className}', properties: [${descProps}]);"""); + rt.writeln("\r\n}"); return rt.toString(); } + static String _translateClassName(String className) { + var cls = className.split('.'); + var nameSpace = cls.take(cls.length - 1).join('_').toLowerCase(); + return "$nameSpace.${cls.last}"; + } + static String getTypeName(TypeTemplate forTemplate, TemplateDataType templateDataType, List templates) { if (templateDataType.type == DataType.Resource) { if (templateDataType.typeGuid == forTemplate.classId) return forTemplate.className.split('.').last; else { - var tmp = - templates.firstWhere((x) => x.classId == templateDataType.typeGuid); + var tmp = templates.firstWhere((x) => + x.classId == templateDataType.typeGuid && + (x.type == TemplateType.Resource || + x.type == TemplateType.Wrapper)); if (tmp == null) return "dynamic"; // something went wrong - var cls = tmp.className.split('.'); - var nameSpace = cls.take(cls.length - 1).join('_'); - - return "$nameSpace.${cls.last}"; + return _translateClassName(tmp.className); } } else if (templateDataType.type == DataType.ResourceArray) { if (templateDataType.typeGuid == forTemplate.classId) return "List<${forTemplate.className.split('.').last}>"; else { - var tmp = - templates.firstWhere((x) => x.classId == templateDataType.typeGuid); + var tmp = templates.firstWhere((x) => + x.classId == templateDataType.typeGuid && + (x.type == TemplateType.Resource || + x.type == TemplateType.Wrapper)); if (tmp == null) return "dynamic"; // something went wrong - var cls = tmp.className.split('.'); - var nameSpace = cls.take(cls.length - 1).join('_'); - - return "List<$nameSpace.${cls.last}>"; + return "List<${_translateClassName(tmp.className)}>"; + } + } else if (templateDataType.type == DataType.Record) { + if (templateDataType.typeGuid == forTemplate.classId) + return forTemplate.className.split('.').last; + else { + var tmp = templates.firstWhere((x) => + x.classId == templateDataType.typeGuid && + x.type == TemplateType.Record); + if (tmp == null) return "dynamic"; // something went wrong + return _translateClassName(tmp.className); + } + } else if (templateDataType.type == DataType.RecordArray) { + if (templateDataType.typeGuid == forTemplate.classId) + return "List<${forTemplate.className.split('.').last}>"; + else { + var tmp = templates.firstWhere((x) => + x.classId == templateDataType.typeGuid && + x.type == TemplateType.Record); + if (tmp == null) return "dynamic"; // something went wrong + return "List<${_translateClassName(tmp.className)}>"; } } @@ -104,7 +142,7 @@ class TemplateGenerator { case DataType.DecimalArray: return "List"; case DataType.Float32: - return "List"; + return "double"; case DataType.Float32Array: return "List"; case DataType.Float64: @@ -172,7 +210,7 @@ class TemplateGenerator { String username = null, String password = null]) async { try { - if (!_urlRegex.hasMatch(url)) throw new Exception("Invalid IIP URL"); + if (!_urlRegex.hasMatch(url)) throw Exception("Invalid IIP URL"); var path = _urlRegex.allMatches(url).first; var con = await Warehouse.get( @@ -181,12 +219,15 @@ class TemplateGenerator { ? {username: username, password: password} : null); - if (con == null) throw new Exception("Can't connect to server"); + if (con == null) throw Exception("Can't connect to server"); if (isNullOrEmpty(dir)) dir = path[2].replaceAll(":", "_"); var templates = await con.getLinkTemplates(path[3]); + // no longer needed + Warehouse.remove(con); + var dstDir = Directory("lib/$dir"); if (!dstDir.existsSync()) dstDir.createSync(); @@ -201,9 +242,8 @@ class TemplateGenerator { templates.forEach((tmp) { if (tmp != skipTemplate) { var cls = tmp.className.split('.'); - var nameSpace = cls.take(cls.length - 1).join('_'); - imports.writeln( - "import '${tmp.className}.Generated.dart' as $nameSpace;"); + var nameSpace = cls.take(cls.length - 1).join('_').toLowerCase(); + imports.writeln("import '${tmp.className}.g.dart' as $nameSpace;"); } }); @@ -213,51 +253,61 @@ class TemplateGenerator { // make sources templates.forEach((tmp) { + print("Generating `${tmp.className}`."); + if (tmp.type == TemplateType.Resource) { var source = makeImports(tmp) + generateClass(tmp, templates); - var f = File("${dstDir.path}/${tmp.className}.Generated.dart"); + var f = File("${dstDir.path}/${tmp.className}.g.dart"); f.writeAsStringSync(source); } else if (tmp.type == TemplateType.Record) { var source = makeImports(tmp) + generateRecord(tmp, templates); - var f = File("${dstDir.path}/${tmp.className}.Generated.dart"); + var f = File("${dstDir.path}/${tmp.className}.g.dart"); f.writeAsStringSync(source); } }); // generate info class - var typesFile = - "using System; \r\n namespace Esiur { public static class Generated { public static Type[] Resources {get;} = new Type[] { " + - templates - .where((x) => x.type == TemplateType.Resource) - .map((x) => "typeof(${x.className})") - .join(',') + - " }; \r\n public static Type[] Records { get; } = new Type[] { " + - templates - .where((x) => x.type == TemplateType.Record) - .map((x) => "typeof(${x.className})") - .join(',') + - " }; " + - "\r\n } \r\n}"; - var f = File("${dstDir.path}/Esiur.Generated.cs"); + var defineCreators = templates.map((tmp) { + // creator + var className = _translateClassName(tmp.className); + return "Warehouse.defineCreator(${className}, () => ${className}(), () => <${className}>[]);"; + }).join("\r\n"); + + var putTemplates = templates.map((tmp) { + var className = _translateClassName(tmp.className); + return "Warehouse.putTemplate(TypeTemplate.fromType(${className}));"; + }).join("\r\n"); + + var typesFile = makeImports(null) + + "\r\n void init_${dir}(){ ${defineCreators} \r\n ${putTemplates}}"; + + var f = File("${dstDir.path}/init.g.dart"); f.writeAsStringSync(typesFile); return dstDir.path; } catch (ex) { - //File.WriteAllText("C:\\gen\\gettemplate.err", ex.ToString()); throw ex; } } + static String _escape(String str) { + if (str == null) + return "null"; + else + return "r'$str'"; + } + static String generateClass( TypeTemplate template, List templates) { var className = template.className.split('.').last; - var rt = new StringBuffer(); + var rt = StringBuffer(); rt.writeln("class $className extends DistributedResource {"); rt.writeln( - "$className(DistributedConnection connection, int instanceId, int age, String link) : super(connection, instanceId, age, link) {"); +// "$className(DistributedConnection connection, int instanceId, int age, String link) : super(connection, instanceId, age, link) {"); + "$className() {"); template.events.forEach((e) { rt.writeln("on('${e.name}', (x) => _${e.name}Controller.add(x));"); @@ -273,9 +323,9 @@ class TemplateGenerator { .join(",")); rt.writeln(") {"); - rt.writeln("var rt = new AsyncReply<$rtTypeName>();"); + rt.writeln("var rt = AsyncReply<$rtTypeName>();"); rt.writeln( - "invokeByArrayArguments(${f.index}, [${f.arguments.map((x) => x.name).join(',')}])"); + "internal_invokeByArrayArguments(${f.index}, [${f.arguments.map((x) => x.name).join(',')}])"); rt.writeln(".then((x) => rt.trigger(x))"); rt.writeln(".error((x) => rt.triggerError(x))"); rt.writeln(".chunk((x) => rt.triggerChunk(x));"); @@ -299,6 +349,43 @@ class TemplateGenerator { rt.writeln("}"); }); + // add template + var descProps = template.properties.map((p) { + var isArray = p.valueType.type & 0x80 == 0x80; + var ptType = p.valueType.type & 0x7F; + var ptTypeName = getTypeName( + template, TemplateDataType(ptType, p.valueType.typeGuid), templates); + return "Prop('${p.name}', ${ptTypeName}, ${isArray}, ${_escape(p.readExpansion)}, ${_escape(p.writeExpansion)})"; + }).join(', '); + + var descFuncs = template.functions.map((f) { + var isArray = f.returnType.type & 0x80 == 0x80; + var ftType = f.returnType.type & 0x7F; + var ftTypeName = getTypeName( + template, TemplateDataType(ftType, f.returnType.typeGuid), templates); + + var args = f.arguments.map((a) { + var isArray = a.type.type & 0x80 == 0x80; + var atType = a.type.type & 0x7F; + var atTypeName = getTypeName( + template, TemplateDataType(atType, a.type.typeGuid), templates); + return "Arg('${a.name}', ${atTypeName}, ${isArray})"; + }).join(', '); + + return "Func('${f.name}', ${ftTypeName}, ${isArray}, [${args}], ${_escape(f.expansion)})"; + }).join(', '); + + var descEvents = template.events.map((e) { + var isArray = e.argumentType.type & 0x80 == 0x80; + var etType = e.argumentType.type & 0x7F; + var etTypeName = getTypeName(template, + TemplateDataType(etType, e.argumentType.typeGuid), templates); + return "Evt('${e.name}', ${etTypeName}, ${isArray}, ${e.listenable}, ${_escape(e.expansion)})"; + }).join(', '); + + rt.writeln( + "TemplateDescriber get template => TemplateDescriber('${template.className}', properties: [${descProps}], functions: [${descFuncs}], events: [$descEvents]);"); + rt.writeln("\r\n}"); return rt.toString(); diff --git a/lib/src/Resource/FactoryEntry.dart b/lib/src/Resource/FactoryEntry.dart new file mode 100644 index 0000000..c2ad498 --- /dev/null +++ b/lib/src/Resource/FactoryEntry.dart @@ -0,0 +1,7 @@ +class FactoryEntry { + final Type type; + final Function() instanceCreator; + final Function() arrayCreator; + + FactoryEntry(this.type, this.instanceCreator, this.arrayCreator); +} diff --git a/lib/src/Resource/IResource.dart b/lib/src/Resource/IResource.dart index 86695f9..0e58408 100644 --- a/lib/src/Resource/IResource.dart +++ b/lib/src/Resource/IResource.dart @@ -22,7 +22,7 @@ SOFTWARE. */ -import 'package:esiur/src/Resource/Template/TemplateDescriber.dart'; +import './Template/TemplateDescriber.dart'; import '../Resource/Template/TemplateDescriber.dart'; import '../Core/IDestructible.dart'; diff --git a/lib/src/Resource/Template/MemberTemplate.dart b/lib/src/Resource/Template/MemberTemplate.dart index 2d03fba..7c8f9b8 100644 --- a/lib/src/Resource/Template/MemberTemplate.dart +++ b/lib/src/Resource/Template/MemberTemplate.dart @@ -29,6 +29,6 @@ class MemberTemplate DC compose() { - // return DC.ToBytes(Name); + return DC.stringToBytes(_name); } } diff --git a/lib/src/Resource/Template/PropertyTemplate.dart b/lib/src/Resource/Template/PropertyTemplate.dart index 66bfc5d..e39d2b6 100644 --- a/lib/src/Resource/Template/PropertyTemplate.dart +++ b/lib/src/Resource/Template/PropertyTemplate.dart @@ -10,7 +10,7 @@ import '../StorageMode.dart'; class PropertyTemplate extends MemberTemplate { TemplateDataType valueType; - int permission; + int permission = 0; int storage; diff --git a/lib/src/Resource/Template/TemplateDataType.dart b/lib/src/Resource/Template/TemplateDataType.dart index 53aabf3..5186320 100644 --- a/lib/src/Resource/Template/TemplateDataType.dart +++ b/lib/src/Resource/Template/TemplateDataType.dart @@ -26,7 +26,7 @@ class TemplateDataType { TemplateDataType.fromType(type, bool isArray) { int dt; - if (type == null) + if (type == null || type == dynamic) dt = DataType.Void; else if (type is int) { dt = type; @@ -50,7 +50,7 @@ class TemplateDataType { dt = DataType.Int64; else if (type == Float) dt = DataType.Float32; - else if (type == Double) + else if (type == Double || type == double) dt = DataType.Float64; else if (type == String) dt = DataType.String; diff --git a/lib/src/Resource/Template/TemplateDescriber.dart b/lib/src/Resource/Template/TemplateDescriber.dart index 41009b1..f55917d 100644 --- a/lib/src/Resource/Template/TemplateDescriber.dart +++ b/lib/src/Resource/Template/TemplateDescriber.dart @@ -5,9 +5,10 @@ class TemplateDescriber { final List events; final List functions; final String nameSpace; + final int version; TemplateDescriber(this.nameSpace, - {this.properties, this.functions, this.events}); + {this.properties, this.functions, this.events, this.version = 0}); } // class Property { @@ -48,7 +49,8 @@ class Prop { final bool isArray; final String readAnnotation; final String writeAnnotation; - Prop(this.name, this.type, this.isArray, [this.readAnnotation = null, this.writeAnnotation = null]); + Prop(this.name, this.type, this.isArray, + [this.readAnnotation = null, this.writeAnnotation = null]); } class Evt { @@ -58,7 +60,8 @@ class Evt { final bool isArray; final String annotation; - Evt(this.name, this.type, this.isArray, [this.listenable = false, this.annotation]); + Evt(this.name, this.type, this.isArray, + [this.listenable = false, this.annotation]); } class Func { @@ -68,7 +71,7 @@ class Func { final bool isArray; final String annotation; - Func(this.name, this.returnType, this.argsType, this.isArray, + Func(this.name, this.returnType, this.isArray, this.argsType, [this.annotation = null]); } diff --git a/lib/src/Resource/Template/TypeTemplate.dart b/lib/src/Resource/Template/TypeTemplate.dart index c3d66f0..0fe9afe 100644 --- a/lib/src/Resource/Template/TypeTemplate.dart +++ b/lib/src/Resource/Template/TypeTemplate.dart @@ -1,5 +1,7 @@ import 'dart:ffi'; +import '../../Net/IIP/DistributedResource.dart'; + import '../../Data/BinaryList.dart'; import '../../Security/Integrity/SHA256.dart'; @@ -55,8 +57,7 @@ class TypeTemplate { */ //@TODO: implement - static List getDependencies(TypeTemplate template) => - []; + static List getDependencies(TypeTemplate template) => []; EventTemplate getEventTemplateByName(String eventName) { for (var i in _events) if (i.name == eventName) return i; @@ -106,15 +107,27 @@ class TypeTemplate { List get properties => _properties; - TypeTemplate.fromType(Type type, [bool addToWarehouse, bool isWrapper]) { + TypeTemplate.fromType(Type type, [bool addToWarehouse = false]) { + // debugging print("FromType ${type.toString()}"); + var instance = Warehouse.createInstance(type); - if (instance is IRecord) - _templateType = TemplateType.Record; + if (instance is DistributedResource) + _templateType = TemplateType.Wrapper; else if (instance is IResource) _templateType = TemplateType.Resource; + else if (instance is IRecord) + _templateType = TemplateType.Record; else - throw new Exception("Type is neither a resource nor a record."); + throw new Exception( + "Type must implement IResource, IRecord or inherit from DistributedResource."); + + // if (instance is IRecord) + // _templateType = TemplateType.Record; + // else if (instance is IResource) + // _templateType = TemplateType.Resource; + // else + // throw new Exception("Type is neither a resource nor a record."); TemplateDescriber describer = instance.template; @@ -125,47 +138,59 @@ class TypeTemplate { // set guid _classId = getTypeGuid(_className); + _version = describer.version; + if (addToWarehouse) Warehouse.putTemplate(this); // _templates.add(template.classId, template); - for (var i = 0; i < describer.properties.length; i++) { - var pi = describer.properties[i]; - var pt = PropertyTemplate( - this, - i, - pi.name, - TemplateDataType.fromType(pi.type, pi.isArray), - pi.readAnnotation, - pi.writeAnnotation, - 0); - properties.add(pt); - } + if (describer.properties != null) + for (var i = 0; i < describer.properties.length; i++) { + var pi = describer.properties[i]; + var pt = PropertyTemplate( + this, + i, + pi.name, + TemplateDataType.fromType(pi.type, pi.isArray), + pi.readAnnotation, + pi.writeAnnotation, + 0); + properties.add(pt); + } - for (var i = 0; i < describer.functions.length; i++) { - var fi = describer.functions[i]; + if (describer.functions != null) + for (var i = 0; i < describer.functions.length; i++) { + var fi = describer.functions[i]; - List args = fi.argsType.map((arg) => ArgumentTemplate( - arg.name, TemplateDataType.fromType(arg.type, arg.isArray))); + List args = fi.argsType + .map((arg) => ArgumentTemplate( + arg.name, TemplateDataType.fromType(arg.type, arg.isArray))) + .toList(); - var ft = FunctionTemplate(this, i, fi.name, args, - TemplateDataType.fromType(fi.returnType, fi.isArray), fi.annotation); + var ft = FunctionTemplate( + this, + i, + fi.name, + args, + TemplateDataType.fromType(fi.returnType, fi.isArray), + fi.annotation); - functions.add(ft); - } + functions.add(ft); + } - for (var i = 0; i < describer.events.length; i++) { - var ei = describer.events[i]; + if (describer.events != null) + for (var i = 0; i < describer.events.length; i++) { + var ei = describer.events[i]; - var et = new EventTemplate( - this, - i, - ei.name, - TemplateDataType.fromType(ei.type, ei.isArray), - ei.annotation, - ei.listenable); + var et = new EventTemplate( + this, + i, + ei.name, + TemplateDataType.fromType(ei.type, ei.isArray), + ei.annotation, + ei.listenable); - events.add(et); - } + events.add(et); + } // append signals events.forEach(_members.add); diff --git a/lib/src/Resource/Warehouse.dart b/lib/src/Resource/Warehouse.dart index 03e2fe2..0ea9951 100644 --- a/lib/src/Resource/Warehouse.dart +++ b/lib/src/Resource/Warehouse.dart @@ -23,6 +23,7 @@ SOFTWARE. */ import '../Data/AutoList.dart'; +import 'FactoryEntry.dart'; import 'Template/TemplateType.dart'; import 'Template/TypeTemplate.dart'; import '../Data/Guid.dart'; @@ -45,7 +46,6 @@ class Warehouse { static Map _resources = new Map(); static int resourceCounter = 0; - static KeyList> _templates = _initTemplates(); // @@ -60,13 +60,11 @@ class Warehouse { return rt; } - - static KeyList _factory = _getBuiltInTypes(); + static KeyList _factory = _getBuiltInTypes(); static KeyList Function(String, dynamic)> protocols = _getSupportedProtocols(); - static bool _warehouseIsOpen = false; static final _urlRegex = RegExp(r'^(?:([^\s|:]*):\/\/([^\/]*)\/?(.*))'); @@ -470,7 +468,11 @@ class Warehouse { } static T createInstance(Type T) { - return _factory[T].call(); + return _factory[T].instanceCreator.call(); + } + + static List createArray(Type T) { + return _factory[T].arrayCreator.call(); } static AsyncReply newResource(String name, @@ -479,7 +481,7 @@ class Warehouse { IPermissionsManager manager = null, attributes = null, properties = null]) { - var resource = _factory[T].call(); + var resource = _factory[T].instanceCreator.call(); if (properties != null) { dynamic d = resource; @@ -525,8 +527,9 @@ class Warehouse { static TypeTemplate getTemplateByType(Type type) { // loaded ? for (var tmps in _templates.values) - for (var tmp in tmps.values) - if (tmp.className == type.toString()) return tmp; + for (var tmp in tmps.values) if (tmp.definedType == type) return tmp; + + //if (tmp.className == type.toString()) return tmp; var template = new TypeTemplate.fromType(type, true); @@ -562,28 +565,31 @@ class Warehouse { /// /// Class name. /// Resource template. - static TypeTemplate getTemplateByClassName(String className, [TemplateType templateType = TemplateType.Unspecified]) { + static TypeTemplate getTemplateByClassName(String className, + [TemplateType templateType = TemplateType.Unspecified]) { + if (templateType == TemplateType.Unspecified) { + // look in resources + var template = _templates[TemplateType.Resource] + .values + .firstWhere((x) => x.className == className); + if (template != null) return template; - if (templateType == TemplateType.Unspecified) - { - // look in resources - var template = _templates[TemplateType.Resource].values.firstWhere((x) => x.className == className); - if (template != null) - return template; + // look in records + template = _templates[TemplateType.Record] + .values + .firstWhere((x) => x.className == className); + if (template != null) return template; - // look in records - template = _templates[TemplateType.Record].values.firstWhere((x) => x.className == className); - if (template != null) - return template; - - // look in wrappers - template = _templates[TemplateType.Wrapper].values.firstWhere((x) => x.className == className); - return template; - } - else - { - return _templates[templateType].values.firstWhere((x) => x.className == className); - } + // look in wrappers + template = _templates[TemplateType.Wrapper] + .values + .firstWhere((x) => x.className == className); + return template; + } else { + return _templates[templateType] + .values + .firstWhere((x) => x.className == className); + } } static bool remove(IResource resource) { @@ -625,9 +631,17 @@ class Warehouse { return rt; } - static KeyList _getBuiltInTypes() { - var rt = KeyList(); - rt.add(DistributedConnection, () => DistributedConnection()); + static defineCreator( + Type type, Function instanceCreator, Function arrayCreator) { + _factory.add(type, FactoryEntry(type, instanceCreator, arrayCreator)); + } + + static KeyList _getBuiltInTypes() { + var rt = KeyList(); + rt.add( + DistributedConnection, + FactoryEntry(DistributedConnection, () => DistributedConnection(), + () => DistributedConnection())); return rt; } } diff --git a/pubspec.lock b/pubspec.lock index 5ce78d0..f07daae 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -50,6 +50,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.3.1" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" cli_util: dependency: transitive description: @@ -134,6 +141,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "0.6.3" + json_annotation: + dependency: transitive + description: + name: json_annotation + url: "https://pub.dartlang.org" + source: hosted + version: "4.0.1" logging: dependency: transitive description: @@ -204,6 +218,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.0.0" + pubspec_parse: + dependency: "direct main" + description: + name: pubspec_parse + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.0" shelf: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 37028b5..5578a79 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: esiur description: Distributed Object Framework. -version: 1.3.0 -# author: Ahmed Zamil +version: 1.4.0 +#author: Ahmed Zamil homepage: https://github.com/esiur/esiur-dart @@ -11,6 +11,7 @@ environment: dependencies: source_gen: ^1.0.2 args: # + pubspec_parse: dev_dependencies: test: ^1.14.2 diff --git a/test/main.dart b/test/main.dart index 5297603..f17bd6a 100644 --- a/test/main.dart +++ b/test/main.dart @@ -1,22 +1,9 @@ -import 'package:esiur/src/Proxy/TemplateGenerator.dart'; -import "package:test/test.dart"; import 'package:esiur/esiur.dart'; -import 'dart:io'; -import '../lib/localhost/Esiur.Generated.dart'; import 'TestResource.dart'; main() async { try { - testMe(); - var c = EsiurGenerated; - print(c); - print(Warehouse.protocols.length); - - await TemplateGenerator.getTemplate("iip://localhost/sys/cp"); - // var x = await Warehouse.get("iip://localhost/sys/cp", - // {"username": "guest", "password": "123456", "domain": "example.com"}); - // print(x); } catch (ex) { print("Error occured"); print(ex);