Groovy – Java keyword as a method name

Java, like any other language has reserved words. We are not allowed to use these words as method names or variable names. Most of the times that is fine, but sometimes we may find that these reserved words form the best name for a method. Helplessly, with just a sigh, we name the method with its synonym instead.

Groovy, being a JVM language, has the same set of restrictions. But since it is completely dynamic in nature, it handles this scenario a bit differently from within and allows us to use reserved words as method names. All you have to do is wrap the method name within quotes during method definition as shown below and you are done. Cool isn’t it?

class User {
  String name

  String "delete"() {
    name = ""
  }
}
def user = new User(name: "ganesh")
assert "" == user.delete() 

LavaLamp for jQuery lovers!

lavalamp-image

Click on the above image to land in the Lava Lamp Demo page. Then, hover over it and feel for yourself, the nifty effect that Lava Lamp offers. What you just experienced is nothing but the LavaLamp menu packaged as a plugin for the amazing jQuery javascript library. I personally believe that the effect rivals that of flash – Don’t you? Especially considering the fact that it is extremely light weight.

Just so you know, it weighs just 700 bytes(minified)!

Often I have noticed, that the credits are usually granted towards the end. Just for a change, i am going to give my credits at the beginning. This effect was originally written by Guillermo Rauch for the mootools javascript library. All I did was to port it for the benefit of jQuery lovers. Thanks Guillermo for inspiring the javascript world with such a nice effect. A special thanks to Stephan Beal who named it “LavaLamp”, and to Glen Lipka for generously helping with the image sprites. Many fellow jQuery lovers also helped shape this plugin with valuable feedback in the mailing list. Thanks a ton, all you guys.

As User Interface developers, we know that one of the first widgets our visitors use is a “Menu”. Capturing their attention right there is something that we always strive for, and I guess LavaLamp is a step in that direction. Before you get bored with all this useless talk, let me get you started on integrating LavaLamp into your jQuery powered site.

I hope you agree that a typical HTML widget consists of 3 distinct components.

  • A semantically correct HTML markup
  • A CSS to skin the markup
  • An unobstrusive javascript that gives it a purpose

Now lets follow the above steps and implement the LavaLamp menu for your site. Remember, In the process of porting from mootools to jQuery, i have simplified both the javascript and CSS for your convenience. So, be informed that you will need to follow the instructions on this page to get the jQuery version running. Follow the instructions on Guillermo Rauch’s page for the mootools version.

Step 1: The HTML

Since most UI developers believe that an unordered list(ul) represents the correct semantic structure for a Menu/Navbar, we will start by writing just that.

        <ul class="lavaLamp">
            <li><a href="#">Home</a></li>
            <li><a href="#">Plant a tree</a></li>
            <li><a href="#">Travel</a></li>
            <li><a href="#">Ride an elephant</a></li>
        </ul>        

In the markup above, “ul” represents the menu, and each “li” represents a menu-item. At this point it is crucial to understand that we will be adding another artificial “li” to represent the background of the currently highlighted menu-item. Since the background itself is cosmetic and doesn’t represent a menu-item, we will be adding it from javascript. Just to make sure we are in sync, “you need not add this li”, the LavaLamp plugin will take care of it. Once added, the “li” representing the background will look like this.

        <li class="back"><div class="left"></div></li>

Step 2: The CSS

You can skin this markup in many different ways to achieve your own personalized menu. The following style sheet is just one possibility. A few more possibilities are demonstrated in the “Bonus” section towards the end of this blog entry.

/* Styles for the entire LavaLamp menu */        
.lavaLamp {
    position: relative;
    height: 29px; width: 421px;
    background: url("../image/bg.gif") no-repeat top;
    padding: 15px; margin: 10px 0;
    overflow: hidden;
}
    /* Force the list to flow horizontally */
    .lavaLamp li {
        float: left;
        list-style: none;                    
    }
        /* Represents the background of the highlighted menu-item. */
        .lavaLamp li.back {
            background: url("../image/lava.gif") no-repeat right -30px;
            width: 9px; height: 30px;
            z-index: 8;
            position: absolute;
        }
            .lavaLamp li.back .left {
                background: url("../image/lava.gif") no-repeat top left;
                height: 30px;
                margin-right: 9px; 
            }
        /* Styles for each menu-item. */    
        .lavaLamp li a {
            position: relative; overflow: hidden;
            text-decoration: none; 
            text-transform: uppercase;
            font: bold 14px arial;
            color: #fff; outline: none;
            text-align: center;
            height: 30px; top: 7px; 
            z-index: 10; letter-spacing: 0; 
            float: left; display: block;
            margin: auto 10px;    
        }

Trust me, this is a simple style sheet. Follow along to understand what is done in each of its sections.

First, we style the “ul” with the bright orange background image and some basic properties like height, width, padding, margin etc. We use relative positioning because, that way we can absolutely position the background “li” relative to the “ul”. This helps by enabling us to move this background “li” freely within the context of the parent “ul”.

Next, we make the “li”s flow horizontally instead of vertically. By default, it flows vertically. There are a couple of techniques to do this. In this case, we are using the “float:left” to achieve this effect.

Next, we style the artifical “li” that represents the background of the currently highlighted menu-item. This uses the sliding doors technique. Also, notice the absolute positioning used as mentioned above.

Finally, we style the anchor that represents the actual clickable portion of each menu-item. These styles are mostly cosmetic and self-explanatory.

Some of the above rules may not be obvious if you are not very confident in how “positioning” works in CSS. For those, i highly encourage you to quickly read this article on CSS positioning. It is short, sweet and very informative.

Step 3: The Javascript

This is the easy part. Most of the javascript work is taken care by the Lava Lamp plugin itself. As a developer, you just have to include the mandatory and/or optional javascript files and fire a call to initialize the menu.

<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript" src="path/to/jquery.lavalamp.js"></script>
<!-- Optional -->
<script type="text/javascript" src="path/to/jquery.easing.js"></script>

<script type="text/javascript">
    $(function() { $(".lavaLamp").lavaLamp({ fx: "backout", speed: 700 })});
</script>    

Include a reference to the jQuery library and the LavaLamp plugin. Optionally, include the easing plugin as well. It has many cool effects, that are not contained in the core. For instance, the “backout” effect used in this demo is part of the easing plugin. You can download jQuery here, Easing plugin here, and the LavaLamp plugin here.

Next, in the document.ready event, fire a call to initialize the menu. You have the option to supply an easing “fx” , the “speed” with which the animation happens and a callback to be executed when a menu-item is clicked. They are optional, the default “fx” being “linear” and the default “speed” being “500” ms.

That’s it. At this point you should have a working version of LavaLamp menu for your site.

Bonus

Just with some minor changes in the style sheet, you can get a totally different look n feel for the menu. And yes, the HTML markup and the Javascript remain the same. Click on the image below to experience the demo for this underline-imageless lavalamp.

lavalamp-underline-image

Here is one more variation, again with just some minor changes to the style sheet. I know, they don’t look pretty, but all i am saying is that you are limited only by your imagination. Click on the image below to see the demo for this boxed-imageless lavalamp.

lavalamp-box-image

Finally, for your convenience, i have zipped up all the necessary files into a cohesive package. Download it, and open the demo.html to see all the 3 variations in one page.

Feel free to leave a comment with your feedback, suggestions, requests etc.

Update

Based on popular request, LavaLamp Menu has been updated to support jquery 1.2.x versions. Download the zip file for version 0.2.0 of LavaLamp and open the demo.html to check it out for yourself. Since Firefox 3 has some issues with $(document).ready() function, try using $(window).load() instead if you face any problems. Hopefully a future version of Firefox or jQuery will fix the problem.

jCarousel Lite – A jQuery plugin

jcarousellite-img-02

jCarousel Lite is a jQuery plugin that carries you on a carousel ride filled with images and HTML content. Put simply, you can navigate images and/or HTML in a carousel-style widget. It is super light weight, at about 2 KB in size, yet very flexible and customizable to fit most of our needs.

Did I mention that it weighs just 2 KB?

As if that wasn’t enough, the best part is yet to come… You don’t need any special css file or class name to get this to work. Include the js file. Supply the HTML markup. Then, construct the carousel with just a simple function call.

Visit the project page for more information. There you can find a lot of demos and exhaustive documentation. This blog entry is just a teaser for further exploration.

Installing and getting it to work is as trivial as following the 3 steps given below…

Step 1:

Include a reference to the jQuery library and the jCarouselLite plugin. You can download jQuery here and jCarouselLite here. If you like interesting effects, include the Easing plugin as well (Optional). You may also want to use a compatibility easing plugin if you want to use old easing names. If you would like to navigate the carousel using mouse wheel, then include the mouse-wheel plugin as well (Optional).

<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript" src="path/to/jquery.jcarousellite.js"></script>

<!-- Optional -->
<script type="text/javascript" src="path/to/easing.js"></script>
<script type="text/javascript" src="path/to/mousewheel.js"></script>

Step 2:

In your HTML file, provide the markup required by the carousel (a div enclosing an ul). You also need the navigation buttons, but these buttons need not be part of the carousel markup itself. An example follows…

<button class="prev">&laquo;</button>
<button class="next">&raquo;</button>

<div class="any-class">
    <ul>
        <li><img src="image/1.jpg" style="width:150px; height:118px;"></li>
        <li><img src="image/2.jpg" style="width:150px; height:118px;"></li>
        <li><img src="image/3.jpg" style="width:150px; height:118px;"></li>
        <li><img src="image/4.jpg" style="width:150px; height:118px;"></li>
        <li><img src="image/5.jpg" style="width:150px; height:118px;"></li>
    </ul>
</div>

Step 3:

Fire a call to the plugin and supply your navigation buttons. You just managed to architect your own carousel.

$(function() {
    $(".any-class").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev"
    });
});

If you have any comments/suggestions/requests, feel free to drop in a comment or reach @ganeshmax in twitter.

 

Update

Based on popular request, jCarouselLite has been updated to support jquery 1.2.x versions. Goto the download page and download version 1.0.1 to enjoy jquery 1.2.x support. Since Firefox 3 has some issues with $(document).ready() function, try using $(window).load() instead if you face any problems. Hopefully a future version of Firefox or jQuery will fix the problem.

Show time! – First ever Amazon EC2 Success Stories

Amazon, always an innovator, recently unfolded yet another masterpiece to the world in the form of EC2 web-service. Gumiyo.com, an online mobile-commerce provider and Abaca.com, a spam-blocker solution, are now celebrated as the pioneers to launch a production site using Amazon EC2 Service. You can relish the full versions of their success stories here and here.

EC2 (Elastic compute cloud) – the name doesn’t tell much, or does it? For those who are not familiar, EC2 is a dynamically scalable data-center kind of service. It is not a REST/SOAP style web-service that we have come to conventionally recognize. We do not fire a call, and expect a response. Instead, we get access to virtual servers equivalent of Intel Xeon 1.7 GHz, 1.75 GB of RAM, 250 MB/S of network bandwidth and 160 GB of local hard drive space. Any number of such servers are at our disposal in just a matter of minutes, and that my friends, is not just innovative, but a killer idea in the data-center services arena. At 10 cents per hour of instance up-time, this service is something any start-up, if not individuals, should seriously consider. An EC2 account implicitly comes with a S3 account. Of course you can sign-up for S3 separately as well. In case you are wondering what S3 is, keep reading…

S3 (Simple Storage Service) is, well, a simple storage service that can be used to store and retrieve huge volumes of data over the internet. This offering has a similar accent to traditional web-services. The infamous REST and SOAP interfaces are provided for campers at both ends of the web-services campground. The value-add I see in this service is Simplicity, Cost effectiveness and more importantly, the trust that we already have over Amazon’s infrastructure. After all, they are one of the very few survivors of the DotCom boom. At 15 cents for a GB of storage per month and 20 cents for a GB of data transfer, S3 is something that i would use for all my back-up needs. Being a java programmer, I use the JetS3T library from Java.net and see how easy it gets…

// Sample code that uploads a file to S3. 
String access = "YOUR_AWS_ACCESS_KEY"; 
String secret = "YOUR_AWS_SECRET_KEY";
AWSCredentials cred = new AWSCredentials(access, secret);

// I used Rest, you could use Soap
S3Service s3 = new RestS3Service(cred);

// Buckets are like folders, but globally unique
S3Bucket bucket = s3.createBucket(access + ".Test");

// File that you want to upload
File file = new File("SomeFile.txt");

// Upload your file
S3Object s3Object = new S3Object(fileData);
object = s3.putObject(bucket, file);

Start-ups, small businesses and web 2.0 companies should regard these services as “God-Sent”. Well, I guess, I am not wrong. Two startups have already considered it serious enough to launch their production environment on EC2. And I’m sure there are more to come. Lets see what they are up to.

Gumiyo.com is the first end-to-end mobile commerce platform, connecting live buyers and live sellers through mobile phones and through the Web. Using any mobile phone with a built-in camera and a basic data plan you can create ads in 3 easy steps

1. Capture images or video of an item
2. Attach them to a multimedia message with a short description
3. Send it to post [AT] gumiyo [DOT] com

Gumiyo will create an online ad for you and then send you a reply link asking you to review and edit your ad before it is posted. You don’t need to use a mobile phone though. You can login and place your ad any time on the Web. You can even send them your ad as an email with photo or video attachments. Could it get any easier? Check it out for yourself.

Abaca.com is a spam-blocker appliance that you can purchase for under $2000. This email protection gateway offers 99% guaranteed filtration with zero management. At present, I don’t have a need for such an appliance as an individual. So, I didn’t try it out myself.

Will more and more businesses build around these services? Will traditional data-center providers offer EC2 as an option with GUI based configuration? Will amazon create more like these? What do you think?

Hibernate – Difference between session’s get() and load()

Being an avid hibernate fan, I have always defended it in my organization when people throw undue criticism at it in order to protect themselves. In one such debate, a colleague pointed out a pattern in our code-base that introduced needless performance degradation, and condemned hibernate for it. I was glad he brought that up – for 2 reasons. First because, it sure was a problem and called for immediate attention. Second because, once again the problem was not with hibernate, but us. If you look closely at domain driven applications, you will notice that a few core objects are directly referenced by most other objects. Let me clarify what i mean with an example. In an auction application, for example, an Auction is held for an Item, a Bid is placed for an Item, a Buyer buys an Item. The common object referenced here is, well, an Item. This implies that whenever you create a new Auction or Bid you are constrained to supply a reference to Item. The most obvious way to achieve this is by getting a persistent instance of Item from the database using the session.get() method. This works, but it has its limitations.

Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>

Item item = (Item) session.get(Item.class, itemId);

if(item != null) {
   Bid bid = new Bid();
   bid.setItem(item);
   session.saveOrUpdate(bid);
} else {
   // Handle the error condition appropriately
   log.error("Bid placed for an unavailable item");
}

Think about it… How many times will a bid be placed for an Item? Many… Every time a Bid is placed, is it wise to hit the database and retrieve the corresponding Item just to supply it as a reference? I guess not. That is where session.load() comes in. All the above scenarios remaining the same, if you just used session.load() instead of get(), hibernate will not hit the database. Instead it will return a proxy, or an actual instance if it was present in the current session, and that can be used to serve as a reference. What does this buy you? At least 2 advantages. First, you save a trip to the database. Second, the error handling code just got elegant. Take a look at the code snippet below. Here we don’t handle erroneous conditions using null checks. Instead we use exceptions, which sounds appropriate in this scenario. Don’t they?

Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>

try{
   Item item = session.load(Item.class, itemId);
   Bid bid = new Bid();
   bid.setItem(item);
   session.saveOrUpdate(bid);
} catch(ObjectNotFoundException e) {
   // Handle the error condition appropriately
   log.error("Bid placed for an unavailable item");
}

From the above piece of code, it is obvious that, an ObjectNotFoundException may be thrown if the actual Item representing the given item id cannot be found. What i am not clear about – and neither is hibernate documentation – is which method is more likely to cause this exception and why? session.load() seems to have a possibility to throw this exception, and so does saveOrUpdate() for the same fact that item for the given id/proxy is not available. I would love to hear from people who have traveled this path and have an answer. Also, it would be wonderful, if you could point out other differences between session.get() and load() that i may have missed.

A journey of a thousand miles begins with one step.

A blog, being a means of communication, carry numerous different types of messages. Some are nothing more than pointers to other websites, while others campaign lengthy articles; some are personal diaries, others sport hardcore technology; some are edited by one person, others by teams. This being my first post, i wish to clarify what you can expect from my blog in the approaching future.

I, sure did take a looooooong time to enter active participation in blogosphere. Honestly, as a passive player all this time, i have gained a lot from the adept content of some serious bloggers. That strongly encouraged me to contribute back to the community, and learn in the process as well.

I spend my days, as a Software Architect in a product development company near LA working on Java EE, .NET, SOA, ESB and UI technologies. I know – “Architect” is an obscure title, and yes, the same is the case with mine. I am not just a white-board architect. I really do analyze, architect, design, develop, test, build and deploy solutions. Then why am i calling myself an architect? Well, because my business card states that.

The take-away point here is that, i am tech savvy and you can expect technical content. I will not bore you with my pet’s modus operandi, or stories about, how my gym trainer is so fat that i had to train him instead. But, on certain occasions, i might point to interesting articles, celebrate my latest accomplishments or post a couple of my masterpiece photographs ;-). Bear with me on those.