Monday, December 9, 2013

If you love Code Generation, you must love Aspect programming too !

Being a lazy person I love Code generation ! I dont want to waste my life in writing same code again and again and sacrifice movies I could have watched in that time ! ;) That reminds me the great Bill Gates'  great quote, "I would rather hire lazy person for the job, because he/she will find easier way to do that !" !

So code generation, if some tool is there to generate code for you, why not ! I have used primarily Spring Roo and AndroMDA for Java. Both have fascinated me so much ! . AndroMDA for it's generate-from-UML approach and Spring Roo from it unix like shell . AndroMDA is also open-source and comes from a small country in Europe and Spring Roo, as name suggests , its from popular Spring guys.

Little bit about AndroMDA and Spring Roo :

If you have not used one or both of them I am sure you would be curious to know at least basics. AndroMDA - Let's you draw UML and give "stereotypes" lets you apply stereotypes to your objects. For example, stereotype "Entity" makes a class a database entity with all hibernate code for it, "Service" stereotype adds transaction boundaries to methods of that class and lets you add Dao as dependencies on service . So for AndroMDA , UML -> XMI -> Cartridges -> Java/XML code is the way to go. AndroMDA lets developer to worry about implementing  *Impl classes only where you add business logic. These Impl classes obviously extend from base classes where most of the stuff like CRUD operations , validating passed objects are done. Authors of AndroMDA guys are not glamorous and do not come from valley, but the work they have done is amazing.

For Spring Roo, you say on command line to generate an entity , for example, "entity jpa --class ~.domain.AppUser", Roo generates main POJO with annotations to make it an entity but it adds all the code using Aspects, specifically called ITD intertype-declarations. These Aspects add functionality such as CRUD operations on entity, finder methods etc.

Why you should love Aspect Programming if you love Code generation : 

Because aspects supports your laziness even further ! Being in love with code generation, I am sure you are fond of things to work with lightening speed ! You have all the knowledge of how things work , you want to show your friend how you can create website or an app on Friday evening while having beer. You also want to follow best coding practices ! See laziness is not just one reason to use code generation ! :) All these great developers who developed these code generation tools, follow ( and have to follow) best practices !

What is Aspects !?

Typical definition of Aspect programming as per Wikipedia is "is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns.". This word Cross-cutting concerns is bit confusing. It gives feeling that Aspects are limited to logging, security etc. Typical example of cross cutting concern is " aspect saves to have logging code dispersed into your all your code. Instead you write one aspect to print incoming or outgoing parameters and it will log for you. Typical Aspect for logging incoming parameters looks like this 

    pointcut thePointcut(String userid, String password) :  execution(* com.mycompany.backend.web.AppUserController.theMethodToIntercept(..)) && args(userid,password);

    Object around(String userid, String password) : thePointcut(userid,password){"User trying to login : " + userid); // Here logging without touching original method "theMethodToIntercept"
        return proceed(userid,password) ;

Though Aspect promoters say several times that Aspects can be used for better purposes than just logging and security, I have seen developers not getting where they can use Aspects to make their life easier. Aspects evangelists may forget to mention about its big use in project based on code-generation, where developers would understand better how Aspects can make things even easier for them. 

Example of AspectJ users other than just "logging" :

Here is typical example. There is an entity called AppUser in your domain. Roo has generated CRUD operations for you for that entity. When you create user, the password for user should be encrypted. But here you may end up overwriting/overriding the Create method Roo generated for you. Instead if you write "before" or around aspect on that method, your encryptiion code is isolated, you did not have to touch or override the code Roo has generated for you, allowing code-generation (here Roo) to evolve independently. What you are doing here is adding your code like a decoration on the original code. 

Here is example of code generated by Roo to create AppUser :

    @RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> AppUserController.createFromJson(@RequestBody String json) {
        AppUser appUser = AppUser.fromJsonToAppUser(json);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        return new ResponseEntity<String>(headers, HttpStatus.CREATED);

Here is example of the password encryption Aspect which can be added which takes effect before above method is called,

    pointcut aroundCreateUser(String jsonUserString) : execution(* com.softrism.sencha.backend.web.AppUserController.createFromJson(..)) && args(jsonUserString);

    Object around(String jsonUserString) : aroundCreateUSer(jsonUserString){

        AppUser appUser = AppUser.fromJsonToAppUser(jsonUserString);
        ShaPasswordEncoder encoder = new ShaPasswordEncoder(256);
        String password = appUser.getPassword() ;

        String encoded = encoder.encodePassword(password,null);
        String finalJsonUser = appUser.toJson();

        ResponseEntity responseEntity = (ResponseEntity)proceed(finalJsonUser);

        return new ResponseEntity<String>(appUser.toJson(),responseEntity.getHeaders(), responseEntity.getStatusCode());

Now just take your aspects across your Roo or AndroMDA projects :

If  your user entity name is AppUser in all the projects, you can move the aspect as is , if you change the name, just change the name of aspect as per that project. Thats it. User password encryption code just added in a snap in your new projects. Plus, your code-generation tool can independently evolve and there is no need to change anything with your custom code. 

There are so many of such needs where you have to repeat the code like password encryption. So combination of code generation and aspect make it so easy for you to reuse the code that you catch one more flick this evening ! ;)

Monday, November 25, 2013

Waiting for Hybrid-HTML5 to beat Native :)

I remember year of 95/96 when everybody was trying to learn visual programming such as Visual C++, Visual Basic . Microsoft Windows was reigning and native windows development as well. Nobody thought browsers taking that place before Netscape was released. The native windows applications were connecting to remote servers whenever needed.

Browsers picked up and that gave birth to companies like Google, and we, end users, started using browsers more than any downloaded windows applications. Now we use browsers just for anything. In fact, devices like Chrome Notebook is primarily browser based.

After iPhone was released, same series of scenes appear, only difference is the devices are mobile rather than heavy desktops or laptops. iOS and Android developments are still reigning as of end of 2013. Me, as web professional, are waiting for the same switch over happening in mobile ! For me, it's time for world to switch to hybrid native applications which are actually websites running under the native shell.

Different thing about this "history-repeat" is, there is no Microsoft equivalent. What i mean, there is nobody pushing back against web on mobile rather than native applications as Microsoft did in 90s. Though making millions of dollars in native app distribution, both Apple and Google are are supporting mobile -web as much as possible by improving browsers release by release.

There are several frameworks of Javascript, HTML and CSS combinations in the market which works well on all mobile platforms. For example, Sencha Touch which makes web-app looks like exactly same as native app, jQuery Mobile falls in same category. And there are tons of them like backbone.js, angular.js to name a few. There are CSS libraries like Bootstrap to make same website look good using responsive web approach.

Apple/Google has provided WebUIView component in their iOS and Android framework, which lets you embed your "web based" code inside wrapper of native shell. That means, you can download the web-app as native app, but the code inside the native app is nothing but web technologies code using HTML, Javascript and CSS.

There is PhoneGap to fill the gap between native cutting edge features and web-app hidden under the native shell. PhoneGap not just lets you embed the web-based code inside native shell using WebUIView, it provides javascript API to all these newly released hardware features so that it can be used by web code.

All this information above is not new anymore at least end of 2013, what keeps me wondering, despite all these opportunities, what is the reason hybrid web is not picking up compared to native platforms ? What is the most important reason, out of

  1. HTML5 does not look as cool as fully Native Platforms.
  2. Most of the apps are already developed using native platforms, making it very slow adoption of hybrid apps.
  3. The gap-fillers like PhoneGap always lag behind at least a bit compared to native. For example, if Apple introduces NFC, how much time it will take somebody to create PhoneGap plugin to leverage its in web world ?
  4. HTML5/Javascript apps performance is not yet comparable to fully-native apps. But this reminds me of FastBook app developed by Sencha itself which is replica of native facebook app and runs faster ! 
  5. Is web crippled by dynamically typed Javascript compared to strongly typed Java and Objective-C ?
  6. Is web slowed down because there are just too many options when it comes to choose framework for HTML5 ? HTML, dynamic nature of Javascript and CSS combination can give birth to thousands of design patterns. May be its good for the developers who know stuff and can choose easily, but what about those who just get more confused ?
  7. Are native developers salaries more compared to web developers ? :) 
  8. Does hybrid app fall short in security compared to fully-native ?
  9. Are development environments for web like Chrome Developer Tooklit can not compete with Xcode and Eclipse ?
  10. Are iOS and Android just most popular buzz words and developers go behind buzz words ?
I never thought I would come up with around 10 differences which might be making hybrid-mobile apps slower to pick up than native. If you read this blog entry, do comment which one you feel is most important reason and which one is least !

Thursday, January 24, 2013

Pros and Cons of merging web and backend java app on Cloudfoundry

For my application, there are two components. Web Application and background scheduled job . Web application is developed using Spring Roo and scheduled job is built using Spring batch.

Ideally I want to have these two separate projects and deployment for obvious reasons ! But here is problem, Spring-batch scheduled job requires two datasources. One for its own meta-data and other my primary transaction database.

My cloud environment is VMWare's cloudfoundry. When Cloud-foundry deployment environment detects there are two beans with javax.sql.Datasource, it can not auto-reconfigure the datasource to Cloudfoundry service.

In other words, if there is only one javax.sql.Datasource bean in your app, cloudfoundry automatically detects it and connects it to the database service instance. but if there are two beans like that , the code needs to specifically mention which database service each bean needs to use.

Thats where there is "cloud" namespace which you can specify cloud databases in XML itself. But as anybody can guess, once I have that code in XML, my app will stop working in local environment.

So for now, its better to merge my both apps as long as load on the apps is less.

My tweets on similar topics