Friday, August 7, 2015

Moving to a New Home

This blog is moving to new Home. Yay !!

Finally bidding goodbye to Blogger & moving to a more managed Wordpress blog after a good long 7 years & many learnings, though not all transformed into blog entries !!

Revisiting old memories, my journey as a Blogger started with being a part of Sun Campus Ambassador program and I definitely plan to continue and keep blogging about all the new technologies that I get a chance to work with.

So please follow me on the new blog. Also check out the home page I designed & created for myself. Looks cool, right ? ;)

See you there,
Agraj

Tuesday, August 12, 2014

Authenticating Node.js Applications with Passport

Check out my recent post on authenticating Node.js applications with Passport on Tuts+ here. It assumes a basic understanding of Node.js and Mongo but we start by building an Express application from scratch and add new routes, views & authenticate them via Passport. 

Sunday, March 16, 2014

Web Components 101 : Shadow DOM

Unless you've been living under a rock, you must have heard about the latest buzzword in the world of JavaScript - Encapsulation. Encapsulation or Information-hiding is one of the main pillars of object-oriented programming languages which is used to restrict access to some of the object's components. But how does that apply to a language like JavaScript - To find out check out this article I recently authored about Shadow DOM, the underlying technology behind Web components.

Sunday, October 27, 2013

Synchronization in Java

Threads are an integral part of the Java language and have evolved largely introducing new ways to synchronize/lock your data but the basics of Atomicity & Visibility remains same, which are essential to understand and write robust multi-threaded applications. I recently authored a post explaining the basics of Synchronization and introducing the various new ways to lock your data. Let me know in the comments if there is anything in that post that does not make sense.

Wednesday, August 28, 2013

OAuth2.0 for Dummies

Check out my post on OAuth2.0 - the famous access delegation mechanism employed by many big names such as Google, Facebook, Salesforce etc. that eliminates the needs of sharing passwords between applications to exchange data. The post uses Google's OAuth Playground to detail out the communication (authentication and authorization) that occurs between the client and the server when the client is trying to authenticate on behalf of resource owner. It also draws a basic comparison with the earlier version of OAuth - 1.0 and presents a perspective on how things turned ugly when the lead author of the spec resigned !!

Tuesday, March 19, 2013

HTML5 : Web Workers

There isn't much need to emphasize that HTML5 brings with itself, a new set of Javascript armor for the front-end developer. One of the interesting additions that has the potential to change how complex operations in Javascript are performed, is Web Workers. It provides multi-threaded capabilities in a language which was inherently single-threaded otherwise. Check out my detailed writeup on Getting Started with Web Workers here

Sunday, May 6, 2012

Getting Started with HTML5

Do you want your existing website to be HTML5 – compliant ?
All you want to know if you are working on a new project that should follow HTML5 best practices ?
This post tries to answer some of these questions and attempts to try and get started with HTML5 in a flash, using two of the most popular bootstrap frameworks which help you to get started with a robust codebase. Why use it ? Simple, these frameworks contains best practices around front-end development using HTML/JSS/CSS and kick starts you to concentrate on content, rather than developing a template for your site.
HTML5 Boilerplate – H5BP , already at 3.0
Includes
  • Cross-browser compatible using Polyfills/Fallbacks.
  • HTML5 Feature Detection using Modernizr, YepNode
  • CSS3 Media Queries
  • Mobile browser optimizations
  • Download complete, stripped & customized versions
  • CDN hosted jQuery with local failback ( shown below )
image
As you can see, first we try to load jQuery using Google CDN. In the next line, we check the existence using window.jQuery, which will evaluate to true if the library has been loaded successfully, else we load it statically.
  • Also contains some server site configurations like .htaccess file for caching, cross-domain XHR, gzipping, 404 error pages, robots.txt etc.
  • Contains ANT build scripts to integrate easily with your project build system
Paul Irish on HTML5 Boilerplate
Twitter Bootstrap – Just released 2.0
Includes
  • Responsive 12-grid column
  • Custom jQuery plugins for Carousel, Popovers, Accordion, Autocomplete, modals etc.
  • Cross-browser compatible and also includes media queries for smartphones and tablets too
  • Includes many components like Button groups, Button Dropdowns, Navigation components, alerts and progress bars etc
  • Contains extensive out of the box styling for your HTML markup, for elements like Forms, Tables etc. Building a bordered, shaded, alternate colored table was never so easy.
  • The entire framework is built on LESS. The codebase contains several .less files (containing different functionalities) which are then compiled into CSS.
  • Provides several styling as LESS mixings which can be found in mixings.less which you can easily use in your code, or extend them as well.
Comparsion & Conclusion
Both are superb HTML5 bootstrap frameworks, under continuous development which follow best practices developed over the years to build a fast, secure and future-proof site. But in my opinion, H5BP is something that even designers can play with using as a template, they can simply open their favourite design tool and add content. While using Twitter Bootstrap is more developer oriented and requires you to invest some time in understanding the various classes and functionalities it offers. But then, that’s the case with every good thing around you.

Thursday, March 29, 2012

jQuery Custom Effects

Although jQuery provides us with a few basic effects like slideDown/Up, fadeIn/Out etc. and a pretty powerful animate function to create animation/effects on any numeric CSS property, a lot of creative people have written some amazing effects/components that will take your breath away. While we do not plan to reinvent the wheel here but down the road, you may also need to create your own effect and would like to access it like

image

Surprisingly, being able to do so is not as difficult as it might seem at first, and can be achieved by adding a new function property to jQuery.fn object as below:

image

The above function simply extends the jQuery object by adding a new method in the jQuery prototype ( jQuery.fn object ). Before diving deep into the implementation, it is important to understand the concept of prototypal inheritance in JS and reading this article will open your eyes for sure.

Coming back, a naive implementation looks like

image 

Here, we delegate the actual work to animate method and toggle the height & opacity of the selected DOM element for the given speed if any, else a default of 400ms is used. It also allows us to specify a callback function to be called after the animation/effect is complete. To accomplish that, we first check whether the passed variable (fn) is actually a function using isFunction and then call the method passing this as the context.

Another important thing to note is that we are returning the jQuery object back from our function so that you can take advantage of chaining like:

image

So this wraps up a short and simple post on how to create custom effects by extending jQuery object. If you have any questions or comments, please leave them as comments.

Wednesday, February 15, 2012

Servlet Config, Context & Listeners

Why talk about Servlets when there are JSPs…. Right ? That’s what came into mind especially when we read about how JSPs are way more easy and fun to write. But Servlet exists for a more meaningful purpose that than just churn out HTML, for instance they act as a Controller for many frameworks. But this is not about how important Servlets are, rather today we will talk about ServletConfig, ServletContext and ServletContextListeners.
ServletConfig
ServletConfig is a helper object which we can use in our servlets to get configuration of a Servlet. The configuration can include things like Servlet name, its context (described below) and init-parameters. For example, consider the following servlet declaration in a Deployment Descriptor (DD)
image
So instead of hardcoding the feedback email in the servlet responsible for sending the feedback mail, we can simple configure it in the DD and the servlet can pick the value from using ServletConfig as shown below:
image
The container is responsible for creating a ServletConfig object per servlet and pass to it after it has been initialized so it would be good to note that we can not use this object until the init() method i.e. we cannot access these init params inside the servlet’s constructor.
ServletContext
ServletContext, on the other hand acts as a global helper and is not created once per servlet, rather it is created once per application (when an application is deployed) and is normally used to configure application level parameters amongst other things. A typical example would look like:
image
and would be accessed as
image
Now these params can be accessed across all the servlets and JSPs that the application deploys. There are a bunch of other useful information that you can grab from a ServletContext and all of that can be seen here.
ServletContextListener
What if I want to do some special handling when my web application is initialized (or deployed) or destroyed/removed ? The servlet spec gives you a way to hook into the lifecycle of your web application by implementing a ServletContextListener which can listen for these events and act accordingly. Following is an example that picks up the datasource configuration from DD and creates a corresponding DataSource object and save it in ServletContext so that it can be easily retrieved by any servlet wishing to perform a database operation:
The actual code of creating a DataSource object from the string is being left out as it does not serve any purpose for this example. This listener will have to be configured in the deployment descriptor so that it can listen and respond to the lifecycle events as:
image
There are many other types of listeners that we can write to handle different use cases viz. ServletRequestListener, ServletRequestAttributeListener, ServletContextAttributeListener to name a few but we will see them in action some other day.
Disclaimer
With Java EE Annotations, we really don’t have to configure a servlet in DD (as shown in the examples above). They are just there to make things easy to comprehend.

Saturday, December 17, 2011

HTML5 Native Drag ‘n’ Drop

HTML5 does not only mean a whole new world of tags (video, audio, header, footer, article, section etc.) and revolutionary technologies like Geolocation, Application cache, Canvas, Web Workers etc. but it also brings along a rich set of JavaScript API to developers.

Today, we witness one of the interesting feature that it provides; the capability of dragging and dropping elements natively without using any JS framework. The HTML5 spec defines the new events that we should catch in order to handle operations like

  1. Start of drag operation ( dragstart )
  2. Dragging content over another element ( dragover )
  3. Entering the drag area of another element ( dragenter )
  4. End of Drag operation ( drop )

If you have worked with a RIA-friendly language such as ActionScript, then you will found this to be very similar. Having said that, providing this drag and drop support in the browser itself is the reason behind the fame of HTML5.

Coming back, lets see some code in action. We have some images in our page which we want to drag and drop in div container. These images are tagged with class “dragMe” (so that we can attach event listeners to them). Similarly, we have a div container in which we are going to drop these images with an id of “dropOnMe”.

htmlCode

Things to note

  • draggable=true  -  By default, images and links are draggable in nature but I have added this attribute just to convey that any HTML5 element can be selected, dragged and dropped if you add this attribute to it. Also add following CSS to make it work across different browsers

draggableTrueCss

  • Custom data-* attributes  -  Again something, HTML5-blessed. It provides us the capability to define custom data-attributes on any element. Here we use it to define properties of individual images. More on custom data-attributes here.

Next, we add some event handlers to handle drag n drop related events we defined above:

1. Adding Drag Handlers

dragStart

We took a hold of all the elements that are to be dragged and attach to each, a drag handler which will be called whenever you click and try to drag that elements. In the handler, we update the event’s dataTransfer object and set custom properties in the JavaScript object, which we defined in the markup  (yes you guessed it right, we are going to use them in the drop handler)

2. Adding Drop Handlers

dropHandler

Note that we use both e.preventDefault() and return false in the function, to make it work across different browsers; this is needed to make sure that we cancel the default action that the browser will normally take, like surfing to that location (in case of a link). Apart from that, the code just retrieves the data set in dataTransfer object and display that using innerHTML of the div.

3. Adding handlers for dragover & dragenter

dragOverEnterHandlers

Again for making the code work across different browsers (tested on Firefox, IE and Chrome), we need to use both preventDefault() and also return false from the handler in order to inform the browser that you can drop and release the dragged item on this element for which the function is called.

A Lot More…

..can be achieved like customizing the drag icon and even drag and drop across different instances of same browser or even dragging from one browser and dropping in another browser. Stay tuned or check out the spec for more details.

Final Demo Looks like

Too bad that I don’t have a proper hosting solution, so you have to do with images, until you are passionate enough to write the above code yourself.

Initial Screen

image

Dragging an Item

image

Dropped it !!

image

We can add more spice to the tut by adding CSS and some other effects but in the hope that it would overshadow the concept, I emphasize on the minimal code needed for it.

Any suggestions, improvements or bugs are welcome as comments.

Saturday, November 19, 2011

CSS3 Media Queries

Need of Media Queries

Gone were those days when designers had the liberty to design or layout a web page for fixed/minimum resolution as most people would just use their desktop for browsing the web. In this mobile/tablet era, we cannot assume that the desktop would be the only user agent. A large number of users today use their “smartphones” or “tablets” for browsing the web and so it becomes crucial that your website looks as good when viewed from such a device.

Many websites today have different version of websites, one each for desktop and mobile. By detecting the user agent when the user visits the website for the first time, it can redirect them to the mobile version if he is browsing the web using his smartphone. But this solution comes with its own headache of maintaining separate presentation layers for separate mediums and fixing bugs in both !!

This is where Media Queries come into picture. They provide an elegant solution to the problem by providing the ability to switch the CSS based on the user agent or device’s width or orientation. In short, they make your web design adaptive and responsive to change.

Wow, that’s new !!

Not really !!. They were very much a part of CSS2 and HTML4 specification where they were limited to ‘print’ and ‘screen’ only (meaning using CSS2, you can only specify different style-sheets for rendering and printing a web page). But with CSS3, more media types are supported and different style-sheets can be applied based on

  • device-width and height
  • viewport-width and height
  • orientation
  • aspect-ratio
  • device aspect-ratio
  • resolution etc..

Without wasting more time, lets see an example. We will create a layout for a widescreen (desktop layout) and using media queries, we will change the layout and color the markup when we resize the browser (to simulate tablet and mobile size)

wideLayout Layout for Wide Screen

tabletLayout Layout for Tablet or Not So Wide Screen

phoneLayout Layout for a Mobile Device

In this lame-example, we have simple created a three-column layout for a widescreen or desktop, and changed it to a two-column layout for a tablet and coloured the sidebar blue (not to show my design skills of course, but to distinguish between the layouts) and then a stacked layout for a mobile device with red coloured div. and All this by simply switching the CSS for the same HTML file. All the code is explained below:

index.html

<!DOCTYPE HTML>
<head>

<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8" />
<link media="only screen and (min-width: 800px)" rel="stylesheet" href="css/desktop.css" />
<link media="only screen and (min-width: 400px) and (max-width: 800px)" rel="stylesheet" href="css/tablet.css" />
<link media="only screen and (max-width: 400px)" rel="stylesheet" href="css/phone.css" />

</head>
<body>

<div id="header"> Header </div>
<div id="sideBar"> Side Bar </div>
<div id="content"> Content </div>
<div id="extra"> Extra </div>

</body>
</html>

desktop.css

div
{
border: 1px solid;
}
body
{
width:1000px;
margin: auto;
}
#sideBar
{
float:left;
width:250px;
height:600px;
}
#content
{
float:left;
width:448px;
height:600px;
}
#extra
{
margin-left:700px;
width:296px;
height:600px;
}

tablet.css

div
{
border: 1px solid;
}
body
{
width:700px;
margin: auto;
}
#sideBar
{
float:left;
width:200px;
height:600px;
background-color:blue;
}
#content
{
margin-left:202px;
height:600px;
}
#extra
{
clear:both;
}

phone.css

div
{
border: 1px solid;
}
body
{
width:350px;
margin: auto;
}
#sideBar
{
height:100px;
}
#content
{
height:100px;
background-color:red;
}
#extra
{
height:100px;
}

This HTML files simple contains 4 Div’s in the body and head contains links to some style-sheets with media queries using link tag, lets see what these queries mean

<link rel="stylesheet" href="css/desktop.css" media="only screen and (min-width: 800px)" />

It can be read as include the “desktop.css” file if and only if the user agent has a screen and the minimum-width of the device is 800 pixels. Similarly,

<link rel="stylesheet" href="css/tablet.css" media="only screen and (min-width: 400px) and (max-width: 800px)" />

it says that include the “tablet.css” when the user agent has a screen and its width is between 400 to 800 pixels, something that we think should be suitable for a tablet.

<link rel="stylesheet" href="css/phone.css" media="only screen and (max-width: 400px)" />

On the same lines, in this rule, we ask the browser to use “phone.css” if the width is less than 400 pixels. Note that these rules are mutually exclusive because we want them to be like so. Each rule must evaluate to a boolean value and depending on that value, the CSS file is downloaded to the client machine and is used for rendering the HTML markup.

You can also embed the media-query inline in the CSS as follows:

<style type="text/css">       
@media only screen and (max-width: 400px)
{
#content
{
height:100px;
background-color:red;
}
}
</style>

Orientation

Similarly the CSS for phone.css can be broken down into two parts: phonePortrait.css and phoneLandscape.css by applying the following media queries

<link media="only screen and (max-width=400px) and (orientation=portrait)" rel="stylesheet" href="phonePortrait.css" />
<link media="only screen and (max-width=400px) and (orientation=landscape)" rel="stylesheet" href="phoneLandscape.css" />

Width Vs Device-width

"width" refers to the width of the viewport width (or the browser’s width) whereas the "device-width" refers to the width of the device (for desktop users, it is the dimensions of the monitor used, for mobile users, it is the dimensions of the smartphone used). Common sense says we should use device as the browser size may be less than the dimension of the device (esp on desktop)

The complication comes in case of mobiles, where the likes of iDevices and Androids incorrectly reports the viewport-width and also neglects the orientation of the device while calculating the width. To make things work, Apple introduced a new meta-tag: Viewport which is usually used as follows:

<meta name="viewport" content="width=device-width, initial-scale=1">

This instructs the device to report the viewport width equal to the actual width of the device and also take orientation into account while making that calculation. More details can be read here.

Browser Support

Surprisingly, majority of browsers do support media queries but for those who don’t, a JavaScript workaround can be applied which based on the width of the browser, changes the link’s href value to point to the correct CSS file.

Spec

A lot more can be achieved by media queries, all of which has been laid out in the spec here.

Disclaimer

The HTML & CSS used above in the example are merely for demonstrating the power of Media Queries and hence have been intentionally kept lame.

Tuesday, November 15, 2011

Remembering the old Sunny Days

Although my tenure with Sun Microsystems (now Oracle Corp), working as a Sun Campus Ambassador was numbered (just 6 months), but I consider that to be an important phase in my life, a beginning of a new journey, something that motivated me to work on open-source technology and learn new and exciting stuff.

The bad, rather the ugly part is that I cannot access my Sun Blog anymore !! Yes, I have written to Oracle about it, but nothing has happened so far. Still the sole purpose of writing that post was to re-live moments of the past and  thanks to Arun Gupta, I’m re-posting one of my favourite entries again: A poem for me from one of my favourite professor: Dr. P.K. Hazra.

Under the SUN-MICROSYS SunRay
Has bloomed a Lovely Rose,
Over Joyful in Java & Solaris
He is SUN CAMPUS AMBASSADOR Agraj.
Only one request I want to make
to the SUN's shining flower,
To remain in serene silence
During my lecture hour
                Quoted by Dr. P.K Hazra

and As they say,  “I’m really gonna miss this place, I’m gonna my college days…”

Saturday, November 12, 2011

jQuery Mobile: Hello Mobile World

After more than one year of online-hibernation, I’m more than happy to be back and today would be writing about creating a basic mobile application using jQuery Mobile.

Overview

jQuery Mobile provides a robust framework to develop mobile applications on the fly and is as simple as creating a HTML page and including jQuery mobile specific JS and CSS files. The framework is not only pretty straightforward to use, but also provides a familiar approach for web developers (who are already comfortable with HTML, CSS & Javascript/jQuery). It also provides 5 predefined themes to choose from and recently ThemeRoller has been launched which can be used to create a custom theme for your app. Fortunately for you guys, I’m not going to rant about how awesome jQuery Mobile is, as all that can be found here. :-)

Getting Started

In this post, we will be creating a basic contacts app which looks like below:

homePage allFriendsView

addNewFriend

Lets start by creating a basic html file (index.html) for the home page/the first view and add the code below to it:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Friends</title>
<link href="jquery-mobile/jquery.mobile-1.0a3.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-mobile/jquery-1.5.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0a3.min.js" type="text/javascript"></script>
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div data-role="page" id="page">
<div data-role="header">
<h1>My Friends</h1>
</div>
<div data-role="content">
<!-- Logo -->
<div id="logo"> </div>
<ul data-role="listview">
<li><a href="allFriends.html" data-transition="pop">All Friends</a></li>
<li><a href="addFriend.html" data-transition="fade">Add Friend</a></li>
</ul>
</div>
<div data-role="footer" data-position="fixed">
<h4>&copy; Copyright 2011</h4>
</div>
</div>
</body>
</html>

In the head section, we have included jQuery mobile specific CSS and JS files. We have also included our custom CSS file: styles.css which is primarily used to position the logo for our application and consists of the following code:

#page div #logo {
width: 300px;
height: 100px;
background-image: url(../images/jQueryLogo.jpg);
background-repeat: no-repeat;
background-position: center 0px;
margin-top: 0px;
margin-right: auto;
margin-bottom: 0px;
margin-left: auto;
}

The body contains various div’s which form one view/page of the mobile app. The “page” div usually contains “header”, “content” and a “footer”. These div’s can then contain anything that you want to put inside those sections of the page (following some conventions).

As the name suggests, header and footer are the blocks at top and bottom of the page and the “content” div is used to lay out the elements to be shown in the rest of page. Here, we show a logo and list view of 2 elements.

As you might have noticed we have made extensive use of HTML5 custom data-attributes (the data-* attributes on HTML tags) throughout our tutorial. jQuery mobile leverages this uber cool feature of HTML5 to add capabilities to its framework. These custom data-attributes (like data-role, data-transition, data-position etc) are defined in jQuery Mobile framework and support predefined values.

Lets create another pages/html files, which we will then link to our main page (index.html). Creating the second view/page (allFriends.html) in which we will show all the friends in our list.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>All Friends</title>
<link href="jquery-mobile/jquery.mobile-1.0a3.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-mobile/jquery-1.5.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0a3.min.js" type="text/javascript"></script>
</head>

<div data-role="page">
<div data-role="header">
<a href="index.html" data-icon="home"> Home </a>
<h1> All Friends</h1>
<a href="index.html" data-icon="back"> Back </a>
</div>

<div data-role="content">
<ul data-role="listview">
<li> <a href="friendDetails.html">
<img src="images/face1.jpg">
<h3> Andrea </h3>
<p> Office Colleague </p>
</a>
</li>
<li> <a href="friendDetails.html">
<img src="images/face2.jpg">
<h3> Aria </h3>
<p> Childhood Friend </p>
</a>
</li>
<li> <a href="friendDetails.html">
<img src="images/face3.jpg">
<h3> Tom </h3>
<p> Brother </p>
</a>
</li>
<li> <a href="friendDetails.html">
<img src="images/face4.jpg">
<h3> Home </h3>
<p> Danger </p>
</a>
</li>
<li> <a href="friendDetails.html">
<img src="images/face5.jpg">
<h3> Melinda </h3>
<p> Close Friend </p>
</a>
</li>
<li> <a href="friendDetails.html">
<img src="images/face6.jpg">
<h3> Taanya </h3>
<p> College </p>
</a>
</li>
<li> <a href="friendDetails.html">
<img src="images/face7.jpg">
<h3> Micheal </h3>
<p> Rockstar </p>
</a>
</li>
<li> <a href="friendDetails.html">
<img src="images/face8.jpg">
<h3> Maria </h3>
<p> Friend </p>
</a>
</li>
</ul>
</div>

<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<!-- Add icons here for Delete, Edit, Call Friend -->
<li><a href="#" data-icon="info" data-iconpos="top">Edit</a></li>
<li><a href="#" data-icon="delete" data-iconpos="top">Delete</a></li>
<li><a href="#" data-icon="alert" data-iconpos="top">Call</a></li>
</ul>
</div><!-- /navbar -->
</div><!-- /footer -->

</div>

<body>
</body>
</html>

By writing this small piece of code, we can show the thumbnails in the listview along with some description of each element. To make things simpler, this is simply some static data hardcoded into HTML. A real-world application would read this data from some persistence store and using jQuery would create this markup dynamically with that data.

jQuery Mobile also provides a rich set of form elements as can be read here. We create a simple form using the html below (addFriend.html) to show some basic form elements to create the third page/view of our app in which we provide a simple form to add a new friends in the existing contacts.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Add Friend</title>
<link href="jquery-mobile/jquery.mobile-1.0a3.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-mobile/jquery-1.5.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0a3.min.js" type="text/javascript"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<a href="index.html" data-icon="home"> Home </a>
<h1> Add Friend </h1>
<a href="index.html" data-icon="back"> Back </a>
</div>
<div data-role="content">
<form action=”submit.jsp” method="post">
<div data-role="fieldcontain">
<label for="name">Name: </label>
<input type="text" name="name" id="name" placeholder="Enter Name"/>
</div>
<div data-role="fieldcontain">
<label for="gender">Gender:</label>
<select name="gender" id="gender" data-role="slider">
<option value="MALE">Male</option>
<option value="FEMALE">Female</option>
</select>
</div>
<div data-role="fieldcontain">
<label for="age">Age</label>
<input type="range" name="age" id="age" min="0" max="100" value="0"/>
</div>
<fieldset class="ui-grid-a">
<div class="ui-block-a">
<a href="index.html" data-role="button" id="cancel">Cancel</a>
</div>
<div class="ui-block-b">
<button type="submit" data-theme="a">Submit</button>
</div>
</fieldset>
</form>
</div>
<div data-role="footer" data-position="fixed">
<h4>&copy; Copyright 2011</h4>
</div>
</div>
</body>
</html>

Again the markup is pretty much similar to a normal HTML page, just we have used certain specific data-roles, specific classes which are defined in the framework to layout the elements in a certain fashion and apply a theme to our UI. Since this is just for introducing the framework and not on developing a fully functional app, so the form submission does not work, rather it gives an elegant error message on click of submit button as we have not provided a submit.jsp page to handle the request. (Done intentionally to show the elegant error handling of the framework)

Single-page template Vs Multiple-page templates

Here we have used one html file per page. We also have an option to keep multiple pages inside one html file. In that case, we need to give id to our pages and link them to each other accordingly using that id. But that can soon explode & become unmanageable, and is only recommended when there is some static data to be shown

CSS Layout Magic

We didn’t write much CSS still our HTML pages looks just like a mobile site and the “header”, “footer” and “content” data-roles are layout perfectly nice. It’s so because of the framework’s CSS file (jquery.mobile-1.0a3.min.css) which we have included in our HTML pages. Again proves what amazing things CSS can do :-)

Dreamweaver Integration with jQuery Mobile

Adobe has done a fantastic job in integrating jQuery Mobile with Dreamweaver and provides several templates to get you started. The editor also supports some level of code-completion for jQuery Mobile and even some support for Javascript.

Want to learn more ?

Even after writing such a long post, its hard to explain each line of code written above so the best way to learn more is to refer to the Docs. Or I might just write another post to explain some more.

Disclaimer

This is just an introduction to jQuery Mobile and might not follow the best practices like normally you would refer to jQuery framework files from some CDN than to include them with your own code. Also, the above code is static in nature, but it can be easily integrated with any database using some script and can form a fully-fledged application.

As always, comments and corrections are welcomed and appreciated.

Friday, September 24, 2010

Runtime Shared Library (RSL) – Flex 3

The best way to reduce the size of your Flex application (or the resultant SWF file) is to use Runtime Shared Library which uses the concept of dynamic linking.

Normally a Flex application consists of your application code as well as the framework code and the both of these codes are statically merged together in a single SWF file. It makes the resultant size of your application (the SWF file) larger by adding some 500 KB’s of data to it, which has to be downloaded each time the application is downloaded to a client.

On the other hand, RSL allows you to decouple your application code with the framework code and allows you to dynamically link both of them as and when needed (while running the application). Without wasting time, lets try and configure our project to use RSL instead of static linking. It can be done either using command line Compiler Options or by changing certain settings in Flex Builder. We’ll go the easy way:

Setup in Flex Builder

Following Steps are needed to Compile and Build a Project in Flex Builder with RSL in it:

  1. Select your Flex Project. Click on Project –> Properties
  2. Go to Flex Build Path
  3. Open Library Path Tab. By default the framework linkage is statically linked --> Merged into Code as shown below:

clip_image002

Change the drop down to Runtime Shared Library (RSL) for dynamic binding.

clip_image004

Make sure that Verify RSL digests checkbox is checked. Click Ok to complete the changes and the project will be recompiled with updated compiler settings.

This will create 2 files for RSL in the Output Folder of your project:

  • framework_3.X.X.XXX.swf (Unsigned/Failover RSL)
  • framework_3.X.X.XXX.swz (Signed RSL)

By default, the Flash player will try and use the Signed RSL to link with your application code on loading but the signed RSL works only with Flash Player 9.0.115 and later. If your clients are using a lower version, then it will be unable to load the Signed RSL (swz) and will automatically switch over to the failover RSL (swf) and use it in place of Signed RSL.

A Major benefit of using Framework RSL is caching. RSLs are cached when they are first used. When they are needed by another application, they can be loaded from the cache rather than across the network. The signed framework RSL (RSL’s can be signed by Adobe only) can be cached in the Flash Player cache as well. This benefits by reducing the initial download time as there is no need to download the framework code every time you need to run your Flex Application. And since the caching is done in the special cache of the Flash Player and not in the browser cache, so this signed RSL can be used for some other Flex Application (served from a different domain than yours) On the other hand, the failover RSL is cached in the browser’s cache.

Compiler Settings

Apart from RSL, while building the project for Production Environment, the debug option must be set to false, else the resultant SWF file will also contain the debug information, which is unnecessary for the production environment. To do so, right click the project, go to Project Properties and open the Flex Compiler View and add

-debug=false

in Additional Compiler Arguments as shown below:

clip_image002[8]

Without doing this also, it will work but the resultant SWF file will have debug information with it. The default value of this parameter is true.

Go Check the output folder of your web application and you will definitely see a reduced SWF file there Happy Flexing :-)

Friday, August 20, 2010

Thread-safe Generic Class in Java

Assuming that you are a Java Developer, I can say that you have at some point or the other must have used Generics in your code, be it using a Generic Collection (if you have worked with Java5+) or in any other way. Even if you are not a Java developer, you must have played with Templates (in C++) in your school/college days.

Today, we are going to do something similar in Java. We are going to create a Generic Stack class in Java, which you can use to create a Stack of Integers, Floating Point Numbers, or a Stack of Students or any custom type that you have. Just to make code a bit more interesting and tough, I have also made it thread-safe so that multiple threads can use this stack without leaving it in an inconsistent state.

public class GenericStack<T> {

private List<T> items;
private int top;
private int size;
private static final int INIT_SIZE = 100;

public GenericStack(){
size = INIT_SIZE;
items = new ArrayList<T>(INIT_SIZE);
top = -1;
}

public GenericStack(int size){
this.size = size;
items = new ArrayList<T>(size);
top = -1;
}

private boolean isEmpty(){
return (top==-1);
}

private boolean isFull(){
return (top == size-1);
}

// Push an Item in Stack
public void push(T item){
synchronized(items){
// While stack is Full
while(isFull()){
try{
// Wait till Stack is Full
items.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
// Produce Item
items.add(++top, item);
// Notify other threads
items.notify();
}
}

// Pop an item out of stack
public T pop(){
T item = null;
synchronized(items){
// While Stack is Empty
while(isEmpty()){
try{
// Wait if its empty
items.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
// Consume an item
item = items.get(top--);
// Notify other threads
items.notify();
}
return item;
}
}

Most of the above code is self-explanatory but lets highlight some of the major concepts used here:
  • To create a Generic class, one must specify the Type along with the class name (as done using T).
  • When you initialize it, all the occurrences of T will be replaced by that particular type.
  • We have also made the above Stack class thread-safe, i.e. it can be shared and updated by multiple threads in a consistent manner using synchronized blocks.
  • We have checked before pushing for a Full Stack and we also check for an Empty Stack before popping an element
  • We have not made the isFull() and isEmpty() methods as synchronized as they are private (hence not visible to clients) and are always called from an synchronized context from within the class.
  • If you need isFull() and isEmpty() to be public then make them also synchronized to make them thread-safe
  • It is always better to have synchronized blocks rather than synchronized methods as it is always better to synchronize as less code as possible. Although, here we could not make much use of this concept but rather than obtaining the lock on the calling object, we obtain a lock on the shared list of items.
  • Calling synchronized(items) means if some other thread has not yet acquired a lock on items (By the way, each Object in Java has an associated Lock with it), then this current thread acquires the associated lock and proceeds. Otherwise if some other thread has currently acquired the synchronized block, then it must wait in the wait list of the object (items) in question. The thread then waits until it receives a notification that the lock has become available for acquisition and then it competes with other waiting threads to acquire the lock.
  • Calling items.wait() results in the current thread being placed in the wait list of items after releasing the lock. You can only call object.wait() after you have acquired the lock on the object.
  • Calling items.notify() results in sending the notification to one of the threads in the wait pool of threads which can then compete for the lock.
  • Note that items.notify() does NOT releases the lock. Only exiting the synchronized block/method releases the lock that was acquired when the thread entered the synchronized block/method.

You can easily create two or more threads (viz. Producer and Consumer) and pass them the same Stack and play with them to randomly create and consume data and check that you Stack class is indeed thread-safe.

Generic Methods

Talking more about generics, you can also make a method accept Generic parameters without the enclosing class declaring the Generic type as done in the following example:

public <T> List<T> createArrayList(T t){
List<T> arr = new ArrayList<T>();
return arr;
}

This weird looking syntax has a meaning:

  • This method basically lets you create an arraylist of any type, type is passed to it as an argument.
  • Since you are not defining the type at Class-level, then there must be a place where you should define the type of your method and distinguish it from other non-generic methods for the compiler.
  • So, we declare the type <T> immediately after public modifier to say that we use a Generic Type T in this method, which like others will be replaced at runtime with any real type. (just like in case of Generic classes)
  • We call this method passing to it a valid reference to any Object of any type (Integer, Float, or you own custom class Student). For example, we can do:
Integer i = 23;
List<Integer> intList = createList(i);

or

Student st = new Student();
// Do anything with st here
List<Student> students = createList(st);

Ok, I agree this is not one of really useful examples for showcasing the power of a generic method but I hope that the intent is clear and so is the syntax. As always, your valuable comments are welcome and desired. Any corrections must also found place in comments. Sayonara :-)