From 614c6853e374bdf34b1834b2928a8eaf2198256c Mon Sep 17 00:00:00 2001 From: Ahmed Zamil Date: Sat, 24 Jul 2021 13:12:43 +0300 Subject: [PATCH] null-safety --- .vscode/launch.json | 10 +- lib/builder.dart | 4 +- lib/src/Core/AsyncBag.dart | 39 +- lib/src/Core/AsyncException.dart | 4 +- lib/src/Core/AsyncQueue.dart | 6 +- lib/src/Core/AsyncReply.dart | 79 +- lib/src/Core/IEventHandler.dart | 72 +- lib/src/Data/AutoList.dart | 15 +- lib/src/Data/BinaryList.dart | 836 +++++------- lib/src/Data/Codec.dart | 221 ++-- lib/src/Data/DC.dart | 51 +- lib/src/Data/Guid.dart | 4 +- lib/src/Data/KeyList.dart | 10 +- lib/src/Data/Record.dart | 2 +- lib/src/Data/SizeObject.dart | 7 +- lib/src/Data/StructureMetadata.dart | 10 +- lib/src/Net/IIP/DistributedConnection.dart | 1086 ++++++++-------- .../Net/IIP/DistributedPropertyContext.dart | 19 +- lib/src/Net/IIP/DistributedResource.dart | 165 ++- lib/src/Net/IIP/DistributedServer.dart | 2 +- lib/src/Net/NetworkBuffer.dart | 178 ++- lib/src/Net/NetworkConnection.dart | 33 +- lib/src/Net/Packets/IIPAuthPacket.dart | 437 +++---- lib/src/Net/Packets/IIPPacket.dart | 1138 +++++++---------- lib/src/Net/SendList.dart | 25 +- lib/src/Net/Sockets/ISocket.dart | 6 +- lib/src/Net/Sockets/TCPSocket.dart | 35 +- lib/src/Proxy/TemplateGenerator.dart | 90 +- lib/src/Resource/FactoryEntry.dart | 4 +- lib/src/Resource/IResource.dart | 2 +- lib/src/Resource/IStore.dart | 24 +- lib/src/Resource/Instance.dart | 785 ++++++------ .../Resource/Template/ArgumentTemplate.dart | 48 +- lib/src/Resource/Template/EventTemplate.dart | 28 +- .../Resource/Template/FunctionTemplate.dart | 24 +- lib/src/Resource/Template/MemberTemplate.dart | 6 +- .../Resource/Template/PropertyTemplate.dart | 74 +- .../Resource/Template/TemplateDataType.dart | 14 +- .../Resource/Template/TemplateDescriber.dart | 14 +- lib/src/Resource/Template/TypeTemplate.dart | 75 +- lib/src/Resource/Warehouse.dart | 181 +-- .../Security/Authority/Authentication.dart | 29 +- lib/src/Security/Authority/Session.dart | 6 +- lib/src/Security/Authority/Source.dart | 22 +- lib/src/Security/Integrity/SHA256.dart | 299 +++-- pubspec.lock | 59 +- pubspec.yaml | 8 +- test/main.dart | 56 +- 48 files changed, 3022 insertions(+), 3320 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 0480a62..59d8701 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -11,12 +11,12 @@ "type": "dart" }, { - "program": "test/template_test/.dart_tool/build/entrypoint/build.dart", - "name": "template_test", - "cwd": "template_test", + + "name": "Test", + "program": "test/template_test/bin/service.dart", "request": "launch", - "type": "dart", - "args": ["serve"], + "type": "dart" + } ] } \ No newline at end of file diff --git a/lib/builder.dart b/lib/builder.dart index 018ded1..3c75719 100644 --- a/lib/builder.dart +++ b/lib/builder.dart @@ -9,7 +9,7 @@ import 'package:yaml/yaml.dart'; class TemplateBuilder implements Builder { //BuilderOptions options; String _fileName; - TemplateBuilder([BuilderOptions options]) : _fileName = _get_dest(options); + TemplateBuilder([BuilderOptions? options]) : _fileName = _get_dest(options); @override Future build(BuildStep buildStep) async { @@ -21,7 +21,7 @@ class TemplateBuilder implements Builder { await buildStep.writeAsString(id, content); } - static String _get_dest(BuilderOptions options) { + static String _get_dest(BuilderOptions? options) { const defaultDestination = 'lib/src/iip_template.dart'; if (options == null) return defaultDestination; if (options.config == null) return defaultDestination; diff --git a/lib/src/Core/AsyncBag.dart b/lib/src/Core/AsyncBag.dart index 6f2a93a..1aedf65 100644 --- a/lib/src/Core/AsyncBag.dart +++ b/lib/src/Core/AsyncBag.dart @@ -1,55 +1,62 @@ import 'AsyncReply.dart'; import '../Resource/Warehouse.dart'; +// class ReplyIndex { +// int index; +// AsyncReply reply; +// T +// } class AsyncBag extends AsyncReply> { List> _replies = >[]; - List _results = []; + + //List _results = []; int _count = 0; bool _sealedBag = false; - Type arrayType; + Type? arrayType; seal() { //print("SEALED"); if (_sealedBag) return; - _sealedBag = true; - if (_results.length == 0) trigger([]); + if (_replies.length == 0) trigger([]); - for (var i = 0; i < _results.length; i++) { + var results = List.filled(_replies.length, null); + + for (var i = 0; i < _replies.length; i++) { var k = _replies[i]; var index = i; - k.then((r) { - _results[index] = r; + k..then((r) { + results[index] = r; _count++; - if (_count == _results.length) { + if (_count == _replies.length) { if (arrayType != null) { - var ar = Warehouse.createArray(arrayType); - _results.forEach(ar.add); - trigger(ar); + var ar = Warehouse.createArray(arrayType as Type); + results.forEach(ar.add); + trigger(ar as List); } else { - trigger(_results); + trigger(results.cast()); } } - }).error((ex) { + })..error((ex) { triggerError(ex); }); } } - add(AsyncReply reply) { + void add(AsyncReply reply) { if (!_sealedBag) { - _results.add(null); + //_results.add(null); _replies.add(reply); } } - addBag(AsyncBag bag) { + void addBag(AsyncBag bag) { bag._replies.forEach((r) { add(r); }); diff --git a/lib/src/Core/AsyncException.dart b/lib/src/Core/AsyncException.dart index f4b0c82..62a084c 100644 --- a/lib/src/Core/AsyncException.dart +++ b/lib/src/Core/AsyncException.dart @@ -4,7 +4,7 @@ import 'ErrorType.dart'; class AsyncException implements Exception { final ErrorType type; final int code; - final String message; + final String? message; AsyncException(this.type, this.code, this.message) {} @@ -20,7 +20,7 @@ class AsyncException implements Exception { ": " + (message ?? ""); else - return code.toString() + ": " + message; + return code.toString() + ": " + (message ?? ''); } @override diff --git a/lib/src/Core/AsyncQueue.dart b/lib/src/Core/AsyncQueue.dart index 02884b7..6ab4c18 100644 --- a/lib/src/Core/AsyncQueue.dart +++ b/lib/src/Core/AsyncQueue.dart @@ -2,8 +2,8 @@ library esiur; import 'AsyncReply.dart'; -class AsyncQueue extends AsyncReply { - List> _list = >[]; +class AsyncQueue extends AsyncReply { + List> _list = >[]; // object queueLock = new object(); @@ -23,7 +23,7 @@ class AsyncQueue extends AsyncReply { processQueue(null); } - void processQueue(T o) { + void processQueue(T? o) { //lock (queueLock) for (var i = 0; i < _list.length; i++) if (_list[i].ready) { diff --git a/lib/src/Core/AsyncReply.dart b/lib/src/Core/AsyncReply.dart index e01a3f2..f172324 100644 --- a/lib/src/Core/AsyncReply.dart +++ b/lib/src/Core/AsyncReply.dart @@ -29,9 +29,9 @@ import 'ProgressType.dart'; class AsyncReply implements Future { List _callbacks = []; - T _result; + late T _result; - List _errorCallbacks = []; + List _errorCallbacks = []; List _progressCallbacks = []; @@ -39,7 +39,7 @@ class AsyncReply implements Future { List _chunkCallbacks = []; bool _resultReady = false; - AsyncException _exception; + AsyncException? _exception; bool get ready { return _resultReady; @@ -49,7 +49,7 @@ class AsyncReply implements Future { _resultReady = value; } - T get result { + T? get result { return _result; } @@ -62,26 +62,20 @@ class AsyncReply implements Future { return this; } - AsyncReply then(FutureOr onValue(T value), {Function onError}) { + AsyncReply then(FutureOr onValue(T value), {Function? onError}) { _callbacks.add(onValue); + if (onError != null) { - if (onError is Function(dynamic, dynamic)) { - _errorCallbacks.add((ex) => onError(ex, null)); - } else if (onError is Function(dynamic)) { - _errorCallbacks.add(onError); - } else if (onError is Function()) { - _errorCallbacks.add((ex) => onError()); - } else if (onError is Function(Object, StackTrace)) { - _errorCallbacks.add((ex) => onError(ex, null)); - } + _errorCallbacks.add(onError); } - if (_resultReady) onValue(result); + if (_resultReady) onValue(result as T); - if (R == Null) - return null; - else - return this as AsyncReply; +// if (R == Null) + // return null; + //else + //if (R == T) + return AsyncReply(); } AsyncReply whenComplete(FutureOr action()) { @@ -90,21 +84,39 @@ class AsyncReply implements Future { } Stream asStream() { - return null; + return Stream.empty(); + //return null; } - AsyncReply catchError(Function onError, {bool test(Object error)}) { - return this.error(onError); - } +// Future catchError(Function onError, {bool test(Object error)?}); + + AsyncReply catchError(Function onError, {bool test(Object error)?}) { + ///return this.error(onError); + + _errorCallbacks.add(onError); + + if (_exception != null) { + if (onError is Function(dynamic, dynamic)) { + onError(_exception, null); + } else if (onError is Function(dynamic)) { + onError(_exception); + } else if (onError is Function()) { + onError(); + } else if (onError is Function(Object, StackTrace)) { + onError(_exception as Object, StackTrace.current); + } + } - AsyncReply timeout(Duration timeLimit, {FutureOr onTimeout()}) { return this; } - AsyncReply error(Function(dynamic) callback) { - _errorCallbacks.add(callback); + AsyncReply timeout(Duration timeLimit, {FutureOr onTimeout()?}) { + return this; + } - if (_exception != null) callback(_exception); + AsyncReply error(callback(AsyncException ex)) { + _errorCallbacks.add(callback); + if (_exception != null) callback(_exception as AsyncException); return this; } @@ -144,10 +156,19 @@ class AsyncReply implements Future { //{ if (this._errorCallbacks.length == 0) - throw _exception; + throw _exception as AsyncException; else _errorCallbacks.forEach((x) { - x(_exception); + if (x is Function(dynamic, dynamic)) { + x(_exception, null); + } else if (x is Function(dynamic)) { + x(_exception); + } else if (x is Function()) { + x(); + } else if (x is Function(Object, StackTrace)) { + x(_exception as Object, StackTrace.current); + } + //x(_exception as AsyncException); }); //} diff --git a/lib/src/Core/IEventHandler.dart b/lib/src/Core/IEventHandler.dart index 5ce71eb..7f17a0f 100644 --- a/lib/src/Core/IEventHandler.dart +++ b/lib/src/Core/IEventHandler.dart @@ -1,48 +1,38 @@ -class IEventHandler -{ - Map> _events; +class IEventHandler { + Map> _events = {}; - register(String event) - { - _events[event.toLowerCase()] = []; + register(String event) { + _events[event.toLowerCase()] = []; + } + + IEventHandler() {} + + emitArgs(String event, List arguments) { + //event = event.toLowerCase(); + + var et = _events[event.toLowerCase()]; + if (et != null) { + for (var i = 0; i < et.length; i++) + if (Function.apply(et[i], arguments) != null) return true; } - IEventHandler() - { - _events = {}; - } + return false; + } - emitArgs(String event, List arguments) - { - event = event.toLowerCase(); - if (_events.containsKey(event)) - for(var i = 0; i < _events[event].length; i++) - if (Function.apply(_events[event][i], arguments) != null) - return true; + on(String event, Function callback) { + event = event.toLowerCase(); + if (_events.containsKey(event)) register(event); + _events[event]?.add(callback); + return this; + } - return false; - } - - on(String event, Function callback) - { - event = event.toLowerCase(); - // add - if (!_events.containsKey(event)) - register(event); - - _events[event].add(callback); - return this; - } - - off(event, callback) - { - event = event.toString(); - if (_events.containsKey(event)) - { - if (callback != null) - _events[event].remove(callback); - else - this._events[event] = []; - } + off(event, callback) { + event = event.toString(); + if (_events.containsKey(event)) { + if (callback != null) + _events[event]?.remove(callback); + else + this._events[event] = []; } + } } diff --git a/lib/src/Data/AutoList.dart b/lib/src/Data/AutoList.dart index 472d296..761319f 100644 --- a/lib/src/Data/AutoList.dart +++ b/lib/src/Data/AutoList.dart @@ -2,14 +2,14 @@ import '../Core/IDestructible.dart'; import 'Codec.dart'; import 'dart:collection'; -class AutoList extends IDestructible with IterableMixin { +class AutoList extends IDestructible with IterableMixin { List _list = []; - ST _state; - bool _removableList; + ST? _state; + late bool _removableList; - sort(Function comparer) { - _list.sort(comparer); + sort(int Function(T, T)? compare) { + _list.sort(compare); } Iterator get iterator => _list.iterator; @@ -26,7 +26,7 @@ class AutoList extends IDestructible with IterableMixin { /// Create a new instance of AutoList /// State object to be included when an event is raised. - AutoList([ST state, List values]) { + AutoList([ST? state, List? values]) { this._state = state; this._removableList = Codec.implementsInterface(); @@ -105,8 +105,7 @@ class AutoList extends IDestructible with IterableMixin { /// clear() { if (_removableList) - _list - .forEach((x) => (x as IDestructible)?.off("destroy", _itemDestroyed)); + _list.forEach((x) => (x as IDestructible).off("destroy", _itemDestroyed)); // lock (syncRoot) _list.clear(); diff --git a/lib/src/Data/BinaryList.dart b/lib/src/Data/BinaryList.dart index 21c520c..74d4eb5 100644 --- a/lib/src/Data/BinaryList.dart +++ b/lib/src/Data/BinaryList.dart @@ -30,82 +30,56 @@ import 'DC.dart'; import 'DataType.dart'; import 'Guid.dart'; -class BinaryList -{ - var _list = []; +class BinaryList { + var _list = []; - int get length => _list.length; + int get length => _list.length; - BinaryList addDateTime(DateTime value) - { - _list.addAll(DC.dateTimeToBytes(value)); - return this; - } + void addDateTime(DateTime value) { + _list.addAll(DC.dateTimeToBytes(value)); + } - BinaryList insertDateTime(int position, DateTime value) - { - _list.insertAll(position, DC.dateTimeToBytes(value)); - return this; - } + void insertDateTime(int position, DateTime value) { + _list.insertAll(position, DC.dateTimeToBytes(value)); + } + void addDateTimeArray(List value) { + _list.addAll(DC.dateTimeArrayToBytes(value)); + } - BinaryList addDateTimeArray(List value) - { - _list.addAll(DC.dateTimeArrayToBytes(value)); - return this; - } + void insertDateTimeArray(int position, List value) { + _list.insertAll(position, DC.dateTimeArrayToBytes(value)); + } - BinaryList insertDateTimeArray(int position, List value) - { - _list.insertAll(position, DC.dateTimeArrayToBytes(value)); - return this; - } + void addGuid(Guid value) { + _list.addAll(DC.guidToBytes(value)); + } - BinaryList addGuid(Guid value) - { - _list.addAll(DC.guidToBytes(value)); - return this; - } + void insertGuid(int position, Guid value) { + _list.insertAll(position, DC.guidToBytes(value)); + } - BinaryList insertGuid(int position, Guid value) - { - _list.insertAll(position, DC.guidToBytes(value)); - return this; - } + void addGuidArray(List value) { + _list.addAll(DC.guidArrayToBytes(value)); + } - BinaryList addGuidArray(List value) - { - _list.addAll(DC.guidArrayToBytes(value)); - return this; - } + void insertGuidArray(int position, List value) { + _list.insertAll(position, DC.guidArrayToBytes(value)); + } - BinaryList insertGuidArray(int position, List value) - { - _list.insertAll(position, DC.guidArrayToBytes(value)); - return this; - } + void addUint8Array(Uint8List value) { + _list.addAll(value); + } + void addDC(DC value) { + _list.addAll(value.toArray()); + } - BinaryList addUint8Array(Uint8List value) - { - _list.addAll(value); - return this; - } + void insertUint8Array(int position, Uint8List value) { + _list.insertAll(position, value); + } - BinaryList addDC(DC value) - { - _list.addAll(value.toArray()); - return this; - } - - BinaryList insertUint8Array(int position, Uint8List value) - { - _list.insertAll(position, value); - return this; - } - - - /* + /* BinaryList addHex(String value) { return this.addUint8Array(DC.fromHex(value, null)); @@ -117,434 +91,316 @@ class BinaryList } */ - - BinaryList addString(String value) - { - _list.addAll(DC.stringToBytes(value)); - return this; + void addString(String value) { + _list.addAll(DC.stringToBytes(value)); + } + + void insertString(int position, String value) { + _list.insertAll(position, DC.stringToBytes(value)); + } + + void addStringArray(List value) { + _list.addAll(DC.stringArrayToBytes(value)); + } + + void insertStringArray(int position, List value) { + _list.insertAll(position, DC.stringArrayToBytes(value)); + } + + void insertUint8(int position, int value) { + _list.insert(position, value); + } + + void addUint8(int value) { + _list.add(value); + } + + void addInt8(int value) { + _list.add(value); + } + + void insertInt8(int position, int value) { + _list.insert(position, value); + } + + void addInt8Array(Int8List value) { + _list.addAll(DC.int8ArrayToBytes(value)); + } + + void insertInt8Array(int position, Int8List value) { + _list.insertAll(position, DC.int8ArrayToBytes(value)); + } + + void addChar(int value) { + _list.addAll(DC.charToBytes(value)); + } + + void InsertChar(int position, int value) { + _list.insertAll(position, DC.charToBytes(value)); + } + + void addCharArray(Uint16List value) { + _list.addAll(DC.charArrayToBytes(value)); + } + + void InsertCharArray(int position, Uint16List value) { + _list.insertAll(position, DC.charArrayToBytes(value)); + } + + void addBoolean(bool value) { + _list.addAll(DC.boolToBytes(value)); + } + + void insertBoolean(int position, bool value) { + _list.insertAll(position, DC.boolToBytes(value)); + } + + void addBooleanArray(List value) { + _list.addAll(DC.boolToBytes(value)); + } + + void insertBooleanArray(int position, List value) { + _list.insertAll(position, DC.boolToBytes(value)); + } + + void addUint16(int value) { + _list.addAll(DC.uint16ToBytes(value)); + } + + void insertUint16(int position, int value) { + _list.insertAll(position, DC.uint16ToBytes(value)); + } + + void addUint16Array(Uint16List value) { + _list.addAll(DC.uint16ArrayToBytes(value)); + } + + void insertUint16Array(int position, Uint16List value) { + _list.insertAll(position, DC.uint16ArrayToBytes(value)); + } + + void addInt16(int value) { + _list.addAll(DC.int16ToBytes(value)); + } + + void insertInt16(int position, int value) { + _list.insertAll(position, DC.int16ToBytes(value)); + } + + void addInt16Array(Int16List value) { + _list.addAll(DC.int16ArrayToBytes(value)); + } + + void insertInt16Array(int position, Int16List value) { + _list.insertAll(position, DC.int16ArrayToBytes(value)); + } + + void addUint32(int value) { + _list.addAll(DC.uint32ToBytes(value)); + } + + void insertUint32(int position, int value) { + _list.insertAll(position, DC.uint32ToBytes(value)); + } + + void addUint32Array(Uint32List value) { + _list.addAll(DC.uint32ArrayToBytes(value)); + } + + void InsertUint32Array(int position, Uint32List value) { + _list.insertAll(position, DC.uint32ArrayToBytes(value)); + } + + void addInt32(int value) { + _list.addAll(DC.int32ToBytes(value)); + } + + void insertInt32(int position, int value) { + _list.insertAll(position, DC.int32ToBytes(value)); + } + + void addInt32Array(Int32List value) { + _list.addAll(DC.int32ArrayToBytes(value)); + } + + void insertInt32Array(int position, Int32List value) { + _list.insertAll(position, DC.int32ArrayToBytes(value)); + } + + void addUint64(int value) { + _list.addAll(DC.uint64ToBytes(value)); + } + + void insertUint64(int position, int value) { + _list.insertAll(position, DC.uint64ToBytes(value)); + } + + void addUint64Array(Uint64List value) { + _list.addAll(DC.uint64ArrayToBytes(value)); + } + + void InsertUint64Array(int position, Uint64List value) { + _list.insertAll(position, DC.uint64ArrayToBytes(value)); + } + + void addInt64(int value) { + _list.addAll(DC.int64ToBytes(value)); + } + + void insertInt64(int position, int value) { + _list.insertAll(position, DC.int64ToBytes(value)); + } + + void addInt64Array(Int64List value) { + _list.addAll(DC.int64ArrayToBytes(value)); + } + + void insertInt64Array(int position, Int64List value) { + _list.insertAll(position, DC.int64ArrayToBytes(value)); + } + + void addFloat32(double value) { + _list.addAll(DC.float32ToBytes(value)); + } + + void insertFloat32(int position, double value) { + _list.insertAll(position, DC.float32ToBytes(value)); + } + + void addFloat32Array(Float32List value) { + _list.addAll(DC.float32ArrayToBytes(value)); + } + + void insertFloat32Array(int position, Float32List value) { + _list.insertAll(position, DC.float32ArrayToBytes(value)); + } + + void addFloat64(double value) { + _list.addAll(DC.float64ToBytes(value)); + } + + void insertFloat64(int position, double value) { + _list.insertAll(position, DC.float64ToBytes(value)); + } + + void addFloat64Array(Float64List value) { + _list.addAll(DC.float64ArrayToBytes(value)); + } + + void insertFloat64Array(int position, Float64List value) { + _list.insertAll(position, DC.float64ArrayToBytes(value)); + } + + void add(type, value) { + switch (type) { + case DataType.Bool: + addBoolean(value); + return; + case DataType.BoolArray: + addBooleanArray(value); + return; + case DataType.UInt8: + addUint8(value); + return; + case DataType.UInt8Array: + addUint8Array(value); + return; + case DataType.Int8: + addInt8(value); + return; + case DataType.Int8Array: + addInt8Array(value); + return; + case DataType.Char: + addChar(value); + return; + case DataType.CharArray: + addCharArray(value); + return; + case DataType.UInt16: + addUint16(value); + return; + case DataType.UInt16Array: + addUint16Array(value); + return; + case DataType.Int16: + addInt16(value); + return; + case DataType.Int16Array: + addInt16Array(value); + return; + case DataType.UInt32: + addUint32(value); + return; + case DataType.UInt32Array: + addUint32Array(value); + return; + case DataType.Int32: + addInt32(value); + return; + case DataType.Int32Array: + addInt32Array(value); + return; + case DataType.UInt64: + addUint64(value); + return; + case DataType.UInt64Array: + addUint64Array(value); + return; + case DataType.Int64: + addInt64(value); + return; + case DataType.Int64Array: + addInt64Array(value); + return; + + case DataType.Float32: + addFloat32(value); + return; + case DataType.Float32Array: + addFloat32Array(value); + return; + + case DataType.Float64: + addFloat64(value); + return; + case DataType.Float64Array: + addFloat64Array(value); + return; + + case DataType.String: + addString(value); + return; + case DataType.StringArray: + addStringArray(value); + return; + + case DataType.DateTime: + addDateTime(value); + return; + case DataType.DateTimeArray: + addDateTimeArray(value); + return; + + default: + throw new Exception("Not Implemented " + type.ToString()); + //return this; } + } - BinaryList insertString(int position, String value) - { - _list.insertAll(position, DC.stringToBytes(value)); - return this; - } + /// + /// Convert the _list to an array of bytes + /// + /// Bytes array + Uint8List toArray() { + return Uint8List.fromList(_list); + } - BinaryList addStringArray(List value) - { - _list.addAll(DC.stringArrayToBytes(value)); - return this; - } + DC toDC() { + return new DC.fromUint8Array(toArray()); + } - BinaryList insertStringArray(int position, List value) - { - _list.insertAll(position, DC.stringArrayToBytes(value)); - return this; - } - - BinaryList insertUint8(int position, int value) - { - _list.insert(position, value); - return this; - } - - BinaryList addUint8(int value) - { - _list.add(value); - return this; - } - - BinaryList addInt8(int value) - { - _list.add(value); - return this; - } - - BinaryList insertInt8(int position, int value) - { - _list.insert(position, value); - return this; - } - - BinaryList addInt8Array(Int8List value) - { - _list.addAll(DC.int8ArrayToBytes(value)); - return this; - } - - BinaryList insertInt8Array(int position, Int8List value) - { - _list.insertAll(position, DC.int8ArrayToBytes(value)); - return this; - } - - - BinaryList addChar(int value) - { - _list.addAll(DC.charToBytes(value)); - return this; - } - - BinaryList InsertChar(int position, int value) - { - _list.insertAll(position, DC.charToBytes(value)); - return this; - } - - BinaryList addCharArray(Uint16List value) - { - _list.addAll(DC.charArrayToBytes(value)); - return this; - } - - BinaryList InsertCharArray(int position, Uint16List value) - { - _list.insertAll(position, DC.charArrayToBytes(value)); - return this; - } - - - BinaryList addBoolean(bool value) - { - _list.addAll(DC.boolToBytes(value)); - return this; - } - - BinaryList insertBoolean(int position, bool value) - { - _list.insertAll(position, DC.boolToBytes(value)); - return this; - } - - BinaryList addBooleanArray(List value) - { - _list.addAll(DC.boolToBytes(value)); - return this; - } - - BinaryList insertBooleanArray(int position, List value) - { - _list.insertAll(position, DC.boolToBytes(value)); - return this; - } - - BinaryList addUint16(int value) - { - _list.addAll(DC.uint16ToBytes(value)); - return this; - } - - BinaryList insertUint16(int position, int value) - { - _list.insertAll(position, DC.uint16ToBytes(value)); - return this; - } - - BinaryList addUint16Array(Uint16List value) - { - _list.addAll(DC.uint16ArrayToBytes(value)); - return this; - } - - BinaryList insertUint16Array(int position, Uint16List value) - { - _list.insertAll(position, DC.uint16ArrayToBytes(value)); - return this; - } - - - BinaryList addInt16(int value) - { - _list.addAll(DC.int16ToBytes(value)); - return this; - } - - BinaryList insertInt16(int position, int value) - { - _list.insertAll(position, DC.int16ToBytes(value)); - return this; - } - - - BinaryList addInt16Array(Int16List value) - { - _list.addAll(DC.int16ArrayToBytes(value)); - return this; - } - - BinaryList insertInt16Array(int position, Int16List value) - { - _list.insertAll(position, DC.int16ArrayToBytes(value)); - return this; - } - - BinaryList addUint32(int value) - { - _list.addAll(DC.uint32ToBytes(value)); - return this; - } - - BinaryList insertUint32(int position, int value) - { - _list.insertAll(position, DC.uint32ToBytes(value)); - return this; - } - - BinaryList addUint32Array(Uint32List value) - { - _list.addAll(DC.uint32ArrayToBytes(value)); - return this; - } - BinaryList InsertUint32Array(int position, Uint32List value) - { - _list.insertAll(position, DC.uint32ArrayToBytes(value)); - return this; - } - - - BinaryList addInt32(int value) - { - _list.addAll(DC.int32ToBytes(value)); - return this; - } - - BinaryList insertInt32(int position, int value) - { - _list.insertAll(position, DC.int32ToBytes(value)); - return this; - } - - BinaryList addInt32Array(Int32List value) - { - _list.addAll(DC.int32ArrayToBytes(value)); - return this; - } - - BinaryList insertInt32Array(int position, Int32List value) - { - _list.insertAll(position, DC.int32ArrayToBytes(value)); - return this; - } - - - BinaryList addUint64(int value) - { - _list.addAll(DC.uint64ToBytes(value)); - return this; - } - - BinaryList insertUint64(int position, int value) - { - _list.insertAll(position, DC.uint64ToBytes(value)); - return this; - } - - BinaryList addUint64Array(Uint64List value) - { - _list.addAll(DC.uint64ArrayToBytes(value)); - return this; - } - - BinaryList InsertUint64Array(int position, Uint64List value) - { - _list.insertAll(position, DC.uint64ArrayToBytes(value)); - return this; - } - - BinaryList addInt64(int value) - { - _list.addAll(DC.int64ToBytes(value)); - return this; - } - - BinaryList insertInt64(int position, int value) - { - _list.insertAll(position, DC.int64ToBytes(value)); - return this; - } - - BinaryList addInt64Array(Int64List value) - { - _list.addAll(DC.int64ArrayToBytes(value)); - return this; - } - - BinaryList insertInt64Array(int position, Int64List value) - { - _list.insertAll(position, DC.int64ArrayToBytes(value)); - return this; - } - - BinaryList addFloat32(double value) - { - _list.addAll(DC.float32ToBytes(value)); - return this; - } - - BinaryList insertFloat32(int position, double value) - { - _list.insertAll(position, DC.float32ToBytes(value)); - return this; - } - - BinaryList addFloat32Array(Float32List value) - { - _list.addAll(DC.float32ArrayToBytes(value)); - return this; - } - - BinaryList insertFloat32Array(int position, Float32List value) - { - _list.insertAll(position, DC.float32ArrayToBytes(value)); - return this; - } - - - BinaryList addFloat64(double value) - { - _list.addAll(DC.float64ToBytes(value)); - return this; - } - - BinaryList insertFloat64(int position, double value) - { - _list.insertAll(position, DC.float64ToBytes(value)); - return this; - } - - BinaryList addFloat64Array(Float64List value) - { - _list.addAll(DC.float64ArrayToBytes(value)); - return this; - } - - BinaryList insertFloat64Array(int position, Float64List value) - { - _list.insertAll(position, DC.float64ArrayToBytes(value)); - return this; - } - - - - BinaryList add(type, value) - { - switch (type) - { - case DataType.Bool: - addBoolean(value); - return this; - case DataType.BoolArray: - addBooleanArray(value); - return this; - case DataType.UInt8: - addUint8(value); - return this; - case DataType.UInt8Array: - addUint8Array(value); - return this; - case DataType.Int8: - addInt8(value); - return this; - case DataType.Int8Array: - addInt8Array(value); - return this; - case DataType.Char: - addChar(value); - return this; - case DataType.CharArray: - addCharArray(value); - return this; - case DataType.UInt16: - addUint16(value); - return this; - case DataType.UInt16Array: - addUint16Array(value); - return this; - case DataType.Int16: - addInt16(value); - return this; - case DataType.Int16Array: - addInt16Array(value); - return this; - case DataType.UInt32: - addUint32(value); - return this; - case DataType.UInt32Array: - addUint32Array(value); - return this; - case DataType.Int32: - addInt32(value); - return this; - case DataType.Int32Array: - addInt32Array(value); - return this; - case DataType.UInt64: - addUint64(value); - return this; - case DataType.UInt64Array: - addUint64Array(value); - return this; - case DataType.Int64: - addInt64(value); - return this; - case DataType.Int64Array: - addInt64Array(value); - return this; - - case DataType.Float32: - addFloat32(value); - return this; - case DataType.Float32Array: - addFloat32Array(value); - return this; - - case DataType.Float64: - addFloat64(value); - return this; - case DataType.Float64Array: - addFloat64Array(value); - return this; - - case DataType.String: - addString(value); - return this; - case DataType.StringArray: - addStringArray(value); - return this; - - case DataType.DateTime: - addDateTime(value); - return this; - case DataType.DateTimeArray: - addDateTimeArray(value); - return this; - - default: - throw new Exception("Not Implemented " + type.ToString()); - //return this; - } - } - /// - /// Convert the _list to an array of bytes - /// - /// Bytes array - Uint8List toArray() - { - return Uint8List.fromList(_list); - } - - - DC toDC() - { - return new DC.fromUint8Array(toArray()); - } - - - AsyncReply done() - { - return null; - // - } - - -} \ No newline at end of file + AsyncReply done() { + return AsyncReply.ready(null); + } +} diff --git a/lib/src/Data/Codec.dart b/lib/src/Data/Codec.dart index dd7d08b..02b1dd1 100644 --- a/lib/src/Data/Codec.dart +++ b/lib/src/Data/Codec.dart @@ -21,6 +21,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +import '../Core/AsyncException.dart'; +import '../Core/ErrorType.dart'; +import '../Core/ExceptionCode.dart'; + import '../Resource/Template/TemplateType.dart'; import 'DataType.dart'; @@ -93,7 +98,7 @@ class Codec { /// Next structure to compare with the initial /// DistributedConnection is required in case a structure holds items at the other end static int compareStructures( - Structure initial, Structure next, DistributedConnection connection) { + Structure? initial, Structure? next, DistributedConnection connection) { if (next == null) return StructureComparisonResult.Null; if (initial == null) return StructureComparisonResult.Structure; @@ -126,7 +131,7 @@ class Codec { /// Initial record to compare with /// Next record to compare with the initial /// DistributedConnection is required in case a structure holds items at the other end - static int compareRecords(IRecord initial, IRecord next) { + static int compareRecords(IRecord? initial, IRecord? next) { if (next == null) return RecordComparisonResult.Null; if (initial == null) return RecordComparisonResult.Record; @@ -139,9 +144,9 @@ class Codec { return RecordComparisonResult.Record; } - static AsyncBag parseRecordArray( + static AsyncBag parseRecordArray( DC data, int offset, int length, DistributedConnection connection) { - var reply = new AsyncBag(); + var reply = new AsyncBag(); if (length == 0) { reply.seal(); @@ -161,12 +166,12 @@ class Codec { var template = Warehouse.getTemplateByClassId(classId, TemplateType.Record); - reply.arrayType = template.definedType; + reply.arrayType = template?.definedType; - AsyncReply previous = null; + AsyncReply? previous = null; if (result == RecordComparisonResult.Null) - previous = new AsyncReply.ready(null); + previous = AsyncReply.ready(null); else if (result == RecordComparisonResult.Record || result == RecordComparisonResult.RecordSameType) { var cs = data.getUint32(offset); @@ -176,13 +181,13 @@ class Codec { offset += recordLength; } - reply.add(previous); + reply.add(previous as AsyncReply); while (offset < end) { result = data[offset++]; if (result == RecordComparisonResult.Null) - previous = new AsyncReply.ready(null); + previous = new AsyncReply.ready(null); else if (result == RecordComparisonResult.Record || result == RecordComparisonResult.RecordSameType) { var cs = data.getUint32(offset); @@ -193,14 +198,14 @@ class Codec { // do nothing } - reply.add(previous); + reply.add(previous as AsyncReply); } } else { - AsyncReply previous = null; - Guid classId = null; + AsyncReply? previous = null; + Guid? classId = null; if (result == RecordComparisonResult.Null) - previous = new AsyncReply.ready(null); + previous = new AsyncReply.ready(null); else if (result == RecordComparisonResult.Record) { var cs = data.getUint32(offset); var recordLength = cs - 16; @@ -211,13 +216,13 @@ class Codec { offset += recordLength; } - reply.add(previous); + reply.add(previous as AsyncReply); while (offset < end) { result = data[offset++]; if (result == RecordComparisonResult.Null) - previous = new AsyncReply.ready(null); + previous = new AsyncReply.ready(null); else if (result == RecordComparisonResult.Record) { var cs = data.getUint32(offset); var recordLength = cs - 16; @@ -236,7 +241,7 @@ class Codec { // do nothing } - reply.add(previous); + reply.add(previous as AsyncReply); } } @@ -301,7 +306,7 @@ class Codec { static AsyncReply parseRecord( DC data, int offset, int length, DistributedConnection connection, - [Guid classId = null]) { + [Guid? classId = null]) { var reply = new AsyncReply(); if (classId == null) { @@ -317,7 +322,7 @@ class Codec { parseVarArray(data, offset, length, connection).then((ar) { if (template.definedType != null) { var record = - Warehouse.createInstance(template.definedType) as IRecord; + Warehouse.createInstance(template.definedType as Type) as IRecord; Map value = {}; @@ -337,16 +342,24 @@ class Codec { } }); } else { - connection.getTemplate(classId).then((tmp) { - parseVarArray(data, offset, length, connection).then((ar) { - var record = new Record(); + connection.getTemplate(classId) + ..then((tmp) { + if (tmp != null) { + parseVarArray(data, offset, length, connection) + ..then((ar) { + var record = new Record(); - for (var i = 0; i < tmp.properties.length; i++) - record.add(tmp.properties[i].name, ar[i]); + for (var i = 0; i < tmp.properties.length; i++) + record.add(tmp.properties[i].name, ar[i]); - reply.trigger(record); - }); - }).error((x) => reply.triggerError(x)); + reply.trigger(record); + }); + } else { + reply.triggerError(AsyncException(ErrorType.Management, + ExceptionCode.TemplateNotFound.index, null)); + } + }) + ..error((x) => reply.triggerError(x)); } return reply; @@ -377,9 +390,9 @@ class Codec { } static DC composeRecordArray( - List records, DistributedConnection connection, + List? records, DistributedConnection connection, [bool prependLength = false]) { - if (records == null || records?.length == 0) + if (records == null || records.length == 0) return prependLength ? new DC(4) : new DC(0); var rt = new BinaryList(); @@ -391,14 +404,14 @@ class Codec { if (isTyped) { var template = Warehouse.getTemplateByType(T); - if (template != null) { - // typed array ... no need to add class id , it will be included at the first entry - rt.addUint8(0x10 | comparsion); - rt.addGuid(template.classId); - } else // something wrong - { - throw new Exception("Template for type `${T}` not found."); - } + //if (template != null) { + // typed array ... no need to add class id , it will be included at the first entry + rt.addUint8(0x10 | comparsion); + rt.addGuid(template.classId); + //} else // something wrong + //{ + // throw new Exception("Template for type `${T}` not found."); + //} if (comparsion == RecordComparisonResult.Record) rt.addDC(composeRecord(records[0], connection, false, true)); @@ -468,17 +481,17 @@ class Codec { /// If true, prepend the length as UInt32 at the beginning of the returned bytes array /// Array of bytes in the network byte order static DC composeStructureArray( - List structures, DistributedConnection connection, + List? structures, DistributedConnection connection, [bool prependLength = false]) { - if (structures == null || structures?.length == 0) + if (structures == null || structures.length == 0) return prependLength ? new DC(4) : new DC(0); var rt = new BinaryList(); var comparsion = StructureComparisonResult.Structure; rt - .addUint8(comparsion) - .addDC(composeStructure(structures[0], connection, true, true, true)); + ..addUint8(comparsion) + ..addDC(composeStructure(structures[0], connection, true, true, true)); for (var i = 1; i < structures.length; i++) { comparsion = @@ -508,9 +521,9 @@ class Codec { /// Number of bytes to parse /// DistributedConnection is required in case a structure in the array holds items at the other end /// Array of structures - static AsyncBag parseStructureArray( + static AsyncBag parseStructureArray( DC data, int offset, int length, DistributedConnection connection) { - var reply = new AsyncBag(); + var reply = new AsyncBag(); if (length == 0) { reply.seal(); return reply; @@ -520,14 +533,14 @@ class Codec { var result = data[offset++]; - AsyncReply previous = null; + AsyncReply? previous = null; // string[] previousKeys = null; // DataType[] previousTypes = null; StructureMetadata metadata = new StructureMetadata(); if (result == StructureComparisonResult.Null) - previous = new AsyncReply.ready(null); + previous = new AsyncReply.ready(null); else if (result == StructureComparisonResult.Structure) { int cs = data.getUint32(offset); offset += 4; @@ -535,13 +548,13 @@ class Codec { offset += cs; } - reply.add(previous); + reply.add(previous as AsyncReply); while (offset < end) { result = data[offset++]; if (result == StructureComparisonResult.Null) - previous = new AsyncReply.ready(null); + previous = new AsyncReply.ready(null); else if (result == StructureComparisonResult.Structure) { int cs = data.getUint32(offset); offset += 4; @@ -562,7 +575,7 @@ class Codec { offset += cs; } - reply.add(previous); + reply.add(previous as AsyncReply); } reply.seal(); @@ -587,7 +600,10 @@ class Codec { if (includeKeys) { for (var k in value.keys) { var key = DC.stringToBytes(k); - rt.addUint8(key.length).addDC(key).addDC(compose(value[k], connection)); + rt + ..addUint8(key.length) + ..addDC(key) + ..addDC(compose(value[k], connection)); } } else { for (var k in value.keys) @@ -613,9 +629,9 @@ class Codec { /// Structure static AsyncReply parseStructure( DC data, int offset, int length, DistributedConnection connection, - [StructureMetadata metadata = null, - List keys = null, - List types = + [StructureMetadata? metadata = null, + List? keys = null, + List? types = null]) // out string[] parsedKeys, out DataType[] parsedTypes, string[] keys = null, DataType[] types = null) { var reply = new AsyncReply(); @@ -685,9 +701,8 @@ class Codec { /// DistributedConnection is required in case a structure in the array holds items at the other end. /// DataType, in case the data is not prepended with DataType /// Value - static AsyncReply parse( - DC data, int offset, DistributedConnection connection, - [SizeObject sizeObject, int dataType = DataType.Unspecified]) { + static AsyncReply parse(DC data, int offset, DistributedConnection connection, + [SizeObject? sizeObject, int dataType = DataType.Unspecified]) { bool isArray; int t; @@ -850,7 +865,8 @@ class Codec { } } - return null; + // @TODO: Throw exception + return AsyncReply.ready(null); } /// @@ -859,8 +875,8 @@ class Codec { /// Bytes array /// Zero-indexed offset. /// Resource - static AsyncReply parseResource(DC data, int offset) { - return Warehouse.get(data.getUint32(offset)); + static AsyncReply parseResource(DC data, int offset) { + return Warehouse.getById(data.getUint32(offset)); } /// @@ -904,7 +920,7 @@ class Codec { /// Null, same, local, distributed or same class distributed. static int compareResources( - IResource initial, IResource next, DistributedConnection connection) { + IResource? initial, IResource? next, DistributedConnection connection) { if (next == null) return ResourceComparisonResult.Null; else if (next == initial) @@ -924,13 +940,12 @@ class Codec { static DC composeResource( IResource resource, DistributedConnection connection) { if (isLocalResource(resource, connection)) - return DC.uint32ToBytes((resource as DistributedResource).id); + return DC.uint32ToBytes((resource as DistributedResource).id as int); else { - return new BinaryList() - .addGuid(resource.instance.template.classId) - .addUint32(resource.instance.id) + return (BinaryList() + ..addGuid(resource.instance?.template.classId as Guid) + ..addUint32(resource.instance?.id as int)) .toDC(); - //return BinaryList.ToBytes(resource.Instance.Template.ClassId, resource.Instance.Id); } } @@ -943,9 +958,9 @@ class Codec { /// Array of bytes in the network byte order. static DC composeResourceArray( - List resources, DistributedConnection connection, + List? resources, DistributedConnection connection, [bool prependLength = false]) { - if (resources == null || resources?.length == 0) + if (resources == null || resources.length == 0) return prependLength ? new DC(4) : new DC(0); var rt = new BinaryList(); @@ -971,17 +986,17 @@ class Codec { } if (comparsion == ResourceComparisonResult.Local) - rt.addUint32((resources[0] as DistributedResource).id); + rt.addUint32((resources[0] as DistributedResource).id as int); else if (comparsion == ResourceComparisonResult.Distributed) - rt.addUint32(resources[0].instance.id); + rt.addUint32(resources[0].instance?.id as int); for (var i = 1; i < resources.length; i++) { comparsion = compareResources(resources[i - 1], resources[i], connection); rt.addUint8(comparsion); if (comparsion == ResourceComparisonResult.Local) - rt.addUint32((resources[i] as DistributedResource).id); + rt.addUint32((resources[i] as DistributedResource).id as int); else if (comparsion == ResourceComparisonResult.Distributed) - rt.addUint32(resources[i].instance.id); + rt.addUint32(resources[i].instance?.id as int); } if (prependLength) rt.insertInt32(0, rt.length); @@ -997,11 +1012,11 @@ class Codec { /// Zero-indexed offset. /// DistributedConnection is required to fetch resources. /// Array of resources. - static AsyncBag parseResourceArray( + static AsyncBag parseResourceArray( DC data, int offset, int length, DistributedConnection connection) { //print("parseResourceArray ${offset} ${length}"); - var reply = new AsyncBag(); + var reply = new AsyncBag(); if (length == 0) { reply.seal(); return reply; @@ -1031,27 +1046,27 @@ class Codec { reply.arrayType = tmp?.definedType; } - AsyncReply previous = null; + AsyncReply? previous = null; if (result == ResourceComparisonResult.Null) - previous = new AsyncReply.ready(null); + previous = new AsyncReply.ready(null); else if (result == ResourceComparisonResult.Local) { - previous = Warehouse.get(data.getUint32(offset)); + previous = Warehouse.getById(data.getUint32(offset)); offset += 4; } else if (result == ResourceComparisonResult.Distributed) { previous = connection.fetch(data.getUint32(offset)); offset += 4; } - reply.add(previous); + reply.add(previous as AsyncReply); while (offset < end) { result = data[offset++]; - AsyncReply current = null; + AsyncReply? current = null; if (result == ResourceComparisonResult.Null) { - current = new AsyncReply.ready(null); + current = new AsyncReply.ready(null); } else if (result == ResourceComparisonResult.Same) { current = previous; } else if (result == ResourceComparisonResult.Local) { @@ -1062,7 +1077,7 @@ class Codec { offset += 4; } - reply.add(current); + reply.add(current as AsyncReply); previous = current; } @@ -1146,10 +1161,10 @@ class Codec { static DC composePropertyValue(PropertyValue propertyValue, DistributedConnection connection) //, bool includeAge = true) { - return new BinaryList() - .addUint64(propertyValue.age) - .addDateTime(propertyValue.date) - .addDC(compose(propertyValue.value, connection)) + return (BinaryList() + ..addUint64(propertyValue.age) + ..addDateTime(propertyValue.date) + ..addDC(compose(propertyValue.value, connection))) .toDC(); } @@ -1194,7 +1209,8 @@ class Codec { static AsyncReply>> parseHistory(DC data, int offset, int length, IResource resource, DistributedConnection connection) { - var list = new KeyList>(); + var list = < + PropertyTemplate>[]; //new KeyList?>(); var reply = new AsyncReply>>(); @@ -1207,20 +1223,26 @@ class Codec { while (offset < ends) { var index = data[offset++]; - var pt = resource.instance.template.getPropertyTemplateByIndex(index); - list.add(pt, null); - var cs = data.getUint32(offset); - offset += 4; - bagOfBags.add(parsePropertyValueArray(data, offset, cs, connection)); - offset += cs; + var pt = resource.instance?.template.getPropertyTemplateByIndex(index); + if (pt != null) { + list.add(pt); //, null); + var cs = data.getUint32(offset); + offset += 4; + bagOfBags.add(parsePropertyValueArray(data, offset, cs, connection)); + offset += cs; + } } bagOfBags.seal(); bagOfBags.then((x) { - for (var i = 0; i < list.length; i++) list[list.keys.elementAt(i)] = x[i]; + var keyList = KeyList>(); - reply.trigger(list); + for (var i = 0; i < list.length; i++) keyList.add(list[i], x[i]); + + //list[list.keys.elementAt(i)] = x[i]; + + reply.trigger(keyList); }); return reply; @@ -1239,9 +1261,10 @@ class Codec { var rt = new BinaryList(); for (var i = 0; i < history.length; i++) - rt.addUint8(history.keys.elementAt(i).index).addDC( - composePropertyValueArray( - history.values.elementAt(i), connection, true)); + rt + ..addUint8(history.keys.elementAt(i).index) + ..addDC(composePropertyValueArray( + history.values.elementAt(i), connection, true)); if (prependLength) rt.insertInt32(0, rt.length); @@ -1292,7 +1315,7 @@ class Codec { if (value is Function(DistributedConnection)) value = Function.apply(value, [connection]); else if (value is DistributedPropertyContext) - value = (value as DistributedPropertyContext).method(connection); + value = value.method?.call(connection); var type = getDataType(value, connection); var rt = new BinaryList(); @@ -1304,15 +1327,17 @@ class Codec { case DataType.String: var st = DC.stringToBytes(value); - rt.addInt32(st.length).addDC(st); + rt + ..addInt32(st.length) + ..addDC(st); break; case DataType.Resource: - rt.addUint32((value as DistributedResource).id); + rt.addUint32((value as DistributedResource).id as int); break; case DataType.DistributedResource: - rt.addUint32((value as IResource).instance.id); + rt.addUint32((value as IResource).instance?.id as int); break; case DataType.Structure: diff --git a/lib/src/Data/DC.dart b/lib/src/Data/DC.dart index 16aeff4..b2633e6 100644 --- a/lib/src/Data/DC.dart +++ b/lib/src/Data/DC.dart @@ -34,8 +34,8 @@ const UNIX_EPOCH = 621355968000000000; const TWO_PWR_32 = (1 << 16) * (1 << 16); class DC with IterableMixin { - Uint8List _data; - ByteData _dv; + late Uint8List _data; + late ByteData _dv; DC(int length) { _data = new Uint8List(length); @@ -245,7 +245,8 @@ class DC with IterableMixin { var list = new BinaryList(); for (var i = 0; i < value.length; i++) { var s = DC.stringToBytes(value[i]); - list.addUint32(s.length).addUint8Array(s.toArray()); + list..addUint32(s.length) + ..addUint8Array(s.toArray()); } return list.toDC(); @@ -289,67 +290,67 @@ class DC with IterableMixin { Uint8List.fromList(_data.getRange(offset, offset + length).toList())); } - getInt8(int offset) { + int getInt8(int offset) { return _dv.getInt8(offset); } - getUint8(int offset) { + int getUint8(int offset) { return _data[offset]; // this.dv.getUint8(offset); } - getInt16(int offset) { + int getInt16(int offset) { return _dv.getInt16(offset); } - getUint16(int offset) { + int getUint16(int offset) { return _dv.getUint16(offset); } - getInt32(int offset) { + int getInt32(int offset) { return _dv.getInt32(offset); } - getUint32(int offset) { + int getUint32(int offset) { return _dv.getUint32(offset); } - getFloat32(int offset) { + double getFloat32(int offset) { return _dv.getFloat32(offset); } - getFloat64(int offset) { + double getFloat64(int offset) { return _dv.getFloat64(offset); } - setInt8(int offset, int value) { + void setInt8(int offset, int value) { return _dv.setInt8(offset, value); } - setUint8(int offset, int value) { + void setUint8(int offset, int value) { return _dv.setUint8(offset, value); } - setInt16(int offset, int value) { + void setInt16(int offset, int value) { return _dv.setInt16(offset, value); } - setUint16(int offset, int value) { + void setUint16(int offset, int value) { return _dv.setUint16(offset, value); } - setInt32(int offset, int value) { + void setInt32(int offset, int value) { return _dv.setInt32(offset, value); } - setUint32(int offset, int value) { + void setUint32(int offset, int value) { return _dv.setUint32(offset, value); } - setFloat32(int offset, double value) { + void setFloat32(int offset, double value) { return _dv.setFloat32(offset, value); } - setFloat64(int offset, double value) { + void setFloat64(int offset, double value) { return _dv.setFloat64(offset, value); } @@ -397,7 +398,7 @@ class DC with IterableMixin { return this.getUint8(offset) > 0; } - setBoolean(int offset, bool value) { + void setBoolean(int offset, bool value) { this.setUint8(offset, value ? 1 : 0); } @@ -411,7 +412,7 @@ class DC with IterableMixin { return String.fromCharCode(this.getUint16(offset)); } - setChar(int offset, int value) { + void setChar(int offset, int value) { this.setUint16(offset, value); //value.codeUnitAt(0)); } @@ -462,11 +463,11 @@ class DC with IterableMixin { return rt; } - getInt64(offset) { + int getInt64(offset) { return _dv.getUint64(offset); } - getUint64(offset) { + int getUint64(offset) { return _dv.getInt64(offset); } @@ -478,7 +479,7 @@ class DC with IterableMixin { _dv.setUint64(offset, value); } - setDateTime(offset, DateTime value) { + void setDateTime(offset, DateTime value) { // Unix Epoch var ticks = UNIX_EPOCH + (value.millisecondsSinceEpoch * 10000); this.setUint64(offset, ticks); @@ -500,7 +501,7 @@ class DC with IterableMixin { return new Guid(this.clip(offset, 16)); } - setGuid(int offset, Guid guid) { + void setGuid(int offset, Guid guid) { set(guid.value, offset); } diff --git a/lib/src/Data/Guid.dart b/lib/src/Data/Guid.dart index 5b74928..cb6510d 100644 --- a/lib/src/Data/Guid.dart +++ b/lib/src/Data/Guid.dart @@ -3,8 +3,8 @@ import 'DC.dart'; class Guid { DC _data; - Guid(DC data) { - _data = data; + Guid(this._data) { + } DC get value => _data; diff --git a/lib/src/Data/KeyList.dart b/lib/src/Data/KeyList.dart index 9794c83..49ef573 100644 --- a/lib/src/Data/KeyList.dart +++ b/lib/src/Data/KeyList.dart @@ -43,9 +43,9 @@ class KeyList extends IEventHandler with MapMixin { at(int index) => _map.values.elementAt(index); - bool _removableList; + late bool _removableList; - T take(KT key) { + T? take(KT key) { if (_map.containsKey(key)) { var v = _map[key]; remove(key); @@ -89,20 +89,20 @@ class KeyList extends IEventHandler with MapMixin { clear() { if (_removableList) for (var v in _map.values) - (v as IDestructible)?.off("destroy", _itemDestroyed); + (v as IDestructible).off("destroy", _itemDestroyed); _map.clear(); emitArgs("cleared", [this]); } - T remove(key) { + T? remove(key) { if (!_map.containsKey(key)) return null; var value = _map[key]; if (_removableList) - (value as IDestructible)?.off("destroy", _itemDestroyed); + (value as IDestructible).off("destroy", _itemDestroyed); _map.remove(key); diff --git a/lib/src/Data/Record.dart b/lib/src/Data/Record.dart index 8689466..083bc1a 100644 --- a/lib/src/Data/Record.dart +++ b/lib/src/Data/Record.dart @@ -4,7 +4,7 @@ import 'IRecord.dart'; import 'KeyList.dart'; class Record extends KeyList with IRecord { - Map _props; + Map _props = Map(); @override Map serialize() { diff --git a/lib/src/Data/SizeObject.dart b/lib/src/Data/SizeObject.dart index fb2f2d8..f1270d2 100644 --- a/lib/src/Data/SizeObject.dart +++ b/lib/src/Data/SizeObject.dart @@ -1,4 +1,3 @@ -class SizeObject -{ - int size; -} \ No newline at end of file +class SizeObject { + int size = 0; +} diff --git a/lib/src/Data/StructureMetadata.dart b/lib/src/Data/StructureMetadata.dart index 5305f20..ae82e1f 100644 --- a/lib/src/Data/StructureMetadata.dart +++ b/lib/src/Data/StructureMetadata.dart @@ -1,8 +1,6 @@ -class StructureMetadata -{ +class StructureMetadata { + List? keys; // = []; + List? types;// - List keys; - List types; - //const StructureMetadata(this.keys, this.types); -} \ No newline at end of file +} diff --git a/lib/src/Net/IIP/DistributedConnection.dart b/lib/src/Net/IIP/DistributedConnection.dart index fa92116..1bdab86 100644 --- a/lib/src/Net/IIP/DistributedConnection.dart +++ b/lib/src/Net/IIP/DistributedConnection.dart @@ -22,7 +22,6 @@ SOFTWARE. */ - import '../../Resource/Template/TemplateDescriber.dart'; import '../../Resource/Template/TemplateType.dart'; import '../../Security/Authority/AuthenticationMethod.dart'; @@ -93,20 +92,20 @@ class DistributedConnection extends NetworkConnection with IStore { /// //public event ErrorEvent OnError; - AsyncReply _openReply; + AsyncReply? _openReply; - DistributedServer _server; + DistributedServer? _server; IIPPacket _packet = new IIPPacket(); IIPAuthPacket _authPacket = new IIPAuthPacket(); - Session _session; + Session? _session; - DC _localPasswordOrToken; - DC _localNonce, _remoteNonce; + DC? _localPasswordOrToken; + DC? _localNonce, _remoteNonce; - String _hostname; - int _port; + String? _hostname; + int _port = 10518; bool _ready = false, _readyToEstablish = false; @@ -115,8 +114,8 @@ class DistributedConnection extends NetworkConnection with IStore { KeyList> _resourceRequests = new KeyList>(); - KeyList> _templateRequests = - new KeyList>(); + KeyList> _templateRequests = + new KeyList>(); //KeyList> _pathRequests = new KeyList>(); Map _templates = new Map(); KeyList> _requests = @@ -130,13 +129,13 @@ class DistributedConnection extends NetworkConnection with IStore { /// /// Local username to authenticate ourselves. /// - String get localUsername => _session.localAuthentication.username; + String get localUsername => _session?.localAuthentication.username ?? ""; /// /// Peer's username. /// String get remoteUsername => - _session.remoteAuthentication.username; // { get; set; } + _session?.remoteAuthentication.username ?? ""; // { get; set; } /// /// Working domain. @@ -146,7 +145,7 @@ class DistributedConnection extends NetworkConnection with IStore { /// /// The session related to this connection. /// - Session get session => _session; + Session? get session => _session; /// /// Distributed server responsible for this connection, usually for incoming connections. @@ -162,7 +161,7 @@ class DistributedConnection extends NetworkConnection with IStore { /// Send data to the other end as parameters /// /// Values will be converted to bytes then sent. - SendList sendParams([AsyncReply> reply = null]) { + SendList sendParams([AsyncReply>? reply = null]) { return new SendList(this, reply); } @@ -181,21 +180,19 @@ class DistributedConnection extends NetworkConnection with IStore { if (trigger == ResourceTrigger.Open) { if (_server != null) return new AsyncReply.ready(true); - var host = instance.name.split(":"); + var host = (instance as Instance).name.split(":"); // assign domain from hostname if not provided var address = host[0]; var port = host.length > 1 ? int.parse(host[1]) : 10518; - var domain = instance.attributes.containsKey("domain") - ? instance.attributes["domain"] - : address; + var domain = instance?.attributes["domain"] ?? address; - if (instance.attributes.containsKey("username") && - instance.attributes.containsKey("password")) { - var username = instance.attributes["username"].toString(); + if (instance?.attributes.containsKey("username") == true && + instance?.attributes.containsKey("password") == true) { + var username = instance?.attributes["username"] as String; var password = - DC.stringToBytes(instance.attributes["password"].toString()); + DC.stringToBytes(instance?.attributes["password"] as String); return connect( method: AuthenticationMethod.Credentials, @@ -204,9 +201,9 @@ class DistributedConnection extends NetworkConnection with IStore { port: port, passwordOrToken: password, username: username); - } else if (instance.attributes.containsKey("token")) { - var token = DC.stringToBytes(instance.attributes["token"].toString()); - var tokenIndex = instance.attributes["tokenIndex"] ?? 0; + } else if (instance?.attributes.containsKey("token") == true) { + var token = DC.stringToBytes(instance?.attributes["token"] ?? ""); + var tokenIndex = instance?.attributes["tokenIndex"] ?? 0; return connect( method: AuthenticationMethod.Credentials, domain: domain, @@ -227,14 +224,14 @@ class DistributedConnection extends NetworkConnection with IStore { } AsyncReply connect( - {AuthenticationMethod method, - ISocket socket, - String hostname, - int port, - String username, - int tokenIndex, - DC passwordOrToken, - String domain}) { + {AuthenticationMethod method = AuthenticationMethod.None, + ISocket? socket, + String? hostname, + int? port, + String? username, + int? tokenIndex, + DC? passwordOrToken, + String? domain}) { if (_openReply != null) throw AsyncException(ErrorType.Exception, 0, "Connection in progress"); @@ -244,10 +241,10 @@ class DistributedConnection extends NetworkConnection with IStore { _session = new Session(new ClientAuthentication(), new HostAuthentication()); - _session.localAuthentication.method = method; - _session.localAuthentication.tokenIndex = tokenIndex; - _session.localAuthentication.domain = domain; - _session.localAuthentication.username = username; + _session?.localAuthentication.method = method; + _session?.localAuthentication.tokenIndex = tokenIndex; + _session?.localAuthentication.domain = domain; + _session?.localAuthentication.username = username; _localPasswordOrToken = passwordOrToken; } @@ -259,14 +256,16 @@ class DistributedConnection extends NetworkConnection with IStore { _port = port ?? _port; _hostname = hostname ?? _hostname; - socket.connect(_hostname, _port).then((x) { - assign(socket); + if (_hostname == null) throw Exception("Host not specified."); + + socket.connect(_hostname as String, _port).then((x) { + assign(socket as ISocket); }).error((x) { - _openReply.triggerError(x); + _openReply?.triggerError(x); _openReply = null; }); - return _openReply; + return _openReply as AsyncReply; } @override @@ -316,42 +315,42 @@ class DistributedConnection extends NetworkConnection with IStore { /// /// IResource interface. /// - Instance instance; + Instance? instance; _declare() { - var dmn = DC.stringToBytes(session.localAuthentication.domain); + var dmn = DC.stringToBytes(_session?.localAuthentication.domain ?? ""); - if (session.localAuthentication.method == + if (_session?.localAuthentication.method == AuthenticationMethod.Credentials) { // declare (Credentials -> No Auth, No Enctypt) - var un = DC.stringToBytes(session.localAuthentication.username); + var un = DC.stringToBytes(_session?.localAuthentication.username ?? ""); sendParams() - .addUint8(0x60) - .addUint8(dmn.length) - .addDC(dmn) - .addDC(_localNonce) - .addUint8(un.length) - .addDC(un) - .done(); //, dmn, localNonce, (byte)un.Length, un); - } else if (session.localAuthentication.method == + ..addUint8(0x60) + ..addUint8(dmn.length) + ..addDC(dmn) + ..addDC(_localNonce as DC) + ..addUint8(un.length) + ..addDC(un) + ..done(); //, dmn, localNonce, (byte)un.Length, un); + } else if (_session?.localAuthentication.method == AuthenticationMethod.Token) { sendParams() - .addUint8(0x70) - .addUint8(dmn.length) - .addDC(dmn) - .addDC(_localNonce) - .addUint64(session.localAuthentication.tokenIndex) - .done(); //, dmn, localNonce, token + ..addUint8(0x70) + ..addUint8(dmn.length) + ..addDC(dmn) + ..addDC(_localNonce as DC) + ..addUint64(_session?.localAuthentication.tokenIndex ?? 0) + ..done(); //, dmn, localNonce, token - } else if (session.localAuthentication.method == + } else if (_session?.localAuthentication.method == AuthenticationMethod.None) { sendParams() - .addUint8(0x40) - .addUint8(dmn.length) - .addDC(dmn) - .done(); //, dmn, localNonce, token + ..addUint8(0x40) + ..addUint8(dmn.length) + ..addDC(dmn) + ..done(); //, dmn, localNonce, token } } @@ -362,16 +361,16 @@ class DistributedConnection extends NetworkConnection with IStore { assign(ISocket socket) { super.assign(socket); - session.remoteAuthentication.source.attributes[SourceAttributeType.IPv4] = - socket.remoteEndPoint.address; - session.remoteAuthentication.source.attributes[SourceAttributeType.Port] = - socket.remoteEndPoint.port; - session.localAuthentication.source.attributes[SourceAttributeType.IPv4] = - socket.localEndPoint.address; - session.localAuthentication.source.attributes[SourceAttributeType.Port] = - socket.localEndPoint.port; + _session?.remoteAuthentication.source + ?.attributes[SourceAttributeType.IPv4] = socket.remoteEndPoint?.address; + _session?.remoteAuthentication.source + ?.attributes[SourceAttributeType.Port] = socket.remoteEndPoint?.port; + _session?.localAuthentication.source?.attributes[SourceAttributeType.IPv4] = + socket.localEndPoint?.address; + _session?.localAuthentication.source?.attributes[SourceAttributeType.Port] = + socket.localEndPoint?.port; - if (session.localAuthentication.type == AuthenticationType.Client) { + if (_session?.localAuthentication.type == AuthenticationType.Client) { // declare (Credentials -> No Auth, No Enctypt) _declare(); } @@ -429,10 +428,10 @@ class DistributedConnection extends NetworkConnection with IStore { init(); } - String link(IResource resource) { + String? link(IResource resource) { if (resource is DistributedResource) { - if (resource.instance.store == this) - return this.instance.name + "/" + resource.id.toString(); + if (resource.instance?.store == this) + return (this.instance?.name ?? "") + "/" + resource.id.toString(); } return null; @@ -440,15 +439,16 @@ class DistributedConnection extends NetworkConnection with IStore { void init() { _queue.then((x) { - if (x.type == DistributedResourceQueueItemType.Event) - x.resource.internal_emitEventByIndex(x.index, x.value); + if (x?.type == DistributedResourceQueueItemType.Event) + x?.resource.internal_emitEventByIndex(x.index, x.value); else - x.resource.internal_updatePropertyByIndex(x.index, x.value); + x?.resource.internal_updatePropertyByIndex(x.index, x.value); }); var r = new Random(); - _localNonce = new DC(32); - for (var i = 0; i < 32; i++) _localNonce[i] = r.nextInt(255); + var n = new DC(32); + for (var i = 0; i < 32; i++) n[i] = r.nextInt(255); + _localNonce = n; } int processPacket( @@ -732,7 +732,7 @@ class DistributedConnection extends NetworkConnection with IStore { } else { offset += rt; - if (session.localAuthentication.type == AuthenticationType.Host) { + if (_session?.localAuthentication.type == AuthenticationType.Host) { if (_authPacket.command == IIPAuthPacketCommand.Declare) { if (_authPacket.remoteMethod == AuthenticationMethod.Credentials && _authPacket.localMethod == AuthenticationMethod.None) { @@ -796,14 +796,20 @@ class DistributedConnection extends NetworkConnection with IStore { IIPAuthPacketAction.NewConnection) { if (_readyToEstablish) { var r = new Random(); - session.id = new DC(32); - for (var i = 0; i < 32; i++) session.id[i] = r.nextInt(255); - sendParams().addUint8(0x28).addDC(session.id).done(); + var sid = DC(32); + + for (var i = 0; i < 32; i++) sid[i] = r.nextInt(255); + _session?.id = sid; + + sendParams() + ..addUint8(0x28) + ..addDC(sid) + ..done(); _ready = true; - _openReply.trigger(true); + _openReply?.trigger(true); _openReply = null; emitArgs("ready", []); //OnReady?.Invoke(this); @@ -812,55 +818,64 @@ class DistributedConnection extends NetworkConnection with IStore { } } } - } else if (_session.localAuthentication.type == + } else if (_session?.localAuthentication.type == AuthenticationType.Client) { if (_authPacket.command == IIPAuthPacketCommand.Acknowledge) { if (_authPacket.remoteMethod == AuthenticationMethod.None) { - sendParams().addUint8(0x20).addUint16(0).done(); + sendParams() + ..addUint8(0x20) + ..addUint16(0) + ..done(); } else if (_authPacket.remoteMethod == AuthenticationMethod.Credentials || _authPacket.remoteMethod == AuthenticationMethod.Token) { _remoteNonce = _authPacket.remoteNonce; // send our hash - var localHash = SHA256.compute(new BinaryList() - .addDC(_localPasswordOrToken) - .addDC(_localNonce) - .addDC(_remoteNonce) + var localHash = SHA256.compute((BinaryList() + ..addDC(_localPasswordOrToken as DC) + ..addDC(_localNonce as DC) + ..addDC(_remoteNonce as DC)) .toDC()); - sendParams().addUint8(0).addDC(localHash).done(); + sendParams() + ..addUint8(0) + ..addDC(localHash) + ..done(); } //SendParams((byte)0, localHash); } else if (_authPacket.command == IIPAuthPacketCommand.Action) { if (_authPacket.action == IIPAuthPacketAction.AuthenticateHash) { // check if the server knows my password - var remoteHash = SHA256.compute(new BinaryList() - .addDC(_remoteNonce) - .addDC(_localNonce) - .addDC(_localPasswordOrToken) + var remoteHash = SHA256.compute((BinaryList() + ..addDC(_remoteNonce as DC) + ..addDC(_localNonce as DC) + ..addDC(_localPasswordOrToken as DC)) .toDC()); if (remoteHash.sequenceEqual(_authPacket.hash)) { // send establish request - sendParams().addUint8(0x20).addUint16(0).done(); + sendParams() + ..addUint8(0x20) + ..addUint16(0) + ..done(); } else { sendParams() - .addUint8(0xc0) - .addUint8(ExceptionCode.ChallengeFailed.index) - .addUint16(16) - .addString("Challenge Failed") - .done(); + ..addUint8(0xc0) + ..addUint8(ExceptionCode.ChallengeFailed.index) + ..addUint16(16) + ..addString("Challenge Failed") + ..done(); //SendParams((byte)0xc0, 1, 5, DC.ToBytes("Error")); } } else if (_authPacket.action == IIPAuthPacketAction.ConnectionEstablished) { - session.id = _authPacket.sessionId; + _session?.id = _authPacket.sessionId; _ready = true; - _openReply.trigger(true); + _openReply?.trigger(true); _openReply = null; emitArgs("ready", []); @@ -870,7 +885,7 @@ class DistributedConnection extends NetworkConnection with IStore { } else if (_authPacket.command == IIPAuthPacketCommand.Error) { var ex = AsyncException(ErrorType.Management, _authPacket.errorCode, _authPacket.errorMessage); - _openReply.triggerError(ex); + _openReply?.triggerError(ex); _openReply = null; emitArgs("error", [ex]); //OnError?.Invoke(this, authPacket.ErrorCode, authPacket.ErrorMessage); @@ -891,14 +906,17 @@ class DistributedConnection extends NetworkConnection with IStore { // Console.WriteLine("DR " + hostType + " " + data.Available + " " + RemoteEndPoint.ToString()); var msg = data.read(); int offset = 0; - int ends = msg.length; - //List packs = []; + if (msg != null) { + int ends = msg.length; - var chunkId = (new Random()).nextInt(1000000); + //List packs = []; - while (offset < ends) { - offset = processPacket(msg, offset, ends, data, chunkId); + var chunkId = (new Random()).nextInt(1000000); + + while (offset < ends) { + offset = processPacket(msg, offset, ends, data, chunkId); + } } } @@ -919,7 +937,7 @@ class DistributedConnection extends NetworkConnection with IStore { /// AsyncReply put(IResource resource) { if (Codec.isLocalResource(resource, this)) - _resources.add((resource as DistributedResource).id, resource); + _resources.add((resource as DistributedResource).id as int, resource); // else .. put it in the server.... return AsyncReply.ready(true); } @@ -947,17 +965,21 @@ class DistributedConnection extends NetworkConnection with IStore { var c = _callbackCounter++; // avoid thread racing _requests.add(c, reply); - return sendParams(reply).addUint8(0x40 | action).addUint32(c); + return (sendParams(reply) + ..addUint8(0x40 | action) + ..addUint32(c)); } //int _maxcallerid = 0; SendList sendReply(int action, int callbackId) { - return sendParams().addUint8((0x80 | action)).addUint32(callbackId); + return (sendParams() + ..addUint8((0x80 | action)) + ..addUint32(callbackId)); } SendList sendEvent(int evt) { - return sendParams().addUint8((evt)); + return (sendParams()..addUint8((evt))); } AsyncReply sendListenRequest(int instanceId, int index) { @@ -966,11 +988,11 @@ class DistributedConnection extends NetworkConnection with IStore { _requests.add(c, reply); sendParams() - .addUint8(0x40 | IIPPacketAction.Listen) - .addUint32(c) - .addUint32(instanceId) - .addUint8(index) - .done(); + ..addUint8(0x40 | IIPPacketAction.Listen) + ..addUint32(c) + ..addUint32(instanceId) + ..addUint8(index) + ..done(); return reply; } @@ -980,11 +1002,11 @@ class DistributedConnection extends NetworkConnection with IStore { _requests.add(c, reply); sendParams() - .addUint8(0x40 | IIPPacketAction.Unlisten) - .addUint32(c) - .addUint32(instanceId) - .addUint8(index) - .done(); + ..addUint8(0x40 | IIPPacketAction.Unlisten) + ..addUint32(c) + ..addUint32(instanceId) + ..addUint8(index) + ..done(); return reply; } @@ -997,19 +1019,19 @@ class DistributedConnection extends NetworkConnection with IStore { _requests.add(c, reply); sendParams() - .addUint8(0x40 | IIPPacketAction.InvokeFunctionArrayArguments) - .addUint32(c) - .addUint32(instanceId) - .addUint8(index) - .addDC(pb) - .done(); + ..addUint8(0x40 | IIPPacketAction.InvokeFunctionArrayArguments) + ..addUint32(c) + ..addUint32(instanceId) + ..addUint8(index) + ..addDC(pb) + ..done(); return reply; } - AsyncReply sendDetachRequest(int instanceId) { + AsyncReply? sendDetachRequest(int instanceId) { try { - return sendRequest(IIPPacketAction.DetachResource) - .addUint32(instanceId) + return (sendRequest(IIPPacketAction.DetachResource) + ..addUint32(instanceId)) .done(); } catch (ex) { return null; @@ -1025,54 +1047,54 @@ class DistributedConnection extends NetworkConnection with IStore { _requests.add(c, reply); sendParams() - .addUint8(0x40 | IIPPacketAction.InvokeFunctionNamedArguments) - .addUint32(c) - .addUint32(instanceId) - .addUint8(index) - .addDC(pb) - .done(); + ..addUint8(0x40 | IIPPacketAction.InvokeFunctionNamedArguments) + ..addUint32(c) + ..addUint32(instanceId) + ..addUint8(index) + ..addDC(pb) + ..done(); return reply; } void sendError(ErrorType type, int callbackId, int errorCode, - [String errorMessage = ""]) { - var msg = DC.stringToBytes(errorMessage); + [String? errorMessage]) { + var msg = DC.stringToBytes(errorMessage ?? ""); if (type == ErrorType.Management) sendParams() - .addUint8(0xC0 | IIPPacketReport.ManagementError) - .addUint32(callbackId) - .addUint16(errorCode) - .done(); + ..addUint8(0xC0 | IIPPacketReport.ManagementError) + ..addUint32(callbackId) + ..addUint16(errorCode) + ..done(); else if (type == ErrorType.Exception) sendParams() - .addUint8(0xC0 | IIPPacketReport.ExecutionError) - .addUint32(callbackId) - .addUint16(errorCode) - .addUint16(msg.length) - .addDC(msg) - .done(); + ..addUint8(0xC0 | IIPPacketReport.ExecutionError) + ..addUint32(callbackId) + ..addUint16(errorCode) + ..addUint16(msg.length) + ..addDC(msg) + ..done(); } void sendProgress(int callbackId, int value, int max) { sendParams() - .addUint8(0xC0 | IIPPacketReport.ProgressReport) - .addUint32(callbackId) - .addInt32(value) - .addInt32(max) - .done(); + ..addUint8(0xC0 | IIPPacketReport.ProgressReport) + ..addUint32(callbackId) + ..addInt32(value) + ..addInt32(max) + ..done(); //SendParams(, callbackId, value, max); } void sendChunk(int callbackId, dynamic chunk) { var c = Codec.compose(chunk, this, true); sendParams() - .addUint8(0xC0 | IIPPacketReport.ChunkStream) - .addUint32(callbackId) - .addDC(c) - .done(); + ..addUint8(0xC0 | IIPPacketReport.ChunkStream) + ..addUint32(callbackId) + ..addDC(c) + ..done(); } - void iipReply(int callbackId, [List results = null]) { + void iipReply(int callbackId, [List? results = null]) { var req = _requests.take(callbackId); req?.trigger(results); } @@ -1085,8 +1107,8 @@ class DistributedConnection extends NetworkConnection with IStore { }); } - void iipReportError( - int callbackId, ErrorType errorType, int errorCode, String errorMessage) { + void iipReportError(int callbackId, ErrorType errorType, int errorCode, + String? errorMessage) { var req = _requests.take(callbackId); req?.triggerError(new AsyncException(errorType, errorCode, errorMessage)); } @@ -1101,7 +1123,7 @@ class DistributedConnection extends NetworkConnection with IStore { if (_requests.containsKey(callbackId)) { var req = _requests[callbackId]; Codec.parse(data, 0, this).then((x) { - req.triggerChunk(x); + req?.triggerChunk(x); }); } } @@ -1112,7 +1134,7 @@ class DistributedConnection extends NetworkConnection with IStore { if (_resources.contains(resourceId)) { var r = _resources[resourceId]; _resources.remove(resourceId); - r.destroy(); + r?.destroy(); } } @@ -1122,13 +1144,10 @@ class DistributedConnection extends NetworkConnection with IStore { _queue.add(item); Codec.parse(content, 0, this).then((arguments) { - var pt = r.instance.template.getPropertyTemplateByIndex(index); + var pt = r.instance?.template.getPropertyTemplateByIndex(index); if (pt != null) { - item.trigger(new DistributedResourceQueueItem( - r as DistributedResource, - DistributedResourceQueueItemType.Propery, - arguments, - index)); + item.trigger(DistributedResourceQueueItem( + r, DistributedResourceQueueItemType.Propery, arguments, index)); } else { // ft found, fi not found, this should never happen _queue.remove(item); @@ -1180,7 +1199,7 @@ class DistributedConnection extends NetworkConnection with IStore { _queue.add(item); Codec.parse(content, 0, this).then((arguments) { - var et = r.instance.template.getEventTemplateByIndex(index); + var et = r.instance?.template.getEventTemplateByIndex(index); if (et != null) { item.trigger(new DistributedResourceQueueItem( r, DistributedResourceQueueItemType.Event, arguments, index)); @@ -1229,40 +1248,50 @@ class DistributedConnection extends NetworkConnection with IStore { void iipEventChildAdded(int resourceId, int childId) { fetch(resourceId).then((parent) { - fetch(childId).then((child) { - parent.instance.children.add(child); - }); + if (parent != null) + fetch(childId).then((child) { + if (child != null) parent.instance?.children.add(child); + }); }); } void iipEventChildRemoved(int resourceId, int childId) { fetch(resourceId).then((parent) { - fetch(childId).then((child) { - parent.instance.children.remove(child); - }); + if (parent != null) + fetch(childId).then((child) { + if (child != null) parent.instance?.children.remove(child); + }); }); } void iipEventRenamed(int resourceId, DC name) { - fetch(resourceId).then((resource) { - resource.instance.attributes["name"] = name.getString(0, name.length); - }); + fetch(resourceId) + ..then((resource) { + if (resource != null) { + resource.instance?.attributes["name"] = + name.getString(0, name.length); + } + }); } void iipEventAttributesUpdated(int resourceId, DC attributes) { - fetch(resourceId).then((resource) { - var attrs = attributes.getStringArray(0, attributes.length); + fetch(resourceId) + ..then((resource) { + if (resource != null) { + var attrs = attributes.getStringArray(0, attributes.length); - getAttributes(resource, attrs).then((s) { - resource.instance.setAttributes(s); + getAttributes(resource, attrs).then((s) { + resource.instance?.setAttributes(s); + }); + } }); - }); } void iipRequestAttachResource(int callback, int resourceId) { Warehouse.getById(resourceId).then((r) { if (r != null) { - if (r.instance.applicable(session, ActionType.Attach, null) == + if (r.instance + ?.applicable(_session as Session, ActionType.Attach, null) == Ruling.Denied) { sendError(ErrorType.Management, callback, 6); return; @@ -1270,28 +1299,28 @@ class DistributedConnection extends NetworkConnection with IStore { _unsubscrive(r); - var link = DC.stringToBytes(r.instance.link); + var link = DC.stringToBytes(r.instance?.link ?? ""); if (r is DistributedResource) { // reply ok sendReply(IIPPacketAction.AttachResource, callback) - .addGuid(r.instance.template.classId) - .addUint64(r.instance.age) - .addUint16(link.length) - .addDC(link) - .addDC(Codec.composePropertyValueArray( - (r as DistributedResource).internal_serialize(), this, true)) - .done(); + ..addGuid(r.instance?.template.classId as Guid) + ..addUint64(r.instance?.age as int) + ..addUint16(link.length) + ..addDC(link) + ..addDC(Codec.composePropertyValueArray( + r.internal_serialize(), this, true)) + ..done(); } else { // reply ok sendReply(IIPPacketAction.AttachResource, callback) - .addGuid(r.instance.template.classId) - .addUint64(r.instance.age) - .addUint16(link.length) - .addDC(link) - .addDC(Codec.composePropertyValueArray( - r.instance.serialize(), this, true)) - .done(); + ..addGuid((r.instance as Instance).template.classId) + ..addUint64((r.instance as Instance).age) + ..addUint16(link.length) + ..addDC(link) + ..addDC(Codec.composePropertyValueArray( + (r.instance as Instance).serialize(), this, true)) + ..done(); } _subscribe(r); @@ -1313,39 +1342,39 @@ class DistributedConnection extends NetworkConnection with IStore { var instance = (sender.owner as Instance); var name = DC.stringToBytes(newValue.toString()); sendEvent(IIPPacketEvent.ChildRemoved) - .addUint32(instance.id) - .addUint16(name.length) - .addDC(name) - .done(); + ..addUint32(instance.id) + ..addUint16(name.length) + ..addDC(name) + ..done(); } } void _children_OnRemoved(Instance sender, IResource value) { sendEvent(IIPPacketEvent.ChildRemoved) - .addUint32(sender.id) - .addUint32(value.instance.id) - .done(); + ..addUint32(sender.id) + ..addUint32(value.instance?.id as int) + ..done(); } void _children_OnAdd(Instance sender, IResource value) { //if (sender.applicable(sender.Resource, this.session, ActionType.)) sendEvent(IIPPacketEvent.ChildAdded) - .addUint32(sender.id) - .addUint32(value.instance.id) - .done(); + ..addUint32(sender.id) + ..addUint32((value.instance as Instance).id) + ..done(); } void _subscribe(IResource resource) { - resource.instance.on("resourceEventOccurred", _instance_EventOccurred); - resource.instance.on("resourceModified", _instance_PropertyModified); - resource.instance.on("resourceDestroyed", _instance_ResourceDestroyed); - _subscriptions[resource] = new List(); + resource.instance?.on("resourceEventOccurred", _instance_EventOccurred); + resource.instance?.on("resourceModified", _instance_PropertyModified); + resource.instance?.on("resourceDestroyed", _instance_ResourceDestroyed); + _subscriptions[resource] = []; } void _unsubscrive(IResource resource) { - resource.instance.off("resourceEventOccurred", _instance_EventOccurred); - resource.instance.off("resourceModified", _instance_PropertyModified); - resource.instance.off("resourceDestroyed", _instance_ResourceDestroyed); + resource.instance?.off("resourceEventOccurred", _instance_EventOccurred); + resource.instance?.off("resourceModified", _instance_PropertyModified); + resource.instance?.off("resourceDestroyed", _instance_ResourceDestroyed); _subscriptions.remove(resource); } @@ -1358,10 +1387,10 @@ class DistributedConnection extends NetworkConnection with IStore { // reply ok sendReply(IIPPacketAction.ReattachResource, callback) - .addUint64(r.instance.age) - .addDC(Codec.composePropertyValueArray( - r.instance.serialize(), this, true)) - .done(); + ..addUint64((r.instance as Instance).age) + ..addDC(Codec.composePropertyValueArray( + (r.instance as Instance).serialize(), this, true)) + ..done(); } else { // reply failed sendError(ErrorType.Management, callback, @@ -1384,6 +1413,7 @@ class DistributedConnection extends NetworkConnection with IStore { }); } +//@TODO: implement this void iipRequestCreateResource( int callback, int storeId, int parentId, DC content) { Warehouse.getById(storeId).then((store) { @@ -1400,7 +1430,8 @@ class DistributedConnection extends NetworkConnection with IStore { } // check security - if (store.instance.applicable(session, ActionType.CreateResource, null) != + if (store.instance?.applicable( + _session as Session, ActionType.CreateResource, null) != Ruling.Allowed) { sendError( ErrorType.Management, callback, ExceptionCode.CreateDenied.index); @@ -1411,7 +1442,7 @@ class DistributedConnection extends NetworkConnection with IStore { // check security if (parent != null) if (parent.instance - .applicable(session, ActionType.AddChild, null) != + ?.applicable(_session as Session, ActionType.AddChild, null) != Ruling.Allowed) { sendError(ErrorType.Management, callback, ExceptionCode.AddChildDenied.index); @@ -1461,15 +1492,15 @@ class DistributedConnection extends NetworkConnection with IStore { var pi = matching[0].getParameters(); // cast arguments - List args = null; + //List? args = null; if (pi.length > 0) { int argsCount = pi.length; - args = new List(pi.length); + //args = new List(pi.length); if (pi[pi.length - 1].parameterType.runtimeType == DistributedConnection) { - args[--argsCount] = this; + //args[--argsCount] = this; } if (parameters != null) { @@ -1480,14 +1511,15 @@ class DistributedConnection extends NetworkConnection with IStore { } // create the resource - IResource resource = + IResource? resource = null; //Activator.CreateInstance(type, args) as IResource; - Warehouse.put(name, resource, store as IStore, parent) + Warehouse.put( + name, resource as IResource, store, parent) .then((ok) { sendReply(IIPPacketAction.CreateResource, callback) - .addUint32(resource.instance.id) - .done(); + ..addUint32((resource.instance as Instance).id) + ..done(); }).error((ex) { // send some error sendError(ErrorType.Management, callback, @@ -1508,8 +1540,8 @@ class DistributedConnection extends NetworkConnection with IStore { return; } - if (r.instance.store.instance - .applicable(session, ActionType.Delete, null) != + if (r.instance?.store?.instance + ?.applicable(_session as Session, ActionType.Delete, null) != Ruling.Allowed) { sendError( ErrorType.Management, callback, ExceptionCode.DeleteDenied.index); @@ -1535,27 +1567,28 @@ class DistributedConnection extends NetworkConnection with IStore { } // if (!r.instance.store.instance.applicable(r, session, ActionType.InquireAttributes, null)) - if (r.instance.applicable(session, ActionType.InquireAttributes, null) != + if (r.instance?.applicable( + _session as Session, ActionType.InquireAttributes, null) != Ruling.Allowed) { sendError(ErrorType.Management, callback, ExceptionCode.ViewAttributeDenied.index); return; } - List attrs = null; + List? attrs = null; if (!all) attrs = attributes.getStringArray(0, attributes.length); - var st = r.instance.getAttributes(attrs); + var st = r.instance?.getAttributes(attrs); if (st != null) sendReply( - all - ? IIPPacketAction.GetAllAttributes - : IIPPacketAction.GetAttributes, - callback) - .addDC(Codec.composeStructure(st, this, true, true, true)) - .done(); + all + ? IIPPacketAction.GetAllAttributes + : IIPPacketAction.GetAttributes, + callback) + ..addDC(Codec.composeStructure(st, this, true, true, true)) + ..done(); else sendError(ErrorType.Management, callback, ExceptionCode.GetAttributesFailed.index); @@ -1578,7 +1611,7 @@ class DistributedConnection extends NetworkConnection with IStore { } if (parent.instance - .applicable(this.session, ActionType.AddChild, null) != + ?.applicable(_session as Session, ActionType.AddChild, null) != Ruling.Allowed) { sendError(ErrorType.Management, callback, ExceptionCode.AddChildDenied.index); @@ -1586,14 +1619,14 @@ class DistributedConnection extends NetworkConnection with IStore { } if (child.instance - .applicable(this.session, ActionType.AddParent, null) != + ?.applicable(_session as Session, ActionType.AddParent, null) != Ruling.Allowed) { sendError(ErrorType.Management, callback, ExceptionCode.AddParentDenied.index); return; } - parent.instance.children.add(child); + parent.instance?.children.add(child); sendReply(IIPPacketAction.AddChild, callback).done(); //child.instance.Parents @@ -1616,23 +1649,23 @@ class DistributedConnection extends NetworkConnection with IStore { return; } - if (parent.instance - .applicable(this.session, ActionType.RemoveChild, null) != + if (parent.instance?.applicable( + _session as Session, ActionType.RemoveChild, null) != Ruling.Allowed) { sendError(ErrorType.Management, callback, ExceptionCode.AddChildDenied.index); return; } - if (child.instance - .applicable(this.session, ActionType.RemoveParent, null) != + if (child.instance?.applicable( + _session as Session, ActionType.RemoveParent, null) != Ruling.Allowed) { sendError(ErrorType.Management, callback, ExceptionCode.AddParentDenied.index); return; } - parent.instance.children.remove(child); + parent.instance?.children.remove(child); sendReply(IIPPacketAction.RemoveChild, callback).done(); //child.instance.Parents @@ -1648,14 +1681,15 @@ class DistributedConnection extends NetworkConnection with IStore { return; } - if (resource.instance.applicable(this.session, ActionType.Rename, null) != + if (resource.instance + ?.applicable(_session as Session, ActionType.Rename, null) != Ruling.Allowed) { sendError( ErrorType.Management, callback, ExceptionCode.RenameDenied.index); return; } - resource.instance.name = name.getString(0, name.length); + resource.instance?.name = name.getString(0, name.length); sendReply(IIPPacketAction.RenameResource, callback).done(); }); } @@ -1669,9 +1703,11 @@ class DistributedConnection extends NetworkConnection with IStore { } sendReply(IIPPacketAction.ResourceChildren, callback) - .addDC(Codec.composeResourceArray( - resource.instance.children.toList(), this, true)) - .done(); + ..addDC(Codec.composeResourceArray( + resource.instance?.children.toList() as List, + this, + true)) + ..done(); }); } @@ -1684,9 +1720,9 @@ class DistributedConnection extends NetworkConnection with IStore { } sendReply(IIPPacketAction.ResourceParents, callback) - .addDC(Codec.composeResourceArray( - resource.instance.parents.toList(), this, true)) - .done(); + ..addDC(Codec.composeResourceArray( + resource.instance?.parents.toList() as List, this, true)) + ..done(); }); } @@ -1699,19 +1735,19 @@ class DistributedConnection extends NetworkConnection with IStore { return; } - if (r.instance.store.instance - .applicable(session, ActionType.UpdateAttributes, null) != + if (r.instance?.store?.instance?.applicable( + _session as Session, ActionType.UpdateAttributes, null) != Ruling.Allowed) { sendError(ErrorType.Management, callback, ExceptionCode.UpdateAttributeDenied.index); return; } - List attrs = null; + List? attrs = null; if (!all) attrs = attributes.getStringArray(0, attributes.length); - if (r.instance.removeAttributes(attrs)) + if (r.instance?.removeAttributes(attrs) == true) sendReply( all ? IIPPacketAction.ClearAllAttributes @@ -1733,8 +1769,8 @@ class DistributedConnection extends NetworkConnection with IStore { return; } - if (r.instance.store.instance - .applicable(session, ActionType.UpdateAttributes, null) != + if (r.instance?.store?.instance?.applicable( + _session as Session, ActionType.UpdateAttributes, null) != Ruling.Allowed) { sendError(ErrorType.Management, callback, ExceptionCode.UpdateAttributeDenied.index); @@ -1743,7 +1779,7 @@ class DistributedConnection extends NetworkConnection with IStore { Codec.parseStructure(attributes, 0, attributes.length, this) .then((attrs) { - if (r.instance.setAttributes(attrs, clearAttributes)) + if (r.instance?.setAttributes(attrs, clearAttributes) == true) sendReply( clearAttributes ? IIPPacketAction.ClearAllAttributes @@ -1758,13 +1794,14 @@ class DistributedConnection extends NetworkConnection with IStore { } void iipRequestLinkTemplates(int callback, String resourceLink) { - var queryCallback = (List r) { + var queryCallback = (List? r) { if (r == null) sendError(ErrorType.Management, callback, ExceptionCode.ResourceNotFound.index); else { var list = r.where((x) => - x.instance.applicable(session, ActionType.ViewTemplate, null) != + x.instance?.applicable( + _session as Session, ActionType.ViewTemplate, null) != Ruling.Denied); if (list.length == 0) @@ -1777,26 +1814,28 @@ class DistributedConnection extends NetworkConnection with IStore { List templates = []; list.forEach((resource) { - templates.addAll( - TypeTemplate.getDependencies(resource.instance.template) - .where((x) => !templates.contains(x))); + templates.addAll(TypeTemplate.getDependencies( + resource.instance?.template as TypeTemplate) + .where((x) => !templates.contains(x))); }); templates.forEach((t) { - msg.addInt32(t.content.length).addDC(t.content); + msg + ..addInt32(t.content.length) + ..addDC(t.content); }); // digggg sendReply(IIPPacketAction.LinkTemplates, callback) - .addInt32(msg.length) - .addUint8Array(msg.toArray()) - .done(); + ..addInt32(msg.length) + ..addUint8Array(msg.toArray()) + ..done(); } } }; if (_server?.entryPoint != null) - _server.entryPoint.query(resourceLink, this).then(queryCallback); + _server?.entryPoint?.query(resourceLink, this).then(queryCallback); else Warehouse.query(resourceLink).then(queryCallback); } @@ -1805,9 +1844,9 @@ class DistributedConnection extends NetworkConnection with IStore { var t = Warehouse.getTemplateByClassName(className); if (t != null) { sendReply(IIPPacketAction.TemplateFromClassName, callback) - .addInt32(t.content.length) - .addDC(t.content) - .done(); + ..addInt32(t.content.length) + ..addDC(t.content) + ..done(); } else { // reply failed sendError( @@ -1819,9 +1858,9 @@ class DistributedConnection extends NetworkConnection with IStore { var t = Warehouse.getTemplateByClassId(classId); if (t != null) sendReply(IIPPacketAction.TemplateFromClassId, callback) - .addInt32(t.content.length) - .addDC(t.content) - .done(); + ..addInt32(t.content.length) + ..addDC(t.content) + ..done(); else { // reply failed sendError( @@ -1833,9 +1872,9 @@ class DistributedConnection extends NetworkConnection with IStore { Warehouse.getById(resourceId).then((r) { if (r != null) sendReply(IIPPacketAction.TemplateFromResourceId, callback) - .addInt32(r.instance.template.content.length) - .addDC(r.instance.template.content) - .done(); + ..addInt32(r.instance?.template.content.length as int) + ..addDC(r.instance?.template.content as DC) + ..done(); else { // reply failed sendError(ErrorType.Management, callback, @@ -1852,7 +1891,8 @@ class DistributedConnection extends NetworkConnection with IStore { } else { var list = r .where((x) => - x.instance.applicable(session, ActionType.Attach, null) != + x.instance?.applicable( + _session as Session, ActionType.Attach, null) != Ruling.Denied) .toList(); @@ -1861,8 +1901,8 @@ class DistributedConnection extends NetworkConnection with IStore { ExceptionCode.ResourceNotFound.index); else sendReply(IIPPacketAction.QueryLink, callback) - .addDC(Codec.composeResourceArray(list, this, true)) - .done(); + ..addDC(Codec.composeResourceArray(list, this, true)) + ..done(); } }); } @@ -1874,17 +1914,16 @@ class DistributedConnection extends NetworkConnection with IStore { Warehouse.getById(resourceId).then((r) { if (r != null) { Codec.parseVarArray(content, 0, content.length, this).then((arguments) { - var ft = r.instance.template.getFunctionTemplateByIndex(index); + var ft = r.instance?.template.getFunctionTemplateByIndex(index); if (ft != null) { if (r is DistributedResource) { - var rt = (r as DistributedResource) - .internal_invokeByArrayArguments(index, arguments); + var rt = r.internal_invokeByArrayArguments(index, arguments); if (rt != null) { rt.then((res) { - sendReply(IIPPacketAction.InvokeFunctionArrayArguments, - callback) - .addDC(Codec.compose(res, this)) - .done(); + sendReply( + IIPPacketAction.InvokeFunctionArrayArguments, callback) + ..addDC(Codec.compose(res, this)) + ..done(); }); } else { // function not found on a distributed object @@ -1913,17 +1952,16 @@ class DistributedConnection extends NetworkConnection with IStore { if (r != null) { Codec.parseStructure(content, 0, content.length, this) .then((namedArgs) { - var ft = r.instance.template.getFunctionTemplateByIndex(index); + var ft = r.instance?.template.getFunctionTemplateByIndex(index); if (ft != null) { if (r is DistributedResource) { - var rt = (r as DistributedResource) - .internal_invokeByNamedArguments(index, namedArgs); + var rt = r.internal_invokeByNamedArguments(index, namedArgs); if (rt != null) { rt.then((res) { - sendReply(IIPPacketAction.InvokeFunctionNamedArguments, - callback) - .addDC(Codec.compose(res, this)) - .done(); + sendReply( + IIPPacketAction.InvokeFunctionNamedArguments, callback) + ..addDC(Codec.compose(res, this)) + ..done(); }); } else { // function not found on a distributed object @@ -1949,7 +1987,7 @@ class DistributedConnection extends NetworkConnection with IStore { void iipRequestListen(int callback, int resourceId, int index) { Warehouse.getById(resourceId).then((r) { if (r != null) { - var et = r.instance.template.getEventTemplateByIndex(index); + var et = r.instance?.template.getEventTemplateByIndex(index); if (et != null) { if (r is DistributedResource) { @@ -1990,7 +2028,7 @@ class DistributedConnection extends NetworkConnection with IStore { void iipRequestUnlisten(int callback, int resourceId, int index) { Warehouse.getById(resourceId).then((r) { if (r != null) { - var et = r.instance.template.getEventTemplateByIndex(index); + var et = r.instance?.template.getEventTemplateByIndex(index); if (et != null) { if (r is DistributedResource) { @@ -2058,12 +2096,19 @@ class DistributedConnection extends NetworkConnection with IStore { // }); // } + // @TODO: implement this void iipRequestInquireResourceHistory( int callback, int resourceId, DateTime fromDate, DateTime toDate) { Warehouse.getById(resourceId).then((r) { if (r != null) { - r.instance.store.getRecord(r, fromDate, toDate).then((results) { - var history = Codec.composeHistory(results, this, true); + r.instance?.store?.getRecord(r, fromDate, toDate).then((results) { + if (results != null) { + var history = Codec.composeHistory(results, this, true); + + sendReply(IIPPacketAction.ResourceHistory, callback) + ..addDC(history) + ..done(); + } /* ulong fromAge = 0; @@ -2081,10 +2126,6 @@ class DistributedConnection extends NetworkConnection with IStore { } }*/ - - sendReply(IIPPacketAction.ResourceHistory, callback) - .addDC(history) - .done(); }); } }); @@ -2123,7 +2164,7 @@ class DistributedConnection extends NetworkConnection with IStore { int callback, int resourceId, int index, DC content) { Warehouse.getById(resourceId).then((r) { if (r != null) { - var pt = r.instance.template.getPropertyTemplateByIndex(index); + var pt = r.instance?.template.getPropertyTemplateByIndex(index); if (pt != null) { Codec.parse(content, 0, this).then((value) { if (r is DistributedResource) { @@ -2144,8 +2185,8 @@ class DistributedConnection extends NetworkConnection with IStore { var pi = null; // pt.Info; if (pi != null) { - if (r.instance.applicable( - session, ActionType.SetProperty, pt, this) == + if (r.instance?.applicable(_session as Session, + ActionType.SetProperty, pt, this) == Ruling.Denied) { sendError(ErrorType.Exception, callback, ExceptionCode.SetPropertyDenied.index); @@ -2169,7 +2210,7 @@ class DistributedConnection extends NetworkConnection with IStore { pi.setValue(r, value); sendReply(IIPPacketAction.SetProperty, callback).done(); } catch (ex) { - sendError(ErrorType.Exception, callback, 0, ex.message); + sendError(ErrorType.Exception, callback, 0, ex.toString()); } } else { // pt found, pi not found, this should never happen @@ -2196,26 +2237,25 @@ class DistributedConnection extends NetworkConnection with IStore { /// /// Class GUID. /// TypeTemplate. - AsyncReply getTemplate(Guid classId) { + AsyncReply getTemplate(Guid classId) { if (_templates.containsKey(classId)) - return new AsyncReply.ready(_templates[classId]); + return AsyncReply.ready(_templates[classId]); else if (_templateRequests.containsKey(classId)) - return _templateRequests[classId]; + return _templateRequests[classId] as AsyncReply; var reply = new AsyncReply(); _templateRequests.add(classId, reply); - sendRequest(IIPPacketAction.TemplateFromClassId) - .addGuid(classId) - .done() - .then((rt) { - _templateRequests.remove(classId); - _templates[(rt[0] as TypeTemplate).classId] = rt[0] as TypeTemplate; - Warehouse.putTemplate(rt[0] as TypeTemplate); - reply.trigger(rt[0]); - }).error((ex) { - reply.triggerError(ex); - }); + (sendRequest(IIPPacketAction.TemplateFromClassId)..addGuid(classId)).done() + ..then((rt) { + _templateRequests.remove(classId); + _templates[(rt[0] as TypeTemplate).classId] = rt[0] as TypeTemplate; + Warehouse.putTemplate(rt[0] as TypeTemplate); + reply.trigger(rt[0]); + }) + ..error((ex) { + reply.triggerError(ex); + }); return reply; } @@ -2226,15 +2266,17 @@ class DistributedConnection extends NetworkConnection with IStore { /// /// Path to the resource. /// Resource - AsyncReply get(String path) { - var rt = new AsyncReply(); + AsyncReply get(String path) { + var rt = new AsyncReply(); - query(path).then((ar) { - if (ar?.length > 0) - rt.trigger(ar[0]); - else - rt.trigger(null); - }).error((ex) => rt.triggerError(ex)); + query(path) + ..then((ar) { + if (ar.length > 0) + rt.trigger(ar[0]); + else + rt.trigger(null); + }) + ..error((ex) => rt.triggerError(ex)); return rt; } @@ -2244,10 +2286,10 @@ class DistributedConnection extends NetworkConnection with IStore { /// /// Instance Id /// Resource - AsyncReply retrieve(int iid) { + AsyncReply retrieve(int iid) { for (var r in _resources.values) - if (r.instance.id == iid) return new AsyncReply.ready(r); - return new AsyncReply.ready(null); + if (r.instance?.id == iid) return new AsyncReply.ready(r); + return new AsyncReply.ready(null); } AsyncReply> getLinkTemplates(String link) { @@ -2255,27 +2297,28 @@ class DistributedConnection extends NetworkConnection with IStore { var l = DC.stringToBytes(link); - sendRequest(IIPPacketAction.LinkTemplates) - .addUint16(l.length) - .addDC(l) + (sendRequest(IIPPacketAction.LinkTemplates) + ..addUint16(l.length) + ..addDC(l)) .done() - .then((rt) { - List templates = []; - // parse templates + ..then((rt) { + List templates = []; + // parse templates - DC data = rt[0]; - //var offset = 0; - for (int offset = 0; offset < data.length;) { - var cs = data.getUint32(offset); - offset += 4; - templates.add(TypeTemplate.parse(data, offset, cs)); - offset += cs; - } + DC data = rt[0]; + //var offset = 0; + for (int offset = 0; offset < data.length;) { + var cs = data.getUint32(offset); + offset += 4; + templates.add(TypeTemplate.parse(data, offset, cs)); + offset += cs; + } - reply.trigger(templates); - }).error((ex) { - reply.triggerError(ex); - }); + reply.trigger(templates); + }) + ..error((ex) { + reply.triggerError(ex); + }); return reply; } @@ -2293,7 +2336,7 @@ class DistributedConnection extends NetworkConnection with IStore { if (request != null) { // dig for dead locks if (resource != null) // dead lock - return new AsyncReply.ready(_resources[id]); + return AsyncReply.ready(resource); else return request; } else if (resource != null && !resource.suspended) @@ -2302,112 +2345,115 @@ class DistributedConnection extends NetworkConnection with IStore { var reply = new AsyncReply(); _resourceRequests.add(id, reply); - sendRequest(IIPPacketAction.AttachResource) - .addUint32(id) - .done() - .then((rt) { - // @TODO: Generator code - DistributedResource dr; + (sendRequest(IIPPacketAction.AttachResource)..addUint32(id)).done() + ..then((rt) { + // @TODO: Generator code + DistributedResource dr; - if (resource == null) { - var template = - Warehouse.getTemplateByClassId(rt[0], TemplateType.Wrapper); - if (template?.definedType != null) { - dr = Warehouse.createInstance(template?.definedType); - dr.internal_init(this, id, rt[1], rt[2]); - } else { - dr = new DistributedResource(); - dr.internal_init(this, id, rt[1], rt[2]); - } - } else - dr = resource; - - //var dr = resource ?? new DistributedResource(this, id, rt[1], rt[2]); - - getTemplate(rt[0] as Guid).then((tmp) { - //print("New template "); - - var d = rt[3] as DC; - - // ClassId, ResourceAge, ResourceLink, Content if (resource == null) { - Warehouse.put(id.toString(), dr, this, null, tmp).then((ok) { - Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) { - //print("attached"); - dr.internal_attach(ar); - _resourceRequests.remove(id); - reply.trigger(dr); - }); - }).error((ex) => reply.triggerError(ex)); - } else { - Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) { - //print("attached"); - dr.internal_attach(ar); - _resourceRequests.remove(id); - reply.trigger(dr); + var template = + Warehouse.getTemplateByClassId(rt[0], TemplateType.Wrapper); + if (template?.definedType != null) { + dr = Warehouse.createInstance(template?.definedType as Type); + dr.internal_init(this, id, rt[1], rt[2]); + } else { + dr = new DistributedResource(); + dr.internal_init(this, id, rt[1], rt[2]); + } + } else + dr = resource; + + //var dr = resource ?? new DistributedResource(this, id, rt[1], rt[2]); + + getTemplate(rt[0] as Guid) + ..then((tmp) { + //print("New template "); + + var d = rt[3] as DC; + + // ClassId, ResourceAge, ResourceLink, Content + if (resource == null) { + Warehouse.put(id.toString(), dr, this, null, tmp) + ..then((ok) { + Codec.parsePropertyValueArray(d, 0, d.length, this) + .then((ar) { + //print("attached"); + dr.internal_attach(ar); + _resourceRequests.remove(id); + reply.trigger(dr); + }); + }) + ..error((ex) => reply.triggerError(ex)); + } else { + Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) { + //print("attached"); + if (ar != null) dr.internal_attach(ar); + _resourceRequests.remove(id); + reply.trigger(dr); + }); + } + }) + ..error((ex) { + reply.triggerError(ex); }); - } - }).error((ex) { + }) + ..error((ex) { reply.triggerError(ex); }); - }).error((ex) { - reply.triggerError(ex); - }); return reply; } - AsyncReply> getChildren(IResource resource) { - var rt = new AsyncReply>(); + AsyncReply> getChildren(IResource resource) { + var rt = new AsyncReply>(); sendRequest(IIPPacketAction.ResourceChildren) - .addUint32(resource.instance.id) - .done() - .then((ar) { - var d = ar[0] as DC; - Codec.parseResourceArray(d, 0, d.length, this).then((resources) { - rt.trigger(resources); - }).error((ex) => rt.triggerError(ex)); - }); + ..addUint32(resource.instance?.id as int) + ..done().then((ar) { + var d = ar[0] as DC; + Codec.parseResourceArray(d, 0, d.length, this).then((resources) { + rt.trigger(resources); + }).error((ex) => rt.triggerError(ex)); + }); return rt; } - AsyncReply> getParents(IResource resource) { - var rt = new AsyncReply>(); + AsyncReply> getParents(IResource resource) { + var rt = new AsyncReply>(); sendRequest(IIPPacketAction.ResourceParents) - .addUint32(resource.instance.id) - .done() - .then((ar) { - var d = ar[0] as DC; - Codec.parseResourceArray(d, 0, d.length, this).then((resources) { - rt.trigger(resources); - }).error((ex) => rt.triggerError(ex)); - }); + ..addUint32((resource.instance as Instance).id) + ..done().then((ar) { + var d = ar[0] as DC; + Codec.parseResourceArray(d, 0, d.length, this) + .then((resources) { + rt.trigger(resources); + }).error((ex) => rt.triggerError(ex)); + }); return rt; } AsyncReply removeAttributes(IResource resource, - [List attributes = null]) { + [List? attributes = null]) { var rt = new AsyncReply(); if (attributes == null) - sendRequest(IIPPacketAction.ClearAllAttributes) - .addUint32(resource.instance.id) + (sendRequest(IIPPacketAction.ClearAllAttributes) + ..addUint32(resource.instance?.id as int)) .done() - .then((ar) => rt.trigger(true)) - .error((ex) => rt.triggerError(ex)); + ..then((ar) => rt.trigger(true)) + ..error((ex) => rt.triggerError(ex)); else { var attrs = DC.stringArrayToBytes(attributes); - sendRequest(IIPPacketAction.ClearAttributes) - .addUint32(resource.instance.id) - .addInt32(attrs.length) - .addDC(attrs) + (sendRequest(IIPPacketAction.ClearAttributes) + ..addUint32(resource.instance?.id as int) + ..addInt32(attrs.length) + ..addDC(attrs)) .done() - .then((ar) => rt.trigger(true)) - .error((ex) => rt.triggerError(ex)); + ..then((ar) => rt.trigger(true)) + ..error((ex) => rt.triggerError(ex)); } return rt; @@ -2418,47 +2464,51 @@ class DistributedConnection extends NetworkConnection with IStore { var rt = new AsyncReply(); sendRequest(clearAttributes - ? IIPPacketAction.UpdateAllAttributes - : IIPPacketAction.UpdateAttributes) - .addUint32(resource.instance.id) - .addDC(Codec.composeStructure(attributes, this, true, true, true)) - .done() - .then((ar) => rt.trigger(true)) - .error((ex) => rt.triggerError(ex)); + ? IIPPacketAction.UpdateAllAttributes + : IIPPacketAction.UpdateAttributes) + ..addUint32(resource.instance?.id as int) + ..addDC(Codec.composeStructure(attributes, this, true, true, true)) + ..done() + .then((ar) => rt.trigger(true)) + .error((ex) => rt.triggerError(ex)); return rt; } AsyncReply getAttributes(IResource resource, - [List attributes = null]) { + [List? attributes = null]) { var rt = new AsyncReply(); if (attributes == null) { - sendRequest(IIPPacketAction.GetAllAttributes) - .addUint32(resource.instance.id) + (sendRequest(IIPPacketAction.GetAllAttributes) + ..addUint32(resource.instance?.id as int)) .done() - .then((ar) { - var d = ar[0] as DC; - Codec.parseStructure(d, 0, d.length, this).then((st) { - resource.instance.setAttributes(st); - rt.trigger(st); - }).error((ex) => rt.triggerError(ex)); - }); + ..then((ar) { + var d = ar[0] as DC; + Codec.parseStructure(d, 0, d.length, this) + ..then((st) { + resource.instance?.setAttributes(st); + rt.trigger(st); + }) + ..error((ex) => rt.triggerError(ex)); + }); } else { var attrs = DC.stringArrayToBytes(attributes); - sendRequest(IIPPacketAction.GetAttributes) - .addUint32(resource.instance.id) - .addInt32(attrs.length) - .addDC(attrs) + (sendRequest(IIPPacketAction.GetAttributes) + ..addUint32(resource.instance?.id as int) + ..addInt32(attrs.length) + ..addDC(attrs)) .done() - .then((ar) { - var d = ar[0] as DC; - Codec.parseStructure(d, 0, d.length, this).then((st) { - resource.instance.setAttributes(st); + ..then((ar) { + var d = ar[0] as DC; + Codec.parseStructure(d, 0, d.length, this) + ..then((st) { + resource.instance?.setAttributes(st); - rt.trigger(st); - }).error((ex) => rt.triggerError(ex)); - }); + rt.trigger(st); + }) + ..error((ex) => rt.triggerError(ex)); + }); } return rt; @@ -2471,34 +2521,33 @@ class DistributedConnection extends NetworkConnection with IStore { /// From date. /// To date. /// - AsyncReply>> getRecord( + AsyncReply>?> getRecord( IResource resource, DateTime fromDate, DateTime toDate) { if (resource is DistributedResource) { var dr = resource as DistributedResource; if (dr.connection != this) return new AsyncReply< - KeyList>>.ready(null); + KeyList>?>.ready(null); var reply = new AsyncReply>>(); sendRequest(IIPPacketAction.ResourceHistory) - .addUint32(dr.id) - .addDateTime(fromDate) - .addDateTime(toDate) - .done() - .then((rt) { - var content = rt[0] as DC; + ..addUint32(dr.id as int) + ..addDateTime(fromDate) + ..addDateTime(toDate) + ..done().then((rt) { + var content = rt[0] as DC; - Codec.parseHistory(content, 0, content.length, resource, this) - .then((history) => reply.trigger(history)); - }).error((ex) => reply.triggerError(ex)); + Codec.parseHistory(content, 0, content.length, resource, this) + .then((history) => reply.trigger(history)); + }).error((ex) => reply.triggerError(ex)); return reply; } else - return new AsyncReply< - KeyList>>.ready(null); + return AsyncReply>?>.ready( + null); } /// @@ -2506,20 +2555,19 @@ class DistributedConnection extends NetworkConnection with IStore { /// /// Link path. /// - AsyncReply> query(String path) { + AsyncReply> query(String path) { var str = DC.stringToBytes(path); - var reply = new AsyncReply>(); + var reply = new AsyncReply>(); sendRequest(IIPPacketAction.QueryLink) - .addUint16(str.length) - .addDC(str) - .done() - .then((args) { - var content = args[0] as DC; + ..addUint16(str.length) + ..addDC(str) + ..done().then((args) { + var content = args[0] as DC; - Codec.parseResourceArray(content, 0, content.length, this) - .then((resources) => reply.trigger(resources)); - }).error((ex) => reply.triggerError(ex)); + Codec.parseResourceArray(content, 0, content.length, this) + .then((resources) => reply.trigger(resources)); + }).error((ex) => reply.triggerError(ex)); return reply; } @@ -2533,35 +2581,33 @@ class DistributedConnection extends NetworkConnection with IStore { /// Resource attributeds. /// Values for the resource properties. /// New resource instance - AsyncReply create( + AsyncReply create( IStore store, IResource parent, String className, List parameters, Structure attributes, Structure values) { - var reply = new AsyncReply(); - var pkt = new BinaryList() - .addUint32(store.instance.id) - .addUint32(parent.instance.id) - .addUint8(className.length) - .addString(className) - .addDC(Codec.composeVarArray(parameters, this, true)) - .addDC(Codec.composeStructure(attributes, this, true, true, true)) - .addDC(Codec.composeStructure(values, this)); + var reply = new AsyncReply(); + var pkt = BinaryList() + ..addUint32((store.instance as Instance).id) + ..addUint32((parent.instance as Instance).id) + ..addUint8(className.length) + ..addString(className) + ..addDC(Codec.composeVarArray(parameters, this, true)) + ..addDC(Codec.composeStructure(attributes, this, true, true, true)) + ..addDC(Codec.composeStructure(values, this)); pkt.insertInt32(8, pkt.length); - sendRequest(IIPPacketAction.CreateResource) - .addDC(pkt.toDC()) - .done() - .then((args) { - var rid = args[0]; + (sendRequest(IIPPacketAction.CreateResource)..addDC(pkt.toDC())).done() + ..then((args) { + var rid = args[0]; - fetch(rid).then((r) { - reply.trigger(r); + fetch(rid).then((r) { + reply.trigger(r); + }); }); - }); return reply; } @@ -2570,42 +2616,42 @@ class DistributedConnection extends NetworkConnection with IStore { // compose the packet _unsubscrive(resource); sendEvent(IIPPacketEvent.ResourceDestroyed) - .addUint32(resource.instance.id) - .done(); + ..addUint32((resource.instance as Instance).id) + ..done(); } void _instance_PropertyModified(IResource resource, String name, newValue) { - var pt = resource.instance.template.getPropertyTemplateByName(name); + var pt = resource.instance?.template.getPropertyTemplateByName(name); if (pt == null) return; sendEvent(IIPPacketEvent.PropertyUpdated) - .addUint32(resource.instance.id) - .addUint8(pt.index) - .addDC(Codec.compose(newValue, this)) - .done(); + ..addUint32(resource.instance?.id as int) + ..addUint8(pt.index) + ..addDC(Codec.compose(newValue, this)) + ..done(); } // private void Instance_EventOccurred(IResource resource, string name, string[] users, DistributedConnection[] connections, object[] args) void _instance_EventOccurred(IResource resource, issuer, - List receivers, String name, dynamic args) { - var et = resource.instance.template.getEventTemplateByName(name); + List? receivers, String name, dynamic args) { + var et = resource.instance?.template.getEventTemplateByName(name); if (et == null) return; if (receivers != null) if (!receivers.contains(this.session)) return; - if (resource.instance - .applicable(this.session, ActionType.ReceiveEvent, et, issuer) == + if (resource.instance?.applicable( + _session as Session, ActionType.ReceiveEvent, et, issuer) == Ruling.Denied) return; // compose the packet sendEvent(IIPPacketEvent.EventOccurred) - .addUint32(resource.instance.id) - .addUint8(et.index) - .addDC(Codec.compose(args, this, true)) - .done(); + ..addUint32((resource.instance as Instance).id) + ..addUint8(et.index) + ..addDC(Codec.compose(args, this, true)) + ..done(); } @override diff --git a/lib/src/Net/IIP/DistributedPropertyContext.dart b/lib/src/Net/IIP/DistributedPropertyContext.dart index 2f7109e..0a64b69 100644 --- a/lib/src/Net/IIP/DistributedPropertyContext.dart +++ b/lib/src/Net/IIP/DistributedPropertyContext.dart @@ -1,18 +1,11 @@ import 'DistributedConnection.dart'; -class DistributedPropertyContext -{ - dynamic value; - DistributedConnection connection; - dynamic Function(DistributedConnection) method; +class DistributedPropertyContext { + dynamic value; + DistributedConnection? connection; + dynamic Function(DistributedConnection)? method; - DistributedPropertyContext(this.method) - { + DistributedPropertyContext(this.method) {} - } - - DistributedPropertyContext.setter(this.value, this.connection) - { - - } + DistributedPropertyContext.setter(this.value, this.connection) {} } diff --git a/lib/src/Net/IIP/DistributedResource.dart b/lib/src/Net/IIP/DistributedResource.dart index b6a96db..f312ee5 100644 --- a/lib/src/Net/IIP/DistributedResource.dart +++ b/lib/src/Net/IIP/DistributedResource.dart @@ -22,6 +22,9 @@ SOFTWARE. */ + +import '../../Resource/Instance.dart'; + import '../../Core/AsyncException.dart'; import '../../Core/ErrorType.dart'; import '../../Core/ExceptionCode.dart'; @@ -40,18 +43,17 @@ import '../Packets/IIPPacketAction.dart'; import '../../Resource/Template/EventTemplate.dart'; - class DistributedResource extends IResource { - int _instanceId; - DistributedConnection _connection; + int? _instanceId; + DistributedConnection? _connection; bool _attached = false; //bool _isReady = false; - String _link; - int _age; + String? _link; + int? _age; - List _properties; + List _properties = []; bool _destroyed = false; List> _queued_updates = []; @@ -59,17 +61,17 @@ class DistributedResource extends IResource { /// /// Connection responsible for the distributed resource. /// - DistributedConnection get connection => _connection; + DistributedConnection? get connection => _connection; /// /// Resource link /// - String get link => _link; + String? get link => _link; /// /// Instance Id given by the other end. /// - int get id => _instanceId; + int? get id => _instanceId; //bool get destroyed => _destroyed; @@ -84,7 +86,7 @@ class DistributedResource extends IResource { void destroy() { _destroyed = true; _attached = false; - _connection.sendDetachRequest(_instanceId); + _connection?.sendDetachRequest(_instanceId as int); emitArgs("destroy", [this]); } @@ -137,13 +139,19 @@ class DistributedResource extends IResource { /// /// List internal_serialize() { - var props = new List(_properties.length); + // var props = _properties as List; + // var rt = List(_properties.length); - for (var i = 0; i < _properties.length; i++) - props[i] = new PropertyValue( - _properties[i], instance.getAge(i), instance.getModificationDate(i)); + // for (var i = 0; i < _properties.length; i++) + // rt[i] = new PropertyValue(_properties[i], instance?.getAge(i) as int, + // instance?.getModificationDate(i) as DateTime); - return props; + return List.generate( + _properties.length, + (i) => PropertyValue(_properties[i], instance?.getAge(i) as int, + instance?.getModificationDate(i) as DateTime)); + + //return rt; } bool internal_attach(List properties) { @@ -152,14 +160,16 @@ class DistributedResource extends IResource { else { _suspended = false; - _properties = new List(properties.length); // object[properties.Length]; + //_properties = new List(properties.length); // object[properties.Length]; //_events = new DistributedResourceEvent[Instance.Template.Events.Length]; for (var i = 0; i < properties.length; i++) { - instance.setAge(i, properties[i].age); - instance.setModificationDate(i, properties[i].date); - _properties[i] = properties[i].value; + instance?.setAge(i, properties[i].age); + instance?.setModificationDate(i, properties[i].date); + + _properties.add(properties[i].value); + //_properties[i] = properties[i].value; } // trigger holded events/property updates. @@ -180,9 +190,12 @@ class DistributedResource extends IResource { } AsyncReply listen(event) { - EventTemplate et = event is EventTemplate + if (_destroyed) throw new Exception("Trying to access destroyed object"); + if (_suspended) throw new Exception("Trying to access suspended object"); + + EventTemplate? et = event is EventTemplate ? event - : instance.template.getEventTemplateByName(event); + : instance?.template.getEventTemplateByName(event); if (et == null) return AsyncReply().triggerError(new AsyncException( @@ -192,13 +205,17 @@ class DistributedResource extends IResource { return AsyncReply().triggerError(new AsyncException( ErrorType.Management, ExceptionCode.NotListenable.index, "")); - return _connection.sendListenRequest(_instanceId, et.index); + return _connection?.sendListenRequest(_instanceId as int, et.index) + as AsyncReply; } AsyncReply unlisten(event) { - EventTemplate et = event is EventTemplate + if (_destroyed) throw new Exception("Trying to access destroyed object"); + if (_suspended) throw new Exception("Trying to access suspended object"); + + EventTemplate? et = event is EventTemplate ? event - : instance.template.getEventTemplateByName(event); + : instance?.template.getEventTemplateByName(event); if (et == null) return AsyncReply().triggerError(new AsyncException( @@ -208,48 +225,60 @@ class DistributedResource extends IResource { return AsyncReply().triggerError(new AsyncException( ErrorType.Management, ExceptionCode.NotListenable.index, "")); - return connection.sendUnlistenRequest(_instanceId, et.index); + return connection?.sendUnlistenRequest(_instanceId as int, et.index) + as AsyncReply; } void internal_emitEventByIndex(int index, dynamic args) { // neglect events when the object is not yet attached if (!_attached) return; - var et = instance.template.getEventTemplateByIndex(index); - emitArgs(et.name, [args]); - //emitArgs(event, arguments) - instance.emitResourceEvent(null, null, et.name, args); + var et = instance?.template.getEventTemplateByIndex(index); + if (et != null) { + emitArgs(et.name, [args]); + instance?.emitResourceEvent(null, null, et.name, args); + } } - AsyncReply internal_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"); + + if (instance == null) throw Exception("Object not initialized."); + + var ins = instance as Instance; + + if (index >= ins.template.functions.length) + throw new Exception("Function index is incorrect"); + + return connection?.sendInvokeByNamedArguments( + _instanceId as int, index, namedArgs) as AsyncReply; + } + + 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"); + if (instance == null) throw Exception("Object not initialized."); - if (index >= instance.template.functions.length) + var ins = instance as Instance; + + if (index >= ins.template.functions.length) throw new Exception("Function index is incorrect"); - return connection.sendInvokeByNamedArguments(_instanceId, index, namedArgs); - } - - 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"); - - if (index >= instance.template.functions.length) - throw new Exception("Function index is incorrect"); - - return connection.sendInvokeByArrayArguments(_instanceId, index, args); + return _connection?.sendInvokeByArrayArguments( + _instanceId as int, index, args) as AsyncReply; } operator [](String index) { - var pt = instance.template.getPropertyTemplateByName(index); + var pt = instance?.template.getPropertyTemplateByName(index); if (pt != null) return get(pt.index); } operator []=(String index, value) { - var pt = instance.template.getPropertyTemplateByName(index); + var pt = instance?.template.getPropertyTemplateByName(index); if (pt != null) set(pt.index, value); } @@ -266,7 +295,7 @@ class DistributedResource extends IResource { var memberName = _getMemberName(invocation.memberName); if (invocation.isMethod) { - var ft = instance.template.getFunctionTemplateByName(memberName); + var ft = instance?.template.getFunctionTemplateByName(memberName); if (_attached && ft != null) { if (invocation.namedArguments.length > 0) { @@ -281,14 +310,14 @@ class DistributedResource extends IResource { } } } else if (invocation.isSetter) { - var pt = instance.template.getPropertyTemplateByName(memberName); + var pt = instance?.template.getPropertyTemplateByName(memberName); if (pt != null) { set(pt.index, invocation.positionalArguments[0]); return true; } } else if (invocation.isGetter) { - var pt = instance.template.getPropertyTemplateByName(memberName); + var pt = instance?.template.getPropertyTemplateByName(memberName); if (pt != null) { return get(pt.index); @@ -304,7 +333,9 @@ class DistributedResource extends IResource { /// Zero-based property index. /// Value get(int index) { - if (index >= _properties.length) return null; + //if (_properties == null) return null; + //var props = _properties as List; + //if (index >= props.length) return null; return _properties[index]; } @@ -312,9 +343,12 @@ class DistributedResource extends IResource { if (!_attached) { _queued_updates.add(KeyValuePair(index, value)); } else { - var pt = instance.template.getPropertyTemplateByIndex(index); - _properties[index] = value; - instance.emitModification(pt, value); + var pt = instance?.template.getPropertyTemplateByIndex(index); + + if (pt != null) { + _properties[index] = value; + instance?.emitModification(pt, value); + } } } @@ -325,23 +359,24 @@ class DistributedResource extends IResource { /// Value /// Indicator when the property is set. AsyncReply set(int index, dynamic value) { - if (index >= _properties.length) return null; + if (index >= _properties.length) + throw Exception("Property with index `${index}` not found."); var reply = new AsyncReply(); + var con = _connection as DistributedConnection; - var parameters = Codec.compose(value, connection); - connection - .sendRequest(IIPPacketAction.SetProperty) - .addUint32(_instanceId) - .addUint8(index) - .addDC(parameters) + var parameters = Codec.compose(value, con); + (con.sendRequest(IIPPacketAction.SetProperty) + ..addUint32(_instanceId as int) + ..addUint8(index) + ..addDC(parameters)) .done() - .then((res) { - // not really needed, server will always send property modified, - // this only happens if the programmer forgot to emit in property setter - _properties[index] = value; - reply.trigger(null); - }); + ..then((res) { + // not really needed, server will always send property modified, + // this only happens if the programmer forgot to emit in property setter + _properties[index] = value; + reply.trigger(null); + }); return reply; } diff --git a/lib/src/Net/IIP/DistributedServer.dart b/lib/src/Net/IIP/DistributedServer.dart index 78e245e..3beb396 100644 --- a/lib/src/Net/IIP/DistributedServer.dart +++ b/lib/src/Net/IIP/DistributedServer.dart @@ -17,7 +17,7 @@ class DistributedServer extends IResource { return AsyncReply.ready(true); } - EntryPoint entryPoint; + EntryPoint? entryPoint; @override getProperty(String name) => null; diff --git a/lib/src/Net/NetworkBuffer.dart b/lib/src/Net/NetworkBuffer.dart index 8e53f83..3c37808 100644 --- a/lib/src/Net/NetworkBuffer.dart +++ b/lib/src/Net/NetworkBuffer.dart @@ -25,110 +25,82 @@ SOFTWARE. import '../Data/DC.dart'; import 'dart:core'; -class NetworkBuffer -{ - DC _data; +class NetworkBuffer { + DC _data = new DC(0); - int _neededDataLength = 0; - - NetworkBuffer() - { + int _neededDataLength = 0; + + NetworkBuffer() {} + + bool get protected => _neededDataLength > _data.length; + + int get available => _data.length; + + void holdForNextWrite(DC src, int offset, int size) { + holdFor(src, offset, size, size + 1); + } + + void holdFor(DC src, int offset, int size, int needed) { + //lock (syncLock) + //{ + if (size >= needed) throw new Exception("Size >= Needed !"); + + //trim = true; + _data = DC.combine(src, offset, size, _data, 0, _data.length); + _neededDataLength = needed; + + //} + } + + void holdForNeeded(DC src, int needed) { + holdFor(src, 0, src.length, needed); + } + + bool protect(DC data, int offset, int needed) { + int dataLength = _data.length - offset; + + // protection + if (dataLength < needed) { + holdFor(data, offset, dataLength, needed); + return true; + } else + return false; + } + + void write(DC src, int offset, int length) { + //lock(syncLock) + _data.append(src, offset, length); + } + + bool get canRead { + if (_data.length == 0) return false; + if (_data.length < _neededDataLength) return false; + + return true; + } + + DC? read() { + //lock (syncLock) + //{ + if (_data.length == 0) return null; + + DC? rt = null; + + if (_neededDataLength == 0) { + rt = _data; + _data = new DC(0); + } else { + if (_data.length >= _neededDataLength) { + rt = _data; _data = new DC(0); - } - - bool get protected => _neededDataLength > _data.length; - - int get available => _data.length; - - - - void holdForNextWrite(DC src, int offset, int size) - { - holdFor(src, offset, size, size + 1); - } - - - void holdFor(DC src, int offset, int size, int needed) - { - //lock (syncLock) - //{ - if (size >= needed) - throw new Exception("Size >= Needed !"); - - //trim = true; - _data = DC.combine(src, offset, size, _data, 0, _data.length); - _neededDataLength = needed; - - //} - } - - void holdForNeeded(DC src, int needed) - { - holdFor(src, 0, src.length, needed); - } - - bool protect(DC data, int offset, int needed) - { - int dataLength = _data.length - offset; - - // protection - if (dataLength < needed) - { - holdFor(data, offset, dataLength, needed); - return true; - } - else - return false; - } - - - - void write(DC src, int offset, int length) - { - //lock(syncLock) - _data.append(src, offset, length); - } - - bool get canRead - { - if (_data.length == 0) - return false; - if (_data.length < _neededDataLength) - return false; - - return true; - } - - DC read() - { - //lock (syncLock) - //{ - if (_data.length == 0) - return null; - - DC rt = null; - - if (_neededDataLength == 0) - { - rt = _data; - _data = new DC(0); - } - else - { - if (_data.length >= _neededDataLength) - { - rt = _data; - _data = new DC(0); - _neededDataLength = 0; - return rt; - } - else - { - return null; - } - } - //} - + _neededDataLength = 0; return rt; + } else { + return null; } -} \ No newline at end of file + } + //} + + return rt; + } +} diff --git a/lib/src/Net/NetworkConnection.dart b/lib/src/Net/NetworkConnection.dart index 48fc5af..9b0a30b 100644 --- a/lib/src/Net/NetworkConnection.dart +++ b/lib/src/Net/NetworkConnection.dart @@ -32,9 +32,9 @@ import '../Data/DC.dart'; import 'Sockets/IPEndPoint.dart'; class NetworkConnection extends IDestructible with INetworkReceiver { - ISocket _sock; + ISocket? _sock; - DateTime _lastAction; + DateTime _lastAction = DateTime.now(); //public delegate void DataReceivedEvent(NetworkConnection sender, NetworkBuffer data); //public delegate void ConnectionClosedEvent(NetworkConnection sender); @@ -48,7 +48,6 @@ class NetworkConnection extends IDestructible with INetworkReceiver { bool _processing = false; - void destroy() { // if (connected) close(); @@ -58,7 +57,7 @@ class NetworkConnection extends IDestructible with INetworkReceiver { NetworkConnection() {} - ISocket get socket => _sock; + ISocket? get socket => _sock; void assign(ISocket socket) { _lastAction = DateTime.now(); @@ -71,14 +70,14 @@ class NetworkConnection extends IDestructible with INetworkReceiver { //socket.on("connect", socket_OnConnect); } - ISocket unassign() { + ISocket? unassign() { if (_sock != null) { // connected = false; // _sock.off("close", socket_OnClose); // _sock.off("connect", socket_OnConnect); // _sock.off("receive", socket_OnReceive); - _sock.receiver = null; + _sock?.receiver = null; var rt = _sock; _sock = null; @@ -92,17 +91,13 @@ class NetworkConnection extends IDestructible with INetworkReceiver { emitArgs("dataReceived", [data]); } - void connected(){ + void connected() {} - } - - void disconnected(){ - - } + void disconnected() {} void close() { try { - if (_sock != null) _sock.close(); + if (_sock != null) _sock?.close(); } catch (ex) { //Global.Log("NetworkConenction:Close", LogType.Error, ex.ToString()); @@ -111,17 +106,17 @@ class NetworkConnection extends IDestructible with INetworkReceiver { DateTime get lastAction => _lastAction; - IPEndPoint get remoteEndPoint => _sock?.remoteEndPoint; + IPEndPoint? get remoteEndPoint => _sock?.remoteEndPoint; - IPEndPoint get localEndPoint => _sock?.localEndPoint; + IPEndPoint? get localEndPoint => _sock?.localEndPoint; - bool get isConnected => _sock.state == SocketState.Established; + bool get isConnected => _sock?.state == SocketState.Established; void send(DC msg) { try { if (_sock != null) { _lastAction = DateTime.now(); - _sock.send(msg); + _sock?.send(msg); } } catch (ex) { //Console.WriteLine(ex.ToString()); @@ -151,8 +146,8 @@ class NetworkConnection extends IDestructible with INetworkReceiver { if (_sock == null) return; // Closed ? - if (_sock.state == SocketState.Closed || - _sock.state == SocketState.Terminated) // || !connected) + if (_sock?.state == SocketState.Closed || + _sock?.state == SocketState.Terminated) // || !connected) return; _lastAction = DateTime.now(); diff --git a/lib/src/Net/Packets/IIPAuthPacket.dart b/lib/src/Net/Packets/IIPAuthPacket.dart index 5586ae3..39817ae 100644 --- a/lib/src/Net/Packets/IIPAuthPacket.dart +++ b/lib/src/Net/Packets/IIPAuthPacket.dart @@ -26,276 +26,215 @@ import 'IIPAuthPacketAction.dart'; import 'IIPAuthPacketCommand.dart'; import '../../Security/Authority/AuthenticationMethod.dart'; -class IIPAuthPacket -{ +class IIPAuthPacket { + int command = 0; + int action = 0; - int command; - int action; + int errorCode = 0; + String errorMessage = ""; - int errorCode; - String errorMessage; + AuthenticationMethod localMethod = AuthenticationMethod.None; - AuthenticationMethod localMethod; + DC? sourceInfo; - DC sourceInfo; + DC? hash; - DC hash; + DC? sessionId; - DC sessionId; + AuthenticationMethod remoteMethod = AuthenticationMethod.None; - AuthenticationMethod remoteMethod; + String? domain; - String domain; + int certificateId = 0; - int certificateId; + String? localUsername; - String localUsername; + String? remoteUsername; - String remoteUsername; + DC? localPassword; - DC localPassword; + DC? remotePassword; - DC remotePassword; + DC? localToken; - DC localToken; + DC? remoteToken; - DC remoteToken; + DC? asymetricEncryptionKey; - DC asymetricEncryptionKey; + DC? localNonce; - DC localNonce; + DC? remoteNonce; - DC remoteNonce; + int remoteTokenIndex = 0; - int remoteTokenIndex; + int _dataLengthNeeded = 0; - int _dataLengthNeeded; + bool _notEnough(int offset, int ends, int needed) { + if (offset + needed > ends) { + _dataLengthNeeded = needed - (ends - offset); + return true; + } else + return false; + } - bool _notEnough(int offset, int ends, int needed) - { - if (offset + needed > ends) - { - _dataLengthNeeded = needed - (ends - offset); - return true; + toString() { + return command.toString() + " " + action.toString(); + } + + int parse(DC data, int offset, int ends) { + var oOffset = offset; + + if (_notEnough(offset, ends, 1)) return -_dataLengthNeeded; + + command = (data[offset] >> 6); + + if (command == IIPAuthPacketCommand.Action) { + action = (data[offset++] & 0x3f); + + if (action == IIPAuthPacketAction.AuthenticateHash) { + if (_notEnough(offset, ends, 32)) return -_dataLengthNeeded; + + hash = data.clip(offset, 32); + + //var hash = new byte[32]; + //Buffer.BlockCopy(data, (int)offset, hash, 0, 32); + //Hash = hash; + + offset += 32; + } else if (action == IIPAuthPacketAction.NewConnection) { + if (_notEnough(offset, ends, 2)) return -_dataLengthNeeded; + + var length = data.getUint16(offset); + + offset += 2; + + if (_notEnough(offset, ends, length)) return -_dataLengthNeeded; + + sourceInfo = data.clip(offset, length); + + //var sourceInfo = new byte[length]; + //Buffer.BlockCopy(data, (int)offset, sourceInfo, 0, length); + //SourceInfo = sourceInfo; + + offset += 32; + } else if (action == IIPAuthPacketAction.ResumeConnection || + action == IIPAuthPacketAction.ConnectionEstablished) { + //var sessionId = new byte[32]; + + if (_notEnough(offset, ends, 32)) return -_dataLengthNeeded; + + sessionId = data.clip(offset, 32); + + //Buffer.BlockCopy(data, (int)offset, sessionId, 0, 32); + //SessionId = sessionId; + + offset += 32; + } + } else if (command == IIPAuthPacketCommand.Declare) { + remoteMethod = AuthenticationMethod.values[((data[offset] >> 4) & 0x3)]; + localMethod = AuthenticationMethod.values[((data[offset] >> 2) & 0x3)]; + var encrypt = ((data[offset++] & 0x2) == 0x2); + + if (_notEnough(offset, ends, 1)) return -_dataLengthNeeded; + + var domainLength = data[offset++]; + if (_notEnough(offset, ends, domainLength)) return -_dataLengthNeeded; + + var domain = data.getString(offset, domainLength); + + this.domain = domain; + + offset += domainLength; + + if (remoteMethod == AuthenticationMethod.Credentials) { + if (localMethod == AuthenticationMethod.None) { + if (_notEnough(offset, ends, 33)) return -_dataLengthNeeded; + + remoteNonce = data.clip(offset, 32); + + offset += 32; + + var length = data[offset++]; + + if (_notEnough(offset, ends, length)) return -_dataLengthNeeded; + + remoteUsername = data.getString(offset, length); + + offset += length; } - else - return false; + } else if (remoteMethod == AuthenticationMethod.Token) { + if (localMethod == AuthenticationMethod.None) { + if (_notEnough(offset, ends, 40)) return -_dataLengthNeeded; + + remoteNonce = data.clip(offset, 32); + + offset += 32; + + remoteTokenIndex = data.getUint64(offset); + offset += 8; + } + } + + if (encrypt) { + if (_notEnough(offset, ends, 2)) return -_dataLengthNeeded; + + var keyLength = data.getUint16(offset); + + offset += 2; + + if (_notEnough(offset, ends, keyLength)) return -_dataLengthNeeded; + + asymetricEncryptionKey = data.clip(offset, keyLength); + + offset += keyLength; + } + } else if (command == IIPAuthPacketCommand.Acknowledge) { + remoteMethod = AuthenticationMethod.values[((data[offset] >> 4) & 0x3)]; + localMethod = AuthenticationMethod.values[((data[offset] >> 2) & 0x3)]; + var encrypt = ((data[offset++] & 0x2) == 0x2); + + if (remoteMethod == AuthenticationMethod.None) { + if (localMethod == AuthenticationMethod.None) { + // do nothing + } + } else if (remoteMethod == AuthenticationMethod.Credentials || + remoteMethod == AuthenticationMethod.Token) { + if (localMethod == AuthenticationMethod.None) { + if (_notEnough(offset, ends, 32)) return -_dataLengthNeeded; + + remoteNonce = data.clip(offset, 32); + offset += 32; + } + } + + if (encrypt) { + if (_notEnough(offset, ends, 2)) return -_dataLengthNeeded; + + var keyLength = data.getUint16(offset); + + offset += 2; + + if (_notEnough(offset, ends, keyLength)) return -_dataLengthNeeded; + + asymetricEncryptionKey = data.clip(offset, keyLength); + + offset += keyLength; + } + } else if (command == IIPAuthPacketCommand.Error) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + offset++; + errorCode = data[offset++]; + + var cl = data.getUint16(offset); + offset += 2; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + errorMessage = data.getString(offset, cl); + offset += cl; } - toString() - { - return command.toString() + " " + action.toString(); - } - - int parse(DC data, int offset, int ends) - { - var oOffset = offset; - - if (_notEnough(offset, ends, 1)) - return -_dataLengthNeeded; - - command = (data[offset] >> 6); - - if (command == IIPAuthPacketCommand.Action) - { - action = (data[offset++] & 0x3f); - - if (action == IIPAuthPacketAction.AuthenticateHash) - { - if (_notEnough(offset, ends, 32)) - return -_dataLengthNeeded; - - hash = data.clip(offset, 32); - - //var hash = new byte[32]; - //Buffer.BlockCopy(data, (int)offset, hash, 0, 32); - //Hash = hash; - - offset += 32; - } - else if (action == IIPAuthPacketAction.NewConnection) - { - if (_notEnough(offset, ends, 2)) - return -_dataLengthNeeded; - - var length = data.getUint16(offset); - - offset += 2; - - if (_notEnough(offset, ends, length)) - return -_dataLengthNeeded; - - sourceInfo = data.clip(offset, length); - - //var sourceInfo = new byte[length]; - //Buffer.BlockCopy(data, (int)offset, sourceInfo, 0, length); - //SourceInfo = sourceInfo; - - offset += 32; - } - else if (action == IIPAuthPacketAction.ResumeConnection - || action == IIPAuthPacketAction.ConnectionEstablished) - { - //var sessionId = new byte[32]; - - if (_notEnough(offset, ends, 32)) - return -_dataLengthNeeded; - - sessionId = data.clip(offset, 32); - - //Buffer.BlockCopy(data, (int)offset, sessionId, 0, 32); - //SessionId = sessionId; - - offset += 32; - } - } - else if (command == IIPAuthPacketCommand.Declare) - { - remoteMethod = AuthenticationMethod.values[((data[offset] >> 4) & 0x3)]; - localMethod = AuthenticationMethod.values[((data[offset] >> 2) & 0x3)]; - var encrypt = ((data[offset++] & 0x2) == 0x2); - - - if (_notEnough(offset, ends, 1)) - return -_dataLengthNeeded; - - var domainLength = data[offset++]; - if (_notEnough(offset, ends, domainLength)) - return -_dataLengthNeeded; - - var domain = data.getString(offset, domainLength); - - this.domain = domain; - - offset += domainLength; - - - if (remoteMethod == AuthenticationMethod.Credentials) - { - if (localMethod == AuthenticationMethod.None) - { - if (_notEnough(offset, ends, 33)) - return -_dataLengthNeeded; - - - remoteNonce = data.clip(offset, 32); - - offset += 32; - - var length = data[offset++]; - - if (_notEnough(offset, ends, length)) - return -_dataLengthNeeded; - - remoteUsername = data.getString(offset, length); - - - offset += length; - } - } - else if (remoteMethod == AuthenticationMethod.Token) - { - if (localMethod == AuthenticationMethod.None) - { - if (_notEnough(offset, ends, 40)) - return -_dataLengthNeeded; - - remoteNonce = data.clip(offset, 32); - - offset += 32; - - remoteTokenIndex = data.getUint64(offset); - offset += 8; - } - } - - - - if (encrypt) - { - if (_notEnough(offset, ends, 2)) - return -_dataLengthNeeded; - - var keyLength = data.getUint16(offset); - - offset += 2; - - if (_notEnough(offset, ends, keyLength)) - return -_dataLengthNeeded; - - - asymetricEncryptionKey = data.clip(offset, keyLength); - - offset += keyLength; - } - } - else if (command == IIPAuthPacketCommand.Acknowledge) - { - remoteMethod = AuthenticationMethod.values[ ((data[offset] >> 4) & 0x3)]; - localMethod = AuthenticationMethod.values[ ((data[offset] >> 2) & 0x3)]; - var encrypt = ((data[offset++] & 0x2) == 0x2); - - if (remoteMethod == AuthenticationMethod.None) - { - if (localMethod == AuthenticationMethod.None) - { - // do nothing - } - } - else if (remoteMethod == AuthenticationMethod.Credentials - || remoteMethod == AuthenticationMethod.Token) - { - if (localMethod == AuthenticationMethod.None) - { - if (_notEnough(offset, ends, 32)) - return -_dataLengthNeeded; - - remoteNonce = data.clip(offset, 32); - offset += 32; - - } - } - - if (encrypt) - { - if (_notEnough(offset, ends, 2)) - return -_dataLengthNeeded; - - var keyLength = data.getUint16(offset); - - offset += 2; - - if (_notEnough(offset, ends, keyLength)) - return -_dataLengthNeeded; - - asymetricEncryptionKey = data.clip(offset, keyLength); - - offset += keyLength; - } - } - else if (command == IIPAuthPacketCommand.Error) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - offset++; - errorCode = data[offset++]; - - - var cl = data.getUint16(offset); - offset += 2; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - errorMessage = data.getString(offset, cl); - offset += cl; - - } - - - return offset - oOffset; - - } - -} \ No newline at end of file + return offset - oOffset; + } +} diff --git a/lib/src/Net/Packets/IIPPacket.dart b/lib/src/Net/Packets/IIPPacket.dart index 732395d..aacff19 100644 --- a/lib/src/Net/Packets/IIPPacket.dart +++ b/lib/src/Net/Packets/IIPPacket.dart @@ -31,716 +31,536 @@ import 'IIPPacketReport.dart'; import '../../Data/Codec.dart'; import '../../Data/DataType.dart'; -class IIPPacket -{ +class IIPPacket { + int report = 0; + int command = 0; - + int action = 0; + int event = 0; + int previousCommand = 0; - int report; + int previousAction = 0; - int command; + int previousEvent = 0; - int action; + int resourceId = 0; + int newResourceId = 0; - int event; + int childId = 0; + int storeId = 0; - int previousCommand; + int resourceAge = 0; + DC content = DC(0); + int errorCode = 0; + String errorMessage = ""; + String className = ""; + String resourceLink = ""; + Guid classId = Guid(DC(0)); + int methodIndex = 0; + String methodName = ""; + int callbackId = 0; + int progressValue = 0; + int progressMax = 0; + DateTime fromDate = DateTime(2000); + DateTime toDate = DateTime(2000); + int fromAge = 0; + int toAge = 0; + int _dataLengthNeeded = 0; + int _originalOffset = 0; - int previousAction; + bool _notEnough(int offset, int ends, int needed) { + if (offset + needed > ends) { + _dataLengthNeeded = needed - (ends - offset); + //_dataLengthNeeded = (needed - (ends - offset)) + (offset - _originalOffset); - int previousEvent; + return true; + } else + return false; + } + int parse(DC data, int offset, int ends) { + _originalOffset = offset; - int resourceId; - int newResourceId; + if (_notEnough(offset, ends, 1)) return -_dataLengthNeeded; - int childId; - int storeId; + previousCommand = command; - int resourceAge; - DC content; - int errorCode; - String errorMessage; - String className ; - String resourceLink ; - Guid classId ; - int methodIndex ; - String methodName; - int callbackId ; - int progressValue; - int progressMax ; - DateTime fromDate ; - DateTime toDate; - int fromAge; - int toAge; + command = (data[offset] >> 6); - int _dataLengthNeeded; - int _originalOffset; + if (command == IIPPacketCommand.Event) { + event = (data[offset++] & 0x3f); + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; - bool _notEnough(int offset, int ends, int needed) - { - if (offset + needed > ends) - { - _dataLengthNeeded = needed - (ends - offset); - //_dataLengthNeeded = (needed - (ends - offset)) + (offset - _originalOffset); + resourceId = data.getUint32(offset); + offset += 4; + } else if (command == IIPPacketCommand.Report) { + report = (data[offset++] & 0x3f); - return true; - } - else - return false; + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + callbackId = data.getUint32(offset); + offset += 4; + } else { + previousAction = action; + action = (data[offset++] & 0x3f); + + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + callbackId = data.getUint32(offset); + offset += 4; } - int parse(DC data, int offset, int ends) - { - _originalOffset = offset; + if (command == IIPPacketCommand.Event) { + if (event == IIPPacketEvent.ResourceReassigned) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; - if (_notEnough(offset, ends, 1)) - return -_dataLengthNeeded; + newResourceId = data.getUint32(offset); + offset += 4; + } else if (event == IIPPacketEvent.ResourceDestroyed) { + // nothing to parse + } else if (event == IIPPacketEvent.ChildAdded || + event == IIPPacketEvent.ChildRemoved) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; - previousCommand = command; + childId = data.getUint32(offset); + offset += 4; + } else if (event == IIPPacketEvent.Renamed) { + if (_notEnough(offset, ends, 2)) return -_dataLengthNeeded; - command = (data[offset] >> 6); - - if (command == IIPPacketCommand.Event) - { - event = (data[offset++] & 0x3f); + var cl = data.getUint16(offset); + offset += 2; - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; - resourceId = data.getUint32(offset); - offset += 4; + content = data.clip(offset, cl); + + offset += cl; + } else if (event == IIPPacketEvent.PropertyUpdated || + event == IIPPacketEvent.EventOccurred) { + if (_notEnough(offset, ends, 2)) return -_dataLengthNeeded; + + methodIndex = data[offset++]; + + var dt = data[offset++]; + var size = DataType.size(dt); + + if (size < 0) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + var cl = data.getUint32(offset); + offset += 4; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + content = data.clip(offset - 5, cl + 5); + offset += cl; + } else { + if (_notEnough(offset, ends, size)) return -_dataLengthNeeded; + + content = data.clip(offset - 1, size + 1); + offset += size; } - else if (command == IIPPacketCommand.Report) - { - report = (data[offset++] & 0x3f); + } + // else if (event == IIPPacketEvent.EventOccurred) + // { + // if (_notEnough(offset, ends, 5)) + // return -_dataLengthNeeded; - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; + // methodIndex = data[offset++]; - callbackId = data.getUint32(offset); - offset += 4; + // var cl = data.getUint32( offset); + // offset += 4; + + // if (_notEnough(offset, ends, cl)) + // return -_dataLengthNeeded; + + // content = data.clip(offset, cl); + // offset += cl; + + // } + // Attribute + else if (event == IIPPacketEvent.AttributesUpdated) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + var cl = data.getUint32(offset); + offset += 4; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + content = data.clip(offset, cl); + + offset += cl; + } + } else if (command == IIPPacketCommand.Request) { + if (action == IIPPacketAction.AttachResource) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + } else if (action == IIPPacketAction.ReattachResource) { + if (_notEnough(offset, ends, 12)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + + resourceAge = data.getUint64(offset); + offset += 8; + } else if (action == IIPPacketAction.DetachResource) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + } else if (action == IIPPacketAction.CreateResource) { + if (_notEnough(offset, ends, 12)) return -_dataLengthNeeded; + + storeId = data.getUint32(offset); + offset += 4; + resourceId = data.getUint32(offset); + offset += 4; + + var cl = data.getUint32(offset); + offset += 4; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + content = data.clip(offset, cl); + } else if (action == IIPPacketAction.DeleteResource) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + } else if (action == IIPPacketAction.AddChild || + action == IIPPacketAction.RemoveChild) { + if (_notEnough(offset, ends, 8)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + childId = data.getUint32(offset); + offset += 4; + } else if (action == IIPPacketAction.RenameResource) { + if (_notEnough(offset, ends, 6)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + var cl = data.getUint16(offset); + offset += 2; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + content = data.clip(offset, cl); + offset += cl; + } else if (action == IIPPacketAction.TemplateFromClassName) { + if (_notEnough(offset, ends, 1)) return -_dataLengthNeeded; + + var cl = data[offset++]; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + className = data.getString(offset, cl); + offset += cl; + } else if (action == IIPPacketAction.TemplateFromClassId) { + if (_notEnough(offset, ends, 16)) return -_dataLengthNeeded; + + classId = data.getGuid(offset); + offset += 16; + } else if (action == IIPPacketAction.TemplateFromResourceId) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + } else if (action == IIPPacketAction.QueryLink || + action == IIPPacketAction.LinkTemplates) { + if (_notEnough(offset, ends, 2)) return -_dataLengthNeeded; + + var cl = data.getUint16(offset); + offset += 2; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + resourceLink = data.getString(offset, cl); + offset += cl; + } else if (action == IIPPacketAction.ResourceChildren || + action == IIPPacketAction.ResourceParents) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + } else if (action == IIPPacketAction.ResourceHistory) { + if (_notEnough(offset, ends, 20)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + + fromDate = data.getDateTime(offset); + offset += 8; + + toDate = data.getDateTime(offset); + offset += 8; + } else if (action == IIPPacketAction.InvokeFunctionArrayArguments || + action == IIPPacketAction.InvokeFunctionNamedArguments) { + if (_notEnough(offset, ends, 9)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + + methodIndex = data[offset++]; + + var cl = data.getUint32(offset); + offset += 4; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + content = data.clip(offset, cl); + offset += cl; + } else if (action == IIPPacketAction.Listen || + action == IIPPacketAction.Unlisten) { + if (_notEnough(offset, ends, 5)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + + methodIndex = data[offset++]; + } + // else if (action == IIPPacketAction.GetProperty) + // { + // if (_notEnough(offset, ends, 5)) + // return -_dataLengthNeeded; + + // resourceId = data.getUint32(offset); + // offset += 4; + + // methodIndex = data[offset++]; + + // } + // else if (action == IIPPacketAction.GetPropertyIfModified) + // { + // if (_notEnough(offset, ends, 9)) + // return -_dataLengthNeeded; + + // resourceId = data.getUint32(offset); + // offset += 4; + + // methodIndex = data[offset++]; + + // resourceAge = data.getUint64(offset); + // offset += 8; + + // } + else if (action == IIPPacketAction.SetProperty) { + if (_notEnough(offset, ends, 6)) return -_dataLengthNeeded; + + resourceId = data.getUint32(offset); + offset += 4; + + methodIndex = data[offset++]; + + var dt = data[offset++]; + var size = DataType.size(dt); + + if (size < 0) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + var cl = data.getUint32(offset); + offset += 4; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + content = data.clip(offset - 5, cl + 5); + offset += cl; + } else { + if (_notEnough(offset, ends, size)) return -_dataLengthNeeded; + + content = data.clip(offset - 1, size + 1); + offset += size; } - else - { - previousAction = action; - action = (data[offset++] & 0x3f); + } + // Attributes + else if (action == IIPPacketAction.UpdateAllAttributes || + action == IIPPacketAction.GetAttributes || + action == IIPPacketAction.UpdateAttributes || + action == IIPPacketAction.ClearAttributes) { + if (_notEnough(offset, ends, 8)) return -_dataLengthNeeded; - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; + resourceId = data.getUint32(offset); + offset += 4; + var cl = data.getUint32(offset); + offset += 4; - callbackId = data.getUint32(offset); - offset += 4; + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + content = data.clip(offset, cl); + offset += cl; + } + } else if (command == IIPPacketCommand.Reply) { + if (action == IIPPacketAction.AttachResource || + action == IIPPacketAction.ReattachResource) { + if (_notEnough(offset, ends, 26)) return -_dataLengthNeeded; + + classId = data.getGuid(offset); + offset += 16; + + resourceAge = data.getUint64(offset); + offset += 8; + + var cl = data.getUint16(offset); + offset += 2; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + resourceLink = data.getString(offset, cl); + offset += cl; + + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + cl = data.getUint32(offset); + offset += 4; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + content = data.clip(offset, cl); + offset += cl; + } else if (action == IIPPacketAction.DetachResource) { + // nothing to do + } else if (action == IIPPacketAction.CreateResource) { + if (_notEnough(offset, ends, 20)) return -_dataLengthNeeded; + + //ClassId = data.GetGuid(offset); + //offset += 16; + + resourceId = data.getUint32(offset); + offset += 4; + } else if (action == IIPPacketAction.DetachResource) { + // nothing to do + } + // Inquire + else if (action == IIPPacketAction.TemplateFromClassName || + action == IIPPacketAction.TemplateFromClassId || + action == IIPPacketAction.TemplateFromResourceId || + action == IIPPacketAction.QueryLink || + action == IIPPacketAction.ResourceChildren || + action == IIPPacketAction.ResourceParents || + action == IIPPacketAction.ResourceHistory || + action == IIPPacketAction.LinkTemplates + // Attribute + || + action == IIPPacketAction.GetAllAttributes || + action == IIPPacketAction.GetAttributes) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + var cl = data.getUint32(offset); + offset += 4; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + content = data.clip(offset, cl); + offset += cl; + } else if (action == IIPPacketAction.InvokeFunctionArrayArguments || + action == IIPPacketAction.InvokeFunctionNamedArguments) + //|| action == IIPPacketAction.GetProperty + //|| action == IIPPacketAction.GetPropertyIfModified) + { + if (_notEnough(offset, ends, 1)) return -_dataLengthNeeded; + + var dt = data[offset++]; + var size = DataType.size(dt); + + if (size < 0) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; + + var cl = data.getUint32(offset); + offset += 4; + + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; + + content = data.clip(offset - 5, cl + 5); + offset += cl; + } else { + if (_notEnough(offset, ends, size)) return -_dataLengthNeeded; + + content = data.clip(offset - 1, size + 1); + offset += size; } + } else if (action == IIPPacketAction.SetProperty || + action == IIPPacketAction.Listen || + action == IIPPacketAction.Unlisten) { + // nothing to do + } + } else if (command == IIPPacketCommand.Report) { + if (report == IIPPacketReport.ManagementError) { + if (_notEnough(offset, ends, 2)) return -_dataLengthNeeded; - if (command == IIPPacketCommand.Event) - { - if (event == IIPPacketEvent.ResourceReassigned) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; + errorCode = data.getUint16(offset); + offset += 2; + } else if (report == IIPPacketReport.ExecutionError) { + if (_notEnough(offset, ends, 2)) return -_dataLengthNeeded; - newResourceId = data.getUint32( offset); - offset += 4; + errorCode = data.getUint16(offset); + offset += 2; - } - else if (event == IIPPacketEvent.ResourceDestroyed) - { - // nothing to parse - } - else if (event == IIPPacketEvent.ChildAdded - || event == IIPPacketEvent.ChildRemoved) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; + if (_notEnough(offset, ends, 2)) return -_dataLengthNeeded; - childId = data.getUint32(offset); - offset += 4; - } - else if(event == IIPPacketEvent.Renamed) - { - if (_notEnough(offset, ends, 2)) - return -_dataLengthNeeded; + var cl = data.getUint16(offset); + offset += 2; - var cl = data.getUint16(offset); - offset += 2; + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; + errorMessage = data.getString(offset, cl); + offset += cl; + } else if (report == IIPPacketReport.ProgressReport) { + if (_notEnough(offset, ends, 8)) return -_dataLengthNeeded; - content = data.clip(offset, cl); + progressValue = data.getInt32(offset); + offset += 4; + progressMax = data.getInt32(offset); + offset += 4; + } else if (report == IIPPacketReport.ChunkStream) { + if (_notEnough(offset, ends, 1)) return -_dataLengthNeeded; - offset += cl; - } - else if (event == IIPPacketEvent.PropertyUpdated - || event == IIPPacketEvent.EventOccurred) - { - if (_notEnough(offset, ends, 2)) - return -_dataLengthNeeded; + var dt = data[offset++]; + var size = DataType.size(dt); - methodIndex = data[offset++]; + if (size < 0) { + if (_notEnough(offset, ends, 4)) return -_dataLengthNeeded; - var dt = data[offset++]; - var size = DataType.size(dt); + var cl = data.getUint32(offset); + offset += 4; - if (size < 0) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; + if (_notEnough(offset, ends, cl)) return -_dataLengthNeeded; - var cl = data.getUint32( offset); - offset += 4; + content = data.clip(offset - 5, cl + 5); + offset += cl; + } else { + if (_notEnough(offset, ends, size)) return -_dataLengthNeeded; - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip( offset - 5, cl + 5); - offset += cl; - } - else - { - if (_notEnough(offset, ends, size)) - return -_dataLengthNeeded; - - content = data.clip(offset - 1, size + 1); - offset += size; - } - } - // else if (event == IIPPacketEvent.EventOccurred) - // { - // if (_notEnough(offset, ends, 5)) - // return -_dataLengthNeeded; - - // methodIndex = data[offset++]; - - // var cl = data.getUint32( offset); - // offset += 4; - - // if (_notEnough(offset, ends, cl)) - // return -_dataLengthNeeded; - - // content = data.clip(offset, cl); - // offset += cl; - - // } - // Attribute - else if (event == IIPPacketEvent.AttributesUpdated) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - var cl = data.getUint32(offset); - offset += 4; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip(offset, cl); - - offset += cl; - } + content = data.clip(offset - 1, size + 1); + offset += size; } - else if (command == IIPPacketCommand.Request) - { - if (action == IIPPacketAction.AttachResource) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - } - else if (action == IIPPacketAction.ReattachResource) - { - if (_notEnough(offset, ends, 12)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - - resourceAge = data.getUint64(offset); - offset += 8; - - } - else if (action == IIPPacketAction.DetachResource) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - - } - else if (action == IIPPacketAction.CreateResource) - { - if (_notEnough(offset, ends, 12)) - return -_dataLengthNeeded; - - storeId = data.getUint32(offset); - offset += 4; - resourceId = data.getUint32(offset); - offset += 4; - - var cl = data.getUint32(offset); - offset += 4; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip(offset, cl); - } - else if (action == IIPPacketAction.DeleteResource) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - - } - else if (action == IIPPacketAction.AddChild - || action == IIPPacketAction.RemoveChild) - { - if (_notEnough(offset, ends, 8)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - childId = data.getUint32(offset); - offset += 4; - } - else if (action == IIPPacketAction.RenameResource) - { - if (_notEnough(offset, ends, 6)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - var cl = data.getUint16(offset); - offset += 2; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip(offset, cl); - offset += cl; - } - else if (action == IIPPacketAction.TemplateFromClassName) - { - if (_notEnough(offset, ends, 1)) - return -_dataLengthNeeded; - - var cl = data[offset++]; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - className = data.getString(offset, cl); - offset += cl; - - } - else if (action == IIPPacketAction.TemplateFromClassId) - { - if (_notEnough(offset, ends, 16)) - return -_dataLengthNeeded; - - classId = data.getGuid(offset); - offset += 16; - - } - else if (action == IIPPacketAction.TemplateFromResourceId) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - } - else if (action == IIPPacketAction.QueryLink - || action == IIPPacketAction.LinkTemplates) - { - if (_notEnough(offset, ends, 2)) - return -_dataLengthNeeded; - - var cl = data.getUint16(offset); - offset += 2; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - resourceLink = data.getString(offset, cl); - offset += cl; - } - else if (action == IIPPacketAction.ResourceChildren - || action == IIPPacketAction.ResourceParents) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - } - else if (action == IIPPacketAction.ResourceHistory) - { - if (_notEnough(offset, ends, 20)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - - fromDate = data.getDateTime(offset); - offset += 8; - - toDate = data.getDateTime(offset); - offset += 8; - - } - else if (action == IIPPacketAction.InvokeFunctionArrayArguments - || action == IIPPacketAction.InvokeFunctionNamedArguments) - { - if (_notEnough(offset, ends, 9)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - - methodIndex = data[offset++]; - - var cl = data.getUint32(offset); - offset += 4; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip(offset, cl); - offset += cl; - - } - else if (action == IIPPacketAction.Listen - || action == IIPPacketAction.Unlisten) - { - if (_notEnough(offset, ends, 5)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - - methodIndex = data[offset++]; - } - // else if (action == IIPPacketAction.GetProperty) - // { - // if (_notEnough(offset, ends, 5)) - // return -_dataLengthNeeded; - - // resourceId = data.getUint32(offset); - // offset += 4; - - // methodIndex = data[offset++]; - - // } - // else if (action == IIPPacketAction.GetPropertyIfModified) - // { - // if (_notEnough(offset, ends, 9)) - // return -_dataLengthNeeded; - - // resourceId = data.getUint32(offset); - // offset += 4; - - // methodIndex = data[offset++]; - - // resourceAge = data.getUint64(offset); - // offset += 8; - - // } - else if (action == IIPPacketAction.SetProperty) - { - if (_notEnough(offset, ends, 6)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - - methodIndex = data[offset++]; - - - var dt = data[offset++]; - var size = DataType.size(dt); - - if (size < 0) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - var cl = data.getUint32(offset); - offset += 4; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip(offset-5, cl + 5); - offset += cl; - } - else - { - if (_notEnough(offset, ends, size)) - return -_dataLengthNeeded; - - content = data.clip(offset-1, size + 1); - offset += size; - } - } - // Attributes - else if (action == IIPPacketAction.UpdateAllAttributes - || action == IIPPacketAction.GetAttributes - || action == IIPPacketAction.UpdateAttributes - || action == IIPPacketAction.ClearAttributes) - { - if (_notEnough(offset, ends, 8)) - return -_dataLengthNeeded; - - resourceId = data.getUint32(offset); - offset += 4; - var cl = data.getUint32(offset); - offset += 4; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip(offset, cl); - offset += cl; - } - } - else if (command == IIPPacketCommand.Reply) - { - if (action == IIPPacketAction.AttachResource - || action == IIPPacketAction.ReattachResource) - { - - if (_notEnough(offset, ends, 26)) - return -_dataLengthNeeded; - - classId = data.getGuid(offset); - offset += 16; - - resourceAge = data.getUint64(offset); - offset += 8; - - var cl = data.getUint16(offset); - offset += 2; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - resourceLink = data.getString(offset, cl); - offset += cl; - - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - cl = data.getUint32(offset); - offset += 4; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip(offset, cl); - offset += cl; - } - else if (action == IIPPacketAction.DetachResource) - { - // nothing to do - } - else if (action == IIPPacketAction.CreateResource) - { - if (_notEnough(offset, ends, 20)) - return -_dataLengthNeeded; - - //ClassId = data.GetGuid(offset); - //offset += 16; - - resourceId = data.getUint32(offset); - offset += 4; - - } - else if (action == IIPPacketAction.DetachResource) - { - // nothing to do - } - // Inquire - else if (action == IIPPacketAction.TemplateFromClassName - || action == IIPPacketAction.TemplateFromClassId - || action == IIPPacketAction.TemplateFromResourceId - || action == IIPPacketAction.QueryLink - || action == IIPPacketAction.ResourceChildren - || action == IIPPacketAction.ResourceParents - || action == IIPPacketAction.ResourceHistory - || action == IIPPacketAction.LinkTemplates - // Attribute - || action == IIPPacketAction.GetAllAttributes - || action == IIPPacketAction.GetAttributes) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - var cl = data.getUint32(offset); - offset += 4; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip(offset, cl); - offset += cl; - } - else if (action == IIPPacketAction.InvokeFunctionArrayArguments - || action == IIPPacketAction.InvokeFunctionNamedArguments) - //|| action == IIPPacketAction.GetProperty - //|| action == IIPPacketAction.GetPropertyIfModified) - { - if (_notEnough(offset, ends, 1)) - return -_dataLengthNeeded; - - var dt = data[offset++]; - var size = DataType.size(dt); - - if (size < 0) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - var cl = data.getUint32(offset); - offset += 4; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip(offset - 5, cl + 5); - offset += cl; - } - else - { - if (_notEnough(offset, ends, size)) - return -_dataLengthNeeded; - - content = data.clip(offset - 1, size + 1); - offset += size; - } - } - else if (action == IIPPacketAction.SetProperty - || action == IIPPacketAction.Listen - || action == IIPPacketAction.Unlisten) - { - // nothing to do - } - } - else if (command == IIPPacketCommand.Report) - { - if (report == IIPPacketReport.ManagementError) - { - if (_notEnough(offset, ends, 2)) - return -_dataLengthNeeded; - - errorCode = data.getUint16(offset); - offset += 2; - } - else if (report == IIPPacketReport.ExecutionError) - { - if (_notEnough(offset, ends, 2)) - return -_dataLengthNeeded; - - errorCode = data.getUint16(offset); - offset += 2; - - if (_notEnough(offset, ends, 2)) - return -_dataLengthNeeded; - - var cl = data.getUint16(offset); - offset += 2; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - errorMessage = data.getString(offset, cl); - offset += cl; - } - else if (report == IIPPacketReport.ProgressReport) - { - if (_notEnough(offset, ends, 8)) - return -_dataLengthNeeded; - - progressValue = data.getInt32(offset); - offset += 4; - progressMax = data.getInt32(offset); - offset += 4; - } - else if (report == IIPPacketReport.ChunkStream) - { - if (_notEnough(offset, ends, 1)) - return -_dataLengthNeeded; - - var dt = data[offset++]; - var size = DataType.size(dt); - - if (size < 0) - { - if (_notEnough(offset, ends, 4)) - return -_dataLengthNeeded; - - var cl = data.getUint32(offset); - offset += 4; - - if (_notEnough(offset, ends, cl)) - return -_dataLengthNeeded; - - content = data.clip(offset - 5, cl + 5); - offset += cl; - } - else - { - if (_notEnough(offset, ends, size)) - return -_dataLengthNeeded; - - content = data.clip(offset - 1, size + 1); - offset += size; - } - } - } - - return offset - _originalOffset; + } } + return offset - _originalOffset; + } + toString() { + var rt = command.toString(); + if (command == IIPPacketCommand.Event) { + rt += " " + event.toString(); + } else if (command == IIPPacketCommand.Request) { + rt += " " + action.toString(); + if (action == IIPPacketAction.AttachResource) { + rt += + " CID: " + callbackId.toString() + " RID: " + resourceId.toString(); + } + } else if (command == IIPPacketCommand.Reply) + rt += " " + action.toString(); + else if (command == IIPPacketCommand.Report) rt += " " + report.toString(); - - - - toString() - { - var rt = command.toString(); - - if (command == IIPPacketCommand.Event) - { - rt += " " + event.toString(); - } - else if (command == IIPPacketCommand.Request) - { - rt += " " + action.toString(); - if (action == IIPPacketAction.AttachResource) - { - rt += " CID: " + callbackId.toString() + " RID: " + resourceId.toString(); - } - } - else if (command == IIPPacketCommand.Reply) - rt += " " + action.toString(); - else if (command == IIPPacketCommand.Report) - rt += " " + report.toString(); - - return rt; - } - + return rt; + } } diff --git a/lib/src/Net/SendList.dart b/lib/src/Net/SendList.dart index 8ea6b98..e94bf49 100644 --- a/lib/src/Net/SendList.dart +++ b/lib/src/Net/SendList.dart @@ -2,21 +2,16 @@ import '../Data/BinaryList.dart'; import '../Core/AsyncReply.dart'; import 'NetworkConnection.dart'; -class SendList extends BinaryList -{ - NetworkConnection connection; - AsyncReply> reply; +class SendList extends BinaryList { + NetworkConnection connection; + AsyncReply>? reply; - SendList(NetworkConnection connection, AsyncReply> reply) - { - this.reply = reply; - this.connection = connection; - } + SendList(this.connection, this.reply) {} - @override - AsyncReply> done() - { - connection.send(super.toDC()); - return reply; - } + @override + AsyncReply> done() { + connection.send(super.toDC()); + + return reply ?? AsyncReply.ready([]); + } } diff --git a/lib/src/Net/Sockets/ISocket.dart b/lib/src/Net/Sockets/ISocket.dart index 428ed39..06f3a9d 100644 --- a/lib/src/Net/Sockets/ISocket.dart +++ b/lib/src/Net/Sockets/ISocket.dart @@ -37,7 +37,7 @@ abstract class ISocket extends IDestructible { //void send(DC message); - INetworkReceiver receiver; + INetworkReceiver? receiver; void send(DC message, [int offset, int size]); void close(); @@ -45,6 +45,6 @@ abstract class ISocket extends IDestructible { bool begin(); AsyncReply accept(); - IPEndPoint remoteEndPoint; - IPEndPoint localEndPoint; + IPEndPoint? remoteEndPoint; + IPEndPoint? localEndPoint; } diff --git a/lib/src/Net/Sockets/TCPSocket.dart b/lib/src/Net/Sockets/TCPSocket.dart index a78c8e3..b1b05c9 100644 --- a/lib/src/Net/Sockets/TCPSocket.dart +++ b/lib/src/Net/Sockets/TCPSocket.dart @@ -37,7 +37,7 @@ import 'IPEndPoint.dart'; import '../../Core/AsyncReply.dart'; class TCPSocket extends ISocket { - Socket sock; + Socket? sock; NetworkBuffer receiveNetworkBuffer = new NetworkBuffer(); //bool asyncSending; @@ -61,15 +61,18 @@ class TCPSocket extends ISocket { } */ - IPEndPoint _localEP, _remoteEP; + IPEndPoint? _localEP, _remoteEP; bool begin() { if (began) return false; began = true; - _localEP = IPEndPoint(sock.address.rawAddress, sock.port); - _remoteEP = IPEndPoint(sock.remoteAddress.rawAddress, sock.remotePort); + if (sock != null) { + var s = sock as Socket; + _localEP = IPEndPoint(s.address.rawAddress, s.port); + _remoteEP = IPEndPoint(s.remoteAddress.rawAddress, s.remotePort); + } return true; } @@ -82,7 +85,7 @@ class TCPSocket extends ISocket { var dc = new DC.fromList(data); receiveNetworkBuffer.write(dc, 0, dc.length); - receiver.networkReceive(this, receiveNetworkBuffer); + receiver?.networkReceive(this, receiveNetworkBuffer); //emitArgs("receive", [receiveNetworkBuffer]); @@ -101,7 +104,7 @@ class TCPSocket extends ISocket { void doneHandler() { close(); - sock.destroy(); + sock?.destroy(); } AsyncReply connect(String hostname, int port) { @@ -134,13 +137,13 @@ class TCPSocket extends ISocket { return rt; } - IPEndPoint get localEndPoint => _localEP; - IPEndPoint get remoteEndPoint => _remoteEP; + IPEndPoint? get localEndPoint => _localEP; + IPEndPoint? get remoteEndPoint => _remoteEP; SocketState get state => _state; - TCPSocket.fromSocket(Socket socket) { - sock = socket; + TCPSocket.fromSocket(this.sock) { + //sock = socket; //if (socket.) // _state = SocketState.Established; } @@ -160,8 +163,16 @@ class TCPSocket extends ISocket { //emitArgs("close", []); } - void send(DC message, [int offset, int size]) { - if (state == SocketState.Established) sock.add(message.toList()); + void send(DC message, [int? offset, int? size]) { + if (state == SocketState.Established) { + if (offset != null && size == null) { + sock?.add(message.clip(offset, message.length - offset).toList()); + } else if (offset != null && size != null) { + sock?.add(message.clip(offset, size).toList()); + } else { + sock?.add(message.toList()); + } + } } void destroy() { diff --git a/lib/src/Proxy/TemplateGenerator.dart b/lib/src/Proxy/TemplateGenerator.dart index a3e8398..d2893b7 100644 --- a/lib/src/Proxy/TemplateGenerator.dart +++ b/lib/src/Proxy/TemplateGenerator.dart @@ -21,7 +21,7 @@ class TemplateGenerator { rt.writeln("class ${className} extends IRecord {"); template.properties.forEach((p) { - var ptTypeName = getTypeName(template, p.valueType, templates); + var ptTypeName = getTypeName(template, p.valueType, templates, false); rt.writeln("${ptTypeName}? ${p.name};"); rt.writeln(); }); @@ -53,8 +53,8 @@ class TemplateGenerator { 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); + var ptTypeName = getTypeName(template, + TemplateDataType(ptType, p.valueType.typeGuid), templates, false); // return "Prop(\"${p.name}\", ${ptTypeName}, ${isArray})"; return "Prop('${p.name}', ${ptTypeName}, ${isArray}, ${_escape(p.readExpansion)}, ${_escape(p.writeExpansion)})"; }).join(', '); @@ -67,17 +67,20 @@ class TemplateGenerator { return rt.toString(); } - static String _translateClassName(String className) { + static String _translateClassName(String className, bool nullable) { var cls = className.split('.'); var nameSpace = cls.take(cls.length - 1).join('_').toLowerCase(); - return "$nameSpace.${cls.last}"; + return "$nameSpace.${cls.last}${nullable ? '?' : ''}"; } - static String getTypeName(TypeTemplate forTemplate, - TemplateDataType templateDataType, List templates) { + static String getTypeName( + TypeTemplate forTemplate, + TemplateDataType templateDataType, + List templates, + bool nullable) { if (templateDataType.type == DataType.Resource) { if (templateDataType.typeGuid == forTemplate.classId) - return forTemplate.className.split('.').last; + return forTemplate.className.split('.').last + (nullable ? "?" : ""); else { var tmp = templates.firstWhere((x) => x.classId == templateDataType.typeGuid && @@ -86,11 +89,11 @@ class TemplateGenerator { if (tmp == null) return "dynamic"; // something went wrong - return _translateClassName(tmp.className); + return _translateClassName(tmp.className, nullable); } } else if (templateDataType.type == DataType.ResourceArray) { if (templateDataType.typeGuid == forTemplate.classId) - return "List<${forTemplate.className.split('.').last}>"; + return "List<${forTemplate.className.split('.').last + (nullable ? '?' : '')}>"; else { var tmp = templates.firstWhere((x) => x.classId == templateDataType.typeGuid && @@ -99,27 +102,27 @@ class TemplateGenerator { if (tmp == null) return "dynamic"; // something went wrong - return "List<${_translateClassName(tmp.className)}>"; + return "List<${_translateClassName(tmp.className, nullable)}>"; } } else if (templateDataType.type == DataType.Record) { if (templateDataType.typeGuid == forTemplate.classId) - return forTemplate.className.split('.').last; + return forTemplate.className.split('.').last + (nullable ? '?' : ''); 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); + return _translateClassName(tmp.className, nullable); } } else if (templateDataType.type == DataType.RecordArray) { if (templateDataType.typeGuid == forTemplate.classId) - return "List<${forTemplate.className.split('.').last}>"; + return "List<${forTemplate.className.split('.').last + (nullable ? '?' : '')}?>"; 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)}>"; + return "List<${_translateClassName(tmp.className, nullable)}>"; } } @@ -130,13 +133,13 @@ class TemplateGenerator { case DataType.BoolArray: return "List"; case DataType.Char: - return "String"; + return "String" + (nullable ? "?" : ""); case DataType.CharArray: - return "List"; + return "List"; case DataType.DateTime: return "DateTime"; case DataType.DateTimeArray: - return "List"; + return "List"; case DataType.Decimal: return "double"; case DataType.DecimalArray: @@ -168,11 +171,11 @@ class TemplateGenerator { case DataType.String: return "String"; case DataType.StringArray: - return "List"; + return "List"; case DataType.Structure: - return "Structure"; + return "Structure" + (nullable ? "?" : ""); case DataType.StructureArray: - return "List"; + return "List"; case DataType.UInt16: return "int"; case DataType.UInt16Array: @@ -206,24 +209,24 @@ class TemplateGenerator { } static Future getTemplate(String url, - [String dir = null, - String username = null, - String password = null]) async { + [String? dir = null, + String? username = null, + String? password = null]) async { try { if (!_urlRegex.hasMatch(url)) throw Exception("Invalid IIP URL"); var path = _urlRegex.allMatches(url).first; var con = await Warehouse.get( - path[1] + "://" + path[2], + (path[1] as String) + "://" + (path[2] as String), !isNullOrEmpty(username) && !isNullOrEmpty(password) ? {username: username, password: password} : null); if (con == null) throw Exception("Can't connect to server"); - if (isNullOrEmpty(dir)) dir = path[2].replaceAll(":", "_"); + if (isNullOrEmpty(dir)) dir = (path[2] as String).replaceAll(":", "_"); - var templates = await con.getLinkTemplates(path[3]); + var templates = await con.getLinkTemplates(path[3] as String); // no longer needed Warehouse.remove(con); @@ -234,7 +237,7 @@ class TemplateGenerator { //Map namesMap = Map(); - var makeImports = (TypeTemplate skipTemplate) { + var makeImports = (TypeTemplate? skipTemplate) { var imports = StringBuffer(); imports.writeln("import 'dart:async';"); imports.writeln("import 'package:esiur/esiur.dart';"); @@ -270,12 +273,12 @@ class TemplateGenerator { var defineCreators = templates.map((tmp) { // creator - var className = _translateClassName(tmp.className); - return "Warehouse.defineCreator(${className}, () => ${className}(), () => <${className}>[]);"; + var className = _translateClassName(tmp.className, false); + return "Warehouse.defineCreator(${className}, () => ${className}(), () => <${className}?>[]);"; }).join("\r\n"); var putTemplates = templates.map((tmp) { - var className = _translateClassName(tmp.className); + var className = _translateClassName(tmp.className, false); return "Warehouse.putTemplate(TypeTemplate.fromType(${className}));"; }).join("\r\n"); @@ -291,7 +294,7 @@ class TemplateGenerator { } } - static String _escape(String str) { + static String _escape(String? str) { if (str == null) return "null"; else @@ -316,10 +319,11 @@ class TemplateGenerator { rt.writeln("}"); template.functions.forEach((f) { - var rtTypeName = getTypeName(template, f.returnType, templates); + var rtTypeName = getTypeName(template, f.returnType, templates, true); rt.write("AsyncReply<$rtTypeName> ${f.name}("); rt.write(f.arguments - .map((x) => getTypeName(template, x.type, templates) + " " + x.name) + .map((x) => + getTypeName(template, x.type, templates, true) + " " + x.name) .join(",")); rt.writeln(") {"); @@ -333,14 +337,14 @@ class TemplateGenerator { }); template.properties.forEach((p) { - var ptTypeName = getTypeName(template, p.valueType, templates); + var ptTypeName = getTypeName(template, p.valueType, templates, true); rt.writeln("${ptTypeName} get ${p.name} { return get(${p.index}); }"); rt.writeln( "set ${p.name}(${ptTypeName} value) { set(${p.index}, value); }"); }); template.events.forEach((e) { - var etTypeName = getTypeName(template, e.argumentType, templates); + var etTypeName = getTypeName(template, e.argumentType, templates, true); rt.writeln( "final _${e.name}Controller = StreamController<$etTypeName>();"); @@ -353,22 +357,22 @@ class TemplateGenerator { 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); + var ptTypeName = getTypeName(template, + TemplateDataType(ptType, p.valueType.typeGuid), templates, false); 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 ftTypeName = getTypeName(template, + TemplateDataType(ftType, f.returnType.typeGuid), templates, false); 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); + var atTypeName = getTypeName(template, + TemplateDataType(atType, a.type.typeGuid), templates, false); return "Arg('${a.name}', ${atTypeName}, ${isArray})"; }).join(', '); @@ -379,7 +383,7 @@ class TemplateGenerator { var isArray = e.argumentType.type & 0x80 == 0x80; var etType = e.argumentType.type & 0x7F; var etTypeName = getTypeName(template, - TemplateDataType(etType, e.argumentType.typeGuid), templates); + TemplateDataType(etType, e.argumentType.typeGuid), templates, false); return "Evt('${e.name}', ${etTypeName}, ${isArray}, ${e.listenable}, ${_escape(e.expansion)})"; }).join(', '); diff --git a/lib/src/Resource/FactoryEntry.dart b/lib/src/Resource/FactoryEntry.dart index c2ad498..2d5c852 100644 --- a/lib/src/Resource/FactoryEntry.dart +++ b/lib/src/Resource/FactoryEntry.dart @@ -1,7 +1,7 @@ class FactoryEntry { final Type type; - final Function() instanceCreator; - final Function() arrayCreator; + 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 0e58408..d13cd71 100644 --- a/lib/src/Resource/IResource.dart +++ b/lib/src/Resource/IResource.dart @@ -33,7 +33,7 @@ import 'Instance.dart'; abstract class IResource extends IDestructible { AsyncReply trigger(ResourceTrigger trigger); - Instance instance; + Instance? instance; invoke(String name, List arguments); setProperty(String name, value); diff --git a/lib/src/Resource/IStore.dart b/lib/src/Resource/IStore.dart index 05f43f8..c35fe12 100644 --- a/lib/src/Resource/IStore.dart +++ b/lib/src/Resource/IStore.dart @@ -28,18 +28,20 @@ import '../Data/KeyList.dart'; import './Template/PropertyTemplate.dart'; import '../Data/PropertyValue.dart'; -// old +// old // abstract class IStore extends IResource // new -abstract class IStore implements IResource -{ - AsyncReply get(String path); - AsyncReply retrieve(int iid); - AsyncReply put(IResource resource); - String link(IResource resource); - bool record(IResource resource, String propertyName, dynamic value, int age, DateTime dateTime); - bool modify(IResource resource, String propertyName, dynamic value, int age, DateTime dateTime); - bool remove(IResource resource); +abstract class IStore implements IResource { + AsyncReply get(String path); + AsyncReply retrieve(int iid); + AsyncReply put(IResource resource); + String? link(IResource resource); + bool record(IResource resource, String propertyName, dynamic value, int age, + DateTime dateTime); + bool modify(IResource resource, String propertyName, dynamic value, int age, + DateTime dateTime); + bool remove(IResource resource); - AsyncReply>> getRecord(IResource resource, DateTime fromDate, DateTime toDate); + AsyncReply>?> getRecord( + IResource resource, DateTime fromDate, DateTime toDate); } diff --git a/lib/src/Resource/Instance.dart b/lib/src/Resource/Instance.dart index 80df889..dd76754 100644 --- a/lib/src/Resource/Instance.dart +++ b/lib/src/Resource/Instance.dart @@ -21,123 +21,97 @@ import './Template/MemberTemplate.dart'; import '../Data/PropertyValue.dart'; import 'Warehouse.dart'; -class Instance extends IEventHandler -{ - String _name; +class Instance extends IEventHandler { + String _name; - AutoList _children; - IResource _resource; - IStore _store; - AutoList _parents; - //bool inherit; - TypeTemplate _template; + late AutoList _children; + IResource _resource; + IStore? _store; + late AutoList _parents; + //bool inherit; + late TypeTemplate _template; - AutoList _managers; + late AutoList _managers; + late KeyList _attributes; - KeyList _attributes; + List _ages = []; + List _modificationDates = []; + int _instanceAge; + DateTime? _instanceModificationDate; - List _ages = new List(); - List _modificationDates = new List(); - int _instanceAge; - DateTime _instanceModificationDate; + int _id; - int _id; + /// + /// Instance attributes are custom properties associated with the instance, a place to store information by IStore. + /// + KeyList get attributes => _attributes; + @override + String toString() => _name + " (" + (link ?? '') + ")"; - /// - /// Instance attributes are custom properties associated with the instance, a place to store information by IStore. - /// - KeyList get attributes => _attributes; - - @override - String toString() => _name + " (" + link + ")"; - - - bool removeAttributes([List attributes = null]) - { - if (attributes == null) - this._attributes.clear(); - else - { - for (var attr in attributes) - this.attributes.remove(attr); - } - - return true; + bool removeAttributes([List? attributes = null]) { + if (attributes == null) + this._attributes.clear(); + else { + for (var attr in attributes) this.attributes.remove(attr); } - Structure getAttributes([List attributes = null]) - { - var st = new Structure(); + return true; + } - if (attributes == null) - { - var clone = this.attributes.keys.toList(); - clone.add("managers"); - attributes = clone.toList(); - } + Structure getAttributes([List? attributes = null]) { + var st = new Structure(); - for(var attr in attributes) - { - if (attr == "name") - st["name"] = _name; - else if (attr == "managers") - { - var mngrs = new List(); - - for (var i = 0; i < _managers.length; i++) - { - var mst = new Structure(); - mst["type"] = _managers[i].runtimeType; - mst["settings"] = _managers[i].settings; - - mngrs.add(mst); - } - - st["managers"] = mngrs; - } - else if (attr == "parents") - { - st["parents"] = _parents.toList(); - } - else if (attr == "children") - { - st["children"] = _children.toList(); - } - else if (attr == "childrenCount") - { - st["childrenCount"] = _children.count; - } - else if (attr == "type") - { - st["type"] = resource.runtimeType; - } - else - st[attr] = _attributes[attr]; - } - - return st; + if (attributes == null) { + var clone = this.attributes.keys.toList(); + clone.add("managers"); + attributes = clone.toList(); } - bool setAttributes(Structure attributes, [bool clearAttributes = false]) - { - try - { + for (var attr in attributes) { + if (attr == "name") + st["name"] = _name; + else if (attr == "managers") { + var mngrs = []; - if (clearAttributes) - _attributes.clear(); + for (var i = 0; i < _managers.length; i++) { + var mst = new Structure(); + mst["type"] = _managers[i].runtimeType; + mst["settings"] = _managers[i].settings; - for (var attrKey in attributes.keys) - if (attrKey == "name") - _name = attributes[attrKey]; - else if (attrKey == "managers") - { - _managers.clear(); + mngrs.add(mst); + } - var mngrs = attributes[attrKey] as List; - // this is not implemented now, Flutter doesn't support mirrors, needs a workaround @ Warehouse.registerManager - /* + st["managers"] = mngrs; + } else if (attr == "parents") { + st["parents"] = _parents.toList(); + } else if (attr == "children") { + st["children"] = _children.toList(); + } else if (attr == "childrenCount") { + st["childrenCount"] = _children.count; + } else if (attr == "type") { + st["type"] = resource.runtimeType; + } else + st[attr] = _attributes[attr]; + } + + return st; + } + + bool setAttributes(Structure attributes, [bool clearAttributes = false]) { + try { + if (clearAttributes) _attributes.clear(); + + for (var attrKey in attributes.keys) + if (attrKey == "name") + _name = attributes[attrKey] as String; + else if (attrKey == "managers") { + _managers.clear(); + + var mngrs = attributes[attrKey] as List; + // this is not implemented now, Flutter doesn't support mirrors, needs a workaround @ Warehouse.registerManager + /* for (var mngr in mngrs) { var m = mngr as Structure; @@ -153,22 +127,17 @@ class Instance extends IEventHandler return false; } */ - } - else - { - _attributes[attrKey] = attributes[attrKey]; - } - + } else { + _attributes[attrKey] = attributes[attrKey]; } - catch(ex) - { - return false; - } - - return true; + } catch (ex) { + return false; } - - /* + + return true; + } + + /* public Structure GetAttributes() { var st = new Structure(); @@ -192,73 +161,67 @@ class Instance extends IEventHandler return st; }*/ - /// - /// Get the age of a given property index. - /// - /// Zero-based property index. - /// Age. - int getAge(int index) - { - if (index < _ages.length) - return _ages[index]; - else - return 0; - } + /// + /// Get the age of a given property index. + /// + /// Zero-based property index. + /// Age. + int getAge(int index) { + if (index < _ages.length) + return _ages[index]; + else + return 0; + } - /// - /// Set the age of a property. - /// - /// Zero-based property index. - /// Age. - void setAge(int index, int value) - { - if (index < _ages.length) - { - _ages[index] = value; - if (value > _instanceAge) - _instanceAge = value; - } + /// + /// Set the age of a property. + /// + /// Zero-based property index. + /// Age. + void setAge(int index, int value) { + if (index < _ages.length) { + _ages[index] = value; + if (value > _instanceAge) _instanceAge = value; } + } - /// - /// Set the modification date of a property. - /// - /// Zero-based property index. - /// Modification date. - void setModificationDate(int index, DateTime value) - { - if (index < _modificationDates.length) - { - _modificationDates[index] = value; - if (_instanceModificationDate == null || value.millisecondsSinceEpoch > _instanceModificationDate.millisecondsSinceEpoch) - _instanceModificationDate = value; - } + /// + /// Set the modification date of a property. + /// + /// Zero-based property index. + /// Modification date. + void setModificationDate(int index, DateTime value) { + if (index < _modificationDates.length) { + _modificationDates[index] = value; + if (_instanceModificationDate == null || + value.millisecondsSinceEpoch > + (_instanceModificationDate as DateTime).millisecondsSinceEpoch) + _instanceModificationDate = value; } + } - /// - /// Get modification date of a specific property. - /// - /// Zero-based property index - /// Modification date. - DateTime getModificationDate(int index) - { - if (index < _modificationDates.length) - return _modificationDates[index]; - else - return new DateTime(0); - } + /// + /// Get modification date of a specific property. + /// + /// Zero-based property index + /// Modification date. + DateTime getModificationDate(int index) { + if (index < _modificationDates.length) + return _modificationDates[index]; + else + return new DateTime(0); + } - - /// - /// Load property value (used by stores) - /// - /// Property name - /// Property age - /// Property value - /// - bool loadProperty(String name, int age, DateTime modificationDate, dynamic value) - { - /* + /// + /// Load property value (used by stores) + /// + /// Property name + /// Property age + /// Property value + /// + bool loadProperty( + String name, int age, DateTime modificationDate, dynamic value) { + /* var pt = _template.getPropertyTemplate(name); if (pt == null) @@ -281,64 +244,58 @@ class Instance extends IEventHandler setModificationDate(pt.index, modificationDate); */ - return true; + return true; + } + /// + /// Age of the instance, incremented by 1 in every modification. + /// + int get age => _instanceAge; + // this must be internal + set age(value) => _instanceAge = value; + + /// + /// Last modification date. + /// + DateTime? get modificationDate => _instanceModificationDate; + + /// + /// Instance Id. + /// + int get id => _id; + + /// + /// Import properties from bytes array. + /// + /// + /// + bool deserialize(List properties) { + for (var i = 0; i < properties.length; i++) { + var pt = _template.getPropertyTemplateByIndex(i); + if (pt != null) { + var pv = properties[i]; + loadProperty(pt.name, pv.age, pv.date, pv.value); + } } - /// - /// Age of the instance, incremented by 1 in every modification. - /// - int get age => _instanceAge; - // this must be internal - set age (value) => _instanceAge = value; + return true; + } - /// - /// Last modification date. - /// - DateTime get modificationDate => _instanceModificationDate; - - /// - /// Instance Id. - /// - int get id => _id; - - /// - /// Import properties from bytes array. - /// - /// - /// - bool deserialize(List properties) - { - for (var i = 0; i < properties.length; i++) - { - var pt = _template.getPropertyTemplateByIndex(i); - if (pt != null) - { - var pv = properties[i]; - loadProperty(pt.name, pv.age, pv.date, pv.value); - } - } + /// + /// Export all properties with ResourceProperty attributed as bytes array. + /// + /// + List serialize() { + List props = []; - return true; + for (var pt in _template.properties) { + // var rt = pt.info.getValue(resource, null); + // props.add(new PropertyValue(rt, _ages[pt.index], _modificationDates[pt.index])); } - /// - /// Export all properties with ResourceProperty attributed as bytes array. - /// - /// - List serialize() - { - List props = new List(); - - for (var pt in _template.properties) - { - // var rt = pt.info.getValue(resource, null); - // props.add(new PropertyValue(rt, _ages[pt.index], _modificationDates[pt.index])); - } - - return props; - } - /* + return props; + } + /* public bool Deserialize(byte[] data, uint offset, uint length) { @@ -347,7 +304,7 @@ class Instance extends IEventHandler return true; } */ - /* + /* public byte[] Serialize(bool includeLength = false, DistributedConnection sender = null) { @@ -405,70 +362,62 @@ class Instance extends IEventHandler } */ - /// - /// If True, the instance can be stored to disk. - /// - /// - bool isStorable() - { - return false; + /// + /// If True, the instance can be stored to disk. + /// + /// + bool isStorable() { + return false; + } + + void emitModification(PropertyTemplate pt, dynamic value) { + _instanceAge++; + var now = DateTime.now().toUtc(); + + _ages[pt.index] = _instanceAge; + _modificationDates[pt.index] = now; + + if (pt.storage == StorageMode.NonVolatile) { + _store?.modify(_resource, pt.name, value, _ages[pt.index], now); + } else if (pt.storage == StorageMode.Recordable) { + _store?.record(_resource, pt.name, value, _ages[pt.index], now); } + emitArgs("resourceModified", [_resource, pt.name, value]); + //_resource.emitArgs("modified", [pt.name, value]); + _resource.emitArgs(":${pt.name}", [value]); + } - void emitModification(PropertyTemplate pt, dynamic value) - { - _instanceAge++; - var now = DateTime.now().toUtc(); - - _ages[pt.index] = _instanceAge; - _modificationDates[pt.index] = now; - - if (pt.storage == StorageMode.NonVolatile) - { - _store.modify(_resource, pt.name, value, _ages[pt.index], now); - } - else if (pt.storage == StorageMode.Recordable) - { - _store.record(_resource, pt.name, value, _ages[pt.index], now); - } - - emitArgs("resourceModified", [_resource, pt.name, value]); - //_resource.emitArgs("modified", [pt.name, value]); - _resource.emitArgs(":${pt.name}", [value]); + /// + /// Notify listeners that a property was modified. + /// + /// + /// + /// + modified(String propertyName) { + var valueObject = new ValueObject(); + if (getPropertyValue(propertyName, valueObject)) { + var pt = _template.getPropertyTemplateByName(propertyName); + if (pt != null) emitModification(pt, valueObject.value); } + } - /// - /// Notify listeners that a property was modified. - /// - /// - /// - /// - modified(String propertyName) - { - var valueObject = new ValueObject(); - if (getPropertyValue(propertyName, valueObject)) - { - var pt = _template.getPropertyTemplateByName(propertyName); - emitModification(pt, valueObject.value); - } - } + emitResourceEvent( + issuer, List? receivers, String name, dynamic args) { + emitArgs( + "resourceEventOccurred", [_resource, issuer, receivers, name, args]); + } - emitResourceEvent(issuer, List receivers, String name, dynamic args) - { - emitArgs("resourceEventOccurred", [_resource, issuer, receivers, name, args]); - } + /// + /// Get the value of a given property by name. + /// + /// Property name + /// Output value + /// True, if the resource has the property. + bool getPropertyValue(String name, ValueObject valueObject) { + var pt = _template.getPropertyTemplateByName(name); - /// - /// Get the value of a given property by name. - /// - /// Property name - /// Output value - /// True, if the resource has the property. - bool getPropertyValue(String name, ValueObject valueObject) - { - var pt = _template.getPropertyTemplateByName(name); - - /* + /* if (pt != null && pt.info != null) { valueObject.value = pt.info.getValue(_resource, null); @@ -476,146 +425,130 @@ class Instance extends IEventHandler }*/ - valueObject.value = null; - return false; - } + valueObject.value = null; + return false; + } - - /* + /* public bool Inherit { get { return inherit; } }*/ - /// - /// List of parents. - /// - AutoList get parents => _parents; - + /// + /// List of parents. + /// + AutoList get parents => _parents; - /// - /// Store responsible for creating and keeping the resource. - /// - IStore get store => _store; + /// + /// Store responsible for creating and keeping the resource. + /// + IStore? get store => _store; - /// - /// List of children. - /// - AutoList get children => _children; - - /// - /// The unique and permanent link to the resource. - /// - String get link - { - if (_store != null) - return _store.link(_resource); - else - { - var l = new List(); + /// + /// List of children. + /// + AutoList get children => _children; - var p = _resource; + /// + /// The unique and permanent link to the resource. + /// + String? get link { + if (_store != null) + return _store?.link(_resource); + else { + var l = []; - while (true) - { - l.insert(0, p.instance.name); + var p = _resource; - if (p.instance.parents.count == 0) - break; + while (true) { + if (p.instance != null) break; + var pi = p.instance as Instance; - p = p.instance.parents.first(); - } + l.insert(0, pi.name); - return l.join("/"); - } - + if (pi.parents.count == 0) break; + + p = pi.parents.first; + } + + return l.join("/"); + } + } + + /// + /// Instance name. + /// + String get name => _name; + set name(value) => name = value; + + /// + /// Resource managed by this instance. + /// + IResource get resource => _resource; + + /// + /// Resource template describes the properties, functions and events of the resource. + /// + TypeTemplate get template => _template; + + /// + /// Check for permission. + /// + /// Caller sessions. + /// Action type + /// Function, property or event to check for permission. + /// Permission inquirer. + /// Ruling. + Ruling applicable(Session session, ActionType action, MemberTemplate? member, + [dynamic inquirer = null]) { + for (var i = 0; i < _managers.length; i++) { + var r = _managers[i] + .applicable(this.resource, session, action, member, inquirer); + if (r != Ruling.DontCare) return r; } - /// - /// Instance name. - /// - String get name => _name; - set name(value) => name = value; - + return Ruling.DontCare; + } - /// - /// Resource managed by this instance. - /// - IResource get resource => _resource; - - - /// - /// Resource template describes the properties, functions and events of the resource. - /// - TypeTemplate get template => _template; + /// + /// Execution managers. + /// + AutoList get managers => _managers; - /// - /// Check for permission. - /// - /// Caller sessions. - /// Action type - /// Function, property or event to check for permission. - /// Permission inquirer. - /// Ruling. - Ruling applicable(Session session, ActionType action, MemberTemplate member, [dynamic inquirer = null]) - { - - for(var i = 0; i < _managers.length; i++) - { - var r = _managers[i].applicable(this.resource, session, action, member, inquirer); - if (r != Ruling.DontCare) - return r; - } + /// + /// Create new instance. + /// + /// Instance Id. + /// Name of the instance. + /// Resource to manage. + /// Store responsible for the resource. + Instance(this._id, this._name, this._resource, this._store, + [TypeTemplate? customTemplate = null, this._instanceAge = 0]) { + _attributes = new KeyList(this); + _children = new AutoList(this); + _parents = new AutoList(this); + _managers = new AutoList(this); - return Ruling.DontCare; + _children.on("add", children_OnAdd); + _children.on("remove", children_OnRemoved); + _parents.on("add", parents_OnAdd); + _parents.on("remove", parents_OnRemoved); + resource.on("destroy", resource_OnDestroy); + + if (customTemplate != null) + _template = customTemplate; + else + _template = Warehouse.getTemplateByType(resource.runtimeType); + + // set ages + for (int i = 0; i < _template.properties.length; i++) { + _ages.add(0); + _modificationDates.add(new DateTime(0)); //DateTime.MinValue); } - /// - /// Execution managers. - /// - AutoList get managers => _managers; - - /// - /// Create new instance. - /// - /// Instance Id. - /// Name of the instance. - /// Resource to manage. - /// Store responsible for the resource. - Instance(int id, String name, IResource resource, IStore store, [TypeTemplate customTemplate = null, int age = 0]) - { - _store = store; - _resource = resource; - _id = id; - _name = name; - _instanceAge = age; - - _attributes = new KeyList(this); - _children = new AutoList(this); - _parents = new AutoList(this); - _managers = new AutoList(this); - - _children.on("add", children_OnAdd); - _children.on("remove", children_OnRemoved); - _parents.on("add", parents_OnAdd); - _parents.on("remove", parents_OnRemoved); - - resource.on("destroy", resource_OnDestroy); - - if (customTemplate != null) - _template = customTemplate; - else - _template = Warehouse.getTemplateByType(resource.runtimeType); - - // set ages - for (int i = 0; i < _template.properties.length; i++) - { - _ages.add(0); - _modificationDates.add(new DateTime(0));//DateTime.MinValue); - } - - /* + /* // connect events Type t = resource.runtimeType; @@ -650,33 +583,33 @@ class Instance extends IEventHandler } */ - } + } - void children_OnRemoved(Instance parent, IResource value) - { - value.instance.parents.remove(_resource); - } + void children_OnRemoved(Instance parent, IResource value) { + value.instance?.parents.remove(_resource); + } - void children_OnAdd(Instance parent, IResource value) - { - if (!value.instance.parents.contains(_resource)) - value.instance.parents.add(_resource); + void children_OnAdd(Instance parent, IResource value) { + if (value.instance != null) { + var ins = value.instance as Instance; + if (ins.parents.contains(_resource)) + value.instance?.parents.add(_resource); } + } - void parents_OnRemoved(Instance parent, IResource value) - { - value.instance.children.remove(_resource); + void parents_OnRemoved(Instance parent, IResource value) { + value.instance?.children.remove(_resource); + } + + void parents_OnAdd(Instance parent, IResource value) { + if (value.instance != null) { + var ins = value.instance as Instance; + if (!ins.children.contains(_resource)) + value.instance?.children.add(_resource); } + } - void parents_OnAdd(Instance parent, IResource value) - { - if (!value.instance.children.contains(_resource)) - value.instance.children.add(_resource); - } - - - void resource_OnDestroy(sender) - { - emitArgs("resourceDestroyed", [sender]); - } + void resource_OnDestroy(sender) { + emitArgs("resourceDestroyed", [sender]); + } } diff --git a/lib/src/Resource/Template/ArgumentTemplate.dart b/lib/src/Resource/Template/ArgumentTemplate.dart index 4fc6359..ee873c9 100644 --- a/lib/src/Resource/Template/ArgumentTemplate.dart +++ b/lib/src/Resource/Template/ArgumentTemplate.dart @@ -3,32 +3,30 @@ import '../../Data/BinaryList.dart'; import "../../Data/ParseResult.dart"; import './TemplateDataType.dart'; -class ArgumentTemplate -{ - String name; +class ArgumentTemplate { + String name; - TemplateDataType type; + TemplateDataType type; - static ParseResult parse(DC data, int offset) - { - var cs = data[offset++]; - var name = data.getString(offset, cs); - offset += cs; - var tdr = TemplateDataType.parse(data, offset); + static ParseResult parse(DC data, int offset) { + var cs = data[offset++]; + var name = data.getString(offset, cs); + offset += cs; + var tdr = TemplateDataType.parse(data, offset); - return ParseResult(cs + 1 + tdr.size, ArgumentTemplate(name, tdr.value)); - } - - ArgumentTemplate(this.name, this.type); - - DC compose() - { - var name = DC.stringToBytes(this.name); - - return new BinaryList() - .addUint8(name.length) - .addDC(name) - .addDC(type.compose()) - .toDC(); - } + return ParseResult( + cs + 1 + tdr.size, ArgumentTemplate(name, tdr.value)); } + + ArgumentTemplate(this.name, this.type); + + DC compose() { + var name = DC.stringToBytes(this.name); + + return (BinaryList() + ..addUint8(name.length) + ..addDC(name) + ..addDC(type.compose())) + .toDC(); + } +} diff --git a/lib/src/Resource/Template/EventTemplate.dart b/lib/src/Resource/Template/EventTemplate.dart index f36af58..f5fc4fe 100644 --- a/lib/src/Resource/Template/EventTemplate.dart +++ b/lib/src/Resource/Template/EventTemplate.dart @@ -6,7 +6,7 @@ import 'MemberType.dart'; import 'TemplateDataType.dart'; class EventTemplate extends MemberTemplate { - String expansion; + String? expansion; bool listenable; TemplateDataType argumentType; @@ -14,21 +14,21 @@ class EventTemplate extends MemberTemplate { var name = super.compose(); if (expansion != null) { - var exp = DC.stringToBytes(expansion); - return new BinaryList() - .addUint8(listenable ? 0x58 : 0x50) - .addUint8(name.length) - .addDC(name) - .addDC(argumentType.compose()) - .addInt32(exp.length) - .addDC(exp) + var exp = DC.stringToBytes(expansion as String); + return (BinaryList() + ..addUint8(listenable ? 0x58 : 0x50) + ..addUint8(name.length) + ..addDC(name) + ..addDC(argumentType.compose()) + ..addInt32(exp.length) + ..addDC(exp)) .toDC(); } else { - return new BinaryList() - .addUint8(listenable ? 0x48 : 0x40) - .addUint8(name.length) - .addDC(name) - .addDC(argumentType.compose()) + return (BinaryList() + ..addUint8(listenable ? 0x48 : 0x40) + ..addUint8(name.length) + ..addDC(name) + ..addDC(argumentType.compose())) .toDC(); } } diff --git a/lib/src/Resource/Template/FunctionTemplate.dart b/lib/src/Resource/Template/FunctionTemplate.dart index 12938a8..1fb1f91 100644 --- a/lib/src/Resource/Template/FunctionTemplate.dart +++ b/lib/src/Resource/Template/FunctionTemplate.dart @@ -7,8 +7,8 @@ import 'ArgumentTemplate.dart'; import 'TemplateDataType.dart'; class FunctionTemplate extends MemberTemplate { - String expansion; - bool isVoid; + String? expansion; + // bool isVoid; TemplateDataType returnType; List arguments; @@ -18,10 +18,10 @@ class FunctionTemplate extends MemberTemplate { var name = super.compose(); var bl = new BinaryList() - .addUint8(name.length) - .addDC(name) - .addDC(returnType.compose()) - .addUint8(arguments.length); + ..addUint8(name.length) + ..addDC(name) + ..addDC(returnType.compose()) + ..addUint8(arguments.length); for (var i = 0; i < arguments.length; i++) bl.addDC(arguments[i].compose()); @@ -29,9 +29,9 @@ class FunctionTemplate extends MemberTemplate { if (expansion != null) { - var exp = DC.stringToBytes(expansion); - bl.addInt32(exp.length) - .addDC(exp); + var exp = DC.stringToBytes(expansion as String); + bl..addInt32(exp.length) + ..addDC(exp); bl.insertUint8(0, 0x10); } else @@ -41,9 +41,9 @@ class FunctionTemplate extends MemberTemplate { } FunctionTemplate(TypeTemplate template, int index, String name, - this.arguments, this.returnType, String expansion) + this.arguments, this.returnType, this.expansion) : super(template, MemberType.Property, index, name) { - this.isVoid = isVoid; - this.expansion = expansion; + + } } diff --git a/lib/src/Resource/Template/MemberTemplate.dart b/lib/src/Resource/Template/MemberTemplate.dart index 7c8f9b8..ffa33c2 100644 --- a/lib/src/Resource/Template/MemberTemplate.dart +++ b/lib/src/Resource/Template/MemberTemplate.dart @@ -17,12 +17,8 @@ class MemberTemplate TypeTemplate get template => _template; - MemberTemplate(TypeTemplate template, MemberType type, int index, String name) + MemberTemplate(this._template, this._type, this._index, this._name) { - this._template = template; - this._type = type; - this._index = index; - this._name = name; } String get fullname => _template.className + "." + _name; diff --git a/lib/src/Resource/Template/PropertyTemplate.dart b/lib/src/Resource/Template/PropertyTemplate.dart index e39d2b6..d264df0 100644 --- a/lib/src/Resource/Template/PropertyTemplate.dart +++ b/lib/src/Resource/Template/PropertyTemplate.dart @@ -14,63 +14,59 @@ class PropertyTemplate extends MemberTemplate { int storage; - String readExpansion; + String? readExpansion; - String writeExpansion; + String? writeExpansion; DC compose() { var name = super.compose(); var pv = ((permission) << 1) | (storage == StorageMode.Recordable ? 1 : 0); if (writeExpansion != null && readExpansion != null) { - var rexp = DC.stringToBytes(readExpansion); - var wexp = DC.stringToBytes(writeExpansion); - return new BinaryList() - .addUint8(0x38 | pv) - .addUint8(name.length) - .addDC(name) - .addDC(valueType.compose()) - .addInt32(wexp.length) - .addDC(wexp) - .addInt32(rexp.length) - .addDC(rexp) + var rexp = DC.stringToBytes(readExpansion as String); + var wexp = DC.stringToBytes(writeExpansion as String); + return (BinaryList() + ..addUint8(0x38 | pv) + ..addUint8(name.length) + ..addDC(name) + ..addDC(valueType.compose()) + ..addInt32(wexp.length) + ..addDC(wexp) + ..addInt32(rexp.length) + ..addDC(rexp)) .toDC(); } else if (writeExpansion != null) { - var wexp = DC.stringToBytes(writeExpansion); - return new BinaryList() - .addUint8(0x30 | pv) - .addUint8(name.length) - .addDC(name) - .addDC(valueType.compose()) - .addInt32(wexp.length) - .addDC(wexp) + var wexp = DC.stringToBytes(writeExpansion as String); + return (BinaryList() + ..addUint8(0x30 | pv) + ..addUint8(name.length) + ..addDC(name) + ..addDC(valueType.compose()) + ..addInt32(wexp.length) + ..addDC(wexp)) .toDC(); } else if (readExpansion != null) { - var rexp = DC.stringToBytes(readExpansion); - return new BinaryList() - .addUint8(0x28 | pv) - .addUint8(name.length) - .addDC(name) - .addDC(valueType.compose()) - .addInt32(rexp.length) - .addDC(rexp) + var rexp = DC.stringToBytes(readExpansion as String); + return (BinaryList() + ..addUint8(0x28 | pv) + ..addUint8(name.length) + ..addDC(name) + ..addDC(valueType.compose()) + ..addInt32(rexp.length) + ..addDC(rexp)) .toDC(); } else - return new BinaryList() - .addUint8(0x20 | pv) - .addUint8(name.length) - .addDC(name) - .addDC(valueType.compose()) + return (BinaryList() + ..addUint8(0x20 | pv) + ..addUint8(name.length) + ..addDC(name) + ..addDC(valueType.compose())) .toDC(); } PropertyTemplate(TypeTemplate template, int index, String name, - TemplateDataType valueType, String read, String write, int storage) + this.valueType, this.readExpansion, this.writeExpansion, this.storage) : super(template, MemberType.Property, index, name) { //this.Recordable = recordable; - this.storage = storage; - this.readExpansion = read; - this.writeExpansion = write; - this.valueType = valueType; } } diff --git a/lib/src/Resource/Template/TemplateDataType.dart b/lib/src/Resource/Template/TemplateDataType.dart index 5186320..5054657 100644 --- a/lib/src/Resource/Template/TemplateDataType.dart +++ b/lib/src/Resource/Template/TemplateDataType.dart @@ -16,11 +16,12 @@ import '../../Resource/Warehouse.dart'; import 'TemplateType.dart'; class TemplateDataType { - int type; - TypeTemplate get typeTemplate => - typeGuid == null ? null : Warehouse.getTemplateByClassId(typeGuid); + late int type; + TypeTemplate? get typeTemplate => typeGuid == null + ? null + : Warehouse.getTemplateByClassId(typeGuid as Guid); - Guid typeGuid; + Guid? typeGuid; // @TODO: implement fromType TemplateDataType.fromType(type, bool isArray) { @@ -98,7 +99,10 @@ class TemplateDataType { type == DataType.ResourceArray || type == DataType.Record || type == DataType.RecordArray) { - return BinaryList().addUint8(type).addDC(typeGuid.value).toDC(); + return (BinaryList() + ..addUint8(type) + ..addDC((typeGuid as Guid).value)) + .toDC(); } else return DC.fromList([type]); } diff --git a/lib/src/Resource/Template/TemplateDescriber.dart b/lib/src/Resource/Template/TemplateDescriber.dart index f55917d..a4625b7 100644 --- a/lib/src/Resource/Template/TemplateDescriber.dart +++ b/lib/src/Resource/Template/TemplateDescriber.dart @@ -1,9 +1,9 @@ import '../../Data/DataType.dart'; class TemplateDescriber { - final List properties; - final List events; - final List functions; + final List? properties; + final List? events; + final List? functions; final String nameSpace; final int version; @@ -47,8 +47,8 @@ class Prop { final String name; final Type type; final bool isArray; - final String readAnnotation; - final String writeAnnotation; + final String? readAnnotation; + final String? writeAnnotation; Prop(this.name, this.type, this.isArray, [this.readAnnotation = null, this.writeAnnotation = null]); } @@ -58,7 +58,7 @@ class Evt { final bool listenable; final Type type; final bool isArray; - final String annotation; + final String? annotation; Evt(this.name, this.type, this.isArray, [this.listenable = false, this.annotation]); @@ -69,7 +69,7 @@ class Func { final Type returnType; final List argsType; final bool isArray; - final String annotation; + final String? annotation; 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 0fe9afe..b6e49d5 100644 --- a/lib/src/Resource/Template/TypeTemplate.dart +++ b/lib/src/Resource/Template/TypeTemplate.dart @@ -22,26 +22,26 @@ import 'TemplateDataType.dart'; import 'TemplateType.dart'; class TypeTemplate { - Guid _classId; - String _className; + late Guid _classId; + late String _className; List _members = []; List _functions = []; List _events = []; List _properties = []; - int _version; + late int _version; //bool isReady; - TemplateType _templateType; + late TemplateType _templateType; - DC _content; + late DC _content; DC get content => _content; TemplateType get type => _templateType; - Type _definedType; + Type? _definedType; - Type get definedType => _definedType; + Type? get definedType => _definedType; /* MemberTemplate getMemberTemplate(MemberInfo member) { @@ -59,32 +59,32 @@ class TypeTemplate { //@TODO: implement static List getDependencies(TypeTemplate template) => []; - EventTemplate getEventTemplateByName(String eventName) { + EventTemplate? getEventTemplateByName(String eventName) { for (var i in _events) if (i.name == eventName) return i; return null; } - EventTemplate getEventTemplateByIndex(int index) { + EventTemplate? getEventTemplateByIndex(int index) { for (var i in _events) if (i.index == index) return i; return null; } - FunctionTemplate getFunctionTemplateByName(String functionName) { + FunctionTemplate? getFunctionTemplateByName(String functionName) { for (var i in _functions) if (i.name == functionName) return i; return null; } - FunctionTemplate getFunctionTemplateByIndex(int index) { + FunctionTemplate? getFunctionTemplateByIndex(int index) { for (var i in _functions) if (i.index == index) return i; return null; } - PropertyTemplate getPropertyTemplateByIndex(int index) { + PropertyTemplate? getPropertyTemplateByIndex(int index) { for (var i in _properties) if (i.index == index) return i; return null; } - PropertyTemplate getPropertyTemplateByName(String propertyName) { + PropertyTemplate? getPropertyTemplateByName(String propertyName) { for (var i in _properties) if (i.name == propertyName) return i; return null; } @@ -143,9 +143,11 @@ class TypeTemplate { if (addToWarehouse) Warehouse.putTemplate(this); // _templates.add(template.classId, template); - if (describer.properties != null) - for (var i = 0; i < describer.properties.length; i++) { - var pi = describer.properties[i]; + if (describer.properties != null) { + var props = describer.properties as List; + + for (var i = 0; i < props.length; i++) { + var pi = props[i]; var pt = PropertyTemplate( this, i, @@ -156,10 +158,13 @@ class TypeTemplate { 0); properties.add(pt); } + } - if (describer.functions != null) - for (var i = 0; i < describer.functions.length; i++) { - var fi = describer.functions[i]; + if (describer.functions != null) { + var funcs = describer.functions as List; + + for (var i = 0; i < funcs.length; i++) { + var fi = funcs[i]; List args = fi.argsType .map((arg) => ArgumentTemplate( @@ -176,10 +181,12 @@ class TypeTemplate { functions.add(ft); } + } - if (describer.events != null) - for (var i = 0; i < describer.events.length; i++) { - var ei = describer.events[i]; + if (describer.events != null) { + var evts = describer.events as List; + for (var i = 0; i < evts.length; i++) { + var ei = evts[i]; var et = new EventTemplate( this, @@ -191,6 +198,7 @@ class TypeTemplate { events.add(et); } + } // append signals events.forEach(_members.add); @@ -200,14 +208,13 @@ class TypeTemplate { properties.forEach(_members.add); // bake it binarily - var b = new BinaryList(); - b - .addUint8(_templateType.index) - .addGuid(classId) - .addUint8(className.length) - .addString(className) - .addInt32(_version) - .addUint16(_members.length); + var b = BinaryList() + ..addUint8(_templateType.index) + ..addGuid(classId) + ..addUint8(className.length) + ..addString(className) + ..addInt32(_version) + ..addUint16(_members.length); functions.forEach((ft) => b.addDC(ft.compose())); properties.forEach((pt) => b.addDC(pt.compose())); @@ -429,7 +436,7 @@ class TypeTemplate { */ - TypeTemplate.parse(DC data, [int offset = 0, int contentLength]) { + TypeTemplate.parse(DC data, [int offset = 0, int? contentLength]) { // cool Dart feature contentLength ??= data.length; @@ -464,7 +471,7 @@ class TypeTemplate { if (type == 0) // function { - String expansion = null; + String? expansion = null; var hasExpansion = ((data[offset++] & 0x10) == 0x10); var name = data.getString(offset + 1, data[offset]); @@ -497,7 +504,7 @@ class TypeTemplate { _functions.add(ft); } else if (type == 1) // property { - String readExpansion = null, writeExpansion = null; + String? readExpansion = null, writeExpansion = null; var hasReadExpansion = ((data[offset] & 0x8) == 0x8); var hasWriteExpansion = ((data[offset] & 0x10) == 0x10); @@ -539,7 +546,7 @@ class TypeTemplate { _properties.add(pt); } else if (type == 2) // Event { - String expansion = null; + String? expansion = null; var hasExpansion = ((data[offset] & 0x10) == 0x10); var listenable = ((data[offset++] & 0x8) == 0x8); diff --git a/lib/src/Resource/Warehouse.dart b/lib/src/Resource/Warehouse.dart index 0ea9951..aad1540 100644 --- a/lib/src/Resource/Warehouse.dart +++ b/lib/src/Resource/Warehouse.dart @@ -22,6 +22,10 @@ SOFTWARE. */ +import '../Core/AsyncException.dart'; +import '../Core/ErrorType.dart'; +import '../Core/ExceptionCode.dart'; + import '../Data/AutoList.dart'; import 'FactoryEntry.dart'; import 'Template/TemplateType.dart'; @@ -41,8 +45,7 @@ import '../Net/IIP/DistributedConnection.dart'; // Centeral Resource Issuer class Warehouse { - static AutoList _stores = - new AutoList(null); + static AutoList _stores = AutoList(); static Map _resources = new Map(); static int resourceCounter = 0; @@ -74,8 +77,8 @@ class Warehouse { /// /// Store instance name /// - static IStore getStore(String name) { - for (var s in _stores) if (s.instance.name == name) return s; + static IStore? getStore(String name) { + for (var s in _stores) if (s.instance?.name == name) return s; return null; } @@ -84,11 +87,11 @@ class Warehouse { /// /// Instance Id /// - static AsyncReply getById(int id) { + static AsyncReply getById(int id) { if (_resources.containsKey(id)) - return new AsyncReply.ready(_resources[id]); + return new AsyncReply.ready(_resources[id]); else - return new AsyncReply.ready(null); + return new AsyncReply.ready(null); } /// @@ -106,20 +109,21 @@ class Warehouse { var rt = new AsyncReply(); bag.then((x) { for (var b in x) - if (!b) { + if (b == null || b == false) { rt.trigger(false); return; } var rBag = new AsyncBag(); for (var rk in _resources.keys) - rBag.add(_resources[rk].trigger(ResourceTrigger.SystemInitialized)); + rBag.add((_resources[rk] as IResource) + .trigger(ResourceTrigger.SystemInitialized)); rBag.seal(); rBag.then((y) { for (var b in y) - if (!b) { + if (b == null || b == false) { rt.trigger(false); return; } @@ -158,7 +162,7 @@ class Warehouse { var rt = new AsyncReply(); bag.then((x) { for (var b in x) - if (!b) { + if (b == null || b == false) { rt.trigger(false); return; } @@ -178,19 +182,21 @@ class Warehouse { for (var child in resources) rt.add(child); else for (var child in resources) - if (child.instance.name == path[index]) rt.add(child); + if (child.instance?.name == path[index]) rt.add(child); } else for (var child in resources) - if (child.instance.name == path[index]) - rt.addAll(qureyIn(path, index + 1, child.instance.children)); + if (child.instance?.name == path[index]) + rt.addAll(qureyIn(path, index + 1, + child.instance?.children as AutoList)); return rt; } - static AsyncReply> query(String path) { + static AsyncReply?> query(String? path) { if (path == null || path == "") { - var roots = _stores.where((s) => s.instance.parents.length == 0).toList(); - return new AsyncReply>.ready(roots); + var roots = + _stores.where((s) => s.instance?.parents.length == 0).toList(); + return new AsyncReply?>.ready(roots); } else { var rt = new AsyncReply>(); get(path).then((x) { @@ -215,40 +221,46 @@ class Warehouse { /// /// /// Resource instance. - static AsyncReply get(String path, + static AsyncReply get(String path, [attributes = null, - IResource parent = null, - IPermissionsManager manager = null]) { - var rt = AsyncReply(); + IResource? parent = null, + IPermissionsManager? manager = null]) { + var rt = AsyncReply(); // Should we create a new store ? if (_urlRegex.hasMatch(path)) { var url = _urlRegex.allMatches(path).first; if (protocols.containsKey(url[1])) { - var handler = protocols[url[1]]; + var handler = + protocols[url[1]] as AsyncReply Function(String, dynamic); var getFromStore = () { - handler(url[2], attributes).then((store) { - if (url[3].length > 0 && url[3] != "") - store.get(url[3]).then((r) { - rt.trigger(r); - }).error((e) => rt.triggerError(e)); - else - rt.trigger(store as T); - }).error((e) { - rt.triggerError(e); - //Warehouse.remove(store); - }); + handler(url[2] as String, attributes) + ..then((store) { + if ((url[3] as String).length > 0 && url[3] != "") + store.get(url[3] as String) + ..then((r) { + rt.trigger(r as T); + }) + ..error((e) => rt.triggerError(e)); + else + rt.trigger(store as T); + }) + ..error((e) { + rt.triggerError(e); + //Warehouse.remove(store); + }); }; if (!_warehouseIsOpen) - open().then((v) { - if (v) - getFromStore(); - else - rt.trigger(null); - }); + open() + ..then((v) { + if (v) + getFromStore(); + else + rt.trigger(null); + }); else getFromStore(); @@ -258,7 +270,7 @@ class Warehouse { query(path).then((rs) { if (rs != null && rs.length > 0) - rt.trigger(rs[0]); + rt.trigger(rs[0] as T); else rt.trigger(null); }); @@ -342,14 +354,14 @@ class Warehouse { /// Resource name. /// IStore that manages the resource. Can be null if the resource is a store. /// Parent resource. if not presented the store becomes the parent for the resource. - static AsyncReply put(String name, T resource, - [IStore store = null, - IResource parent = null, - TypeTemplate customTemplate = null, + static AsyncReply put(String name, T resource, + [IStore? store = null, + IResource? parent = null, + TypeTemplate? customTemplate = null, int age = 0, - IPermissionsManager manager = null, + IPermissionsManager? manager = null, attributes = null]) { - var rt = AsyncReply(); + var rt = AsyncReply(); if (resource.instance != null) { rt.triggerError(Exception("Resource has a store.")); @@ -415,19 +427,21 @@ class Warehouse { resourceCounter++, name, resource, store, customTemplate, age); if (attributes != null) - resource.instance.setAttributes(Structure.fromMap(attributes)); + resource.instance?.setAttributes(Structure.fromMap(attributes)); - if (manager != null) resource.instance.managers.add(manager); + if (manager != null) resource.instance?.managers.add(manager); if (store == parent) parent = null; if (parent == null) { - if (!(resource is IStore)) store.instance.children.add(resource); + if (!(resource is IStore)) store?.instance?.children.add(resource); } else - parent.instance.children.add(resource); + parent.instance?.children.add(resource); var initResource = () { - _resources[resource.instance.id] = resource; + if (resource.instance == null) return; + + _resources[(resource.instance as Instance).id] = resource; if (_warehouseIsOpen) { resource.trigger(ResourceTrigger.Initialize).then((value) { @@ -451,7 +465,7 @@ class Warehouse { _stores.add(resource); initResource(); } else { - store.put(resource).then((value) { + store?.put(resource).then((value) { if (value) initResource(); else @@ -468,20 +482,23 @@ class Warehouse { } static T createInstance(Type T) { - return _factory[T].instanceCreator.call(); + return _factory[T]?.instanceCreator.call(); } static List createArray(Type T) { - return _factory[T].arrayCreator.call(); + return _factory[T]?.arrayCreator.call(); } static AsyncReply newResource(String name, - [IStore store = null, - IResource parent = null, - IPermissionsManager manager = null, + [IStore? store = null, + IResource? parent = null, + IPermissionsManager? manager = null, attributes = null, properties = null]) { - var resource = _factory[T].instanceCreator.call(); + if (_factory[T] == null) + throw Exception("No Instance Creator was found for type ${T}"); + + var resource = _factory[T]?.instanceCreator.call(); if (properties != null) { dynamic d = resource; @@ -494,12 +511,16 @@ class Warehouse { var rt = AsyncReply(); put(name, resource, store, parent, null, 0, manager, attributes) - .then((value) { - if (value != null) - rt.trigger(resource); - else - rt.trigger(null); - }).error((ex) => rt.triggerError(ex)); + ..then((value) { + if (value != null) + rt.trigger(resource); + else + rt.triggerError(AsyncException( + ErrorType.Management, + ExceptionCode.GeneralFailure.index, + "Can't put the resource")); // .trigger(null); + }) + ..error((ex) => rt.triggerError(ex)); return rt; @@ -516,7 +537,7 @@ class Warehouse { /// /// Resource template. static void putTemplate(TypeTemplate template) { - _templates[template.type][template.classId] = template; + _templates[template.type]?[template.classId] = template; } /// @@ -541,22 +562,22 @@ class Warehouse { /// /// Class Id. /// Resource template. - static TypeTemplate getTemplateByClassId(Guid classId, + static TypeTemplate? getTemplateByClassId(Guid classId, [TemplateType templateType = TemplateType.Unspecified]) { if (templateType == TemplateType.Unspecified) { // look in resources - var template = _templates[TemplateType.Resource][classId]; + var template = _templates[TemplateType.Resource]?[classId]; if (template != null) return template; // look in records - template = _templates[TemplateType.Record][classId]; + template = _templates[TemplateType.Record]?[classId]; if (template != null) return template; // look in wrappers - template = _templates[TemplateType.Wrapper][classId]; + template = _templates[TemplateType.Wrapper]?[classId]; return template; } else { - return _templates[templateType][classId]; + return _templates[templateType]?[classId]; } } @@ -565,29 +586,29 @@ class Warehouse { /// /// Class name. /// Resource template. - static TypeTemplate getTemplateByClassName(String className, + static TypeTemplate? getTemplateByClassName(String className, [TemplateType templateType = TemplateType.Unspecified]) { if (templateType == TemplateType.Unspecified) { // look in resources var template = _templates[TemplateType.Resource] - .values + ?.values .firstWhere((x) => x.className == className); if (template != null) return template; // look in records template = _templates[TemplateType.Record] - .values + ?.values .firstWhere((x) => x.className == className); if (template != null) return template; // look in wrappers template = _templates[TemplateType.Wrapper] - .values + ?.values .firstWhere((x) => x.className == className); return template; } else { return _templates[templateType] - .values + ?.values .firstWhere((x) => x.className == className); } } @@ -595,8 +616,8 @@ class Warehouse { static bool remove(IResource resource) { if (resource.instance == null) return false; - if (_resources.containsKey(resource.instance.id)) - _resources.remove(resource.instance.id); + if (_resources.containsKey(resource.instance?.id)) + _resources.remove(resource.instance?.id); else return false; @@ -605,14 +626,14 @@ class Warehouse { // remove all objects associated with the store var toBeRemoved = - _resources.values.where((x) => x.instance.store == resource); + _resources.values.where((x) => x.instance?.store == resource); for (var o in toBeRemoved) remove(o); // StoreDisconnected?.Invoke(resource as IStore); } - if (resource.instance.store != null) - resource.instance.store.remove(resource); + if (resource.instance?.store != null) + resource.instance?.store?.remove(resource); resource.destroy(); diff --git a/lib/src/Security/Authority/Authentication.dart b/lib/src/Security/Authority/Authentication.dart index 85c90b0..0ca2b59 100644 --- a/lib/src/Security/Authority/Authentication.dart +++ b/lib/src/Security/Authority/Authentication.dart @@ -27,27 +27,20 @@ import 'AuthenticationMethod.dart'; import 'AuthenticationType.dart'; import 'Source.dart'; -class Authentication -{ - - int tokenIndex; - AuthenticationMethod method; +class Authentication { + int? tokenIndex; + AuthenticationMethod method = AuthenticationMethod.None; - String username; - //Certificate certificate; - String domain; + String? username; + //Certificate certificate; + String? domain; - String get fullName => username + "@" + domain; - int state; + String get fullName => (username ?? '') + '@' + (domain ?? ''); + int state = 0; - Source source = new Source(); + Source? source; - - final AuthenticationType type; + final AuthenticationType type; - Authentication(this.type) - { - - } + Authentication(this.type) {} } - diff --git a/lib/src/Security/Authority/Session.dart b/lib/src/Security/Authority/Session.dart index 52aa0a4..f1aa183 100644 --- a/lib/src/Security/Authority/Session.dart +++ b/lib/src/Security/Authority/Session.dart @@ -31,7 +31,7 @@ class Session Authentication get remoteAuthentication => _remoteAuth; // public Source Source { get; } - DC id; + DC? id; //DateTime get creation => _creation; @@ -45,10 +45,8 @@ class Session Authentication _localAuth, _remoteAuth; - Session(Authentication localAuthentication, Authentication remoteAuthentication) + Session(this._localAuth, this._remoteAuth) { - this._localAuth = localAuthentication; - this._remoteAuth = remoteAuthentication; } } diff --git a/lib/src/Security/Authority/Source.dart b/lib/src/Security/Authority/Source.dart index 53e0871..ce20e05 100644 --- a/lib/src/Security/Authority/Source.dart +++ b/lib/src/Security/Authority/Source.dart @@ -25,22 +25,12 @@ SOFTWARE. import '../../Data/KeyList.dart'; import 'SourceAttributeType.dart'; -class Source -{ +class Source { + //string id; + String id; - //string id; - String id; - - KeyList attributes; - - Source.from(this.id, this.attributes) - { - - } - - Source() - { - attributes = new KeyList(); - } + KeyList attributes = + new KeyList(); + Source.from(this.id, this.attributes) {} } diff --git a/lib/src/Security/Integrity/SHA256.dart b/lib/src/Security/Integrity/SHA256.dart index e596ff1..6abbe13 100644 --- a/lib/src/Security/Integrity/SHA256.dart +++ b/lib/src/Security/Integrity/SHA256.dart @@ -2,23 +2,18 @@ import '../../Data/DC.dart'; import '../../Data/BinaryList.dart'; import 'dart:typed_data'; -class SHA256 -{ +class SHA256 { + static int RROT(int n, int d) { + return ZSHIFT(n, d) | (n << (32 - d)); + } - static int RROT(int n, int d) - { - return ZSHIFT(n, d) | (n << (32 - d)); - } + // Zero-fill right shift + static int ZSHIFT(int n, int d) { + return (n & 0xFFFFFFFF) >> d; + } - // Zero-fill right shift - static int ZSHIFT(int n, int d) - { - return (n & 0xFFFFFFFF) >> d; - } - - static DC compute(DC msg) - { - /* + static DC compute(DC msg) { + /* Note 1: All variables are 32 bit unsigned integers and addition is calculated modulo 2^32 Note 2: For each round, there is one round constant k[i] and one entry in the message schedule array w[i], 0 ≤ i ≤ 63 Note 3: The compression function uses 8 working variables, a through h @@ -27,134 +22,190 @@ class SHA256 the first word of the input message "abc" after padding is 0x61626380 */ - // Initialize hash values: - // (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // Initialize hash values: + // (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): - var hash = new Uint32List.fromList([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, - 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]); + var hash = new Uint32List.fromList([ + 0x6a09e667, + 0xbb67ae85, + 0x3c6ef372, + 0xa54ff53a, + 0x510e527f, + 0x9b05688c, + 0x1f83d9ab, + 0x5be0cd19 + ]); - // Initialize array of round constants: - // (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311): - var k = new Uint32List.fromList([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]); + // Initialize array of round constants: + // (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311): + var k = new Uint32List.fromList([ + 0x428a2f98, + 0x71374491, + 0xb5c0fbcf, + 0xe9b5dba5, + 0x3956c25b, + 0x59f111f1, + 0x923f82a4, + 0xab1c5ed5, + 0xd807aa98, + 0x12835b01, + 0x243185be, + 0x550c7dc3, + 0x72be5d74, + 0x80deb1fe, + 0x9bdc06a7, + 0xc19bf174, + 0xe49b69c1, + 0xefbe4786, + 0x0fc19dc6, + 0x240ca1cc, + 0x2de92c6f, + 0x4a7484aa, + 0x5cb0a9dc, + 0x76f988da, + 0x983e5152, + 0xa831c66d, + 0xb00327c8, + 0xbf597fc7, + 0xc6e00bf3, + 0xd5a79147, + 0x06ca6351, + 0x14292967, + 0x27b70a85, + 0x2e1b2138, + 0x4d2c6dfc, + 0x53380d13, + 0x650a7354, + 0x766a0abb, + 0x81c2c92e, + 0x92722c85, + 0xa2bfe8a1, + 0xa81a664b, + 0xc24b8b70, + 0xc76c51a3, + 0xd192e819, + 0xd6990624, + 0xf40e3585, + 0x106aa070, + 0x19a4c116, + 0x1e376c08, + 0x2748774c, + 0x34b0bcb5, + 0x391c0cb3, + 0x4ed8aa4a, + 0x5b9cca4f, + 0x682e6ff3, + 0x748f82ee, + 0x78a5636f, + 0x84c87814, + 0x8cc70208, + 0x90befffa, + 0xa4506ceb, + 0xbef9a3f7, + 0xc67178f2 + ]); + // Pre-processing: + // begin with the original message of length L bits + int L = msg.length * 8; + // append a single '1' bit + // append K '0' bits, where K is the minimum number >= 0 such that L + 1 + K + 64 is a multiple of 512 - // Pre-processing: - // begin with the original message of length L bits - int L = msg.length * 8; + var K = 512 - ((L + 1 + 64) % 512); - // append a single '1' bit - // append K '0' bits, where K is the minimum number >= 0 such that L + 1 + K + 64 is a multiple of 512 + if (K == 512) K = 0; - var K = 512 - ((L + 1 + 64) % 512); + var paddingLength = (K + 1) ~/ 8; + var paddingBytes = new DC(paddingLength); + paddingBytes[0] = 0x80; - if (K == 512) - K = 0; + var data = (BinaryList() + ..addDC(msg) + ..addDC(paddingBytes) + ..addUint64(L)) + .toDC(); - var paddingLength = (K + 1) ~/ 8; - var paddingBytes = new DC(paddingLength); - paddingBytes[0] = 0x80; + // append L as a 64-bit big-endian integer, making the total post-processed length a multiple of 512 bits - var data = new BinaryList().addDC(msg).addDC(paddingBytes).addUint64(L).toDC(); + // Process the message in successive 512-bit chunks: + // break message into 512-bit chunks + // for each chunk + for (var chunk = 0; chunk < data.length; chunk += 64) { + // create a 64-entry message schedule array w[0..63] of 32-bit words + // (The initial values in w[0..63] don't matter, so many implementations zero them here) + // copy chunk into first 16 words w[0..15] of the message schedule array + var w = new Uint64List(64); // uint[64]; + for (var i = 0; i < 16; i++) w[i] = data.getUint32(chunk + (i * 4)); - // append L as a 64-bit big-endian integer, making the total post-processed length a multiple of 512 bits + //for(var i = 16; i < 64; i++) + // w[i] = 0; - // Process the message in successive 512-bit chunks: - // break message into 512-bit chunks - // for each chunk + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array: + // for i from 16 to 63 + // s0 := (w[i-15] rightrotate 7) xor (w[i-15] rightrotate 18) xor (w[i-15] rightshift 3) + // s1 := (w[i-2] rightrotate 17) xor (w[i-2] rightrotate 19) xor (w[i-2] rightshift 10) + // w[i] := w[i-16] + s0 + w[i-7] + s1 - for (var chunk = 0; chunk < data.length; chunk += 64) - { - // create a 64-entry message schedule array w[0..63] of 32-bit words - // (The initial values in w[0..63] don't matter, so many implementations zero them here) - // copy chunk into first 16 words w[0..15] of the message schedule array + for (var i = 16; i < 64; i++) { + var s0 = SHA256.RROT(w[i - 15], 7) ^ + SHA256.RROT(w[i - 15], 18) ^ + ZSHIFT(w[i - 15], 3); + var s1 = SHA256.RROT(w[i - 2], 17) ^ + SHA256.RROT(w[i - 2], 19) ^ + ZSHIFT(w[i - 2], 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } - var w = new Uint64List(64);// uint[64]; - for (var i = 0; i < 16; i++) - w[i] = data.getUint32(chunk + (i * 4)); + // Initialize working variables to current hash value: + var a = hash[0]; + var b = hash[1]; + var c = hash[2]; + var d = hash[3]; + var e = hash[4]; + var f = hash[5]; + var g = hash[6]; + var h = hash[7]; - //for(var i = 16; i < 64; i++) - // w[i] = 0; + // Compression function main loop: + for (var i = 0; i < 64; i++) { + var S1 = SHA256.RROT(e, 6) ^ SHA256.RROT(e, 11) ^ SHA256.RROT(e, 25); + var ch = (e & f) ^ ((~e) & g); + var temp1 = h + S1 + ch + k[i] + w[i]; + var S0 = SHA256.RROT(a, 2) ^ SHA256.RROT(a, 13) ^ SHA256.RROT(a, 22); + var maj = (a & b) ^ (a & c) ^ (b & c); + int temp2 = S0 + maj; - // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array: - // for i from 16 to 63 - // s0 := (w[i-15] rightrotate 7) xor (w[i-15] rightrotate 18) xor (w[i-15] rightshift 3) - // s1 := (w[i-2] rightrotate 17) xor (w[i-2] rightrotate 19) xor (w[i-2] rightshift 10) - // w[i] := w[i-16] + s0 + w[i-7] + s1 + h = g; + g = f; + f = e; + e = ZSHIFT(d + temp1, 0); + d = c; + c = b; + b = a; + a = ZSHIFT(temp1 + temp2, 0); + } - for (var i = 16; i < 64; i++) - { - var s0 = SHA256.RROT(w[i - 15], 7) ^ SHA256.RROT(w[i - 15], 18) ^ ZSHIFT(w[i - 15], 3); - var s1 = SHA256.RROT(w[i - 2], 17) ^ SHA256.RROT(w[i - 2], 19) ^ ZSHIFT(w[i - 2], 10); - w[i] = w[i - 16] + s0 + w[i - 7] + s1; - } + // Add the compressed chunk to the current hash value: - // Initialize working variables to current hash value: - var a = hash[0]; - var b = hash[1]; - var c = hash[2]; - var d = hash[3]; - var e = hash[4]; - var f = hash[5]; - var g = hash[6]; - var h = hash[7]; - - - // Compression function main loop: - for (var i = 0; i < 64; i++) - { - var S1 = SHA256.RROT(e, 6) ^ SHA256.RROT(e, 11) ^ SHA256.RROT(e, 25); - var ch = (e & f) ^ ((~e) & g); - var temp1 = h + S1 + ch + k[i] + w[i]; - var S0 = SHA256.RROT(a, 2) ^ SHA256.RROT(a, 13) ^ SHA256.RROT(a, 22); - var maj = (a & b) ^ (a & c) ^ (b & c); - int temp2 = S0 + maj; - - h = g; - g = f; - f = e; - e = ZSHIFT(d + temp1, 0); - d = c; - c = b; - b = a; - a = ZSHIFT(temp1 + temp2, 0); - } - - // Add the compressed chunk to the current hash value: - - hash[0] = ZSHIFT(hash[0] + a, 0); - hash[1] = ZSHIFT(hash[1] + b , 0); - hash[2] = ZSHIFT(hash[2] + c , 0); - hash[3] = ZSHIFT(hash[3] + d , 0); - hash[4] = ZSHIFT(hash[4] + e , 0); - hash[5] = ZSHIFT(hash[5] + f , 0); - hash[6] = ZSHIFT(hash[6] + g , 0); - hash[7] = ZSHIFT(hash[7] + h, 0); - - - } - - - - - // Produce the final hash value (big-endian): - //digest := hash := h0 append h1 append h2 append h3 append h4 append h5 append h6 append h7 - - var results = new BinaryList(); - for (var i = 0; i < 8; i++) - results.addUint32(hash[i]); - - - return results.toDC(); + hash[0] = ZSHIFT(hash[0] + a, 0); + hash[1] = ZSHIFT(hash[1] + b, 0); + hash[2] = ZSHIFT(hash[2] + c, 0); + hash[3] = ZSHIFT(hash[3] + d, 0); + hash[4] = ZSHIFT(hash[4] + e, 0); + hash[5] = ZSHIFT(hash[5] + f, 0); + hash[6] = ZSHIFT(hash[6] + g, 0); + hash[7] = ZSHIFT(hash[7] + h, 0); } + + // Produce the final hash value (big-endian): + //digest := hash := h0 append h1 append h2 append h3 append h4 append h5 append h6 append h7 + + var results = new BinaryList(); + for (var i = 0; i < 8; i++) results.addUint32(hash[i]); + + return results.toDC(); + } } diff --git a/pubspec.lock b/pubspec.lock index f07daae..bc60ef9 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -7,28 +7,28 @@ packages: name: _fe_analyzer_shared url: "https://pub.dartlang.org" source: hosted - version: "22.0.0" + version: "23.0.0" analyzer: dependency: transitive description: name: analyzer url: "https://pub.dartlang.org" source: hosted - version: "1.7.1" + version: "2.0.0" args: dependency: "direct main" description: name: args url: "https://pub.dartlang.org" source: hosted - version: "1.6.0" + version: "2.2.0" async: dependency: transitive description: name: async url: "https://pub.dartlang.org" source: hosted - version: "2.7.0" + version: "2.8.1" boolean_selector: dependency: transitive description: @@ -42,7 +42,7 @@ packages: name: build url: "https://pub.dartlang.org" source: hosted - version: "2.0.2" + version: "2.0.3" charcode: dependency: transitive description: @@ -63,7 +63,7 @@ packages: name: cli_util url: "https://pub.dartlang.org" source: hosted - version: "0.3.0" + version: "0.3.3" collection: dependency: transitive description: @@ -77,14 +77,14 @@ packages: name: convert url: "https://pub.dartlang.org" source: hosted - version: "3.0.0" + version: "3.0.1" coverage: dependency: transitive description: name: coverage url: "https://pub.dartlang.org" source: hosted - version: "0.15.2" + version: "1.0.3" crypto: dependency: transitive description: @@ -98,7 +98,7 @@ packages: name: dart_style url: "https://pub.dartlang.org" source: hosted - version: "2.0.1" + version: "2.0.3" file: dependency: transitive description: @@ -106,6 +106,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "6.1.2" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" glob: dependency: transitive description: @@ -119,21 +126,21 @@ packages: name: http_multi_server url: "https://pub.dartlang.org" source: hosted - version: "2.2.0" + version: "3.0.1" http_parser: dependency: transitive description: name: http_parser url: "https://pub.dartlang.org" source: hosted - version: "3.1.3" + version: "4.0.0" io: dependency: transitive description: name: io url: "https://pub.dartlang.org" source: hosted - version: "0.3.3" + version: "1.0.3" js: dependency: transitive description: @@ -147,7 +154,7 @@ packages: name: json_annotation url: "https://pub.dartlang.org" source: hosted - version: "4.0.1" + version: "4.1.0" logging: dependency: transitive description: @@ -168,21 +175,21 @@ packages: name: meta url: "https://pub.dartlang.org" source: hosted - version: "1.3.0" + version: "1.7.0" mime: dependency: transitive description: name: mime url: "https://pub.dartlang.org" source: hosted - version: "0.9.6+3" + version: "1.0.0" node_preamble: dependency: transitive description: name: node_preamble url: "https://pub.dartlang.org" source: hosted - version: "1.4.8" + version: "2.0.1" package_config: dependency: transitive description: @@ -231,35 +238,35 @@ packages: name: shelf url: "https://pub.dartlang.org" source: hosted - version: "0.7.5" + version: "1.2.0" shelf_packages_handler: dependency: transitive description: name: shelf_packages_handler url: "https://pub.dartlang.org" source: hosted - version: "2.0.0" + version: "3.0.0" shelf_static: dependency: transitive description: name: shelf_static url: "https://pub.dartlang.org" source: hosted - version: "0.2.9+2" + version: "1.1.0" shelf_web_socket: dependency: transitive description: name: shelf_web_socket url: "https://pub.dartlang.org" source: hosted - version: "0.2.3" + version: "1.0.1" source_gen: dependency: "direct main" description: name: source_gen url: "https://pub.dartlang.org" source: hosted - version: "1.0.2" + version: "1.0.5" source_map_stack_trace: dependency: transitive description: @@ -315,21 +322,21 @@ packages: name: test url: "https://pub.dartlang.org" source: hosted - version: "1.16.5" + version: "1.17.10" test_api: dependency: transitive description: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.2.19" + version: "0.4.2" test_core: dependency: transitive description: name: test_core url: "https://pub.dartlang.org" source: hosted - version: "0.3.15" + version: "0.4.0" typed_data: dependency: transitive description: @@ -343,7 +350,7 @@ packages: name: vm_service url: "https://pub.dartlang.org" source: hosted - version: "4.0.0" + version: "7.1.1" watcher: dependency: transitive description: @@ -357,7 +364,7 @@ packages: name: web_socket_channel url: "https://pub.dartlang.org" source: hosted - version: "1.2.0" + version: "2.1.0" webkit_inspection_protocol: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 5578a79..c50cde8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,20 +1,20 @@ name: esiur description: Distributed Object Framework. -version: 1.4.0 +version: 1.4.1 #author: Ahmed Zamil homepage: https://github.com/esiur/esiur-dart environment: - sdk: ">=2.1.0 <3.0.0" + sdk: ">=2.12.0 <3.0.0" dependencies: - source_gen: ^1.0.2 + source_gen: args: # pubspec_parse: dev_dependencies: - test: ^1.14.2 + test: # For information on the generic Dart part of this file, see the # following page: https://www.dartlang.org/tools/pub/pubspec diff --git a/test/main.dart b/test/main.dart index f17bd6a..87e77eb 100644 --- a/test/main.dart +++ b/test/main.dart @@ -3,38 +3,38 @@ import 'TestResource.dart'; main() async { try { - + } catch (ex) { print("Error occured"); print(ex); } } -// describe object -desc(dynamic x) { - if (x is List) { - for (var i = 0; i < x.length; i++) desc(x[i]); - } else if (x is DistributedResource) { - var y = x.instance.template; - print("Fucntions = ${y.functions.length}\n"); - for (var i = 0; i < y.functions.length; i++) { - print("Function ${y.functions[i].name} ${y.functions[i].expansion}"); - } - print("------------------------------\n"); - print("Events = ${y.events.length}\n"); - for (var i = 0; i < y.events.length; i++) { - print("Events ${y.events[i].name} ${y.events[i].expansion}"); - } +// // describe object +// desc(dynamic x) { +// if (x is List) { +// for (var i = 0; i < x.length; i++) desc(x[i]); +// } else if (x is DistributedResource) { +// var y = x.instance?.template; +// print("Fucntions = ${y.functions.length}\n"); +// for (var i = 0; i < y.functions.length; i++) { +// print("Function ${y.functions[i].name} ${y.functions[i].expansion}"); +// } +// print("------------------------------\n"); +// print("Events = ${y.events.length}\n"); +// for (var i = 0; i < y.events.length; i++) { +// print("Events ${y.events[i].name} ${y.events[i].expansion}"); +// } - print("------------------------------\n"); - print("Properties = ${y.properties.length}\n"); - for (var i = 0; i < y.properties.length; i++) { - print( - "Property ${y.properties[i].name} ${y.properties[i].readExpansion}"); - // recursion - //print("value = ${desc(x.get(y.properties[i].index))}"); - } - } else { - print(x.toString()); - } -} +// print("------------------------------\n"); +// print("Properties = ${y.properties.length}\n"); +// for (var i = 0; i < y.properties.length; i++) { +// print( +// "Property ${y.properties[i].name} ${y.properties[i].readExpansion}"); +// // recursion +// //print("value = ${desc(x.get(y.properties[i].index))}"); +// } +// } else { +// print(x.toString()); +// } +// }