2
0
mirror of https://github.com/esiur/esiur-dart.git synced 2025-05-06 04:02:57 +00:00
This commit is contained in:
Ahmed Zamil 2021-07-21 12:18:01 +03:00
parent 737397da11
commit 6be04c39ed
27 changed files with 659 additions and 513 deletions

View File

@ -1,19 +1,13 @@
import 'package:args/args.dart';
import 'dart:io';
void main(List<String> arguments) {
import 'package:args/args.dart';
import 'package:pubspec_parse/pubspec_parse.dart';
import '../lib/src/Proxy/TemplateGenerator.dart';
void main(List<String> arguments) async {
if (arguments.length == 0) {
// print help
print("Esiur package command line");
print("");
print("Usage: <command> [arguments]");
print("");
print("Available commands:");
print("\tget-template\tGet a template from an IIP link.");
print("\tversion: print esiur version.");
print("");
print("Global options:");
print("\t-u, --username\tAuthentication username");
print("\t-p, --password\tAuthentication password");
printUsage();
return;
}
var cmd = arguments[0];
@ -27,15 +21,54 @@ void main(List<String> arguments) {
var link = arguments[1];
final parser = ArgParser()
..addFlag('username', abbr: 'u')
..addFlag('password', abbr: 'p');
..addOption('username', abbr: 'u')
..addOption('password', abbr: 'p')
..addOption('dir', abbr: 'd');
var results = parser.parse(arguments.skip(2));
var username = results['username'];
var password = results['password'];
var dir = results['dir'];
//print("Username ${username} password ${password} dir ${dir}");
// make template
var destDir =
await TemplateGenerator.getTemplate(link, dir, username, password);
print("Generated directory `${destDir}`");
return;
} else if (cmd == "version") {
await printVersion();
} else {
printUsage();
}
}
printUsage() {
// print help
print("Esiur package command line");
print("");
print("Usage: <command> [arguments]");
print("");
print("Available commands:");
print("\tget-template\tGet a template from an IIP link.");
print("\tversion: print esiur version.");
print("");
print("Global options:");
print("\t-u, --username\tAuthentication username");
print("\t-p, --password\tAuthentication password");
print("\t-d, --dir\tName of the directory to generate model inside.");
}
printVersion() async {
var p = Platform.script.pathSegments;
var path = p.take(p.length - 2).join('/') + "/pubspec.yaml";
var yaml = await File(path).readAsString();
var pub = Pubspec.parse(yaml);
print("${pub.name} ${pub.version}");
print("\t${pub.description}");
print("\t${pub.homepage}");
}

View File

@ -2,9 +2,9 @@ import 'package:source_gen/source_gen.dart';
import 'package:build/build.dart';
import 'package:yaml/yaml.dart';
Builder iipService(BuilderOptions options) {
return LibraryBuilder(TemplateGenerator(), generatedExtension: '.info.dart');
}
//Builder iipService(BuilderOptions options) {
//return LibraryBuilder(TemplateBuilder(), generatedExtension: '.info.dart');
//}
class TemplateBuilder implements Builder {
//BuilderOptions options;
@ -36,12 +36,12 @@ class TemplateBuilder implements Builder {
}
}
class TemplateGenerator extends Generator {
@override
String generate(LibraryReader library, BuildStep buildStep) {
return '''
// Source library: ${library.element.source.uri}
const Testinggggg = 3;
''';
}
}
// class TemplateBuilder extends Generator {
// @override
// String generate(LibraryReader library, BuildStep buildStep) {
// return '''
// // Source library: ${library.element.source.uri}
// const Testinggggg = 3;
// ''';
// }
// }

View File

@ -14,6 +14,7 @@ export 'src/Resource/Template/MemberType.dart';
export 'src/Resource/Template/PropertyPermission.dart';
export 'src/Resource/Template/PropertyTemplate.dart';
export 'src/Resource/Template/TypeTemplate.dart';
export 'src/Resource/Template/TemplateDescriber.dart';
// -----------------------------------------------------------------
// Core

View File

@ -1,14 +1,16 @@
import 'AsyncReply.dart';
import '../Resource/Warehouse.dart';
class AsyncBag<T> extends AsyncReply<List<T>> {
List<AsyncReply<T>> _replies = new List<AsyncReply<T>>();
List<AsyncReply<T>> _replies = <AsyncReply<T>>[];
List<T> _results = <T>[];
int _count = 0;
bool _sealedBag = false;
Type arrayType;
seal() {
//print("SEALED");
@ -16,7 +18,7 @@ class AsyncBag<T> extends AsyncReply<List<T>> {
_sealedBag = true;
if (_results.length == 0) trigger(new List<T>());
if (_results.length == 0) trigger(<T>[]);
for (var i = 0; i < _results.length; i++) {
var k = _replies[i];
@ -25,8 +27,15 @@ class AsyncBag<T> extends AsyncReply<List<T>> {
k.then<dynamic>((r) {
_results[index] = r;
_count++;
//print("Seal ${_count}/${_results.length}");
if (_count == _results.length) trigger(_results);
if (_count == _results.length) {
if (arrayType != null) {
var ar = Warehouse.createArray(arrayType);
_results.forEach(ar.add);
trigger(ar);
} else {
trigger(_results);
}
}
}).error((ex) {
triggerError(ex);
});

View File

@ -3,7 +3,7 @@ library esiur;
import 'AsyncReply.dart';
class AsyncQueue<T> extends AsyncReply<T> {
List<AsyncReply<T>> _list = new List<AsyncReply<T>>();
List<AsyncReply<T>> _list = <AsyncReply<T>>[];
// object queueLock = new object();

View File

@ -27,17 +27,16 @@ import 'AsyncException.dart';
import 'ProgressType.dart';
class AsyncReply<T> implements Future<T> {
List<Function(T)> _callbacks = new List<Function(T)>();
List<Function(T)> _callbacks = <Function(T)>[];
T _result;
List<Function(AsyncException)> _errorCallbacks =
new List<Function(AsyncException)>();
List<Function(AsyncException)> _errorCallbacks = <Function(AsyncException)>[];
List<Function(ProgressType, int, int)> _progressCallbacks =
new List<Function(ProgressType, int, int)>();
<Function(ProgressType, int, int)>[];
List<Function(T)> _chunkCallbacks = new List<Function(T)>();
List<Function(T)> _chunkCallbacks = <Function(T)>[];
bool _resultReady = false;
AsyncException _exception;

View File

@ -2,198 +2,165 @@ import '../Core/IDestructible.dart';
import 'Codec.dart';
import 'dart:collection';
class AutoList<T, ST> extends IDestructible with IterableMixin
{
class AutoList<T, ST> extends IDestructible with IterableMixin {
List<T> _list = <T>[];
List<T> _list = new List<T>();
ST _state;
bool _removableList;
sort(Function comparer) {
_list.sort(comparer);
}
ST _state;
bool _removableList;
Iterator<T> get iterator => _list.iterator;
sort(Function comparer)
{
_list.sort(comparer);
}
/// <summary>
/// Convert AutoList to array
/// </summary>
/// <returns>Array</returns>
//List<T> toList()
//{
// list.OrderBy()
// return _list;
//}
Iterator<T> get iterator => _list.iterator;
/// Create a new instance of AutoList
/// <param name="state">State object to be included when an event is raised.</param>
AutoList([ST state, List<T> values]) {
this._state = state;
this._removableList = Codec.implementsInterface<T, IDestructible>();
if (values != null) addRange(values);
/// <summary>
/// Convert AutoList to array
/// </summary>
/// <returns>Array</returns>
//List<T> toList()
//{
// list.OrderBy()
// return _list;
//}
register("modified");
register("added");
register("removed");
register("cleared");
}
/// Create a new instance of AutoList
/// <param name="state">State object to be included when an event is raised.</param>
AutoList([ST state, List<T> values])
{
this._state = state;
this._removableList = Codec.implementsInterface<T, IDestructible>();
/// <summary>
/// Synchronization lock of the list
/// </summary>
//public object SyncRoot
//{
// get
// {
// return syncRoot;
// }
//}
if (values != null)
addRange(values);
/// <summary>
/// First item in the list
/// </summary>
//T first()
//{
// return _list.first;
//}
register("modified");
register("added");
register("removed");
register("cleared");
}
operator [](index) {
return _list[index];
}
operator []=(index, value) {
var oldValue = _list[index];
/// <summary>
/// Synchronization lock of the list
/// </summary>
//public object SyncRoot
//{
// get
// {
// return syncRoot;
// }
//}
if (_removableList) {
if (oldValue != null)
(oldValue as IDestructible).off("destroy", _itemDestroyed);
if (value != null) value.on("destroy", _itemDestroyed);
}
/// <summary>
/// First item in the list
/// </summary>
//T first()
//{
// return _list.first;
//}
//lock (syncRoot)
_list[index] = value;
operator [](index)
{
return _list[index];
}
emitArgs("modified", [_state, index, oldValue, value]);
}
operator []=(index, value)
{
var oldValue = _list[index];
/// <summary>
/// Add item to the list
/// </summary>
add(T value) {
if (_removableList) if (value != null)
(value as IDestructible).on("destroy", _itemDestroyed);
if (_removableList)
{
if (oldValue != null)
(oldValue as IDestructible).off("destroy", _itemDestroyed);
if (value != null)
value.on("destroy", _itemDestroyed);
}
// lock (syncRoot)
_list.add(value);
//lock (syncRoot)
_list[index] = value;
emitArgs("add", [_state, value]);
}
emitArgs("modified", [_state, index, oldValue, value]);
}
/// <summary>
/// Add an array of items to the list
/// </summary>
addRange(List<T> values) {
values.forEach((x) => add(x));
}
/// <summary>
/// Add item to the list
/// </summary>
add(T value)
{
if (_removableList)
if (value != null)
(value as IDestructible).on("destroy", _itemDestroyed);
_itemDestroyed(T sender) {
remove(sender);
}
// lock (syncRoot)
_list.add(value);
/// <summary>
/// Clear the list
/// </summary>
clear() {
if (_removableList)
_list
.forEach((x) => (x as IDestructible)?.off("destroy", _itemDestroyed));
emitArgs("add",[_state, value]);
}
/// <summary>
/// Add an array of items to the list
/// </summary>
addRange(List<T> values)
{
values.forEach((x)=>add(x));
}
_itemDestroyed(T sender)
{
remove(sender);
}
/// <summary>
/// Clear the list
/// </summary>
clear()
{
if (_removableList)
_list.forEach((x)=>(x as IDestructible)?.off("destroy", _itemDestroyed));
// lock (syncRoot)
_list.clear();
_list.clear();
emitArgs("cleared", [_state]);
emitArgs("cleared", [_state]);
}
/// <summary>
/// Remove an item from the list
/// <param name="value">Item to remove</param>
/// </summary>
remove(T value) {
if (!_list.contains(value)) return;
if (_removableList) if (value != null)
(value as IDestructible).off("destroy", _itemDestroyed);
//lock (syncRoot)
_list.remove(value);
emitArgs("removed", [_state, value]);
}
/// <summary>
/// Number of items in the list
/// </summary>
get count => _list.length;
get length => _list.length;
/// <summary>
/// Check if an item exists in the list
/// </summary>
/// <param name="value">Item to check if exists</param>
//contains(T value) => _list.contains(value);
/// <summary>
/// Check if any item of the given array is in the list
/// </summary>
/// <param name="values">Array of items</param>
containsAny(values) {
if (values is List<T>) {
for (var v in values) {
if (_list.contains(v)) return true;
}
/// <summary>
/// Remove an item from the list
/// <param name="value">Item to remove</param>
/// </summary>
remove(T value)
{
if (!_list.contains(value))
return;
if (_removableList)
if (value != null)
(value as IDestructible).off("destroy", _itemDestroyed);
//lock (syncRoot)
_list.remove(value);
emitArgs("removed", [_state, value]);
} else if (values is AutoList<T, ST>) {
for (var v in values._list) {
if (_list.contains(v)) return true;
}
}
/// <summary>
/// Number of items in the list
/// </summary>
get count => _list.length;
get length => _list.length;
return false;
}
/// <summary>
/// Check if an item exists in the list
/// </summary>
/// <param name="value">Item to check if exists</param>
//contains(T value) => _list.contains(value);
/// <summary>
/// Check if any item of the given array is in the list
/// </summary>
/// <param name="values">Array of items</param>
containsAny(values)
{
if (values is List<T>)
{
for(var v in values)
{
if (_list.contains(v))
return true;
}
}
else if (values is AutoList<T, ST>)
{
for(var v in values._list)
{
if (_list.contains(v))
return true;
}
}
return false;
}
@override
@override
void destroy() {
clear();
}

View File

@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import 'package:esiur/src/Resource/Template/TemplateType.dart';
import '../Resource/Template/TemplateType.dart';
import 'DataType.dart';
import 'Guid.dart';
@ -78,10 +78,11 @@ class Codec {
static List<int> getStructureDateTypes(
Structure structure, DistributedConnection connection) {
var keys = structure.getKeys();
var types = new List<int>(keys.length);
var types = new List<int>.generate(
keys.length, (i) => Codec.getDataType(structure[keys[i]], connection));
for (var i = 0; i < keys.length; i++)
types[i] = Codec.getDataType(structure[keys[i]], connection);
// for (var i = 0; i < keys.length; i++)
// types[i] = Codec.getDataType(structure[keys[i]], connection);
return types;
}
@ -325,7 +326,7 @@ class Codec {
record.deserialize(value);
reply.trigger(null);
reply.trigger(record);
} else {
var record = new Record();
@ -336,8 +337,8 @@ class Codec {
}
});
} else {
connection.getTemplate(classId).then((tmp) {
parseVarArray(data, offset, length, connection).then((ar) {
connection.getTemplate(classId).then<dynamic>((tmp) {
parseVarArray(data, offset, length, connection).then<dynamic>((ar) {
var record = new Record();
for (var i = 0; i < tmp.properties.length; i++)
@ -619,8 +620,8 @@ class Codec {
{
var reply = new AsyncReply<Structure>();
var bag = new AsyncBag<dynamic>();
var keylist = new List<String>();
var typelist = new List<int>();
var keylist = <String>[];
var typelist = <int>[];
var sizeObject = new SizeObject();
if (keys == null) {
@ -888,10 +889,9 @@ class Codec {
/// <returns>True, if the resource owner is the given connection, otherwise False.</returns>
static bool isLocalResource(
IResource resource, DistributedConnection connection) {
if (resource is DistributedResource) if ((resource as DistributedResource)
.connection ==
connection) return true;
if (resource is DistributedResource) {
if (resource.connection == connection) return true;
}
return false;
}
@ -1010,7 +1010,26 @@ class Codec {
var end = offset + length;
//
var result = data[offset++];
// Is typed array ?
var type = (data[offset] & 0xF0);
var result = data[offset++] & 0xF;
if (type == ResourceArrayType.Wrapper) {
var classId = data.getGuid(offset);
offset += 16;
var tmp = Warehouse.getTemplateByClassId(classId, TemplateType.Resource);
// not mine, look if the type is elsewhere
if (tmp == null)
Warehouse.getTemplateByClassId(classId, TemplateType.Wrapper);
reply.arrayType = tmp?.definedType;
} else if (type == ResourceArrayType.Static) {
var classId = data.getGuid(offset);
offset += 16;
var tmp = Warehouse.getTemplateByClassId(classId, TemplateType.Wrapper);
reply.arrayType = tmp?.definedType;
}
AsyncReply<IResource> previous = null;
@ -1036,7 +1055,7 @@ class Codec {
} else if (result == ResourceComparisonResult.Same) {
current = previous;
} else if (result == ResourceComparisonResult.Local) {
current = Warehouse.get(data.getUint32(offset));
current = Warehouse.getById(data.getUint32(offset));
offset += 4;
} else if (result == ResourceComparisonResult.Distributed) {
current = connection.fetch(data.getUint32(offset));

View File

@ -9,7 +9,7 @@ class Guid {
DC get value => _data;
bool operator ==(Object other) {
bool operator ==(other) {
if (other is Guid)
return _data.sequenceEqual(other._data);
else
@ -20,4 +20,7 @@ class Guid {
String toString() {
return _data.getString(0, _data.length);
}
@override
int get hashCode => _data.toString().hashCode;
}

View File

@ -27,130 +27,96 @@ import '../Core/IDestructible.dart';
import 'dart:collection';
import 'Codec.dart';
class KeyList<KT, T> extends IEventHandler with MapMixin<KT, T>
{
class KeyList<KT, T> extends IEventHandler with MapMixin<KT, T> {
dynamic owner;
dynamic owner;
Map<KT, T> _map = new Map<KT, T>();
Iterator<KT> get iterator => _map.keys.iterator;
Map<KT, T> _map = new Map<KT, T>();
Iterable<KT> get keys => _map.keys;
Iterable<T> get values => _map.values;
Iterator<KT> get iterator => _map.keys.iterator;
operator[](index) => _map[index];
Iterable<KT> get keys => _map.keys;
Iterable<T> get values => _map.values;
operator []= (index, value) => add(index, value);
operator [](index) => _map[index];
at(int index) => _map.values.elementAt(index);
operator []=(index, value) => add(index, value);
bool _removableList;
at(int index) => _map.values.elementAt(index);
bool _removableList;
T take(KT key)
{
if (_map.containsKey(key))
{
var v = _map[key];
remove(key);
return v;
}
else
return null;
T take(KT key) {
if (_map.containsKey(key)) {
var v = _map[key];
remove(key);
return v;
} else
return null;
}
List<T> toArray() => _map.values.toList();
void add(KT key, T value) {
if (_removableList) if (value != null)
(value as IDestructible).on("destroy", _itemDestroyed);
if (_map.containsKey(key)) {
var oldValue = _map[key];
if (_removableList) if (oldValue != null)
(oldValue as IDestructible).off("destroy", _itemDestroyed);
_map[key] = value;
emitArgs("modified", [key, oldValue, value, this]);
} else {
_map[key] = value;
emitArgs("add", [value, this]);
}
}
List<T> toArray() => _map.values.toList();
_itemDestroyed(T sender) {
removeValue(sender);
}
void add(KT key, T value)
{
if (_removableList)
if (value != null)
(value as IDestructible).on("destroy", _itemDestroyed);
removeValue(T value) {
var toRemove = <KT>[];
for (var k in _map.keys) if (_map[k] == value) toRemove.add(k);
if (_map.containsKey(key))
{
var oldValue = _map[key];
if (_removableList)
if (oldValue != null)
(oldValue as IDestructible).off("destroy", _itemDestroyed);
for (var k in toRemove) remove(k);
}
_map[key] = value;
clear() {
if (_removableList)
for (var v in _map.values)
(v as IDestructible)?.off("destroy", _itemDestroyed);
emitArgs("modified", [key, oldValue, value, this]);
}
else
{
_map[key] = value;
_map.clear();
emitArgs("add", [value, this]);
emitArgs("cleared", [this]);
}
}
}
T remove(key) {
if (!_map.containsKey(key)) return null;
_itemDestroyed(T sender)
{
removeValue(sender);
}
var value = _map[key];
removeValue(T value)
{
var toRemove = new List<KT>();
for (var k in _map.keys)
if (_map[k] == value)
toRemove.add(k);
if (_removableList)
(value as IDestructible)?.off("destroy", _itemDestroyed);
for (var k in toRemove)
remove(k);
}
_map.remove(key);
clear()
{
if (_removableList)
for (var v in _map.values)
(v as IDestructible)?.off("destroy", _itemDestroyed);
_map.clear();
emitArgs("removed", [key, value, this]);
emitArgs("cleared", [this]);
}
return value;
}
int get count => _map.length;
bool contains(KT key) => _map.containsKey(key);
T remove(key)
{
if (!_map.containsKey(key))
return null;
var value = _map[key];
if (_removableList)
(value as IDestructible)?.off("destroy", _itemDestroyed);
_map.remove(key);
emitArgs("removed", [key, value, this]);
return value;
}
int get count => _map.length;
bool contains(KT key) => _map.containsKey(key);
KeyList([owner = null])
{
_removableList = Codec.implementsInterface<T, IDestructible>();
this.owner = owner;
}
}
KeyList([owner = null]) {
_removableList = Codec.implementsInterface<T, IDestructible>();
this.owner = owner;
}
}

View File

@ -1,4 +1,4 @@
import 'package:esiur/src/Resource/Template/TemplateDescriber.dart';
import '../Resource/Template/TemplateDescriber.dart';
import 'IRecord.dart';
import 'KeyList.dart';

View File

@ -22,13 +22,10 @@ SOFTWARE.
*/
import 'dart:ffi';
import 'dart:typed_data';
import 'package:esiur/esiur.dart';
import 'package:esiur/src/Resource/Template/TemplateDescriber.dart';
import 'package:esiur/src/Resource/Template/TemplateType.dart';
import 'package:esiur/src/Security/Authority/AuthenticationMethod.dart';
import '../../Resource/Template/TemplateDescriber.dart';
import '../../Resource/Template/TemplateType.dart';
import '../../Security/Authority/AuthenticationMethod.dart';
import '../../Core/AsyncBag.dart';
@ -44,7 +41,7 @@ import '../../Core/ExceptionCode.dart';
import '../../Core/ErrorType.dart';
import '../../Resource/Warehouse.dart';
import '../Sockets/SocketState.dart';
import 'dart:math';
import '../../Resource/IStore.dart';
import '../../Resource/IResource.dart';
@ -434,9 +431,8 @@ class DistributedConnection extends NetworkConnection with IStore {
String link(IResource resource) {
if (resource is DistributedResource) {
var r = resource as DistributedResource;
if (r.instance.store == this)
return this.instance.name + "/" + r.id.toString();
if (resource.instance.store == this)
return this.instance.name + "/" + resource.id.toString();
}
return null;
@ -445,9 +441,9 @@ class DistributedConnection extends NetworkConnection with IStore {
void init() {
_queue.then((x) {
if (x.type == DistributedResourceQueueItemType.Event)
x.resource.emitEventByIndex(x.index, x.value);
x.resource.internal_emitEventByIndex(x.index, x.value);
else
x.resource.updatePropertyByIndex(x.index, x.value);
x.resource.internal_updatePropertyByIndex(x.index, x.value);
});
var r = new Random();
@ -663,8 +659,7 @@ class DistributedConnection extends NetworkConnection with IStore {
case IIPPacketAction.TemplateFromClassName:
case IIPPacketAction.TemplateFromClassId:
case IIPPacketAction.TemplateFromResourceId:
iipReply(
packet.callbackId, [TypeTemplate.parse(packet.content)]);
iipReply(packet.callbackId, [TypeTemplate.parse(packet.content)]);
break;
case IIPPacketAction.QueryLink:
@ -1285,7 +1280,7 @@ class DistributedConnection extends NetworkConnection with IStore {
.addUint16(link.length)
.addDC(link)
.addDC(Codec.composePropertyValueArray(
(r as DistributedResource).serialize(), this, true))
(r as DistributedResource).internal_serialize(), this, true))
.done();
} else {
// reply ok
@ -1883,7 +1878,7 @@ class DistributedConnection extends NetworkConnection with IStore {
if (ft != null) {
if (r is DistributedResource) {
var rt = (r as DistributedResource)
.invokeByArrayArguments(index, arguments);
.internal_invokeByArrayArguments(index, arguments);
if (rt != null) {
rt.then((res) {
sendReply(IIPPacketAction.InvokeFunctionArrayArguments,
@ -1922,7 +1917,7 @@ class DistributedConnection extends NetworkConnection with IStore {
if (ft != null) {
if (r is DistributedResource) {
var rt = (r as DistributedResource)
.invokeByNamedArguments(index, namedArgs);
.internal_invokeByNamedArguments(index, namedArgs);
if (rt != null) {
rt.then((res) {
sendReply(IIPPacketAction.InvokeFunctionNamedArguments,
@ -2215,8 +2210,7 @@ class DistributedConnection extends NetworkConnection with IStore {
.done()
.then<dynamic>((rt) {
_templateRequests.remove(classId);
_templates[(rt[0] as TypeTemplate).classId] =
rt[0] as TypeTemplate;
_templates[(rt[0] as TypeTemplate).classId] = rt[0] as TypeTemplate;
Warehouse.putTemplate(rt[0] as TypeTemplate);
reply.trigger(rt[0]);
}).error((ex) {
@ -2316,12 +2310,14 @@ class DistributedConnection extends NetworkConnection with IStore {
DistributedResource dr;
if (resource == null) {
var template = Warehouse.getTemplateByClassId(rt[0], TemplateType.Wrapper);
var template =
Warehouse.getTemplateByClassId(rt[0], TemplateType.Wrapper);
if (template?.definedType != null) {
dr = Warehouse.createInstance(template?.definedType);
dr.init(this, id, rt[1], rt[2]);
dr.internal_init(this, id, rt[1], rt[2]);
} else {
dr = new DistributedResource(this, id, rt[1], rt[2]);
dr = new DistributedResource();
dr.internal_init(this, id, rt[1], rt[2]);
}
} else
dr = resource;
@ -2338,7 +2334,7 @@ class DistributedConnection extends NetworkConnection with IStore {
Warehouse.put(id.toString(), dr, this, null, tmp).then<dynamic>((ok) {
Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) {
//print("attached");
dr.attach(ar);
dr.internal_attach(ar);
_resourceRequests.remove(id);
reply.trigger(dr);
});
@ -2346,7 +2342,7 @@ class DistributedConnection extends NetworkConnection with IStore {
} else {
Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) {
//print("attached");
dr.attach(ar);
dr.internal_attach(ar);
_resourceRequests.remove(id);
reply.trigger(dr);
});

View File

@ -22,8 +22,13 @@ SOFTWARE.
*/
import 'package:esiur/esiur.dart';
import 'package:esiur/src/Data/KeyValuePair.dart';
import '../../Core/AsyncException.dart';
import '../../Core/ErrorType.dart';
import '../../Core/ExceptionCode.dart';
import '../../Resource/ResourceTrigger.dart';
import '../../Data/KeyValuePair.dart';
import '../../Resource/IResource.dart';
import '../../Core/AsyncReply.dart';
@ -33,6 +38,9 @@ import '../../Data/Codec.dart';
import './DistributedConnection.dart';
import '../Packets/IIPPacketAction.dart';
import '../../Resource/Template/EventTemplate.dart';
class DistributedResource extends IResource {
int _instanceId;
DistributedConnection _connection;
@ -107,32 +115,28 @@ class DistributedResource extends IResource {
/// <param name="template">Resource template.</param>
/// <param name="instanceId">Instance Id given by the other end.</param>
/// <param name="age">Resource age.</param>
DistributedResource(
DistributedConnection connection, int instanceId, int age, String link) {
this._link = link;
this._connection = connection;
this._instanceId = instanceId;
this._age = age;
}
void init(
DistributedConnection connection, int instanceId, int age, String link) {
this._link = link;
this._connection = connection;
this._instanceId = instanceId;
this._age = age;
}
//void _ready()
//{
// _isReady = true;
// DistributedResource(
// DistributedConnection connection, int instanceId, int age, String link) {
// this._link = link;
// this._connection = connection;
// this._instanceId = instanceId;
// this._age = age;
// }
void internal_init(
DistributedConnection connection, int instanceId, int age, String link) {
this._link = link;
this._connection = connection;
this._instanceId = instanceId;
this._age = age;
}
/// <summary>
/// Export all properties with ResourceProperty attributed as bytes array.
/// </summary>
/// <returns></returns>
List<PropertyValue> serialize() {
List<PropertyValue> internal_serialize() {
var props = new List<PropertyValue>(_properties.length);
for (var i = 0; i < _properties.length; i++)
@ -142,7 +146,7 @@ class DistributedResource extends IResource {
return props;
}
bool attach(List<PropertyValue> properties) {
bool internal_attach(List<PropertyValue> properties) {
if (_attached)
return false;
else {
@ -168,7 +172,7 @@ class DistributedResource extends IResource {
if (_queued_updates.length > 0) {
_queued_updates
.forEach((kv) => updatePropertyByIndex(kv.key, kv.value));
.forEach((kv) => internal_updatePropertyByIndex(kv.key, kv.value));
_queued_updates.clear();
}
}
@ -207,7 +211,7 @@ class DistributedResource extends IResource {
return connection.sendUnlistenRequest(_instanceId, et.index);
}
void emitEventByIndex(int index, dynamic args) {
void internal_emitEventByIndex(int index, dynamic args) {
// neglect events when the object is not yet attached
if (!_attached) return;
@ -217,7 +221,7 @@ class DistributedResource extends IResource {
instance.emitResourceEvent(null, null, et.name, args);
}
AsyncReply<dynamic> invokeByNamedArguments(int index, Structure namedArgs) {
AsyncReply<dynamic> internal_invokeByNamedArguments(int index, Structure namedArgs) {
if (_destroyed) throw new Exception("Trying to access destroyed object");
if (_suspended) throw new Exception("Trying to access suspended object");
@ -228,7 +232,7 @@ class DistributedResource extends IResource {
return connection.sendInvokeByNamedArguments(_instanceId, index, namedArgs);
}
AsyncReply<dynamic> invokeByArrayArguments(int index, List<dynamic> args) {
AsyncReply<dynamic> internal_invokeByArrayArguments(int index, List<dynamic> args) {
if (_destroyed) throw new Exception("Trying to access destroyed object");
if (_suspended) throw new Exception("Trying to access suspended object");
@ -270,9 +274,9 @@ class DistributedResource extends IResource {
for (var p in invocation.namedArguments.keys)
namedArgs[_getMemberName(p)] = invocation.namedArguments[p];
return invokeByNamedArguments(ft.index, namedArgs);
return internal_invokeByNamedArguments(ft.index, namedArgs);
} else {
return invokeByArrayArguments(
return internal_invokeByArrayArguments(
ft.index, invocation.positionalArguments);
}
}
@ -304,7 +308,7 @@ class DistributedResource extends IResource {
return _properties[index];
}
void updatePropertyByIndex(int index, dynamic value) {
void internal_updatePropertyByIndex(int index, dynamic value) {
if (!_attached) {
_queued_updates.add(KeyValuePair(index, value));
} else {

View File

@ -1,4 +1,4 @@
import 'package:esiur/src/Resource/Template/TemplateDescriber.dart';
import '../../Resource/Template/TemplateDescriber.dart';
import '../../Resource/IResource.dart';
import '../../Core/AsyncReply.dart';

View File

@ -23,7 +23,11 @@ SOFTWARE.
*/
import 'dart:io';
import 'package:esiur/esiur.dart';
import '../../Core/ErrorType.dart';
import '../../Core/ExceptionCode.dart';
import '../../Core/AsyncException.dart';
import 'ISocket.dart';
import '../../Data/DC.dart';

View File

@ -10,19 +10,19 @@ import '../Resource/Template/TemplateDataType.dart';
import '../Resource/Template/TypeTemplate.dart';
class TemplateGenerator {
// static RegExp urlRegex = new RegExp("^(?:([\S]*)://([^/]*)/?)");
// static RegExp urlRegex = RegExp("^(?:([\S]*)://([^/]*)/?)");
static final _urlRegex = RegExp(r'^(?:([^\s|:]*):\/\/([^\/]*)\/?(.*))');
static String generateRecord(
TypeTemplate template, List<TypeTemplate> templates) {
var className = template.className.split('.').last;
var rt = new StringBuffer();
var rt = StringBuffer();
rt.writeln("class ${className} extends IRecord {");
template.properties.forEach((p) {
var ptTypeName = getTypeName(template, p.valueType, templates);
rt.writeln("${ptTypeName} ${p.name};");
rt.writeln("${ptTypeName}? ${p.name};");
rt.writeln();
});
@ -48,40 +48,78 @@ class TemplateGenerator {
rt.writeln("return rt;");
rt.writeln("}");
// add template
var descProps = template.properties.map((p) {
var isArray = p.valueType.type & 0x80 == 0x80;
var ptType = p.valueType.type & 0x7F;
var ptTypeName = getTypeName(
template, TemplateDataType(ptType, p.valueType.typeGuid), templates);
// return "Prop(\"${p.name}\", ${ptTypeName}, ${isArray})";
return "Prop('${p.name}', ${ptTypeName}, ${isArray}, ${_escape(p.readExpansion)}, ${_escape(p.writeExpansion)})";
}).join(', ');
rt.writeln("""@override
TemplateDescriber get template => TemplateDescriber('${template.className}', properties: [${descProps}]);""");
rt.writeln("\r\n}");
return rt.toString();
}
static String _translateClassName(String className) {
var cls = className.split('.');
var nameSpace = cls.take(cls.length - 1).join('_').toLowerCase();
return "$nameSpace.${cls.last}";
}
static String getTypeName(TypeTemplate forTemplate,
TemplateDataType templateDataType, List<TypeTemplate> templates) {
if (templateDataType.type == DataType.Resource) {
if (templateDataType.typeGuid == forTemplate.classId)
return forTemplate.className.split('.').last;
else {
var tmp =
templates.firstWhere((x) => x.classId == templateDataType.typeGuid);
var tmp = templates.firstWhere((x) =>
x.classId == templateDataType.typeGuid &&
(x.type == TemplateType.Resource ||
x.type == TemplateType.Wrapper));
if (tmp == null) return "dynamic"; // something went wrong
var cls = tmp.className.split('.');
var nameSpace = cls.take(cls.length - 1).join('_');
return "$nameSpace.${cls.last}";
return _translateClassName(tmp.className);
}
} else if (templateDataType.type == DataType.ResourceArray) {
if (templateDataType.typeGuid == forTemplate.classId)
return "List<${forTemplate.className.split('.').last}>";
else {
var tmp =
templates.firstWhere((x) => x.classId == templateDataType.typeGuid);
var tmp = templates.firstWhere((x) =>
x.classId == templateDataType.typeGuid &&
(x.type == TemplateType.Resource ||
x.type == TemplateType.Wrapper));
if (tmp == null) return "dynamic"; // something went wrong
var cls = tmp.className.split('.');
var nameSpace = cls.take(cls.length - 1).join('_');
return "List<$nameSpace.${cls.last}>";
return "List<${_translateClassName(tmp.className)}>";
}
} else if (templateDataType.type == DataType.Record) {
if (templateDataType.typeGuid == forTemplate.classId)
return forTemplate.className.split('.').last;
else {
var tmp = templates.firstWhere((x) =>
x.classId == templateDataType.typeGuid &&
x.type == TemplateType.Record);
if (tmp == null) return "dynamic"; // something went wrong
return _translateClassName(tmp.className);
}
} else if (templateDataType.type == DataType.RecordArray) {
if (templateDataType.typeGuid == forTemplate.classId)
return "List<${forTemplate.className.split('.').last}>";
else {
var tmp = templates.firstWhere((x) =>
x.classId == templateDataType.typeGuid &&
x.type == TemplateType.Record);
if (tmp == null) return "dynamic"; // something went wrong
return "List<${_translateClassName(tmp.className)}>";
}
}
@ -104,7 +142,7 @@ class TemplateGenerator {
case DataType.DecimalArray:
return "List<double>";
case DataType.Float32:
return "List<double>";
return "double";
case DataType.Float32Array:
return "List<double>";
case DataType.Float64:
@ -172,7 +210,7 @@ class TemplateGenerator {
String username = null,
String password = null]) async {
try {
if (!_urlRegex.hasMatch(url)) throw new Exception("Invalid IIP URL");
if (!_urlRegex.hasMatch(url)) throw Exception("Invalid IIP URL");
var path = _urlRegex.allMatches(url).first;
var con = await Warehouse.get<DistributedConnection>(
@ -181,12 +219,15 @@ class TemplateGenerator {
? {username: username, password: password}
: null);
if (con == null) throw new Exception("Can't connect to server");
if (con == null) throw Exception("Can't connect to server");
if (isNullOrEmpty(dir)) dir = path[2].replaceAll(":", "_");
var templates = await con.getLinkTemplates(path[3]);
// no longer needed
Warehouse.remove(con);
var dstDir = Directory("lib/$dir");
if (!dstDir.existsSync()) dstDir.createSync();
@ -201,9 +242,8 @@ class TemplateGenerator {
templates.forEach((tmp) {
if (tmp != skipTemplate) {
var cls = tmp.className.split('.');
var nameSpace = cls.take(cls.length - 1).join('_');
imports.writeln(
"import '${tmp.className}.Generated.dart' as $nameSpace;");
var nameSpace = cls.take(cls.length - 1).join('_').toLowerCase();
imports.writeln("import '${tmp.className}.g.dart' as $nameSpace;");
}
});
@ -213,51 +253,61 @@ class TemplateGenerator {
// make sources
templates.forEach((tmp) {
print("Generating `${tmp.className}`.");
if (tmp.type == TemplateType.Resource) {
var source = makeImports(tmp) + generateClass(tmp, templates);
var f = File("${dstDir.path}/${tmp.className}.Generated.dart");
var f = File("${dstDir.path}/${tmp.className}.g.dart");
f.writeAsStringSync(source);
} else if (tmp.type == TemplateType.Record) {
var source = makeImports(tmp) + generateRecord(tmp, templates);
var f = File("${dstDir.path}/${tmp.className}.Generated.dart");
var f = File("${dstDir.path}/${tmp.className}.g.dart");
f.writeAsStringSync(source);
}
});
// generate info class
var typesFile =
"using System; \r\n namespace Esiur { public static class Generated { public static Type[] Resources {get;} = new Type[] { " +
templates
.where((x) => x.type == TemplateType.Resource)
.map((x) => "typeof(${x.className})")
.join(',') +
" }; \r\n public static Type[] Records { get; } = new Type[] { " +
templates
.where((x) => x.type == TemplateType.Record)
.map((x) => "typeof(${x.className})")
.join(',') +
" }; " +
"\r\n } \r\n}";
var f = File("${dstDir.path}/Esiur.Generated.cs");
var defineCreators = templates.map((tmp) {
// creator
var className = _translateClassName(tmp.className);
return "Warehouse.defineCreator(${className}, () => ${className}(), () => <${className}>[]);";
}).join("\r\n");
var putTemplates = templates.map((tmp) {
var className = _translateClassName(tmp.className);
return "Warehouse.putTemplate(TypeTemplate.fromType(${className}));";
}).join("\r\n");
var typesFile = makeImports(null) +
"\r\n void init_${dir}(){ ${defineCreators} \r\n ${putTemplates}}";
var f = File("${dstDir.path}/init.g.dart");
f.writeAsStringSync(typesFile);
return dstDir.path;
} catch (ex) {
//File.WriteAllText("C:\\gen\\gettemplate.err", ex.ToString());
throw ex;
}
}
static String _escape(String str) {
if (str == null)
return "null";
else
return "r'$str'";
}
static String generateClass(
TypeTemplate template, List<TypeTemplate> templates) {
var className = template.className.split('.').last;
var rt = new StringBuffer();
var rt = StringBuffer();
rt.writeln("class $className extends DistributedResource {");
rt.writeln(
"$className(DistributedConnection connection, int instanceId, int age, String link) : super(connection, instanceId, age, link) {");
// "$className(DistributedConnection connection, int instanceId, int age, String link) : super(connection, instanceId, age, link) {");
"$className() {");
template.events.forEach((e) {
rt.writeln("on('${e.name}', (x) => _${e.name}Controller.add(x));");
@ -273,9 +323,9 @@ class TemplateGenerator {
.join(","));
rt.writeln(") {");
rt.writeln("var rt = new AsyncReply<$rtTypeName>();");
rt.writeln("var rt = AsyncReply<$rtTypeName>();");
rt.writeln(
"invokeByArrayArguments(${f.index}, [${f.arguments.map((x) => x.name).join(',')}])");
"internal_invokeByArrayArguments(${f.index}, [${f.arguments.map((x) => x.name).join(',')}])");
rt.writeln(".then<dynamic>((x) => rt.trigger(x))");
rt.writeln(".error((x) => rt.triggerError(x))");
rt.writeln(".chunk((x) => rt.triggerChunk(x));");
@ -299,6 +349,43 @@ class TemplateGenerator {
rt.writeln("}");
});
// add template
var descProps = template.properties.map((p) {
var isArray = p.valueType.type & 0x80 == 0x80;
var ptType = p.valueType.type & 0x7F;
var ptTypeName = getTypeName(
template, TemplateDataType(ptType, p.valueType.typeGuid), templates);
return "Prop('${p.name}', ${ptTypeName}, ${isArray}, ${_escape(p.readExpansion)}, ${_escape(p.writeExpansion)})";
}).join(', ');
var descFuncs = template.functions.map((f) {
var isArray = f.returnType.type & 0x80 == 0x80;
var ftType = f.returnType.type & 0x7F;
var ftTypeName = getTypeName(
template, TemplateDataType(ftType, f.returnType.typeGuid), templates);
var args = f.arguments.map((a) {
var isArray = a.type.type & 0x80 == 0x80;
var atType = a.type.type & 0x7F;
var atTypeName = getTypeName(
template, TemplateDataType(atType, a.type.typeGuid), templates);
return "Arg('${a.name}', ${atTypeName}, ${isArray})";
}).join(', ');
return "Func('${f.name}', ${ftTypeName}, ${isArray}, [${args}], ${_escape(f.expansion)})";
}).join(', ');
var descEvents = template.events.map((e) {
var isArray = e.argumentType.type & 0x80 == 0x80;
var etType = e.argumentType.type & 0x7F;
var etTypeName = getTypeName(template,
TemplateDataType(etType, e.argumentType.typeGuid), templates);
return "Evt('${e.name}', ${etTypeName}, ${isArray}, ${e.listenable}, ${_escape(e.expansion)})";
}).join(', ');
rt.writeln(
"TemplateDescriber get template => TemplateDescriber('${template.className}', properties: [${descProps}], functions: [${descFuncs}], events: [$descEvents]);");
rt.writeln("\r\n}");
return rt.toString();

View File

@ -0,0 +1,7 @@
class FactoryEntry {
final Type type;
final Function() instanceCreator;
final Function() arrayCreator;
FactoryEntry(this.type, this.instanceCreator, this.arrayCreator);
}

View File

@ -22,7 +22,7 @@ SOFTWARE.
*/
import 'package:esiur/src/Resource/Template/TemplateDescriber.dart';
import './Template/TemplateDescriber.dart';
import '../Resource/Template/TemplateDescriber.dart';
import '../Core/IDestructible.dart';

View File

@ -29,6 +29,6 @@ class MemberTemplate
DC compose()
{
// return DC.ToBytes(Name);
return DC.stringToBytes(_name);
}
}

View File

@ -10,7 +10,7 @@ import '../StorageMode.dart';
class PropertyTemplate extends MemberTemplate {
TemplateDataType valueType;
int permission;
int permission = 0;
int storage;

View File

@ -26,7 +26,7 @@ class TemplateDataType {
TemplateDataType.fromType(type, bool isArray) {
int dt;
if (type == null)
if (type == null || type == dynamic)
dt = DataType.Void;
else if (type is int) {
dt = type;
@ -50,7 +50,7 @@ class TemplateDataType {
dt = DataType.Int64;
else if (type == Float)
dt = DataType.Float32;
else if (type == Double)
else if (type == Double || type == double)
dt = DataType.Float64;
else if (type == String)
dt = DataType.String;

View File

@ -5,9 +5,10 @@ class TemplateDescriber {
final List<Evt> events;
final List<Func> functions;
final String nameSpace;
final int version;
TemplateDescriber(this.nameSpace,
{this.properties, this.functions, this.events});
{this.properties, this.functions, this.events, this.version = 0});
}
// class Property<T> {
@ -48,7 +49,8 @@ class Prop {
final bool isArray;
final String readAnnotation;
final String writeAnnotation;
Prop(this.name, this.type, this.isArray, [this.readAnnotation = null, this.writeAnnotation = null]);
Prop(this.name, this.type, this.isArray,
[this.readAnnotation = null, this.writeAnnotation = null]);
}
class Evt {
@ -58,7 +60,8 @@ class Evt {
final bool isArray;
final String annotation;
Evt(this.name, this.type, this.isArray, [this.listenable = false, this.annotation]);
Evt(this.name, this.type, this.isArray,
[this.listenable = false, this.annotation]);
}
class Func {
@ -68,7 +71,7 @@ class Func {
final bool isArray;
final String annotation;
Func(this.name, this.returnType, this.argsType, this.isArray,
Func(this.name, this.returnType, this.isArray, this.argsType,
[this.annotation = null]);
}

View File

@ -1,5 +1,7 @@
import 'dart:ffi';
import '../../Net/IIP/DistributedResource.dart';
import '../../Data/BinaryList.dart';
import '../../Security/Integrity/SHA256.dart';
@ -55,8 +57,7 @@ class TypeTemplate {
*/
//@TODO: implement
static List<TypeTemplate> getDependencies(TypeTemplate template) =>
[];
static List<TypeTemplate> getDependencies(TypeTemplate template) => [];
EventTemplate getEventTemplateByName(String eventName) {
for (var i in _events) if (i.name == eventName) return i;
@ -106,15 +107,27 @@ class TypeTemplate {
List<PropertyTemplate> get properties => _properties;
TypeTemplate.fromType(Type type, [bool addToWarehouse, bool isWrapper]) {
TypeTemplate.fromType(Type type, [bool addToWarehouse = false]) {
// debugging print("FromType ${type.toString()}");
var instance = Warehouse.createInstance(type);
if (instance is IRecord)
_templateType = TemplateType.Record;
if (instance is DistributedResource)
_templateType = TemplateType.Wrapper;
else if (instance is IResource)
_templateType = TemplateType.Resource;
else if (instance is IRecord)
_templateType = TemplateType.Record;
else
throw new Exception("Type is neither a resource nor a record.");
throw new Exception(
"Type must implement IResource, IRecord or inherit from DistributedResource.");
// if (instance is IRecord)
// _templateType = TemplateType.Record;
// else if (instance is IResource)
// _templateType = TemplateType.Resource;
// else
// throw new Exception("Type is neither a resource nor a record.");
TemplateDescriber describer = instance.template;
@ -125,47 +138,59 @@ class TypeTemplate {
// set guid
_classId = getTypeGuid(_className);
_version = describer.version;
if (addToWarehouse) Warehouse.putTemplate(this);
// _templates.add(template.classId, template);
for (var i = 0; i < describer.properties.length; i++) {
var pi = describer.properties[i];
var pt = PropertyTemplate(
this,
i,
pi.name,
TemplateDataType.fromType(pi.type, pi.isArray),
pi.readAnnotation,
pi.writeAnnotation,
0);
properties.add(pt);
}
if (describer.properties != null)
for (var i = 0; i < describer.properties.length; i++) {
var pi = describer.properties[i];
var pt = PropertyTemplate(
this,
i,
pi.name,
TemplateDataType.fromType(pi.type, pi.isArray),
pi.readAnnotation,
pi.writeAnnotation,
0);
properties.add(pt);
}
for (var i = 0; i < describer.functions.length; i++) {
var fi = describer.functions[i];
if (describer.functions != null)
for (var i = 0; i < describer.functions.length; i++) {
var fi = describer.functions[i];
List<ArgumentTemplate> args = fi.argsType.map((arg) => ArgumentTemplate(
arg.name, TemplateDataType.fromType(arg.type, arg.isArray)));
List<ArgumentTemplate> args = fi.argsType
.map((arg) => ArgumentTemplate(
arg.name, TemplateDataType.fromType(arg.type, arg.isArray)))
.toList();
var ft = FunctionTemplate(this, i, fi.name, args,
TemplateDataType.fromType(fi.returnType, fi.isArray), fi.annotation);
var ft = FunctionTemplate(
this,
i,
fi.name,
args,
TemplateDataType.fromType(fi.returnType, fi.isArray),
fi.annotation);
functions.add(ft);
}
functions.add(ft);
}
for (var i = 0; i < describer.events.length; i++) {
var ei = describer.events[i];
if (describer.events != null)
for (var i = 0; i < describer.events.length; i++) {
var ei = describer.events[i];
var et = new EventTemplate(
this,
i,
ei.name,
TemplateDataType.fromType(ei.type, ei.isArray),
ei.annotation,
ei.listenable);
var et = new EventTemplate(
this,
i,
ei.name,
TemplateDataType.fromType(ei.type, ei.isArray),
ei.annotation,
ei.listenable);
events.add(et);
}
events.add(et);
}
// append signals
events.forEach(_members.add);

View File

@ -23,6 +23,7 @@ SOFTWARE.
*/
import '../Data/AutoList.dart';
import 'FactoryEntry.dart';
import 'Template/TemplateType.dart';
import 'Template/TypeTemplate.dart';
import '../Data/Guid.dart';
@ -45,7 +46,6 @@ class Warehouse {
static Map<int, IResource> _resources = new Map<int, IResource>();
static int resourceCounter = 0;
static KeyList<TemplateType, KeyList<Guid, TypeTemplate>> _templates =
_initTemplates(); //
@ -60,13 +60,11 @@ class Warehouse {
return rt;
}
static KeyList<Type, Function()> _factory = _getBuiltInTypes();
static KeyList<Type, FactoryEntry> _factory = _getBuiltInTypes();
static KeyList<String, AsyncReply<IStore> Function(String, dynamic)>
protocols = _getSupportedProtocols();
static bool _warehouseIsOpen = false;
static final _urlRegex = RegExp(r'^(?:([^\s|:]*):\/\/([^\/]*)\/?(.*))');
@ -470,7 +468,11 @@ class Warehouse {
}
static T createInstance<T>(Type T) {
return _factory[T].call();
return _factory[T].instanceCreator.call();
}
static List<T> createArray<T>(Type T) {
return _factory[T].arrayCreator.call();
}
static AsyncReply<T> newResource<T extends IResource>(String name,
@ -479,7 +481,7 @@ class Warehouse {
IPermissionsManager manager = null,
attributes = null,
properties = null]) {
var resource = _factory[T].call();
var resource = _factory[T].instanceCreator.call();
if (properties != null) {
dynamic d = resource;
@ -525,8 +527,9 @@ class Warehouse {
static TypeTemplate getTemplateByType(Type type) {
// loaded ?
for (var tmps in _templates.values)
for (var tmp in tmps.values)
if (tmp.className == type.toString()) return tmp;
for (var tmp in tmps.values) if (tmp.definedType == type) return tmp;
//if (tmp.className == type.toString()) return tmp;
var template = new TypeTemplate.fromType(type, true);
@ -562,28 +565,31 @@ class Warehouse {
/// </summary>
/// <param name="className">Class name.</param>
/// <returns>Resource template.</returns>
static TypeTemplate getTemplateByClassName(String className, [TemplateType templateType = TemplateType.Unspecified]) {
static TypeTemplate getTemplateByClassName(String className,
[TemplateType templateType = TemplateType.Unspecified]) {
if (templateType == TemplateType.Unspecified) {
// look in resources
var template = _templates[TemplateType.Resource]
.values
.firstWhere((x) => x.className == className);
if (template != null) return template;
if (templateType == TemplateType.Unspecified)
{
// look in resources
var template = _templates[TemplateType.Resource].values.firstWhere((x) => x.className == className);
if (template != null)
return template;
// look in records
template = _templates[TemplateType.Record]
.values
.firstWhere((x) => x.className == className);
if (template != null) return template;
// look in records
template = _templates[TemplateType.Record].values.firstWhere((x) => x.className == className);
if (template != null)
return template;
// look in wrappers
template = _templates[TemplateType.Wrapper].values.firstWhere((x) => x.className == className);
return template;
}
else
{
return _templates[templateType].values.firstWhere((x) => x.className == className);
}
// look in wrappers
template = _templates[TemplateType.Wrapper]
.values
.firstWhere((x) => x.className == className);
return template;
} else {
return _templates[templateType]
.values
.firstWhere((x) => x.className == className);
}
}
static bool remove(IResource resource) {
@ -625,9 +631,17 @@ class Warehouse {
return rt;
}
static KeyList<Type, Function()> _getBuiltInTypes() {
var rt = KeyList<Type, Function()>();
rt.add(DistributedConnection, () => DistributedConnection());
static defineCreator(
Type type, Function instanceCreator, Function arrayCreator) {
_factory.add(type, FactoryEntry(type, instanceCreator, arrayCreator));
}
static KeyList<Type, FactoryEntry> _getBuiltInTypes() {
var rt = KeyList<Type, FactoryEntry>();
rt.add(
DistributedConnection,
FactoryEntry(DistributedConnection, () => DistributedConnection(),
() => DistributedConnection()));
return rt;
}
}

View File

@ -50,6 +50,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.1"
checked_yaml:
dependency: transitive
description:
name: checked_yaml
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.1"
cli_util:
dependency: transitive
description:
@ -134,6 +141,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "0.6.3"
json_annotation:
dependency: transitive
description:
name: json_annotation
url: "https://pub.dartlang.org"
source: hosted
version: "4.0.1"
logging:
dependency: transitive
description:
@ -204,6 +218,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.0"
pubspec_parse:
dependency: "direct main"
description:
name: pubspec_parse
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.0"
shelf:
dependency: transitive
description:

View File

@ -1,7 +1,7 @@
name: esiur
description: Distributed Object Framework.
version: 1.3.0
# author: Ahmed Zamil <ahmed@esiur.com>
version: 1.4.0
#author: Ahmed Zamil <ahmed@esiur.com>
homepage: https://github.com/esiur/esiur-dart
@ -11,6 +11,7 @@ environment:
dependencies:
source_gen: ^1.0.2
args: #
pubspec_parse:
dev_dependencies:
test: ^1.14.2

View File

@ -1,22 +1,9 @@
import 'package:esiur/src/Proxy/TemplateGenerator.dart';
import "package:test/test.dart";
import 'package:esiur/esiur.dart';
import 'dart:io';
import '../lib/localhost/Esiur.Generated.dart';
import 'TestResource.dart';
main() async {
try {
testMe();
var c = EsiurGenerated;
print(c);
print(Warehouse.protocols.length);
await TemplateGenerator.getTemplate("iip://localhost/sys/cp");
// var x = await Warehouse.get("iip://localhost/sys/cp",
// {"username": "guest", "password": "123456", "domain": "example.com"});
// print(x);
} catch (ex) {
print("Error occured");
print(ex);