Showing posts with label TODO. Show all posts
Showing posts with label TODO. Show all posts

Friday, October 25, 2013

ORMapping in Dart

A persistence support using relational DB is very basic requirement for any real world applications.
Right now, there seems no such tools available in Dart.
but there are a few DB driver for SQL server.
in this situation, what we can do in simplest way would be following.
  1.  delegate generating db scheme to JPA. In order  to do this, we use the same annotation as JPA in Dart class. and from this dart class, using reflection, we generate Java source code with the same JPA annotation defined in the dart class. The rest of generating scheme in db can be automated in some script.
  2.  Once we had a db scheme, we can access db. one way is to use Java itself to access db and Dart will access the object as Json through web API, but this approach may make system complicated since Dart needs Java server. So if we avoid intermediate Java and can directly access DB, that would be more simple approach.Since Dart class has already annotations, so it should be possible to provide reflection based plumbing to map row data to entity properties.
 Normally we will need to start from defining abstract(interface) class for db entity(table).
then we need to provide the implementation class for this interface.
But manual implementation of such implementation class are tedious and mechanical. It should be automated. One way is just to generate such an implementation class from the interface classes. But code generation approach often create more problem for maintenance etc. So it is better to avoid this approach. Also code generation bloat the code size, and it will not good approach for running on client side.

but if we define abstract class we need to define another class implementing the methods, so in this approach, we cannot avoid code generation.
So we need to define a concrete class which has no db mapping codes.

The simple solution for this is just using inheritance.

@Entity()
@Table(name: "A")
class A extends Persistence {
    @Id()
    @Basic(optional: false)
    @Column(name: "id")
    String _id;

    @Basic(optional: false)
    @Column(name: "i")
    int _i;
    
    @ManyToOne()
    B _b;

    @OneToMany(mappedBy: "a")
    List<C> _cs;
    
    String get id => get(const Symbol("id"));
    void set id(String v)=>set(const Symbol("id"), v);

    int get i => get(const Symbol("i"));
    void set i(int v)=>set(const Symbol("i"), v);

    B get b => get(const Symbol("b"));
    void set b(B v)=>set(const Symbol("b"), v);

    List<C> get cs => get(const Symbol("cs"));
    void set cs(List<C> v)=>set(const Symbol("cs"), v);
}
we define persistence root class called Persistence. This class will use reflection for intercepting getter/setter to access database. The only annoyance is we needs to define getter/setter calling methods get/set defined in the Persistence class. This would be a reasonable compromise. If dart has a build-in intercepting mechanism for getter/setter, we may further skip this definitions, and it may be a good proposal for Dart language..

The basic idea required to implement the Persistent class is the same as Monitor class, but it uses different annotation(JPA style), and will have SQL Driver access codes.

Another aspect of OR mapping is query. Often they introduce new query language mainly to avoid join operation. So we may create such query language or implement some standard query language in Dart, but we may just use ordinary SQL for this purpose. if it uses many-to-many relationship,  JPA creates intermediate table so writing query require such knowledge, but other relationships , the db table representation is simple. (and it is better to avoid many-to-may to simplify the db scheme).

So I think I will just go with SQL query based approach.
 But still some idea from https://github.com/polux/parsers, may be used to implement simple query language.

Wednesday, October 16, 2013

Implicit Delayed Initialization of GUI Components with Reflection

Previous sample code is a bit inferior compared to polymer HTML GUI specification style since the layout related codes were scattered around many places. It should have more declarative specification gathered in the close places.

One of the main reason for this mess was these sub components need to know the parent and it is impossible to get access in field declaration parts. So they must have been moved to constructor.
Also attribute related specification clutter the codes.

We can fix these issues by introducing two ideas.
  1.  use annotation for sub components in which attribute specification(small GUI related information, will be specified.
  2.  Implicit delayed initialization of sub components. This means when a component is instantiated, it will inspect these annotated sub component fields, and set the parent and additional information depending on the annotation and its parameters. The nice thing about this approach is that this procedure is recursive.
    when  the component is created, it starts initializing the sub components whose sub components are already initialized when the sub component is created.
Followings will be the new way to define layout.

class NameBadge extends Component with Monitor {

  @UI_TextInput(label: "Enter New Name:", String)
  final TextInputComp textInput = new TextInputComp();
  
  @UI_Button(label: "Generate pirate name")
  final ButtonComp button = new ButtonComp();
  
  @UI_Radio(label: "Male", name:"maleOrFemale")
  final RadioComp maleRadio = new RadioComp();
  
  @UI_Radio(label: "Female", name:"maleOrFemale")
  final RadioComp femaleRadio = new RadioComp();
  
  Element _createElement(Element elm) => 
      elm
        ..nodes.add(
            new Element.div()
              ..classes.add("entry")
              ..nodes.add(textInput.element)
              ..nodes.add(button.element)
              ..nodes.add(maleRadio.element)
              ..nodes.add(femaleRadio.element))
        ..nodes.add(
            new Element.div()
              ..classes.add("outer")
              ..nodes.add(new Element.div()..classes.add('boilerplate')..text = 'Hi! My name is')
              ..nodes.add(_initDiv0(new Element.div()..classes.add('name')..text = _badgename)));
  ...

  NameBadge(Component parent): super(parent, const[APP]) {
    this.button.onClick((e) { badgename = pirateName(); });
    this.maleRadio.onClick((_, comp){ male = true; });
    this.femaleRadio.onClick((_, comp){ female = true; });
    ...

Thursday, October 10, 2013

JsonMapper and JPA

One area I haven't investigated for Jason Mapper is the case where entity  have general network structure rather than tree structure where no sharing of objects occurs

I need to check how dart handle such cases, for parse, stringify.
When I checked the dart:json code, there was a code to check repeated occurrence  (for the recent version of Json lib.)

for stringify, if it does not check, either the same entity will be serialized repeatedly, and worst, if there are circular references, it will go into infinite loop.

for parse, essentially original json string need to have some id information so that other part of json code can refer to it.
when json see new json id, it may not be loaded yet, so substituting the actual object must be delayed until that object is created. so the fromJson will be more complicated.(but it will be still simple if we push closure to assign to the entity field  with given parameter, and when object is created with given id, it should  retrieve those closures and apply them with the newly created entity object.)

There is a Java project called jackson, I guess it will handle such cases, and if there is a some notation to represent such reference in json, Dart's json mapper should follow the convention.

This is important, since json is good format to communicate Java and Dart.
 If both are following the same format, we can pass Dart's object to Java, and vice versa.
This may happen through Dart's VM and JVM message passing protocol similar to Dart's  javascript call mechanisms (although I don't know if such lib exist now), or through HTTP protocol using REST style API such as CouchDB.
Both approaches are relying on converting an entity object to json string.

The useful application of this approach will be the support of JPA(Java Persistence API) in Dart.
It will be achieved by a Restfull service in HTTP server implemented by Servlet where the mapped Java object are to be serialized to Json string(using Jackson).

Since building JPA like service in Dart will be not simple task, this will be a quickest  way. the main problem will be some performance issues for server side Dart's access to JPA.(For client side, if it directly calls this servlet service, there should be no performance issues.) 
But such loosely coupled architecture will allow to use separate CPU cores for JVM to run Java Servlet for JPA and Dart VM to run HTTP client(server) to consume(provide) JPA services from servlet, so it may not be so inefficient.

Also if we provide such restful service, it may be called directly from client side (browser).
We may consider an additional query for Restful API in which query condition can be expressed as a dart expression  like CouchDB (CouchDB uses JavaScript for such filter function).
This may require some dynamic loading of Dart code, so it may not be so straightforward, but it may be interesting to investigate the possibility.

For such a binding, there should be a tool to map between Dart and Java persistent classes.
One direction is to start from annotated Dart classes, and generate corresponding Java JPA entity classes with the same annotation.

The other direction is to start JPA Entity Java classes, and generate Dart annotated classes.

For this end, we should define Dart annotation classes corresponding to JPA annotation classes in Java.

Monday, September 30, 2013

Injecting DBDriver/Logger, AOP in Dart

In order to have GUI component, each component should not have a direct dependency to a specific driver. For instance, in the sample app, AppController has reference to CouchDBClientDao, but we if want to allow other DB driver later, that should not be directly defined in the component class.
This issue can be handled in Java as annotation based injection. JPA entity factory etc can be injected through annotation.

In order to support this, there will be a few approaches.
One approach is to simulate Java's approach. but it requires a special run time lib support for actual injection. So these are actually not within an ordinal programming control, and create some opaqueness for the code behavior, so I actually do not like this idea much.

The other approach is to delegate this injection job to code(programmer) itself. Anyway entry program needs to do some environment setting job normally, adding a task to inject code to appropriate library is not much big deal. and it will allows programmer 100% control over what is happening in program execution time.

then how can we find the location of the class(instance) to inject db driver.
sometimes that component are in deeply nested from top level component node.

That time we may use query feature defined at Component class.
This approach is similar to query in Dart.
To inject to annotated filed for an instance, whenever instance is created, this injection code must be applied. So instance level injection is a bit costly operation.

Or the other hand, static class level injection can be done only once, so this should be efficient.
for instance, dbdriver, logger can be injected to a  static filed.



Saturday, September 28, 2013

Entity annotations for GUI/Persistence

It is useful to use annotations to excludes hints information from the main source code and to avoid cluttering files which are used in program but not integrated in language source code file system.
Such files will become maintenance problem later.

There are mainly two usage cases for entity class.
  • GUI annotation. for instance, we may want to use customized label name other than default field name, we can attach such information as annotation for the getter definition.
  • Persistence mapping. This is essentially the same as JPA. we may want to more info how OR or DB scheme is associated with the entity.


CouchDB and generic DAO class

Generic GUI and CouchDB will be a good match.
Since Couch does not require scheme definition, it will be possible to develop generic  class to support CRUD features.

class DAO<T> {
 void  save(T t);
 void update(T t);
void delete(T t);
Iterable<T> query(String condition);

}

In particular, such application will be running on server side, we will not have constraint using mirror.

Actually I already created such library for DartExpenseServer mentioned in earlier post.
One of the issue was to support a mapping to/from Json object for the entity class.
In the application, this mapping methods were hand coded. But it is desireble to automate this step by a library.

Such Library should be easily implemented with mirror.

Restriction of Mirror in JS mode

I almost finished developing CRUD features for generic GUI library.



It just consists from Table and Form, and additional supporting components for Input.
Although there are more rooms for refinements, but it's working and written as I hoped.

The size of code is quite small, and is general enough.
For this type of library to be meaningful, it must be easily customized without touching the library itself.
In order to do so, it provides mechanism to inject features from outside.

Also it defines some basic patterns, like create, update to follow so that recursive operation would work properly.

But when I tried running it with javascript mode, I found out it does not run.
It looks like such mirror features are not yet supported in javascript mode.(there is a note on 5/2013).

Also there is an issue for the generated javascript code.
if we include dart:mirrors, the current code generates  7238 total methods!(impressive, I will never able to write such lines(methods) of javascript code)

Out of it,  5318 methods retained for use by dart:mirrors.
(But still my codes generated 2000 methods!)

So it seems not good idea to use dart:mirror for javascript mode.

One of the approach to overcome this restriction, and run generic GUI library application on browser is to avoid using mirror library itself.
This can be done if we generate an implementation class for some mirror like API  from concrete classes which is used in a application.

And we can also use two versions of implementations, one is for Dartium mode using the mirror library,  and the other is for javascript mode, the implementation classes are to be generated by a Dart application in Dartium mode.