Tuesday, October 5, 2010

Important Callers - My first android app into the wild

Important
Callers
After developing several Android apps just for fun I finally developed the Important Callers app which can be used by many app users. The app is quite simple and helps the mobile user to not miss important calls by selecting the contacts as important one through the this app.

This is the review (very poor on first day) page of AppBrain for my app and if you have AppBrain installed in your mobile you can install the app from the web page itself. I am upgrading the app as I have started receiving  errors and comments as well.

Tuesday, August 17, 2010

Using jQuery with Vaadin

After spending some time with Vaadin and developing a small application and a usability framework the moment came in which Vaadin application had to be integrated with another existing application. The integration wasn't tough at all due to the nice work done by the Vaadin folks.

However at my place we have separate team for Vaadin core development and jQuery / JavaScript doing the client side hacking. So to make the job easier for both the sides I developed a small Contact Us demo application which creates a Vaadin form and beautifies it with jQuery Effects and Tooltip plugin.

Monday, July 19, 2010

Story Board - a small app built with jQuery and jQuery UI

After spending much time with Java and other Java technologies working behind the curtains in the dark and smoky rooms I started exploring front-end dominant languages like JavaScript, HTML5 and much talked CSS.

There are many JavaScript libraries and tools available out there but in all I really liked jQuery; it is simple and easy to use and growing at very rapid speed. More and more applications have started using jQuery extensively.

In this small application (I call it StoryBoard) I have used jQuery along with equally power jQuery UI library which gives a lot of functionality and control with much less code.

I use http://jsfiddle.net/ along with NetBeans to create small demo and find it really helpful to develop and test the application rapidly.

Monday, May 10, 2010

Twitter API with jQuery

After spending some time with Twitter REST API and jQuery; I decided to develop a small application to test both of these together. The example uses jQuery Ajax commands to load the given users public timeline through Twitter REST API.

jQuery is awesome and very popular JavaScript library which provides zillions of operations to manipulate client side objects. jQuery Ajax operations make it very easy to call the Twitter REST API and get the data in JSON format. The following line of code will call the Twitter for a user public timeline.

var url = "http://twitter.com/status/user_timeline/"+ $("input#tweepal").val()+".json?callback=?"; 
$.getJSON( url, function( data ){
   // process the reply  
});

For simplicity I have taken a textbox to enter the Twitter username with id "tweepal". The Twitter REST url contains a query string parameter "callback" without which Twitter reply will not be available to the Ajax function. Once received the data can be accessed like a normal JavaScript object. The received object is an array of tweets which can be easily traversed with jQuery.each() function.

$.each(data, function(n, tweet){
      $("div#tweet_time").val(tweet.created_at);
      $("div#tweet_text").val(tweet.text);
});

This completes all the blocks required to interact with Twitter from client side only. 


However there are plenty of libraries available for Twitter but its always exiting to make something on your own (specially using Twitter). Well I am struggling on how to post update using OAuth in same example. Will definitely post if get success.

Wednesday, April 14, 2010

jVark - A small Java/XMPP library to play with Aardvark

After spending some time with Aardvark, i found the tool really great to get answers pretty fast. Aardvark provides many ways to interact with the service however there are no APIs available as such to interact with the service programmatically. Meanwhile I was trying to make my hands dirty with Google GTalk service and developed a small and silly utility to interact with Aardvark service through GTalk in Java.

The library is very basic and helps the developer to connect to Aardvark and fire some command and see the response from Aardvark. jVark source is available at http://code.google.com/p/jvark

However the library requires significant amount of improvement for extensive use.

Friday, April 9, 2010

Distributed component events

The application is inspired from the Seam Component Events and uses Spring AOP for event trapping and JGroup for event distribution. The system is divided into two parts Event Generation and Event Consumption. Simple POJOs can be turned into event generator or event consumer.

// Event Generator
@Component("temperature-sensor")
public class TemperatureManager{
    @Out
    private Temperature currentTemperature;

    @RaiseEvent("temperature-updated")
    public void temperatureUpdated(Temperature t){
        this.currentTemperature = t;
    }
}
// Event Consumer
@Component("graph-generator")
public class GraphGenerator{
    @In
    private Temperature currentTemperature;

    @ConsumeEvent("temperature-updated")
    public void updateTemperature(){
        graph.displayTemperature(currentTemperature);
        // refresh graph
    }
}

The above two classes can be part of a single JVM or multiple JVM, with JGroup in place Event Consumer will still consume the events generated by the Event Generator running in different JVM. Spring AOP keeps track of the RaiseEvent annotation and does all the distribution and communication stuff.

Full source code and required libraries with NetBeans project is available at : component-events.rar

Wednesday, April 7, 2010

A cool Vaadin application on Google App Engine

Vaadin, as we all know is a rapidly growing GWT based Java Web Framework. The coolest feature of Vaadin is that there is no client/server concept as it is in GWT. The developer can freely code anything "anywhere" and Vaadin will handle all the client/server related stuffs. 

One of our existing in-house production application is built using GWT and causing lot of difficulties for developers in terms of understanding the model and designing the proper application. So to retain all the GWT features and offload the additional burdens we (as such I) have decided to move to the Vaadin and redesign the existing application.

To convince the technical and management team and for demonstration purpose I developed a small application in Vaadin and uploaded it to the Google Application Engine (click here) so that others can also get the idea and at the same time I can load test the application and get all the execution details from the App Engine dashboard.  

The application contains a simple functionality where in which the user can design her custom entry forms, enter/save form data and finally view the saved data in a table. The application was built in few hours only so it doesn't have "next big ground breaking idea" or the nice GUI but Vaadin provides fairly nice UI which can work for any application to start with.

To speed up the development I extended the basic Form functionality to a Generic Form so that UI Forms can be created not only from Java Beans but from java.util.Map also. The reason to choose this is because some of our applications are purely data centric where in which numbers of UI forms are presented to users; however the fields in every form can very even after application deployment so to reduce the repetitive development effort I have taken the model where in which forms not only can be generated at runtime but can behave line a normal pre-coded form in most of the cases.

There are still many points to resolve before we finally switch over to Vaadin as our web application development framework but with the growing popularity of the framework and new initiative like Vaadin Directory acceptance would not be much difficult.

Vaadin demo application url: http://vaadincoolapp.appspot.com/

Monday, April 5, 2010

gag - Google Annotations Gallery

gag is a new exciting open source library has been released by Google for Java. Google Annotations Gallery contains handful of annotations to spice up the code. This new library is aiming to express the code in the more realistic way than just plain old non-readable Javadoc comments. 
Not only one can leave expressive remarks in the code, but can use these annotations to draw attention to her poetic endeavors. Apart from static documentation some annotations use runtime instrumentation to perform annotated behavior also. The annotations are divided into following different categories:


Disclaimer: Disclaimer annotations allow you to disclose certain relevant facts about your code. If you want to ease your conscience with full transparency, then consider these annotations.

Enforceable: Enforceable Annotations are annotations enforced by dynamic bytecode instrumentation. Use the following annotations, then run your applications with the javaagent:gag-agent.jar option and your annotations get enforced at runtime.

Literary and Literary Verse: Coding is truly an art. These annotations can help you make your code come alive and help the artist within you be recognized. These speak for themselves . . . so to speak. You'll forever be revered for your code style and your code style. Literary Verse is a newly added sub package of Literary.

Remarks: Remarks annotations replaces the conventional Javadoc comments. These annotations helps better expressing the code than usual Javadoc comments.

Team: This is the new category added recently. The annotations express the team behavior and can be used to express events took place during team development.

Follwing is the list of my personal favorite annotations from the gag gallery:

From Desclaimer:
@com.google.gag.annotation.disclaimer.BossMadeMeDoIt("i swear its not my fault")
@com.google.gag.annotation.disclaimer.IAmAwesome("really, this is the coolest code i have ever written")
@com.google.gag.annotation.disclaimer.WrittenWhile("i m lost, i m lost, omg i m lost")
@com.google.gag.annotation.disclaimer.LegacySucks

From Enforceable:
@com.google.gag.annotation.enforceable.AnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything
@com.google.gag.annotation.enforceable.Noop

From Literary:
@com.google.gag.annotation.literary.Metaphor
@com.google.gag.annotation.literary.Oxymoron("truly a fine mess")

From Remarks:
@com.google.gag.annotation.remark.WTF("this is bullshit")
@com.google.gag.annotation.remark.LOL("this is legend...... wait for it ....ary")
@com.google.gag.annotation.remark.ThisWouldBeOneLineIn(language="groovy", toWit="the method isnt required at all")

From Team:
@com.google.gag.annotation.team.Visionary("this will surely put the Internet back in 90's")
@com.google.gag.annotation.team.Fired(person="asok", reason="well it wasnt his fault")

Well I am enjoying this treat and if you are a gut busting coder I am sure you will also enjoy too. Besides you can also submit your brilliant annotations to the library from the project mailing list.

Friday, March 12, 2010

Another NoSQL Database : FluidDB

FluidDB is another database in the NoSQL category. It is a cloud based data store and follows the Wiki style approach for data storage. By Wiki style user can create objects in the FluidDB space and modify the existing one. Yet it uses a permission model which differentiates the it from being exact Wiki like.

FluidDB provides HTTP API interface with JSON and provides the HTTP Basic Authentication. FluidDB is in the early private Alpha stage and exposed to only limited number of users. A Sandbox is available where anyone can play with the database and for more detail look one can request the private access by sending the FluidDB Team a Mail request.

FluidDB is basically divided into four parts: 1)User 2)Namespace 3)Tag 4)Object. The User is the primary entity like in any other case. User will create Namespaces, Tags or Objects. Namespace is a logical name and physical separation which primarily describes the Subject the User is interested in like Movie, Sport, Book, etc. Tags are the attributes which describe the subject further in detail like Genre, Year and Awards Tags in Movies Namespace. Tags can exist without Namespaces also like Event, Hot, New can be used irrespective of the subject. Objects are the key entities as they contains actual data. An Object can be created with a String value like http://twitter.com/dhavaln or Die Hard With Vengeance as a topic which can be expressed in detail with various Tags.

An Object can be annotated with Tags from any User or any Namespace. By attaching a Tag to an Object user can provide additional information as a Tag Value for that Object like:

Object: Die Hard With Vengeance
Tags:
  Movie=
  Movie/Genre=Action
  Movie/Year=1995

As you can see same name can be used as a Namespace and as a Tag also. Tag may not contain any value alternatively known as Marker Tags.

FluidDB provides a simple query mechanism through which Objects can be search in the FluidDB space with Tag and Tag values. The following query will return all the Objects having Movie/Year value as 1995.

/Movie/Year = 1995

/Movie/Year > 1995 will return all Objects having Movie/Year value greater than 1995. There are many other conditional approaches provided by FluidDB for searching and can be found here.

Many developers has started using the interesting FluidDB and created API libraries for various languages which can be found here. I have already started using the database with JFluidDB and finding its usefulness in many cases.

The simple HTTP and JSON based interface makes FluidDB widely acceptable in many problem domains in various languages and frameworks.

Thursday, March 4, 2010

Spring Roo with NetBeans

I am a NetBeans user and there are no reason to change the IDE for any tool as NetBeans try to accommodate most of the frameworks and tools. However most of the modern frameworks/tools has easy integration with the Eclipse, Spring Roo is latest in the list. I started evaluating Spring Roo for one of our internal small test application.

Due to the fact that Spring Roo integrated already with Spring Tool Suite (STS) they support using STS IDE for all development. After few here and there i could finally run as well as modify the Spring Roo application in NetBeans IDE.

Maven is a compulsory requirement (until the Ant/Ivy integration is available) for Spring Roo to run, so make sure Maven is configured and NetBeans is referring to the proper Maven repository.

1. Create the project from  the Roo Shell and fill the required artifacts for the basic startup.






2. Do perform:eclipse to generate the Eclipse artifacts and open the project in STS

3. Right click on the project and go to the Refactoring, select Push All option. A dialog box will show with number of files, select all the files and click on Ok. This will convert all the AspectJ code (.aj) to pure Java code. This is the point for which Spring Roo is considered to be non-intrusive and you can actually detach the Spring Roo from the application altogether.



4. Open the created application in NetBeans through Import Eclipse Project/Workspace option. Do clean and build and go for Run application. If not configured anything NetBeans will ask for the Web Server which can be selected to installed Apache Server.




Still there are many things in Spring Roo you can not do in NetBeans but for all those things, again one can go back to the command prompt or to the STS for required changes, refactor again and refresh the NetBeans project to take the new changes.

Tuesday, March 2, 2010

Easyb Revisited - A Groovy based BDD Testing Framework

easyb is a behavior driven development framework for testing. easyb accepts the Groovy syntax for better explanation of the test scenarios. The first time i encountered easyb, i could not understand the syntactical and semantical sugar but after learning Groovy now i am finding the framework pretty good and useful.

easyb provides two types of templates: one is Ruby RSpac based "it 'should...'" style and another is "given".."when".."then" style. I use the "given.." style because its very explanatory and yet simple make someone understand.

Let's take an example to understand the benefits of the easyb from a programmer and non-programmer's point.

// A utility class to be tested
public class StringList{
      public void add(String element){
           if(element == null){
                  throw new RuntimeException("Null values not allowed");
           }
           // add value
      }
}

//easyb story - given..when..then style
scenario "check StringList with null value addition", {   // scenario with a reason
     given "an empty StringList", {  // what all things available in the scenario
          strList = new StringList()
     }


     when "insert null value", {   // what all operations has to be carried out in the scenario
          insertNull = {
                strList.add(null)
          }
     }


     then "a runtime exception should be thrown", {  // what should be the result
           ensureThrows(RuntimeException){
                  insertNull()
           }
     }
}

//easyb story - it 'should..' style
description 'check StringList with null value addition'


before "initialize the StringList before each spec", {
    strList = new StringList()
}


it "should throw an exception when null value inserted", {
    ensureThrows(RuntimeException){
         strList.add(null)
    }
}

The above stories can be easily divided into two parts one who writes plain test scenarios and another who fills the valid code for testing. No additional knowledge or logic is required to write the test case. An online system can very well generate this kind of templates based on the user input.

// plain test scenario
scenario "check StringList with null value addition", {   // scenario with a reason
     given "an empty StringList", {  // what all things available in the scenario
     }

     when "insert null value", {   // what all operations has to be carried out in the scenario
     }

     then "a runtime exception should be thrown", {  // what should be the result
     }
}

The development or testing team can fill the scenario blocks later with actual code. easyb generates report with pending scenarios and executable scenarios. Pending scenarios are those in which no test code has been added so user can easily identify pending test cases from the reports.

The textual description is right available with the code and is also executable and comes in the result report. The approach helps team members to understand the test cases without much efforts or external documentation. 

The easyb comes in a .tar.gz distribution having easyb jar along with Groovy and Apache Commons CLI. So no additional Groovy dependencies are required.

...dev\tdd\easyb>java -cp .;$easyb_home\easyb-0.9.6.jar;$easyb_home\commons-cli-1.2.jar;$easyb_home\groovy-1.6.4.jar org.easyb.BehaviorRunner *.groovy

The above statement will execute all the .groovy files through easyb interpreter BehaviorRunner. There are various switches for detail result of the execution.

easyb generates the result reports in various formats like PlainText, HTML and XML, which can be integrated with any test-case reporting system.

The flexible syntax helps the business analyst and testing team to create test scenarios independent of the development team. A web-based test scenario identification system would be very helpful in generating various kinds of test cases from different users.

I use Netbeans IDE for all my development purpose. There is no plugin available for NetBeans but Eclipse and IntelliJ provides plugin for easyb. For NetBeans one can use the Ant scriptlets provided at Running easyb.

Additional refrences:

Monday, March 1, 2010

bsGrid - A simple HTML/Javascript/jQuery based data grid

bsGrid is a small javascript/jquery based data grid i have developed for data visualization. The grid is Ajax enabled and for each data operation calls a special service URL.

The grid provides basis functionalities like Sorting, Complex Searching, Paging, Column Freezing, etc. The server to client communication is in JSON so that simple POJOs can be used on the server side.


As of now the code uses Servlet for initial rendering but soon that will be converted to a jQuery Plugin for multiple platform. For other detail refer to the Google Code project site : http://code.google.com/p/bsgrid

Tuesday, February 23, 2010

Open Source NoSQL Databases

The article lists open-source databases falls into the NoSQL category. NoSQL is another database paradigm where conventional relational approach and SQL query has no space, rather databases follows the semi-structured, graph based or key-value pair based storage approach for new age social and distributed application requirements.

Enjoy the article.

Saturday, February 20, 2010

Google Ambassadors: 45 Essential Google Links

Google has many well-known and some lesser-known products that everyone who uses Google should be familiar with. The following list has been prepared by Google Ambassadors, a group responsible to promote Google products to Internet users, an explanation about the group activities can be found here.

GWT client with REST

This article explains a small prototype i developed for a friend to show how REST services can be used can be used from the client code and avoid additional RPC call. The demo explains only two fundamental class structures to access the remote service.

RequestBuilder
GWT client API is having an HTTP request builder class which helps the application to make remote connection through HTTP request and supported methods (GET, POST).

RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, urlAddress);
builder.sendRequest("", new RequestCallback() {
  
  public void onResponseReceived(Request request, Response response) {
     //use response.getText() to get the resulting text from the service
  }


  public void onError(Request request, Throwable exception) {
     // exception handling
  }
});

XmlParser
GWT client API also provides XML parsing capabilities but to use that XML.gwt.xml has to be included in the modules file.

The following code can parse the XML text and prepare complex node list which can be traversed to access the attributes and node values.

    Document doc = XMLParser.parse(response.getText());

Once Document instance is generated program can start traversal from the root node or can search for the particular nodes based on the name.

    NodeList nodeList = doc.getChildNodes(); // to start from root node
    NodeList nodeList = doc.getElementsByTagName(nodeName);  // to start from selected node

Full source code with example services is available here.

Friday, February 19, 2010

Social Databases

    Like many others i am not a big fan of SQL databases available today. But every application needs some or the other ways to persist the information. Being a Java programmer there are many options available to avoid raw SQL interaction during the development through Hibernate, JDO or JPA. But these all at the end lands at relational database only.

    Soon i started gaining familiarity with the Google Bigtable and Amazon Dynamo for their non-relational approach and why relational database will not help for their kind of applications. Well the approach was shocking and different but fascinated and proven at the same time. Meanwhile many developers realized that they might need different kind of database altogether to help their applications grow and respond faster.

    This realization resulted into many unorthodox, simple yet powerful databases which now-a-days falls into the Social Database category.

    Neo4j is a graph database. It is an embedded, disk-based, fully transactional Java persistence engine that stores data structures rather than in tables. The database is quite small in size, approx <500k jar. It provides objected-oriented API to interact with the database.

   Besides such a small database, Neo4j provides all the usual database features like ACID transaction, durable persistence, transaction recovery and concurrency control.
    
    For further information you can look out this presentation video and slides by Neo4j creator.

    Cassandra is a highly scallable second-generation distributed key-value based database. Initially developed at Facebook and now resides in Apache Incubator. Cassandra combines best features from Amazon Dynamo and Google Bigtable. Cassandra just like Neo4j is tested and proven for high-volume, high-transaction environments. Companies like Facebook, Twitter, Cisco, Mahalo and many more uses Cassandra in their applications.
    
    Cassandra follows the decentralized model where every node in the cluster is having identical information so there is no single point failure. Like many clustered databases, Cassandra follows the Eventually Consistent model and supports advanced features like Read Repair and Hinted Handoff to minimize inconsistency windows. 
    
     There are lot of presentations for the same can be found at SlideShare.net. 

    I have just started my working on this new kind of database. FluidDB is a hosted online cloud database. FluidDB follows the Wiki kind of approach where either user or application can created objects and modify the existing objects. Though it doesn't follow the Wiki model as it is and maintains certain restriction like permission and strict data type. It provides an efficient query mechanism to search through the database. The database provides simple HTTP request API for access.
    
    The database is in the private alpha as of now and you might get an access after sending the FluidDB team a mail API access request. As such i have not explored the database fully but there are plenty of ways this database can be used in today's applications.
     
    Tickery is a simple Twitter based application developed by team FluidDB team for demonstration purpose. 

  With the growing amount of social applications and their complexities we might see varying amount of databases for different requires over the period of time.

    Though these databases will not help you remove the relational databases altogether but will help you deliver the desired complex functionalities fast, easy and with less pain.

Thursday, February 18, 2010

Vaadin-Spring Integration

I remember the time when i was trying to integrate Spring with Struts2 and GWT applications. The problem was rather documenting the integration stuff i tried to remember them and as usual tend to forgot them. So this time have decided to document the Spring integration with Vaadin.

  • web.xml changes
So first we need to add the Spring Context listener to load the bean configuration file.

<listener>
  <listener-class>
    org.springframework.web.context.ContextLoaderListener
  </listener-class>
</listener>

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

Add the Spring Servlet to intercept Vaadin requests

<servlet>
  <servlet-name>VaadinSpringServlet</servlet-name>
  <servlet-class>com.dhaval.web.vaadin.spring.servlet.SpringApplicationServlet</servlet-class>
  <init-param>
    <param-name>applicationBean</param-name>
    <param-value>testApplication</param-value>
  </init-param>
</servlet>

<servlet-mapping>
  <servlet-name>VaadinSpringServlet</servlet-name>
  <url-pattern>/vaadin/*</url-pattern>
</context-param>
  • Spring Servlet
This servlet connects the Spring with Vaadin. The servlet loads the Vaadin Application class and dispatches all the HTTP requests/responses. The Servlet is available in the Simple Application provided by Vaadin Team for Spring integration.
  • Spring bean configuration
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property>name="driverClassName" value="${db.driver}"/>
  <property>name="url" value="${db.url}"/>
  <property>name="username" value="${db.user}"/>
  <property>name="password" value="${db.pass}"/>    
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  <property>name="dataSource" ref="dataSource"/>
</bean>

<bean id="dao.user" class="com.dhaval.web.vaadin.spring.dao.UserDaoImpl">
  <constructor-arg>ref="jdbcTemplate"/>
</bean>

<bean id="testApplication" class="com.dhaval.web.vaadin.spring.MyApplication">
  <constructor-arg>ref="dao.user"/>
</bean>

testApplication bean id is same as we have given in the web.xml as an init-param to Spring Servlet.
  • Vaadin Main Application class
This is my Vaadin Application class

public class MyApplication extends Application{
    private UserDaoImpl userDao;

    public MyApplication(UserDaoImpl userDao){
        this.userDao = userDao;
    }

    public void init() {
        Window mainWindow = new Window("Simple Vaadin Spring Integration");

        final TextField txtUser = new TextField("Enter username");
        Button btnCheckUser = new Button("Check Username");
        final Label lblCheckMsg = new Label("");

        btnCheckUser.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                boolean result = userDao.hasUser(txtUser.getValue().toString());
                if(result){
                    lblCheckMsg.setValue("Available");
                }else{
                    lblCheckMsg.setValue("Not Available");
                }
            }
        });

        mainWindow.addComponent(txtUser);
        mainWindow.addComponent(btnCheckUser);
        mainWindow.addComponent(lblCheckMsg);

        setMainWindow(mainWindow);
   }
}

The full source code is available at vaadin-spring-integration in download section.

Wednesday, February 17, 2010

Groovy GPath for complex object traversal

GPath is a path expression language integrated into Groovy which allows parts of nested structured data to be identified and processed. GPath is named after popular XPath functionality to traverse XML nodes. GPath can be used to process XML nodes or composite objects.

class Person{
String firstName
String lastName
int age
}

def personList = [
new Person(firstName: "dhaval", lastName: "nagar", age: 25),
new Person(firstName: "nachiket", lastName: "patel", age: 24),
]

The easiest way to get all firstName from the above collection is to use collect{} closure:

println personList.collect{it.firstName}
// will print ["dhaval", "nachiket"]

But Groovy believes in shortening the most obvious stuff so the above statement can be rewritten like the following the still get the same result.

println personList.firstName

This feature becomes powerful when combined with Regular Expression. The following statement will print all the person whose first name starts with "d".

println personList.firstName.grep(~/d.*/)
// will print ["dhaval"]

However GPath is more popular to parse the XML documents effectively. Here we will take a small XML document and parse it with XmlSlurper and access it's nodes with GPath.

def mylinks = """
<links>
  <link>
    <id>1</id>
    <url>www.google.com</url>
  </link>
  <link>
    <id>2</id>
    <url>www.apple.co.in</url>
  </link>
</links>
"""

def links = new XmlSlurper().parseText(mylinks)

The following statement will print all the URL ending with "com"
println links.link.url.grep(~/.*com/)

The following statement will print all the URL ending with "co.in". One way to escape the . is to surround it with square brackets.
println links.link.url.grep(~/.*co[.]in/)

If my xml document changes radically, its affects my code very slightly.

def mylinks = """
<links>
  <link id="1" url="www.google.com"/>
  <link id="2" url="www.apple.co.in"/>
</links>    
"""

To find out urls ending with "com" and "co.in":

println links.link.@url.grep(~/.*com/)
println links.link.@url.grep(~/.*co[.]in/)

@ is the operator to access the property of a node. Parsing XML documents in such an easy way is a dream come true for a Java programmer.

Monday, February 15, 2010

Aardvark - A Valuable Business Tool

Couple of days before I got a news that Google acquired another popular Internet service called Aardvark in nearly $50 Millions. Aardvark is a social search engine service that connects users live with friends or friends-of-friends who are able to answer their questions. Based on my short interaction with the tool i realized that it can become a great boon for any kind of organizations.

I started using the Aardvark after this news and i found it really good tool to get the answers properly and pretty fast. I am using Yahoo Answers for all my non-technical questions and Stackoverflow for technical questions as I am a software engineer. Though both of these tools are doing pretty well, I was still finding that both the services are missing something.

Now to show Aardvark from an organization perspective, I work in a quite a big organization which employs huge and diversified manpower. Such a big enterprise contains an MIS system to keep employee profile information for future references. However its really hard to keep the latest profile information of each of the employee in the organization.

Every organization generates enormous amount of industry specific problem. When the problem arise they either seek an internal help based on the employee profile information or contact external agencies for support. In any case its time consuming at first and huge investment at the end, in the worst case an organization spends huge money on an external agency who fails to do the job and eventually either the problem is dropped or they find someone from inside.

To not cause such a heavy damage, now a days most of the companies (well software in particular) use Wiki/Forum/Blogs to tackle the situation and spread the knowledge. But this approach is limited to a set of companies and its not interactive. User seeking the information has to search through the set of services to find the answer to his problem.

People tend to learn new things every now and then so their profile keeps on updating compared to organization which prefers to update the profile information every six months or a year. So this approach creates mismatch between the actual employee profile and its organizational print. Because of this match many a times Organization end up hiring brand new resource or seek for some external agency to solve the problem.

Aardvark is a tool which can really bridge the gap between this mismatch. Employee getting new knowledge every now and then can update her profile immediately. Aardvark is intelligent enough in delegating the question to right persons. Such an intelligent and fast communication medium can be used in Enterprises to solve problems immediately without investing further valuable resources.

Well while writing this Aardvark is officially part of Google so in future we might see many new features combined with existing Google services.

Thursday, February 11, 2010

Google Buzz - sharing with GMail

Buzz a new service just announced by Google available under the GMail account. Buzz is designed to share day to day stuffs like text, images, videos, etc. Most of the features are similar to other popular social sharing services apart from the GMail front and other Google services integration.

Following are few buzzes of the Buzz.
  • Two mode of sharing is available. Public sharing similar to twitter and Private sharing where update is visible to the users of selected group(s)
  • Many external applications can be configured as a connected sites like YouTube, Google Reader, Picasa, Blogspot, Blogger and Flickr. As such you can paste link having images or videos, Buzz will scan the media files and show you the available contents to select if there are multiple images or videos available. I tried with flickr, vimeo, wikipedia and smashingmagazine
  • All Buzz entries are available in your Google Profile page under Buzz tab
  • Any post shared in the Google Reader will be available as a Buzz entry if the Reader is configured as a connected site
  • A Buzz can be directed to user(s) through '@' symbol before the username like @dhaval.b.nagar@gmail.com
  • Twitter updates are available as buzz entries if Twitter is configured as a connected site
  • To create RSS for your own Buzz entries, go to your profile page and select the Buzz tab. Copy the URL and add it in the Google Reader under Add Subscription
  • Buzz allows to post Link, Images and Videos to entries. Images can be seen with presentation feature on the same page. Videos can be seen live
  • Each conversation can be seen independently from the Time Link given on the top right of the dialog box
  • As such you can paste any link on the conversation dialog box and Buzz will find all the available images and videos on the page. You can select at max 4 media content to post.
Overall Buzz falls somewhere between the Google Wave and many other popular social applications. With the failure of Google Wave (or may be Buzz in near future) we will see many such applications trying to fit in the "Social Shoe" from Google.

Wednesday, February 10, 2010

Groovy Category and Dynamic Overriding

A Category class is an ordinary class which contains set of methods. The class can be used for a duration of code block and when used first parameter type of each method treats the declared method as its member method.

class TestCategory{
static def test(String str){
return "testing"
}
}

use(TestCategory){
// test() can be called as a member method inside the use block
assert "testing" == "a".test()
}

A category class can contain method without any parameters but it is not possible to use such method in the use block. A category class method should at least have one parameter to get called from the use block. The following code will throw an exception at the time of execution.

class EmptyMethodCategory{
static def emptyMethod(){
return "empty"
}
}

use(EmptyMethodCategory){
assert "empty" == emptyMethod()
}

Operator overriding is the most suitable use of the Category classes. In case of operator overriding, if the caller is not matching with any of the overridden methods, original method will be executed.

class StringSumCategory{
static def plus(String str1, String str2){
return str1.toInteger() + str2.toInteger()
}
}

use(StringSumCategory){
assert 3 == "1" + "2"
assert "12" == "1" + 2
}

If the category class contains a method with only one parameter of type Object, that method will be available to any possible type in Groovy.

class SerializeCategory{
static def serialize(Object obj){
// do serialization stuff
return serializedObj
}
}

use(SerializeCategory){
println 1.serialize()
println "a".serialize()
println ([1, 2, 3].serialize())
println this.serialize()
println serialize()
}

Groovy is full of surprises. It contains some of the best features from many static and dynamic languages.

Spread operator

Spread operator helps Groovy collections (list, range and map) to simple comma separated values. Spread operator is so flexible which can be used anywhere. For example:

def test(a, b, c){
return a + b + c
}

def numList = [1, 2, 3]

If you want to pass the above list of values to the test() method you have to write some boilerplate code to extract the elements and pass them in the method.

Whereas the spread operator is introduced to eliminate boilerplate code and follow clean coding. The above method can be called with the given list without a single extra line of code.

test(*numList)

An asterisk followed by list, range or map will spread the collection and convert all the containing values to comma separated values. The above example will work same for Range.

def numRange = 1..3
test(*numRange)

Map has different syntax compared to List and Range.

def aMap = [a:1, b:2]
def bMap = [c:3, *:aMap]

Likewise Groovy contains many such shortening facilities where development time can be reduces and code can remain clear and understandable.

Groovy spread-dot operator in GPath

GPath is an expression language integrated into Groovy to process nested objects. The dot and spread-dot operators helps to build the GPath expression. The dot operator is used to access the properties and spread-dot operator is used to access property, field or method.

class Person{
String firstName
String lastName
int age

int calc(){
return age * 2
}
}

def personList = [
new Person(firstName: "dhaval", lastName: "nagar", age: 25),
new Person(firstName: "nachiket", lastName: "patel", age: 24)
]

To access the firstName property one can use either of the operators:

println personList.firstName
// ["dhaval", "nachiket"]

println personList*.firstName
// ["dhaval", "nachiket"]

To access the calc() method spread-dot operator has to be used, whereas dot operator will raise an exception:

println personList*.total()
// [50, 48]

Apart from the access restrictions both the operators works differently when collection contains null values like:

personList << null
personList << new Person(firstName: "sandeep", lastName: "shah", age: 30)

println personList.firstName
// ["dhaval", "nachiket", "sandeep"]

println personList*.firstName
// ["dhaval", "nachiket", null, "sandeep"]

The spread-dot operator will add the null value for each null element in the resulting list.

Both the operators works same when the list element is not null but the requested property is null.

personList.clear()
personList << new Person(firstName: "dhaval", lastName: "nagar", age: 25)
personList << new Person(lastName: "nagar", age: 25)

println personList.firstName
// ["dhaval", null]

println personList*.firstName
// ["dhaval", null]

To avoid such null values in the resulting list, grep expression can be used.

println personList.grep{it?.firstName}.firstName
// ["dhaval"]

Here grep will try to evaluate the true boolean condition, as per the Groovy Truth if an object is NULL it will be considered as FALSE. So above expression will reject all the objects where firstName property value is null.