final long timestamp = System.currentTimeMillis();
final String content = "<setgid>" + timestamp + "</setgid>";
//create an XQuery /db/securityTest1/setuid.xquery
final String xquery = "xmldb:store('/db/securityTest2/forSetGidWrite', 'setgid.xml', " + content + ")";
Resource xqueryResource = test.createResource("setgid.xquery", "BinaryResource");
xqueryResource.setContent(xquery);
test.storeResource(xqueryResource);
//set the xquery to be owned by 'test1':'users' and set it 'setgid', and set it 'rx' by ohers, so 'test3' can execute it!
UserManagementService ums = (UserManagementService)test.getService("UserManagementService", "1.0");
xqueryResource = test.getResource("setgid.xquery");
ums.chown(xqueryResource, ums.getAccount("test1"), "users");
ums.chmod(xqueryResource, 02705); //setgid
//create a collection for the XQuery to write into
final CollectionManagementService cms = (CollectionManagementService)test.getService("CollectionManagementService", "1.0");
final Collection colForSetUid = cms.createCollection("forSetGidWrite");
//only allow the group 'users' to write into the collection
ums = (UserManagementService)colForSetUid.getService("UserManagementService", "1.0");
ums.chmod(0570);
//execute the XQuery as the 'test3' user... it should become 'setgid' of 'users' and succeed.
final Collection test3 = DatabaseManager.getCollection(baseUri + "/db/securityTest2", "test3", "test3");
final XPathQueryServiceImpl queryService = (XPathQueryServiceImpl)test3.getService("XPathQueryService", "1.0");
final ResourceSet result = queryService.executeStoredQuery("/db/securityTest2/setgid.xquery");
assertEquals("/db/securityTest2/forSetGidWrite/setgid.xml", result.getResource(0).getContent());
//check the written content
final Resource writtenXmlResource = colForSetUid.getResource("setgid.xml");
assertEquals(content, writtenXmlResource.getContent());
}