2012/10/09
9 Oct, 2012

Introducing Jaggery - The Newer, Easier Way of Writing Web Apps

  • Nuwan Bandara
  • Director - WSO2

Applies to

Jaggery 0.9.0

Contents

What is Jaggery & why do you need it

At present if you want to start on a web app, you have lots of options, in fact too many options! First you will decide on a mainstream language to write up the dynamic part of the app. Immediately after that you have to think about the rich user experience, offline capabilities, and client side rendering. Finally the ORM layer and a persistence medium. Lets say you chose the glorious Java, MySQL combination (maybe JSF, Struts, and Hibernate to get over things sooner and easier) for the dynamic parts and persistence. For the front-end development you might choose a latest HTML5 capable tool kit like Backbone.js, maybe a flavour of JQuery (like JavaScriptMVC) or if you really want flexibility - Vanilla jQuery with your own MV layer.

At this point you are all set and quite happy to start writing your application with a bunch of technologies. It gets interesting when you actually try to capture data from an end user, send it to the server page, perform logic on it and finally persist it. With each of these operations you have to worry about the data formats and incompatibilities. Each time you will end up encoding them in many complex ways, and sometimes on your own custom schemas. For instance in the above app, lets say you take a set of inputs from a user, send it as a JSON object to the server, and now you will have to capture this object in Java, validate it, perform operations and persist it through SQL. To run through the above path, the JSON object needs to be converted to be understood by Java, perform operation on the data set in whatever way the data is converted into and save it via SQL. In each of these conversions there is a high possibility to lose some amount of context or data. Even though every language has a standard way to deal with any sort of a data type (like Gson/JSON.org for Java and json_decode() in PHP), developers have to switch between those approaches and abstractions while not only risking loss of data but understanding all the different syntaxes and idioms.

Further if you need more technical and business benefits such as the ability to scale out the architecture and generate revenue via other third party applications, you will definitely look for creating APIs first for the application and then consume those within. Realizing such a requirement with available technologies such as SOAP/XML with JAX-WS, REST with JAX-RS will add an additional burden for the developer, creating a steep learning curve.

So the offering you might ask? How about run through the entire flow with one technology - not only the presentation, logic and persistence, but also the communicated data format. No encoding, decoding, just using it as it comes. At present developers are increasingly looking at loosely typed languages (like Javascript ;) ) and create amazing work out of them. Its mainly because those languages restrict the developer very little or not at all, and providing the freedom to focus on the work to be done, and not the syntax or the protocol.

Jaggery is about Javascript, about doing everything with Javascript - from presenting to persisting the full breadth of the development. Why Javascript? well, mainly it has less rules to obey and because it talks smoothly in a native language (JSON) (and of course because you get closures). So no more encoding, no more steep learning curves. You can write your responsive front end as well as your server side logic in one single technology and pass through data only in JSON.

Jaggery is only a server side Javascript (SSJS) tool kit. Its not for you to write servers, but only to focus on web applications, design and compose them. Jaggery runs on WSO2 Carbon (also can work on Tomcat) which is an award winning middleware platform, and takes care of the complexities, request/response handling, application deployment, clustering and even multi-tenancy (plus many more). In a nutshell, if you want to write your server side logic in Javascript you don't have to worry about writing the server as well.

Jaggery gives you a clean API to handle the request and response, and all other operations in a server environment. You can manage the session, read files (in streams), talk to databases, do HTTP calls and dozens more. It has a modularized plugin mechanism, where if you need to create a new functionality you can simply import it as a Javascript file, or register it as a module.

How it works (under the hood)

Jaggery users Mozilla Rhino to provide SSJS functionality, and ties up to Tomcat (WSO2 Carbon based multi-tenanted Tomcat) for deployment, session management and request, and response handling. The following diagram describes each of the components associated with Jaggery, and how it provides an enterprise grade server runtime


Internally, using Rhino compiled scripts, Jaggery will convert the javascript (.jag) files into compiled Java classes creating a caching layer improving runtime performance.

As mentioned before, Jaggery can easily be extended. Even though it is built with a set of rich web app development constructs, developers often need to add more functionality and features. Mainly there are two ways to add modules to Jaggery and extend the core framework.

  • Write your own Javascript module and import it.
  • This is the preferred way of doing things. Lets say you need to provide native i18n support for Jaggery. You can simply compose your own i18n module and plug it. Like its already been done at [2]

  • Write a Java class (extending Rhino ScriptableObject) and register it as a module
  • This is the “no-option” solution. If there is no other alternative for the functionality you are looking for, you can simply write it in Java and expose as a module. That's how we have provided the HTTP Request, Response and other core APIs like File, Email, Database etc. [3]

Its compliant to “Common JS”. [4] So you can easily import the hundreds if not thousands of Javascript projects directly to Jaggery. One such example is Mustache [5]. So you can easily do something like,


Restricting a page or a context based on a user role in Jaggery is quite easy and its provided out of the box. With few configurations at jaggery.conf, developers can easily secure contexts and pages with HTTP basic authentication.

"securityConstraints":[
        {
            "securityConstraint":{
                "webResourceCollection":{
                    "name":"foo",
                    "urlPatterns":["/bar/*"],
                    "methods":["GET", "POST", "PUT", "DELETE"]
                },
                "authRoles":["admin"]
            }
        }
    ]

When can you use it

Well, Always :). Considering the demand for apps and APIs at present, I couldn't think of any other rapid development tool kit that can match the productivity gain of Jaggery. Of Course I am bias to it, but if you come to think of it - there's no compilation, bundling or packaging to start with, its Javascript and everybody knows it, you can use hundreds of already built libraries right in the server, its modular and extensible, and comes with an enterprise grade server runtime.

If you dig further in to the Jaggery API, you would see more and more use cases where it will fit right in. For instance Jaggery creates a great environment to build RESTful JSON APIs. I have already explained about the JSON part, and on RESTful nature, you can easily switch the response according to the requested method (request.getMethod()) and to requested content-type (request.getContentType()). Jaggery also supports pattern based URL matching which is a big part in REST application/API development. So you can perform a URL match like,


Also at the configuration level you can statically define a URL-Mapping, this can be done as follows, in jaggery.conf.

Leveraging these advantages, we have created a sample REST app, which exposes a REST API, you can try it out at [6] and check out the source at [7]

Jaggery also provide inbuilt support for connecting with other third party APIs which are secured with OAuth. So from your back end you can talk to the Twitter API through OAuth, and expose the data. We have just done that at [8]

You can do AJAX at the back end (HttpClient functionality). Simply GET, POST, PUT and DELETE


Jaggery also has support for XML. In fact XML manipulation is provided as a trivial operation with E4X. Developers can invoke a feed URL retrieve a feed object through the Jaggery API, and manipulate it with E4X


		    
		        Tove
		        32
		    
		    
		        Jani
		        26
		    
		;
	 
	//or var employees= new XML("Tove32Jani26");
	 
	print("Toves age is - " + employees.person.(name == "Tove").age);
%>

The above being some significant features relevant to this context, you can surely run through the rich API documentation, and also can try out the functionality at that point.

As any developer your next question is tooling support. Is there an IDE for Jaggery? A debugger for it?

The good news is, that the Jaggery team is now working hard on pushing out two plugins for Eclipse and Intellij IDEA. A Rhino based debugger is already getting its finishing touches and will be available soon.

To try things out we have created a sandbox environment at [10] where you have a web editor to do some Jaggery code cutting.

Summary

In summary, I quote jaggeryjs.org,

“Jaggery is an evolving story – as it reaches 1.0 we are by no means hallucinating that we have got everything right or that we are done. We encourage you to come join the party and help evolve Jaggery to really solve the problems it strives to solve.”

Jaggery is at GitHub right now, if you are interested do fork it, build it, improve it and send us a pull request. We are excited to hear your thoughts.

You can mail to jaggery dev list at [email protected] and use the GitHub Issue tracker for reporting issues or for any other queries.

References

  1. https://developer.mozilla.org/en-US/docs/Rhino/JavaScript_Compiler
  2. https://github.com/wso2/jaggery/tree/master/modules/i18n
  3. https://github.com/wso2/jaggery/tree/master/components/hostobjects/org.jaggeryjs.hostobjects.web
  4. https://www.commonjs.org/
  5. https://github.com/janl/mustache.js
  6. https://jaggeryjs.org/coffeeshop/
  7. https://github.com/wso2/jaggery/tree/master/apps/coffeeshop
  8. https://jaggeryjs.org/shout/
  9. https://developer.mozilla.org/en-US/docs/E4X
  10. https://jaggeryjs.org/tryitview.jag

Author

Nuwan Bandara, Associate Technical Lead , WSO2 Inc

 

About Author

  • Nuwan Bandara
  • Director
  • WSO2