Feel free to take a look at the implementation of open source vijava API which has resolved the issue: http://vijava.sf.net. Or, you can just use the API and forget about these tedious details.
Commercial version of open source is also available: http://www.doublecloud.org/2014/01/announcing-vijavang-much-lighter-and-faster-with-commercial-license-and-support/
Disclaimer: I am the creator of the open source.
Steve