Apply SLING-3265.2.patch, contributed by Tommaso Teofili, thanks! Such a large patch is unusual, ok here as it takes into account a number of issues raised during the donation review

git-svn-id: https://svn.apache.org/repos/asf/sling/trunk@1549567 13f79535-47bb-0310-9956-ffa450edef68