Wednesday, December 22, 2010

Lens Comparision

Never thought that I would be writing a lens comparison article ever. But this one had to be written. Since my lenses and the D300 body were stolen on the way back from Benares I had been thinking a lot about getting a lens. I seriously considered a Tokina 17-50mm f/2.8, my old (and now stolen) trusty 18-105mm Nikon and the 16-85mm much praised Nikon. The long-zoom section bothered me (and still does) as there is almost nothing without a constructional flaw except probably 70-300 Nikon but that be saved for another day.
After a lot of flip-flopping I decided to buy the 16-85mm Nikon. Now I still had two lenses from before, the 18-55mm Nikon and the 50mm f/1.8 fixed again Nikon. Immediately I wanted to make a comparison between the three lenses. I just don't want to make any comments. The comparison is right here for you to see.

      18-55mm f/8 1/10s

     16-85mm f/8 1/10s

      50mm f/8 1/10s
And all above were shot in exact same light within minutes of each other. Camera mounted on tripod. The zooms were set to 50mm manually. All were stopped down enough to achive optimum or near optimum performance. The crop was taken slightly off center. The image on the left is obviously the weakest. But the one on the right (50mm prime) is clearly far less flattering than the center image. 16-85mm f/3.5-5.6 AF-S ED shines through the 2 ED and 1 Nano coats on the glass.

Saturday, November 6, 2010

Concurrency for Persistent Storage

I have been thinking about concurrent updates to relational databases and a strategy to deal with the problem. Of course it is not the hottest thing on earth but until I figured out what to do - I just did not know the solution. I will have this documented here in hope of referring to in the future. If this also helps anyone else; I will be glad.
A few words about concurrency itself in the beginning would put the following discussion in the right perspective. Any object that is visible to multiple threads is subject to be read or written by multiple threads. The problem of concurrency arises from the scenario described above. A particular thread may 'think' that it has updated the value of a String variable from "a" to "b" but in reality it may have only updated the value from "c" to "b". Consider the events below.


1. Thread 1 reads the value of a String variable name to be "Joe".
2. Thread 2 also reads the value of a String variable name to be "Joe".
3. Thread 1 & 2 decide to update the value to "Jack" and "Jill" respectively.
4. Thread 2 gets his chance and changes name to "Jill".
5. Thread 1 (having no knowledge of Thread 2's existence changes name to "Jack".


In my real life applications I would like Thread 1 to be informed at step 5 something like this "sorry mate that name has changed. please go and fetch the new value and then come and update it". This problem begins to fade slightly if the threads are required to acquire the intrinsic lock on the name object described above. Note: if we just make the threads acquire the lock, the problem does not go away completely. In order to fix the problem one must acquire the lock, read the current value, ensure that is the same as before acquiring the lock, update the value to the new desired one and release the lock. In code that looks like so.


public void setName(String oldName, String newName){
    synchronized(this){
        String currentName = getName(); // Database equivalent of "Select... for Update"
        if(currentName.equals(oldName)){ // verify name has not been changed since our last read
                name = newName; // only now we are ready to make an exclusive update
        } else{
                throw NameAlreadyChangedException();
        }
    }
}


Ok problem solved. But wait, that name field is stored in a persistent storage and locking a Java object does not necessarily mean that no one else can update that row in the store. That's why most good databases let the user lock a record using "select for update" and it is generally referred as the 'last select'. But that works for some (may be most if not all) relational databases. But I am not ready to make any assumption about the type of store (relational or otherwise). I am looking for a strategy; not a specific solution.


In my test environment I am using Spring, Spring's JpaTemplate and MySQL. And I particularly like the approach of optimistic locking using version attributes. So here goes my Entity class.

@Entity
public class Person {
    @Version
    @Column(name = "VERSION", 
     nullable = false
    )
  private long version;
  @Column(name = "NAME")
  private String name;
  public long getVersion() {
return version;
  }
  private void setVersion(long version) {
     this.version = version;
  }

  public String getName() {
return name;
  }
  public void setName(String name) {
     this.name = name;
  }
}


So JPA provides this @Version annotation and the value of the field is automatically managed (i.e. auto-incremented on every update). Very nice. So my original if(currentName.equals(oldName)) translates to something like if(pojo.getVersion() == persistedPojo.getVersion())
And I can finish off my Repository (aka DAO) code in style like so.

@Repository
public class SupplierRepository extends JPATemplate // not exactly so in real code
...
// pojo.setName() has been called elsewhere
public Person update(Person pojo) {
synchronized (pojo) {
  Supplier persistedPojo = super.find(Supplier.class, pojo.getId());
  if(pojo.getVersion() == persistedPojo.getVersion()) {
    return super.update(pojo);
  }
  else {
    throw new OptimisticLockingFailureException();
  }
 }
}

Beginning with the commented line I can let hundreds of threads call the setName(...) method totally 'un-thread-safely'. Only one is going to be successful in committing the data to the persistence layer anyway. The intrinsic lock acquiring line synchronized(pojo) ensures none but one thread executes the remaining lines. Then the findbyId reads the current row (hence the latest version number) from the store. On verification (if condition) the update happens. The point I want to make here is multiple threads can still get inside the synchronized block (after the first one to get access relinquishes) but they will all fail the version test hence will face the OptimisticLockingFailureException which is an unchecked exception defined by my application.

Thursday, September 16, 2010

Validation in Grails

I had a long time inertia against writing exception handling and displaying user friendly message in the UI. And it appears I am not alone! But is time to shake it off. Welcome to Validation and Error messaging - Grails Style!
Before I get started (and promise I will be done before I notice) some facts.

1. You define constraints in your Domain class. For example..
package foo.bar;
class Item {
String itemName
..
static constraints = {
itemName(blank:false,unique:true, nullable:false)
..
}

2. Now if you say..
def someCoreItemInstance = new Item()
Domain classes have implicit object "error" in them. In fact the above line of code will already populate the error object since someCoreItemInstance violates the constraint (nullable:false). However in an explicit call someCoreItemInstance.validate() will create "error" object and put it in the someCoreItemInstance object; but

3. someCoreItemInstance.save() will automatically call someCoreItemInstance.validate()


In the controller even if you do not do anything extra (there are rare exceptions like while doing a transaction) you must be calling the save method. That automatically puts the error object inside someCoreItemInstance object; but "how do I create nice user friendly error message"?

This is where convention over configuration (over coding!) comes into play. Your error object by default looks for a message in /i18/messages.properties file in the following format.
[Class class] [Attribute attribute] [Constraint constraint]

So in the above example all you need to create nice error message is a message like this...
foo.bar.Item.itemName.nullable = Hey please enter item name

All that remains is to display the message in the gsp page; for that...
<g:hasErrors bean="${someCoreItemInstance}">
<div class="errors">
<g:renderErrors bean="${someCoreItemInstance}" as="list" />
</div>
</g:hasErrors>
...

And thats it!
So all you really need is the message in the correct format and the gsp code to display.

But I want to validate non-domain (where domain class is a class representing a persisted object, think hibernate) classes too. How do I inject the 'error' object into them? Well there seems to be a bit of a confusion but here is what always works.

Lets say you have non-domain class ItemBean and you want to be able to call validate() and want the rest of the magic to happen. So you need...
package foo.bar;
@Validatable
class ItemBean {
...
}

and also enter the following line in Config.groovy
grails.validateable.classes = [foo.bar.ItemBean] // more comma separated allowed


Happy Validating!

Wednesday, August 18, 2010

DBDesigner - Don't Use It


It took me significant googling to finally install DBDesigner. For friends I will document the steps here.
1. Download DBDesigner (rpm version) here
2. After downloading this file you will need alien to convert it to .deb, if you don't have it installed, just type sudo apt-get install alien
3. cd to where you downloaded the rpm package and install it using sudo alien -i DBDesigner4-0.5.4-0.i586.rpm
4. At this point DBDesigner is installed in /opt/DBDesigner4 but if you try to run it (./DBDesigner) it says libborqt-6.9-qt2.3.so: cannot open shared object file: No such file or directory
5. You need the library package. Download it here
6. Convert the package to .deb sudo alien kylixlibs3-borqt-3.0-rh.1.i386.rpm
7. Verify you have the file /usr/lib/libborqt-6.9.0-qt2.3.so
8. Copy and rename the file sudo cp libborqt-6.9.0-qt2.3.so /lib/libborqt-6.9-qt2.3.so
9. Go to /opt/DBDesigner4 and run ./DBDesigner
10. Please change the font ;)


Edit: I do not use DB Designer anymore since the last... hmm 3 years ;) My SQL Workbench is so cool 

Obituary: OpenSolaris

The corporation killed the community spirit again. James Gosling has compared Larry Ellison to Chengiz Khan ("we must not only ensure that we win but also everyone else loose"). They killed OpenSolaris and will only release a Developer MTU. Erstwhile Sun built, contributed and nourished a community that thrives and continues to grow on the principles of open source. The world (including Oracle) has savored the fruits of sun's philosophy and today they are taking away what belongs really to the solaris developers (both inside and outside of sun). Based on patents files by Gosling and his colleagues they have already sued Google for alleged violating of rights (re Android and Dalvik vm). These attacks go beyond the issues between corporations. The open source java community and everything else that was born of that works everyday to make life a better experience. Oracle cannot just take this away. I don't care if Google looses a lawsuit or two (they did try to screw up Java by building this Dalvik anyway) but if Oracle wins and continues to do what it has started, many years of community work done by smart people will just be wasted (I fear). At the moment I am drawing hope from the fact that java is so deep seated in almost all of oracle products that they will not dare to screw with java.