Saturday, July 9, 2016

Romance between Java and Javascript

I recently read about JavaPoly.js, a javascript library, I could not stop myself writing poem on it! It lets you write or use java code (as-is/compiled/jarred) in the browser itself, in place of Javascript !!! Hopefully it will finally fulfill need of strongly typed language for browser applications.

So here is the poem :) I hope I could express my feelings about the war against Javascript me and my team is facing for decades :)

JavaScript lets me sleep, while I write my code,
                But I am sleepless after release, in "firebug" mode!
Java showed me how object oriented is cool,
                When JavaScript tried same, reminds me of an ugly mule!
Why was JavaScript created? I think to kill,
                Java was created, to make coding a zeal!
Why can’t I use, my strong and steady java code,
                In that browser, which is plagued by JavaScript code!
But then I read about JavaPoly,
                I remember my school sweet-heart Dolly,
She talked “verbose”, but everything made sense,
                Now between front-end and back-end, there is no more a fence!  

Having burned my hands (actually finger-tips) while dealing with the whims of "loose" Javascript compared to Java, I used to wonder why was even Javascript devised ?  That too with the name so close to Java. Please ! I totally agree the phrase "Java is to Javascript as Ham is to Hamster" ! I heard Javascript was originally created  in just 10 days when Netscape was released in 90s. No wonder it has some crazy birth defects and even it's dad, Douglas Crockford had to take his child to "shrink" (psychiatrist) and hide those birth-defects and write a bible on only good side of Javascript !

Can It Be A Major Breakthrough ?

I thought JavaPoly is an incredible concept and if it works good, it would be a major breakthrough in front-end development! Imagine this line in your HTML and calling methods of somejava.jar from Javascript !

<script src="https://www.javapoly.com/javapoly.js"></script>

<script type="text/java" src="http://www.verient.com/somejava.jar"></script>

<script type="text/javascript"> com.your.package.doSomething()</script>


Now if you are really into it and got a quick hint what it can do, you will surely appreciate that poem came to my dumb poet mind !

As usual when you dig bit deeper, you always find that all beautiful things have foundation of something very robust on which these cute aromatic plants like JavaPoly grow. Here, there is Doppio JVM. This is JVM written in Javascript ! JavaPoly is actually polyfill on top of the JVM (Polyfill out of the scope of this article)

All JVM Languages ! Not just Java.

I got so excited about the concept, I contacted project-lead John Vilk directly and got some more information. Since this is a pure JVM. It supports all JVM based languages, for example, Scala, Jython, Go, Clojure etc. Are you kidding ? I mean, imagine if this really works ! It will change total Javascript/HTML5 Ecosystem !

I believe too flexible nature of Javascript plus combination of HTML5/CSS3 features and need for Native development, have given rise of just too many patterns giving rise to too many Javascript frameworks. It has also given birth (and deaths) to many strongly typed Javascript based languages, called "compile-to-javascript". But it didn't seem to work except little bit for CoffeScript and now TypeScript. Remember Dart by Google ? When was it's funeral ? All these approaches brought the annoying feeling of "please, no more new language to learn". But with DoppioJVM the new language is nothing but our best old friend called "Java".

This is JVM written in javascript, to be specific, in TypeScript (just like typical JVM is written in C) which you include in your HTML just like any other js. And now you are free to write Java code instead of Javascript. 

Don't Remind Me Of Those Applets ! 

I understand readers might still ask question "you mean, you dont need to download jvm on the machine?" The answer is of course not ! Don't you remember ugly days of Applets development ? Why applets failed miserably ? The idiotic installation issues of Sun JVM on user's machine ! And because of that, the "Mad King" ruler called "Flash" reigning for decade in browser productivity ? But the king was always outsider (plug-in) and finally was defeated and ousted by real world Silicon Valley king with name "Steve Jobs"! 

So defeat of "Flash" was one more reason browser development companies like Google/FireFox and apple itself, started focusing on HTML5 and Javascript. 

Advantages and Of Course, Disadvantages 

The obvious advantages of this appraoch of JVM written in Javascript,

  1. "Finally, the final" strongly typed language for complex browser applications
  2. Real Multi-threading
  3. Familiar File I/O which use browser storage
  4. Familiar Network I/O using browser Websockets
Of course, performance still looks like major hurdle in getting ahead of the game. I tried few java classes/code in the shell provided on DoppioJVM's site, it still has a way to go as far as performance is concerned.

15 years back, I had heard somebody saying he was into "Object Oriented Javascript", I laughed at that time, felt like the guy was just trying to use the buzzword "Object oriented". But then later, when I realized power of Javascript in Object Oriented, I was shocked and was impressed. I did start to respect JavaScript as very powerful language. But still as a Java professional, was not happy with the way Object Oriented was being achieved. I understand there is ES6 coming which is very close again to Java and will make things easier. But still the very big advantage of JavaPoly and Doppio is, reusing the vast work done by millions of developers in Java and reusing that. 

Java on server and JavaScript on browser, always sounded like good marriage but the fact that JavaScript just used "Java" as part of it's name, always sounded cheating too ! :) The JavaPoly/Doppio will revive the romance between the two, I hope, I wish and I really wish (did I say the same thing again again ? ) 

Sunday, March 15, 2015

OSGi : Will these (now) nano-services survive ?

OSGi Reading Survival Guide ?
Last year, I started hearing so much about "micro-services", without reading much about it, i threw a question on Twitter, "Is micro-services same as OSGi ? " . I got an answer from the man who loves starbucks (@starbuxman Josh Long from SpringSource itself ),  that "Nope, OSGi expose services in same JVM but micro-service (usually) does over REST ! "

The first half of the comment I could understand being user of OSGi, but micro-services expose services over REST was new to me (At least around an year back when I started writing this blog entry but never finished!) . Then I realized why Spring Guys are so much for Spring-Boot where servlet container is embedded in the "public static void main" type of applications and that's why Spring Boot helps to create micro-services very quickly.

In order to stick to the title of the blog, let's focus on OSGi. Actually, the name "micro-service" does sound close to OSGi's offering given its nature of "bundle-as-a service". Since OSGi bundles are nothing but small jars exposing services, i thought it would be ok calling those services as "nano-services" compared to Micro-services :)

As far as I understand, OSGi is and was always on the fence whether should be accepted or not (by developers). That's why, I wonder what's the future of OSGi ! If we really try to find out, this division would be really 50-50%. Means 50% developers love it and 50% hate it. And after using OSGi,  I totally can understand why !

Basics of OSGi : As per Wikipedia (it is always good to get official definitions copy-pasted !) - The OSGi (Open Service Gateway initiative) specification describes a module system and service platform for the Java programming language that implements a complete and dynamic component model, something that does not exist in standalone Java/VM environments.  Applications or components, coming in the form of bundles for deployment, can be remotely installed, started, stopped, updated, and uninstalled without requiring a reboot; management of Java packages/classes is specified in great detail.

Under OSGi, all our usual jar files become "bundles". Bundle is self-contained, self-described piece of "service" which exposes its functionality using mechanisms like service-registry. So even if you don't need a particular jar as a bundle, you still have to generate bundle from the jar. There are several ways to convert a jar into bundle with just one command. I am heavy user of Spring Roo which is built upon Felix OSGi container. It contains very easy commands to convert any jar into bundle.

Whole information of the bundle is inside MANIFEST file of the jar. Every jar file has MANIFEST file, but usually ignored in usual monolithic environment of JVM. But in OSGi, it is of high importance and all information of the bundle is configured using this file. For example,

Bundle-Name: Hello World
Bundle-SymbolicName: org.wikipedia.helloworld
Bundle-Description: A Hello World bundle
Bundle-ManifestVersion: 2
Bundle-Version: 1.0.0
Bundle-Activator: org.wikipedia.Activator
Export-Package: org.wikipedia.helloworld;version="1.0.0"
Import-Package: org.osgi.framework;version="1.3.0"


My Experience with OSGi : I personally got very impressed with OSGi's modularity. Other reason was to manage lifecycle of OSGi bundles remotely and installing the bundles in the run-time was good advantage. Not that, we were having very high availability requirement, we could have stopped the server for a second and two and restarted. But still having this provision of getting things done without any downtime sounded a great advantage. Plus the system where we wanted to use it was in need of modularity because we needed several custom parsers to parse different file formats and convert them into our internal format for file processing. Our architect @diligentbytes did great job of finding this as a perfect candidate for OSGi. He used spring-integration and it's "channel" was the service exposed by the bundles and the bundles talked over those channel/services.
Can not find the class ! 

Problems Faced : Since many of jars were using XML based spring configuration, we had a hard time to manage import and exports of the bundle (see Export/Import package headers above) . XML wiring could not be detected by bundlors easily, resulting into missing import and exports in manifest file. Had to deal with several ClassNotFoundExceptions. I started feeling OSGi should be called as CNFE Framework ! :)

So we ended up doing lot of manual editing of the manifest file. It was terrible experience, because as we all know, formatting requirement of manifest file is not so human. It feels like it is machine generated file with limitations of 80 characters per line etc.


Just few facts about OSGi


  1. Equinox is primary OSGi container and there are many like Apache Felix, Apache Karaf etc built on top of Equinox by adding several bells and whistles. There is one called Virgo which was previously called as "DM Server" and  was donated by Spring guys to Eclipse foundation who owned Equinox.
  2. There is something very interesting concept called "Distributed OSGi". OSGi, as mentioned above is modularity inside one JVM process but there was no way to invoke remote bundle's service. This project and reference implementation is the sub-project of main Apache project - CXF
  3. Spring framework guys were big fan of OSGi, but as per verbal information got in SpringOne, developers were always divided on whether to use it or not. So finally they downgraded its use !
  4. OSGi logically fits very good in reusing bundles/services which are common across all applications in the company. For example, separate bundle for logging or database access is nice example.
  5. Same jars with different version can co-exist in OSGi, which can not be done in monolithic java applications.
  6. All major application servers such as Jboss AS, Glassfish , Websphere support OSGi ! 
  7. But having said that, I seriously doubt major companies like Google, Facebook etc have OSGi prevalent. At least I have not come across any blog or article stating such companies are big users of OSGi.
Java 9 - All about modularity ! But who is the winner, OSGi or Project Jigsaw ?

Java 9 inherently has modularity. Initially there was a plan to include OSGi in Java 9 . But the winner is Jigsaw. This article has great overview what is going on in Java 9 for modularity front.  It also describes "Penrose", which is glue between OSGi and Jigsaw. 


Conclusion : OSGi, Go or No-Go ?



When modularity is questioned in Java application, Currently OSGi would be the most popular answer. OSGi's purpose and specifications are fantastic! But trade-off for this advantage is huge. OSGi increases work of the developer by around 5 times. What I felt about OSGi after using it, is exactly depicted in this answer on Quora ! Check the first answer.

Having said that, it is that fact that OSGi has not been taken advantage of from most of the developers community. As rightly said in this question-answer again on quora.

So, I would say, if you are not in real need of modularity on nano-level now, skip OSGi, java 9 might bring it by default, but you will need to wait until 2016 ! 

Monday, October 13, 2014

jHipster, the super baby in SpringRoo's pouch !

In this development productivity blog, I share my excitements about being productive using approaches such as code generators and seeing dream of having that iWAOW application really taking shape over the lazy weekend !


But I was kind of disappointed that my favorite code generator tool, to be specific "app generator" tool, Spring Roo went into maintenance only mode ! I was hoping Spring Roo would get new releases which included modules like Spring Boot, Spring Data Rest on backend and most importantly, greatest and coolest new technologies on front end. For example, Angular JS, Ext-JS/Sencha, Backbone JS. But looks like Spring guys decided to keep Spring Roo where it was. There are some valid reasons SpringRoo was demoted. For example, First of all, the revolution on front end technologies is so huge, that it is not primary business of Spring guys. Also, Roo is based on OSGi which is not much preferred technology by developers, with the debut of Spring Boot, Spring Roo is too old to refactor I guess.

Spring Boot ! (projects.spring.io/spring-boot)


I was excited to listen to launch of Spring Boot live at Santa Clara SpringOne convention, but after trying that, I realized, it is quick way to boot the spring application, but it did not have the command I was looking for, something like

> boot create entity <entityName> ( quick googlers don't copy paste this command please ! :)

This is the cool command I was looking for, but realized that boot had totally different purpose, like gathering dependencies in flash of a second by just looking at the code and following convention-over-configuration approach. That is cool too !

Playing With Play! (playframework.com)

During all this disappointment that Roo is being (only) maintained by some small company in Spain, I was looking who is that can replace Roo. I also checked Play Framework, tried some sample programs but turned out that was from totally different world where even java programmers deny there is standard like Servlets ! But that's fine, I realized great companies like LinkedIn has contributed and used Play a lot and it gives fantastic results. But it is another framework like Spring and I was looking for something on top of base framework which helps in creating at least CRUD application.

jHipster ! (jhipster.github.io ) 

During this search I did have an idea there is one weird named Hipster trying to leap like Roo with all greatest technology stack and here it is, I waited until it's born as stable release and I do see exactly what I looking for,

yo jhipster:entity <anEntity> (Create entity anEntity )
yo jhipster:service aService ( Create service aService) 

Yo !!! Yes, I did say it for the magic it would do and create CRUD angular page including Spring server side, but YO here also mean Yeoman ! The super-cool CRUD generator for 100+ web frameworks is base of jHipster ! In fact, jHipster is one of those hundreds of plugins, called "generators" written to generate server side code using Spring's latest offsprings like Spring-Boot, Spring Data, Spring Data Rest etc..

You can just land on this page and get tired of reading how many plugins have been already written, here you go http://yeoman.io/generators/


Now back to jHipster, I am thrilled about jHipster because, using all these already cool frameworks, it generates full stack web application using Angular and Spring ! Look at the great questions it asks when creating jHipster application !
  1. What is the base name of your application? 
  2. Would you like to use Maven or Gradle? - So, decide your server side build manager !
  3. What is your default Java package name?
  4. Do you want to use Java 8? - Cool ! 
  5. Which *type* of authentication would you like to use? - Superb ! You can also choose OAuth 
  6. Which *type* of database would you like to use? SQL / NoSQL ?
  7. Do you want to use Hibernate 2nd level cache? - Hardcore server side engineers know how it helps !
  8. Do you want to use clustered HTTP sessions? So by default, very minimal in session, almost stateless which is need for scalability.
  9. Do you want to use WebSockets? Applause ! 
  10. Which *production* database would you like to use? Means, you can have different databases already configured in production and development.
  11. Which *development* database would you like to use? 
  12. Would you like to use Grunt or Gulp.js for building the frontend? Cool - Options here too ! 
  13. Would you like to use the Compass CSS Authoring Framework? Incredible ! Compass is most advanced tool to generate CSS.
Imagine the comfort you get by having all these dependencies in your app right there when you start the development !

Hmm.. There are so many technologies embedded as a inherient part of jHipster.

HTML5BoilerPlate - So you dont have to worry adding things like Modernizer on your own. This boiler plate takes care of old browsers too, so many old-school browsers got taken care of.

Twitter Bootstrap : Need to talk anything about this most popular project on Github ?

Bower : Dependency management on client side ! Very popular now a days ! 

Karma, PhantomJS : When it is angular, no need to really mention this as it comes part of Angular. But just not to forget !

Following on server side !

Boot should be mentioned again and again because Boot was mentioned again and again in this year's SpringOne (which I did not attend btw :) , for architecture style of Micro-service. Spring guys have Boot everywhere now a days ! 

And when it is Spring world, I dont have to mention Spring Security, Spring MVC etc Right ? 

I am also so much impressed with what jHipster has for production readiness ! Monitoring with Metrix (which I dont know !) , caching with something called HazerCast (sorry, Dont know this too ) .

Conclusion : 
So in short, jHipster is like a Monster Platter you order in restaurant and avoid hassles of thinking of each item separately and getting that great feeling "I have everything" ! 



Monday, March 17, 2014

Has REST architecture finally put JSP to rest ?

I remember my development manager's sarcastic laugh with his bouncing shoulders when I had tried to access JSP tags from Javascript ! :( That was my first web application project as an intern and I was learning all Servlets, JSP etc. after my short journey in plain java.  I had gotten totally confused with crazy mix of HTML + CSS + Javascript + Java + Scriptlets + JSTL + Struts + whatever is missing in this list.. ! It took me some time to understand what exactly is going on with all these buzzwords of that time..

May be writing JSP is better than writing servlets with "out.println", may be writing JSTL/Struts is better than writing scriptlets, but whenever I looked at any JSP I always thought it was perfect example of "kitchen sink" ! Both kitchen sink and JSP kept on reminding me of each other for years ! And I still feel about JSP the same way !

In all this chaos, Sir Roy Fielding (@fielding) was contemplating to transform this restless world of web development into RESTful world with REST architectural style ! Thanks to him, we are seeing this beautiful architectural style which separates client code and server code so elegantly. It's like marriage made in heaven by giving freedom to each other !


For Those Who Don't Know REST :


For readers, who don't know REST, it's Representational State Transfer ! Still don't get it ? It is based on the concept that all web is made up of "Resources" and when we use web-site as user, we keep on changing the state of the application. So, in short, it's "representing the state of the application" which is "transferred" to the user. Also, we perform 4 basic operations on resources. These 4 operations are popularly called as CRUD, Create, Read, Update and Delete. These 4 operations are (usually) accomplished using POST, GET, PUT and DELETE methods of the HTTP protocol.

Why REST ? :



Current device-diversity and the numerous development platforms have made sure you don't have any other way (mostly) than to go the REST way. And new HTML5 capabilities, increase in javascript efficiency and iOS/Android native platforms have made it easier to go REST way. REST has made the server a real server as its name suggests and has been given the responsibility of doing back end stuff only. So now server just provides data and thats what it should do ! It has nothing to do with HTML, CSS and client side Javascript. So there is no JSP where web designers and server engineers both try to cram in their art ! Though CSS makes web designer's silo to play, not everything can be isolated so much in this JSP model.

It's not just advantages of client/server code isolation and cleaner code, there are so many other advantages in this modern world of application development using RESTful style.. Of course, reader should keep in mind that the REST is a "style" not a "specification", so nothing is wrong or right in REST! (and actually I don't like to say this, sounds so clumsy but.. )

Here are some of those
  1. RIP that troublesome session object on server side ! : REST is stateless. Good REST design sends user-id and  password in every request ! Or at least uses cookies in web-friendly client. So there is no need of long living session object on server side. User is authenticated every time and user data is live only for that request. In today's high performance hardware, authenticating user every time is not at all big burden compared to the advantages it brings.
  2. Cloud computing friendly : Advantages of above fact ? It helps us to RIP those session replication needed for failover as well ! Less memory requirements on server side because no more session objects of million of users. Plus, adding virtual machines in cloud is now does not have the complexity of adding those machines as session buddies in those jboss-like application servers ! So simple round-robin load balancing could be good enough.
  3. Readable and cacheable URLs : Unlike usual web application URL, where parameters are in the URL itself, REST application web URL is clean because all parameters take form of request body rather than the URL and submitted in the form of Json/XML object. Typical URL can be like http://www.example.com/appName/resource/<resource-id>. Being clean URLs, resources can be cached in better way than parameter based URLs.
  4. Versioning freedom (at least in pure REST) : Original definition of REST likes client application start from root URL and subsequently get URLs of further resources. It avoids client to have pre-defined sets of URLs to avoid continuous changes in client code if server URI changes. This is also called HATEOAS (what a scary looking word by the way). It means Hypermedia As The Engine Of Application State. Server provides hypermedia as the state of the application. So even if there is any change in URLs, client does not need to know since client only follows the path provided through server provided objects. 

Practical REST : 


Though ideal/pure REST promotes HATEOAS as mentioned above, practical problem is, that the communication becomes too chatty.  It may end up making hundreds of calls to just show personalized front-page for the user. So many practical people go for fixed API. They handle versioning in different ways. For example www.example.com/v2 or v2.example.com etc.

For this approach, client code needs to change every time there is change in URL. But some avoid this problem by just adding new version related attributes in the payload itself. Next version clients can use those extra/new information, old version client will get the same payload but would not even know what the extra attributes are and will just keep ignoring it.

Everywhere REST


  1. Now most of the leading code generators like Spring Roo, Play framework use RESTful URLs, even in traditional model of JSP (by keeping URLs RESTful ). 
  2. New world of Micro-Services is based on RESTful interaction between those services. New initiatives like Spring Boot helps create REST applications quickly using embedded servlet containers making micro-services easy to develop. 
  3. Spring now now also has Async support for REST using AsyncRestTemplate. 
  4. Almost all Javascript libraries support RESTful calls. Spring now has getting started guides for many Javascript frameworks for consuming RESTful services based on Spring as backend. For example, Spring REST with angular.js https://spring.io/guides/gs/consuming-rest-angularjs  

Conclusion : Pay Your Respects For JSP ! :)




Tuesday, January 14, 2014

Spring Data Should be Renamed to Spring Datta ?

In this Google era, everything should be searchable and Spring Data definitely needs its re-naming ceremony and some cool looking name ! In fact, many of Spring sub-projects needs it's own name like Apache has been doing.

So "Datta" or Dutta is short form of "Dattatreya" and originates from India and it means "God". Spring Data deserves that stature anyway, doesn’t it ?! :)  And if you you don't want to be religious, the same Datta has been transformed as powerful street fighter Dhalsim ! http://en.wikipedia.org/wiki/Dhalsim . I have found Spring Data so powerful, I can't stop writing about it in this usually-developer-productivity-related blog !


Spring Data
For them, who have not used or read about Spring Data. It is name of the umbrella project for everything related to Data. So, Spring Data JPA is working with data using JPA. And Spring Data MongoDB is same shell but works on MongoDB.

Flip-phone Vs Smart-Phone

After reading about Spring Data, I remembered start of my software development career with Java Prepared Statement ! It's like remembering your flip-phone after handling your new S4 or iPhone 5s.
I remember those arguments to pStmt (you remember this variable name ? ) and how I screwed with sequence of arguments ! :)

Then came Hibernate where I could make use of my Object oriented mind to map database tables to objects and I was partially relieved from switching my mind from OO to Relational !

New Logo ? Spring Datta ?
You might ask what Spring Data brings compared to Hibernate/JPA. It goes beyond or on top of JPA/Hibernate where you get far more than only mapping database entities to java objects. Those basics are done by JPA/Hibernate as usual.
Here are some Datta like features of Spring Data ! I am usually excited about any framework's feature which reduces the time of development drastically ! So I would mostly focus on "productivity" features of Spring Data.

Forget about SQL , remember the English !

This is the feature I was really impressed and it got me tempted to try to believe it ! :) Not that I don't believe the new spring.io documentation, in fact it's way too improved and I love those getting started guides ! Short and sweet, plus their sweet requirement in the list of "What you will need"- "You need to have 15 minutes" :)

So what I tried was this. As per documentation, just write the method names in right way, you will get implementation automatically ! So here is my simple method name and it worked so nice !

CustomerRepository customerRepository = context.getBean(CustomerRepository.class);
customerRepository.findByAccountsInternalType("PremiumChecking");

Here each Customer has one or more Accounts. Account has "InternalType" as one of attribute/column which may indicate say Checking, Savings , PremiumChecking etc. So this little piece of English "customerRepository.findByAccountsInternalType("PremiumChecking");  means find customers who have accounts with internal-type equal to PremiumChecking. Wow, this has saved me so much joins or criteria I would have to write if I was using just Hibernate or JPA. So you can go endless findByTable2Colum2Table3Column4 and so on..

And of course you can use all the grammar. For example words like "Between" , "Like" and what not ! See here  http://docs.spring.io/spring-data/jpa/docs/1.2.0.RELEASE/reference/html/#repository-query-keywords

I have used Spring Roo extensively and was amazed by it's auto-generated finder methods but it could never do cross entities join but Spring Data can do it !

Many modern databases are joining under Spring Data umbrella :

As I mentioned above, Spring data is umbrella project and all this "English Vocabulary" can be used on many databases like MongoDB, Neo4J , Hadoop , surely many other databases joining under the umbrella to handle the rain of data from all directions.
Spring data not only works with databases but the same interface can be used for distributed memory like Gemfire too.

Talk in DSL as well :

Spring data supports QueryDSL as well to ease writing complex finders in your code which is more readable. Here is the example by queryDSL itself.

List<Customer> result = query.from(customer)
    .where(customer.lastName.like("A%"), customer.active.eq(true))
    .orderBy(customer.lastName.asc(), customer.firstName.desc())
    .list(customer); 

Add REST on top : There is another project called "Spring Data REST" based on Spring data. I dont know much about it at this time, but I am sure it adds effortless REST support on all what Spring data can do and makes your "modern webapp" development super easy.

Conclusion : One can be super-productive using Spring data ! Go for it ! :)

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){
        log.info("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);
        appUser.persist();
        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);
        appUser.setPassword(encoded);
        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 !

My tweets on similar topics