Thursday, October 10, 2013

JsonMapper application for CouchDB HTTP data handling

There is a neat application of JsonMapper for CouchDB HTTP data conversion. Couch DB is based on json data. So it is good application area to apply jsonMapper between entity object and serialized object. (Here we see an interesting combination of generic type. Namely by defining generic classes, we can create a flow to pass the entity type to the 'doc' field type at runtime. )

In order to extract entities list from json HTTP output, and do some none standard plumbing of attributes(id must be mapped from _id, rev is from _rev), we can use a single fromJson method.

we define following generic class:

class CouchDBFetchData<T> {
  List<CouchDBFetchRowData<T>> _rows;
  
  List<CouchDBFetchRowData<T>> get rows => _rows;
  void set rows( List<CouchDBFetchRowData<T>> rows) { _rows = rows; }
}

class CouchDBFetchRowData<T> {
  T _doc;
  T get doc => _doc;
  void set doc(T doc) { _doc = doc; }
}

This class does not define all json properties, but they are ignored when json is mapped to the entity object.
then we can apply fromJson to the json output. This is the all things we need to get the list of entities. But unfortunately, right now, since there is a bug (as mentioned in previous post), this will fails. but if it is fixed, this should work.

  Future> getAll() {
    return _getData("/$dbName/_all_docs?include_docs=true")
        .then( (json) {
          if (json != "") {
            CouchDBFetchData<T> data = jsonMapper.fromJson(
              new CouchDBFetchData<T>().runtimeType, json, attr_redirect_map: {'id':'_id', 'rev':'_rev'});
            return data.rows.fold([], (list, CouchDBFetchRowData<T> row)=>list..add(row.doc));
          } else {
            return new List();
          }
        }).catchError((_)=>[]);
  }

here is the original inefficient, inelegant approach.

  Future> getAll() {
    return _getData("/$dbName/_all_docs?include_docs=true")
        .then( (json) {
          if (json != "") {
            Map data = parse(json);
            for (var rowData in data["rows"]) {
              Map map = rowData["doc"];
              map['id'] = map['_id'];
              map.remove('_id');
              map['rev'] = map['_rev'];
              map.remove('_rev');
              String json1 = stringify(map); // ugry
              T t = jsonMapper.fromJson(modelType, json1);
              ts.add(t);
          } else {
            return new List();
          }
        }).catchError((_)=>[]);
  }

Tuesday, October 8, 2013

Dart's reflection details

Since I needed to manipulate reflection library to develop reflective json_mapper, I investigated some fine details of library. And found strange behavior.
So I asked to dart-misc mailing list.
Fortunately these question was answered by Gilad Bracha(main designer of Dart), so it became clear for what I should expect from Dart now.

Following style will return a mirror for generic class 'declaration'.

ClassMirror cmirror = reflectClass(new List<A>().runtimeType) 
(ClassMirror cmirror = reflectClass(List<A>)) // not supported yet

the above cmirror correspond to the generic class 'declaration', which is equivalent to none applied generic type, so the type including type variables in the generic class still contain type variables when it is inspected by reflection library. This is called a generic declaration.

So the strange things are even List<A> are applied generic class(type variable are substituted by A), but the  reflectClass returns List<T> class which does not corresponding to any runtime type of an object. I don't know why this is so designed, but this is confusing, and quite useless return result for most of the applications.

But as long as there are some way to return Type of applied generic class, it will be OK.
in fact, there is such a way, but it would be difficult to know without having told the difference!

This will return a mirror for applied generic class. (but not complete yet.. since there is a bug now)

ClassMirror cmirror = reflect(new List<A>()).type;
(ClassMirror cmirror = reflectType(List<A>)) // not supported yet

This cmirror is corresponding to applied generic class, and if we do print  cmirror.reflectedType, it prints List<A>.
So it seems OK, but in fact, I already knew this was not OK.

For json_mapper, we need to get field's type in order to process sub json string.

but if we run following code, the field types are none applied generic types. namely including type variables, not substituted by applied types.

ClassMirror cmirr = reflect(new List()).type;
    print(">>0@@ cmirr.reflectedType: ${cmirr.reflectedType}");
    cmirr.getters.forEach((k, MethodMirror md){
      Type tm = null;
      if (md.returnType is ClassMirror) {

        tm = (md.returnType as ClassMirror).reflectedType;
        print(">>1@@ k: ${k}, tm: ${tm}");
      } else if (md.returnType is TypeVariableMirror) {
        TypeVariableMirror tvmirr = md.returnType;
        print(">>2@@ tvmirr: ${tvmirr.runtimeType}");
      }
    });
output:

>> type: ChouchDBFetchData
>>0@@ cmirr.reflectedType: List
>>1@@ k: Symbol("length"), tm: int
>>1@@ k: Symbol("_capacity"), tm: int
>>2@@ tvmirr: _LocalTypeVariableMirrorImpl
>>2@@ tvmirr: _LocalTypeVariableMirrorImpl
>>2@@ tvmirr: _LocalTypeVariableMirrorImpl
>>1@@ k: Symbol("isEmpty"), tm: bool
>>1@@ k: Symbol("isNotEmpty"), tm: bool
>>1@@ k: Symbol("reversed"), tm: Iterable
>>1@@ k: Symbol("iterator"), tm: Iterator

So essentially right now, there is no way to handle generic class properly.
Fortunately, Gilad agreed this is bug, and google teams is now working on fixing this problem. Actually this is a big bug.

So maybe we will get better mirror lib soon.
Other related issues seems also addressed later release.

like reflectClass(typedef List<A>)(here typedef keyword is 'required' to avoid parsing issue..)
and 'invariant'  reflectType, which probablly it returns applied generic class.

here is his answers:
I've been meaning to update the mirror tutorial on our site, but because significant changes are coming soon, I'm delaying that just a tad longer. That said, those changes have nothing to do with this issue, so I'll try and answer your question here. Bear with me, as it is slightly non-obvious and requires some background.

(A)  ClassMirrors reflect both the classes of objects and class declarations. What's the difference between the class of an object and a class declaration?  Well, in a world without generics you can leave the distinction to philosophers, but once you have generics, you want to distinguish between the one declaration of the generic (i.e, the declaration in the source code) and its many invocations (such as List<String>, List<bool> etc.), aka parameterized types.  All the invocations share the same declaration.

This matters when you ask a class mirror for its methods, and then look up a method and ask for its return type. If the mirror is on List<int>, then the return type of the method #first will be int; if it is List<Element> it will be Element etc.  If ask the same question on a declaration, the return type is E, which is a type variable (and no actual object has a type variable as its type; the type variable is always bound to some specific type).

There is never an object whose type is a generic declaration. Hence there is no Type object that corresponds to a generic declaration, and so a mirror on generic declaration has no Type object associated with it. Which is why hasReflectedType on such a mirror returns false. If you still try and get the reflectedType, it throws. 

Hence the behavior you are seeing. 

Now you might ask why.  We could have reflectClass give you a mirror on the specific Type you passed in, and then the invariant you expected would hold. However, then we'd have a problem if you wanted to get at the declaration. If you wrote reflectClass(List) you might well expect the result to be a mirror on the declaration, but you'd be disappointed. Let's say we have a class 

class G<T> ...

In Dart, the identifier G, used without type arguments, always denotes G<dynamic>.  So you would not get a mirror on the declaration of G (or of List) but a mirror on a specific parameterized type (G<dynamic> or List<dynamic> as the case might be).

We decided to keep reflectClass for the declaration. If you want a mirror on a specific parameterized type, you can get it by reflecting on an instance and asking the instance mirror for its type

reflect(new List<A>()).type

we are planning on adding a function reflectType() that would always return a mirror on the specific Type object passed to it. The the invariant

reflectType(t).reflectedType == t

Dart's annotation

I refined the look and feel of sample app using Dart's annotation.

This feature is very useful for customizing a lot of thing without touching the code itself.
So there are quite a lot of area to use annotations.

The annotation mechanism of Dart is quit easy to use, it is also part of dart:mirrors. So in order to use this on browser, we still need to use my portable_mirror library(I extended the API for this).

The things I have done is:
  1. Table
    • remove id and rev column from table
    • change expenseType to type
       
  2. Form
    • disable id, rev text input
These are specified by annotation for the getter  in Expense class.
Also I fixed table so that it has max height and can use scroll.
So this GUI is now looks beter. but it will be useful to support more annotations to adjust look and feel such as ordering specification. location to put text etc.

class Expense  {
  ....
  
  @GUI_Table(invisible: true)
  @GUI_Form(disabled: true)
  String get id => _id;
  void set id(String i) { _id = i; }
  
  @GUI_Table(invisible: true)
  @GUI_Form(disabled: true)
  String get rev => _rev;
  void set rev(String value) { _rev = value; }
  
  @GUI_Table(label: "type")
  ExpenseType get expenseType => _type;
  void set expenseType(ExpenseType i) { _type = i; }
  
  ...
}

Sunday, October 6, 2013

Reflective JsonMapper (Part 3)

Originally I planed to use generics, but now it is better not to call it generic, but we call it reflective.
  
I completed the support of List(and Map) property in Entity class, and this works for both dynamic(with dart:mirrors lib for Dart VM) and static mode(for javascript).
But I haven't tested on javascript mode yet, but it should work. Also I haven't tested the map case. I will do it later.
This version was committed to Github.

Following is the sample code to show the support of List field in a class.

class A {
  int _i = 0;
  List<B> _bs = [];
  
  A(this._i, this._bs);
  factory A.create() => new A(111, []);
  
  int get i => _i;
  void set i(int ii) { _i == ii; }
  
  List<B> get bs => _bs;
  void set bs(List<B> bs) {_bs = bs; }
}

class B {
  String _s = 'zz';
  B(this._s);
  factory B.create() => new B('ss');
  String get s => _s;
  void set s(String ss) { _s == ss; }
}

test_simple_model() {
      A a = new A.create()..i = 10
        ..bs.add(new B.create()..s = "vvv")
        ..bs.add(new B.create()..s = "eee");
      
      String json = sampleJsonMapper.toJson(a);
      print(">>A@1 test_toJson json: ${json}");
      
      A a1 = sampleJsonMapper.fromJson(A, json);
      print(">>A@2 test_Json a1: ${a1}");
}

And the output of execution:
>>A@1 test_toJson json: {"i": 111,"bs": [{"s": "ss"},{"s": "ss"}]}
>> obj: Instance of 'A'
>>A@2 test_Json a1: Instance of 'A'
>> json: {"i": 10,"bs": [{"s": "ss"},{"s": "vv"}]}

Actually the support of generic type property was a bit difficult due to some confusing behavior of reflectedType property of ClassMirror. And some irreversible operation of types and  typeArguments behavior.

But by keeping type instead of extracting from ClassMirror, I could avoid the current restriction of Miror library. Probably Dart is still early stage, such mirror behavior should be refined.

Following are the problems I found:

1) why we cannot do followings:

var t1 = List<A>;
var cmirr = reflectClass(List<A>);

while we can do for none generic class:
car t = A;
var cmirr = reflectClass<A);

2) how can I create ClassMirror object which has reflectedType.
if we create CirrorClass through reflectClass(new List<B>().runtimeType),
it does not have reflectedType. but if we get ClassMirror from  bs of  A, it has a reflectedType. So there should be some way to create Mirror class which has reflectedType.

3) the reflectClass<List<A>) has all information to make cmirror to have reflectedType(since argumentType A is provided).
It should return ClassMirror with reflectedType.
I think this is very inconvenient behavior, and should be called a bug.

library dart_generics_test;

import 'dart:mirrors';

class A {
  int _i = 0;
  List<B> _bs = [];
  
  int get i => _i;
  void set i(int ii) { _i == ii; }
  
  List<B> get bs => _bs;
  void set bs(List<B> bs) {_bs = bs; }
}

class B {
  String _s = 'zz';
  
  String get s => _s;
  void set s(String ss) { _s == ss; }
}

test_generics() {
  {
    /*
    ClassMirror immir0 = reflectClass(List<B>); // <== this cannot be compiled!
    Type t0 = immir0.reflectedType;
    print(">> ${t0}");
    */
    
    // following code is to get a Type of List<B>, a work around to avoid above problem.  
    InstanceMirror immir = reflect(new List<B>());
    Type t = immir.type.reflectedType;
    print(">>1.1 ${t}");
    
    /*
    ClassMirror cmirr = reflectClass(t);
    Type t2 = cmirr.reflectedType; // here t2 == t, but it throws exception
    print(">>1.2 ${t2}");
    */
  /*
   * Unhandled exception:
Unsupported operation: Declarations of generics have no reflected type
#0      _LocalClassMirrorImpl.reflectedType (dart:mirrors-patch/mirrors_impl.dart:304:7)
#1      test_generics (file:///opt/dart-workspace/reflective_web_dev_kit/sample_app/bin/sample_json_mapper_test.dart:76:21)
#2      main (file:///opt/dart-workspace/reflective_web_dev_kit/sample_app/bin/sample_json_mapper_test.dart:81:16)
   * 
   */
  }

  {
    Type t1 = new B("nn").runtimeType;
    print(">>2.1 ${t1}");
  
    ClassMirror cmirr1 = reflectClass(t1);
    Type t2 = cmirr1.reflectedType; // this is ok
    print(">>2.1 ${t2}");
  }

  {
    Type t1 = new List<B>().runtimeType; // return List<B>
    print(">>3.1 t1: ${t1}");
  
    ClassMirror cmirr1 = reflectClass(t1);
    Type t2 = cmirr1.runtimeType; // return _LocalClassMirrorImpl
    print(">>3.2 t2: ${t2}"); 
    print(">>3.3 cmirr1.hasReflectedType: ${cmirr1.hasReflectedType}"); 
    
    Type t4 = cmirr1.reflectedType; // here it should be t4 == t0, but it throws exception
    print(">>3.3 t4: ${t4}");
  }

  {
    ClassMirror cmirr = reflectClass(A);
    cmirr.getters.forEach((k, MethodMirror md){
      Type tm = (md.returnType as ClassMirror).reflectedType; // this is OK
      print(">>4.1 k: ${k}, tm: ${tm}");
    });
  }
}

main() {
  test_generics();
}

Blogger tip: how to use pretty print

I did not like embedding dart code using quote.
So I a bit investigated to support pretty print in blogger.

Following is the way I found:

  •  open template HTML edit
    add following code just before </head> 
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
    • Blogger Template Designer->Adbanced->Add CSS

      Add following codes:
      pre {
      overflow: auto;
      width: 580px;
      
       white-space: pre-wrap;       /* css-3 */
       white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
       white-space: -pre-wrap;      /* Opera 4-6 */
       white-space: -o-pre-wrap;    /* Opera 7 */
       word-wrap: break-word;       /* Internet Explorer 5.5+ */
      }
      
      /* https://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css */
      
      .prettyprint {
          background: #EEE;
      }
      
      
    •  when you want to embed code, use HTML view, and put code snippets in:
      <pre class="prettyprint lang-dart">Code!</pre>
    https://code.google.com/p/google-code-prettify/wiki/GettingStarted

    http://google-code-prettify.googlecode.com/svn/trunk/README.html

    http://google-code-prettify.googlecode.com/svn/trunk/styles/index.html

    But there is an issue for <, >. they will be recognized as special characters(by html parser?), and enclosed parts are not shown. So if we have these characters, we need to replace them with &lt;, &gt; respectively(i.e, in Code).
    This should be handled by run_prettify.js though.

    GUI action design pattern

    The sample app(CRUDView) class is not so clean with respect to the implementation of how mouse action would trigger window state changes, like some button are disabled and the others are enabled etc.

    Each component class should not have to know anything except what they suppose to do, i.e, some state change.

    All the GUI action should be understood as state transition.
     if we append listener to each node's listener, that is still bad.

    the controlling logic is tightly associated with specific GUI action.
    But what the mouse action will change is the state and that state change is the reason for the logic of GUI change.

    so the logic should be centered around the state change.

    for instance, following code may describe the state transition of each mouse click for the buttons.

    state('a1')..>state('a2')['load'] = load
        ..>state('s3')['save'] = save;
    
    state('a2')..>state('a2')['clear'] = clear
        ..>state('s3')['edit'] = edit;
    

    That way, we see the real logic behind the GUI action. often such a  state is not explicitly expressed in the application code as in the current CRUDView code. and action methods are called from many places associated with buttons.
    That messy way should be avoided.


    GenericType spec in test code

    It is always useful if we have a good unit tests to understand the language spec in details. It is much easier to understand from concrete examples than hight level abstract and often ambiguous description.

    For dart mirror, the code API is not useful, and there are not much detailed explanation of mirror features, so I checked   /dart/tests/lib/mirrors/ folder.

    following test code is useful to understand mirror for generic classes.


    // Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
    // for details. All rights reserved. Use of this source code is governed by a
    // BSD-style license that can be found in the LICENSE file.
    
    library test.type_arguments_test;
    
    import 'dart:mirrors';
    
    import 'package:expect/expect.dart';
    
    class A<T> {}
    class B extends A {}            // Same as class B extends A<dynamic>.
    class C extends A<num, int> {}  // Same as class C extends A<dynamic>.
    class D extends A<int> {}
    class E<S> extends A<S> {}
    class F<R> extends A<int> {}
    class G {}
    class H<A,B,C> {}
    
    typeParameters(mirror, parameterNames) {
      Expect.listEquals(parameterNames.map((n) => new Symbol(n)).toList(),
                        mirror.typeVariables.keys.toList());
    }
    
    typeArguments(mirror, argumentMirrors) {
      Expect.listEquals(argumentMirrors,
                        mirror.typeArguments.values.toList());
      if (!mirror.isOriginalDeclaration) {
        Expect.listEquals(mirror.typeVariables.keys.toList(),
                          mirror.typeArguments.keys.toList());
      }
    }
    
    main() {
      // Declarations.
      typeParameters(reflectClass(A), ['T']);
      typeParameters(reflectClass(B), []);
      typeParameters(reflectClass(C), []);
      typeParameters(reflectClass(D), []);
      typeParameters(reflectClass(E), ['S']);
      typeParameters(reflectClass(F), ['R']);
      typeParameters(reflectClass(G), []);
    
      typeArguments(reflectClass(A), []);
      typeArguments(reflectClass(B), []);
      typeArguments(reflectClass(C), []);
      typeArguments(reflectClass(D), []);
      typeArguments(reflectClass(E), []);
      typeArguments(reflectClass(F), []);
      typeArguments(reflectClass(G), []);
    
      Expect.isTrue(reflectClass(A).isOriginalDeclaration);
      Expect.isTrue(reflectClass(B).isOriginalDeclaration);
      Expect.isTrue(reflectClass(C).isOriginalDeclaration);
      Expect.isTrue(reflectClass(D).isOriginalDeclaration);
      Expect.isTrue(reflectClass(E).isOriginalDeclaration);
      Expect.isTrue(reflectClass(F).isOriginalDeclaration);
      Expect.isTrue(reflectClass(G).isOriginalDeclaration);
    
      Expect.equals(reflectClass(A), reflectClass(A).originalDeclaration);
      Expect.equals(reflectClass(B), reflectClass(B).originalDeclaration);
      Expect.equals(reflectClass(C), reflectClass(C).originalDeclaration);
      Expect.equals(reflectClass(D), reflectClass(D).originalDeclaration);
      Expect.equals(reflectClass(E), reflectClass(E).originalDeclaration);
      Expect.equals(reflectClass(F), reflectClass(F).originalDeclaration);
      Expect.equals(reflectClass(G), reflectClass(G).originalDeclaration);
    
      // Instantiations.
      typeParameters(reflect(new A<num>()).type, ['T']);
      typeParameters(reflect(new B<num>()).type, []);
      typeParameters(reflect(new C()).type, []);
      typeParameters(reflect(new D()).type, []);
      typeParameters(reflect(new E()).type, ['S']);
      typeParameters(reflect(new F<num>()).type, ['R']);
      typeParameters(reflect(new G()).type, []);
      typeParameters(reflect(new H()).type, ['A', 'B', 'C']);
    
      var numMirror = reflectClass(num);
      var dynamicMirror = currentMirrorSystem().dynamicType;
      typeArguments(reflect(new A<num>()).type, [numMirror]);
      typeArguments(reflect(new A<dynamic>()).type, [dynamicMirror]);
      typeArguments(reflect(new A()).type, [dynamicMirror]);
      typeArguments(reflect(new B()).type, []);
      typeArguments(reflect(new C()).type, []);
      typeArguments(reflect(new D()).type, []);
      typeArguments(reflect(new E<num>()).type, [numMirror]);
      typeArguments(reflect(new E<dynamic>()).type, [dynamicMirror]);
      typeArguments(reflect(new E()).type, [dynamicMirror]);
      typeArguments(reflect(new F<num>()).type, [numMirror]);
      typeArguments(reflect(new F<dynamic>()).type, [dynamicMirror]);
      typeArguments(reflect(new F()).type, [dynamicMirror]);
      typeArguments(reflect(new G()).type, []);
      typeArguments(reflect(new H<dynamic, num, dynamic>()).type,
          [dynamicMirror, numMirror, dynamicMirror]);
    
      Expect.isFalse(reflect(new A<num>()).type.isOriginalDeclaration);
      Expect.isTrue(reflect(new B()).type.isOriginalDeclaration);
      Expect.isTrue(reflect(new C()).type.isOriginalDeclaration);
      Expect.isTrue(reflect(new D()).type.isOriginalDeclaration);
      Expect.isFalse(reflect(new E<num>()).type.isOriginalDeclaration);
      Expect.isFalse(reflect(new F<num>()).type.isOriginalDeclaration);
      Expect.isTrue(reflect(new G()).type.isOriginalDeclaration);
      Expect.isFalse(reflect(new H()).type.isOriginalDeclaration);
    
      Expect.equals(reflectClass(A),
                    reflect(new A<num>()).type.originalDeclaration);
      Expect.equals(reflectClass(B),
                    reflect(new B()).type.originalDeclaration);
      Expect.equals(reflectClass(C),
                    reflect(new C()).type.originalDeclaration);
      Expect.equals(reflectClass(D),
                    reflect(new D()).type.originalDeclaration);
      Expect.equals(reflectClass(E),
                    reflect(new E<num>()).type.originalDeclaration);
      Expect.equals(reflectClass(F),
                    reflect(new F<num>()).type.originalDeclaration);
      Expect.equals(reflectClass(G),
                    reflect(new G()).type.originalDeclaration);
      Expect.equals(reflectClass(H),
                    reflect(new H()).type.originalDeclaration);
    
      Expect.notEquals(reflect(new A<num>()).type,
                       reflect(new A<num>()).type.originalDeclaration);
      Expect.equals(reflect(new B()).type,
                    reflect(new B()).type.originalDeclaration);
      Expect.equals(reflect(new C()).type,
                    reflect(new C()).type.originalDeclaration);
      Expect.equals(reflect(new D()).type,
                    reflect(new D()).type.originalDeclaration);
      Expect.notEquals(reflect(new E<num>()).type,
                       reflect(new E<num>()).type.originalDeclaration);
      Expect.notEquals(reflect(new F<num>()).type,
                       reflect(new F<num>()).type.originalDeclaration);
      Expect.equals(reflect(new G()).type,
                    reflect(new G()).type.originalDeclaration);
      Expect.notEquals(reflect(new H()).type,
                       reflect(new H()).type.originalDeclaration);
    
      // Library members are all uninstantaited generics or non-generics.
      currentMirrorSystem().libraries.values.forEach((libraryMirror) {
        libraryMirror.classes.values.forEach((classMirror) {
          // TODO(12282): Deal with generic typedefs.
          if (classMirror is! TypedefMirror) {
            Expect.isTrue(classMirror.isOriginalDeclaration);
            Expect.equals(classMirror, classMirror.originalDeclaration);
          }
        });
      });
    }