Thursday, February 28, 2013

JXPath


We all know about XML and XPath
Basically XPath is a way to query xml files, similar to select statements on a database.
Example: Finding the node BBB in the following xml, you would use the query: /AAA/DDD/BBB
<AAA> 
          <BBB/> 
          <CCC/> 
          <BBB/> 
          <BBB/> 
          <DDD> 
               <
BBB/> 
          </DDD> 
          <CCC/> 
     </AAA>

Of course the query options for the XPath are very complex, and allow easy retrieval of nodes in the xml.
Now let’s say that instead of using xml’s we are using java classes (either it has nothing to do with xml’s or we marshaled the xml to a class for processing).  In essence the concept is very much the same. You have an instance graph of classes, and you want to traverse the graph to get a value on a specific node.
The solution for this is JXPath (http://commons.apache.org/proper/commons-jxpath/). You can now search your graph using standard xpath expressions.

For example:
 Class Address{  
 String zipCode;  
 }  
 Class Location{  
 Address address;  
 }  
 Class Vendor{  
 List<Location> locations;  
 }  

Old code:
 Address address = null;  
 Collection locations = vendor.getLocations();  
 Iterator it = locations.iterator();  
 while (it.hasNext()){  
   Location location = (Location)it.next();  
   String zipCode = location.getAddress().getZipCode();  
   if (zipCode.equals("90210")){  
    address = location.getAddress();  
    break;  
   }  
 }  

JXPath code:
 Address address = (Address)JXPathContext.newContext(vendor).  
      getValue("locations[address/zipCode='90210']/address");  
Further reading:


Wednesday, February 6, 2013

Location auto complete lookup


I have a client that wanted to add the ability for the client to have an autocomplete of location names.
I started thinking of how to implement it and from where to get the information for the location names.
Then i came across of the following service:

Google Places Auto complete: https://developers.google.com/places/documentation/autocomplete

A blog that explians in details of how to use it can be found at:
http://ddewaele.blogspot.co.il/2011/05/introducing-google-places-api.html