There is a util class that already does this. See Alamelu's pull request for details.